summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichael Lando <ml636r@att.com>2018-03-04 14:53:33 +0200
committerMichael Lando <ml636r@att.com>2018-03-07 13:19:05 +0000
commita5445100050e49e83f73424198d73cd72d672a4d (patch)
treecacf4df817df31be23e4e790d1dda857bdae061e
parent51157f92c21976cba4914c378aaa3cba49826931 (diff)
Sync Integ to Master
Change-Id: I71e3acc26fa612127756ac04073a522b9cc6cd74 Issue-ID: SDC-977 Signed-off-by: Gitelman, Tal (tg851x) <tg851x@intl.att.com>
-rw-r--r--.gitignore72
-rw-r--r--asdc-tests/.gitignore4
-rw-r--r--asdc-tests/pom.xml336
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java204
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java518
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java806
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java366
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java609
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java63
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java135
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java226
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java122
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java121
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java272
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java60
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java332
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java88
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java145
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java76
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java71
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java104
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java116
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java222
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java337
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java78
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java80
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java106
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java267
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java57
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java78
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java40
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java52
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java93
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java64
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java36
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java95
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java75
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java66
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java45
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java74
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java106
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java57
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java40
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java38
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java35
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java37
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java46
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java77
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java166
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java90
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java151
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java79
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java88
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java179
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java88
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java121
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java142
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java300
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java98
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java114
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java38
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java58
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java888
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java84
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java135
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java656
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java1789
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java661
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java331
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java696
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java631
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java176
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java94
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java301
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java2301
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java147
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java2003
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java1907
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java3514
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java84
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java307
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java103
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/OpsRejectDistribution.java61
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/SearchFilterCategoryExternalAPI.java285
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java578
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/VFCMTExternalAPI.java388
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java101
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java95
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java186
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java596
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java385
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/LifeCycleExternalAPI.java270
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/UserAPIs.java468
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java441
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java1419
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java104
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java646
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java657
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/FilteredDataByParamsComponentServletTest.java135
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java1829
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java618
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java1524
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java416
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java2893
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java282
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ToscaTemplateVersionTest.java65
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java407
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java274
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/ServiceCertWithoutDeploymentArtifacts.java65
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java2021
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java1022
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java1796
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java379
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java52
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java1395
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java2212
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CustomizationUUIDTest.java433
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java580
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java193
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java326
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java371
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java41
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java124
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java2301
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java480
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java315
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java1795
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java1008
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java1300
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java350
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java368
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java684
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java1194
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java1407
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java2164
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java756
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java1693
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java317
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java141
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/postupgrade/AttKeyPropertiesRenameTest.java95
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/preupgrade/AttKeyPropertiesBeforeRenameTest.java70
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java177
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java125
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java96
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java82
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java273
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java410
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java287
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java130
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java25
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java79
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java78
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java59
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java25
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java83
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java54
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java72
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java77
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java113
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java133
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java59
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java39
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java74
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java66
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java286
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java62
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java166
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java630
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java305
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java656
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java225
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java172
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java692
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java341
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java948
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java137
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java57
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java60
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java920
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java557
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java263
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java87
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java308
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java22
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java304
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java70
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java245
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java252
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java61
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java399
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java122
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java410
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java196
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java262
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java725
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java63
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java564
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java285
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java281
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java223
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java1390
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java116
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java126
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java298
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java86
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java121
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java239
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java358
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java131
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java92
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java275
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java111
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java352
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java438
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java773
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java70
-rw-r--r--asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml11
-rw-r--r--asdc-tests/src/main/resources/ci/conf/attsdc.yaml91
-rw-r--r--asdc-tests/src/main/resources/ci/conf/log4j.properties34
-rw-r--r--asdc-tests/src/main/resources/ci/conf/testngLifeCycle.xml27
-rw-r--r--asdc-tests/src/main/resources/ci/conf/titan.properties8
-rw-r--r--asdc-tests/src/main/resources/ci/conf/truststorebin971 -> 0 bytes
-rw-r--r--asdc-tests/src/main/resources/ci/scripts/startTest.sh88
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml40
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/SearchExternalAPI.xml23
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/artifacts.xml19
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/category.xml11
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/ciFull.xml174
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/externalApis.xml14
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/general.xml11
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/imports.xml12
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/property.xml11
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/resource.xml320
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/sanity.xml330
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/service.xml15
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/testngLifeCycle.xml27
-rw-r--r--asdc-tests/src/main/resources/ci/testSuites/user.xml18
-rw-r--r--asdc-tests/src/test/resources/CI/components/apache/apache-type.yml50
-rw-r--r--asdc-tests/src/test/resources/CI/components/apache/images/apache.pngbin10518 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/apache/scripts/install_apache.sh53
-rw-r--r--asdc-tests/src/test/resources/CI/components/apache/scripts/start_apache.sh10
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/images/relational_db.pngbin51853 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/normative-types-DBMS.yml36
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/images/volume.pngbin16643 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/normative-types-blockStorage.yml40
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/compute/images/compute.pngbin61345 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/compute/normative-types-compute.yml77
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/database/images/relational_db.pngbin51853 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/database/normative-types-database.yml41
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/network/images/network.pngbin159707 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/network/normative-types-network.yml39
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/images/objectstore.pngbin4354 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/normative-types-objectStorage.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/root/images/root.pngbin5335 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/root/normative-types-root.yml168
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/images/software.pngbin55407 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/normative-types-softwareComponent.yml25
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/images/network.pngbin159707 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/normative-types-webApplication.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/components/normativeTypes/webServer/normative-types-webServer.yml24
-rw-r--r--asdc-tests/src/test/resources/CI/configuration.yaml386
-rw-r--r--asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csarbin35433 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC.csarbin57082 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csarbin30674 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csarbin28284 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/ToscaTemplateCsar.csarbin6175 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csarbin36439 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_a.csarbin36439 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_b.csarbin36443 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming.csarbin35872 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_a.csarbin35872 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_add_update.csarbin35852 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_delete_update.csarbin35851 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_update.csarbin36436 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csarbin24750 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/mycompute.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/csars/mycompute2.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/csars/mycompute_failed.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2G.csarbin38917 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV001.csarbin39002 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csarbin39002 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV006-remove-all-nested-artifacts.csarbin39000 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2GV008-change-nested-oam-fileContent.csarbin39013 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2G_a.csarbin38917 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/orig2G_updated.csarbin38791 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/valid_vf.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/valid_vf_a.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/valid_vf_b.csarbin1244 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/valid_vf_c.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/valid_vf_d.csarbin1406 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/valid_vf_f.csarbin1443 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_relate_by_cap_name.csarbin25918 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop.csarbin1411 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csarbin1548 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csarbin1546 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop_failed.csarbin1412 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vfc_artifacts.csarbin48225 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csarbin26179 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vfc_artifacts_update.csarbin48245 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csarbin35471 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.yml23
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.zipbin493 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zipbin411 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.yml10
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.zipbin357 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.yml25
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.zipbin467 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.yml4
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zipbin231 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.yml10
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zipbin384 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/deleteResourcesLanWanDemo.sh36
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/importResourcesLanWanDemo.sh49
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.yml3
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zipbin205 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.json11
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.yml13
-rw-r--r--asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zipbin418 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml.old28
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.zipbin357 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml13
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml.old24
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.zipbin347 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF .yml.old29
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.yml13
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.zipbin343 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml13
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml.old23
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.zipbin346 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/compute/compute.json15
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/compute/compute.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/compute/compute.zipbin477 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/deleteResourcesDemo.sh36
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/importResourcesDemo.sh39
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.zipbin384 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/root/root.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/root/root.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/root/root.zipbin378 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.yml15
-rw-r--r--asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.zipbin358 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.capabilities.yaml13
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.yml2
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.zipbin230 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.yml2
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.zipbin194 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.json13
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.yml3
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.zipbin180 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.zipbin336 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.yml12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.zipbin350 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.yml12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.zipbin347 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.yml12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.zipbin340 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.zipbin337 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.yml15
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.zipbin359 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.zipbin262 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.zipbin256 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.zipbin255 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.zipbin302 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.zipbin254 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.zipbin300 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/capabilityTypes.zipbin320 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/deleteNormative.sh35
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-MMSC/importNormative.sh85
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/VCE_Brocade_Tosca.yaml834
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zipbin1065 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/importVceBrocade.sh89
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.yaml48
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.zipbin805 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.yaml48
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.zipbin795 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.yaml48
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.zipbin796 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.yaml7
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.zipbin339 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.yaml7
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.zipbin395 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.yaml156
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.zipbin1751 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.yaml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.zipbin344 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.yaml10
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.zipbin442 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.yaml10
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.zipbin440 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.yaml10
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.zipbin453 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.yaml10
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.zipbin515 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.yaml10
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.zipbin502 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.yaml7
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.zipbin310 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.yaml32
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.zipbin592 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.yaml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.zipbin309 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.yaml16
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.zipbin414 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.yaml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.zipbin532 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.yaml24
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.zipbin462 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.json11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.yaml28
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.zipbin502 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/vce.brocade.capabilities.yaml191
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/DBMS/DBMS.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.zipbin422 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/blockStorage/blockStorage.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.zipbin392 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/capabilityTypes.yml148
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/capabilityTypes.zipbin1018 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/capabilityTypesCi.zipbin990 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/categoryTypes.yml89
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/categoryTypes.zipbin710 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/compute/compute.json24
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.zipbin559 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/containerApplication/containerApplication.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.zipbin358 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/containerRuntime/containerRuntime.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.zipbin335 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/database/database.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.yml27
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.zipbin517 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/deleteNormative.sh49
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/importNormative.sh89
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.yml11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.zipbin273 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/loadBalancer/loadBalancer.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.zipbin468 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/network/network.json21
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.yml41
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.zipbin461 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.yml31
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.zipbin454 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/normative-port/port.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/notmative-network/network.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.yml41
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.zipbin450 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.zipbin386 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/objectStorage/objectStorage.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.yml31
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.zipbin467 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/port/port.json21
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.yml23
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.zipbin457 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.zipbin435 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/softwareComponent/softwareComponent.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.yml15
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.zipbin398 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/webApplication/webApplication.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.yml11
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.zipbin380 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResource/webServer/webServer.json20
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/Derived_VFC.json26
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.zipbin322 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/VSPPackage.csarbin26339 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_1.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_2.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/csars.zipbin34892 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/fiveLinesAsBlock0.csarbin1325 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion.csarbin1317 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion2.csarbin1315 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion3.csarbin1317 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion4.csarbin1317 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion5.csarbin1319 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile1.csarbin1322 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile2.csarbin1322 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile3.csarbin1319 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile4.csarbin1319 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile5.csarbin1319 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/missingEntryDefintionPair.csarbin1285 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/missingOneLineInToscaMeta.csarbin1295 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf2.csarbin1314 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThanOneMetaFile.csarbin1808 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThenOneYamlFile.csarbin2470 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/noCSARVersion.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/noCreatedByValue.csarbin1304 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/noEntryDefinitionsValue.csarbin1296 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/noNewLineAfterBLock0.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/noTOSCAMetaFileVersionValue.csarbin1315 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlAndMetaFiles.csarbin490 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlFile.csarbin757 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/someValueAfterBlock0.csarbin1322 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaFolderNotExists.csarbin907 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaFileNotExists.csarbin1049 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaOutsideTheFolder.csarbin1286 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/underscoreInsteadOfDash.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/validCsarVersion.csarbin1320 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf.csarbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf_zip.zipbin1316 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_category/empty_category.json22
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.zipbin394 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/empty_contact.json22
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.zipbin409 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/empty_desc.json22
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.zipbin386 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/empty_icon.json22
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.zipbin386 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/empty_payloadName.json22
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.zipbin400 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/empty_resource_name.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.zipbin420 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/empty_tag.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.zipbin400 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/import _multiple_tags.json18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.zipbin408 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/importResource4test.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.zipbin596 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/importResource4testCP.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.zipbin603 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/importResource4testMissingNameSpace.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.zipbin628 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/importResource4testUnknown.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.zipbin616 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/importResource4testUpdateVendorNameAndCategory.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.yml12
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.zipbin411 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/importResource4testUpdateWithoutReqCap.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.yml12
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.zipbin422 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/importResource4testVF.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.zipbin603 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/importResource4testVFC.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.zipbin607 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/importResource4testVL.json17
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.yml30
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.zipbin603 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.yml141
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.zipbin979 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi.zipbin990 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_MissingDerivedFrom.yml132
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_WithoutRoot.yml141
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_category/missing_category.json12
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.zipbin414 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/missing_contact.json21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.zipbin413 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/missing_derived_from.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.yml15
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.zipbin391 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/missing_desc.json15
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.zipbin406 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/missing_icon.json15
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.zipbin406 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/missing_payloadName.json15
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.zipbin420 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/missing_resource_name.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.zipbin424 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/missing_tags.json15
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.zipbin406 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/myCompute/myCompute.json24
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.zipbin567 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.yml29
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.zipbin470 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/portInvalidDefaultValue.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.zipbin610 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userCompute/userCompute.json26
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.yml29
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.zipbin580 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/userUpdateCompute.json22
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.yml39
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.zipbin591 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/validateProporties_happyScenarios.json14
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.zipbin542 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/validateProporties_typeBoolean_valueInit.json14
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.zipbin542 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/validateProporties_typeBoolean_valueString.json14
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.zipbin539 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/validateProporties_typeFloat_valueBoolean.json14
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.zipbin538 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/validateProporties_typeFloat_valueString.json14
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.zipbin538 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/validateProporties_typeInit_valueBoolean.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.zipbin536 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/validateProporties_typeInit_valueFloat.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.yml21
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.zipbin536 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/validateProporties_typeInit_valueString.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.yml50
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.zipbin685 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/validateProporties_typeList_valueUrlCredential.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.yml29
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.zipbin593 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/validateProporties_typeMap_valueUrlCredential.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/normative-types-new-validateProporties_typeString_valueString_special_chars.yml19
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/validateProporties_typeString_valueString_special_chars.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/normative-types-new-validateProporties_typeString_valueString_trimming.yml19
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/validateProporties_typeString_valueString_trimming.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.yml32
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeTestDataType.zipbin608 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/validateProporties_typeTestDataType.json16
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.yml23
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.zipbin333 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml13
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zipbin400 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml14
-rw-r--r--asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zipbin423 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/other/mapping.json182
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml32
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml787
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zipbin2420 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml787
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env787
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml9
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml13
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json11
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml787
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json22
-rw-r--r--asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt3
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml3
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docxbin11307 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf2
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml3
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml3
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json3
-rw-r--r--asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml5
-rw-r--r--asdc-tests/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml787
-rw-r--r--asdc-tests/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zipbin11590 -> 0 bytes
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml603
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml603
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml603
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml787
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_1.yaml144
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_2.yaml469
-rw-r--r--asdc-tests/src/test/resources/CI/tests/heatEnv/yuli.yaml144
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml14
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml56
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml14
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml27
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml26
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml22
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml25
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml32
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml9
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml19
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml18
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml19
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml26
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml23
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml23
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml15
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml53
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml42
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml40
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml198
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml452
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/loadBalancerTestVersion.yml6
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml37
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml25
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml15
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml77
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml34
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml42
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml44
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml16
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml35
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml17
-rw-r--r--asdc-tests/src/test/resources/CI/tests/testCsarAPI/topology.txt1
-rw-r--r--asdc-tests/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt1
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml140
-rw-r--r--asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml140
-rw-r--r--asdc-tests/src/test/resources/config.json12
-rw-r--r--asdc-tests/testng.xml15
-rw-r--r--asdc-tests/testngLifeCycle.xml27
-rw-r--r--asdctool/pom.xml34
-rw-r--r--asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb39
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLITool.java56
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIToolData.java31
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIUtils.java21
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/SpringCLITool.java32
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ArtifactUUIDFixConfiguration.java302
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ConfigurationUploader.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java20
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ESCatalogDAOMock.java41
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchClientMock.java26
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchMocksConfiguration.java27
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/EsHealthCheckDaoMock.java11
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java2445
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java29
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/RestUtils.java61
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/TitanGraphInitializer.java31
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/ArtifactToolBL.java1
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/IArtifactValidatorExecuter.java9
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/NodeToscaArtifactsValidatorExecuter.java1
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ServiceToscaArtifactsValidatorExecutor.java1
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/VFToscaArtifactValidatorExecutor.java1
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VfModuleArtifactPayloadEx.java92
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactUUIDFixMenu.java9
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactValidatorTool.java1
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/GetConsumersMenu.java57
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java299
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineClusterHealthMock.java16
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineMock.java68
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DmaapHealthCheckMock.java16
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/HealthCheckBusinessLogicMock.java21
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java10
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java13
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java73
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java1
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java498
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java137
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportCassandraTableTool.java69
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportTableConfig.java19
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEnvironment.java119
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEvnironmentImportHandler.java99
-rw-r--r--asdctool/src/main/resources/config/configuration.yaml10
-rw-r--r--asdctool/src/main/resources/config/error-configuration.yaml23
-rw-r--r--asdctool/src/main/resources/scripts/getConsumers.sh37
-rw-r--r--asdctool/src/main/resources/scripts/python/user/exportUsers.py41
-rw-r--r--asdctool/src/main/resources/scripts/python/user/importUsers.py60
-rw-r--r--asdctool/src/main/resources/scripts/sdc-migration.sh2
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfigTest.java76
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java76
-rw-r--r--build.gradle1436
-rw-r--r--catalog-be/DME2preferredRouter.txt (renamed from asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/noContent.yml)0
-rw-r--r--catalog-be/pom.xml317
-rw-r--r--catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gzbin102084 -> 105414 bytes
-rw-r--r--catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb53
-rw-r--r--catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb38
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java114
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java42
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java76
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java569
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java503
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java228
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java34
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java35
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java26
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java25
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java27
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java27
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java25
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java31
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java34
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java31
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java34
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java33
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java175
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java89
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java1681
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java84
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java336
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java88
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java1081
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java19
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java40
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java633
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java557
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java512
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java343
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java161
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java122
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java91
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java76
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java220
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java65
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java526
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java43
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java70
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java76
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java158
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java224
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java212
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java79
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java156
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java503
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java68
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java183
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java19
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java69
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java475
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java42
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java1007
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java10279
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java515
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java1420
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java161
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java336
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java413
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java541
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java2154
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java4879
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java489
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java528
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java587
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java402
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java333
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java2627
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java127
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java3733
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java46
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java249
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java526
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java1333
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java92
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java2008
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java165
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java57
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java451
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java56
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java185
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java1673
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java43
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java991
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java13913
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java1807
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java72
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java4230
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java40
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java44
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java44
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java70
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java66
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java67
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java32
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java290
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java553
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java201
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java291
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java248
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java879
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java26
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java38
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java184
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java182
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java7
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java82
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java103
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java47
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java113
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java (renamed from catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java)29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java (renamed from catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java)31
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java416
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java38
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java49
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java51
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java6
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java52
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java257
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java173
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java75
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java413
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java13
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java130
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java66
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java30
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java35
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java150
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java88
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java163
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java42
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java34
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java113
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java216
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java118
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java110
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java89
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java43
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java142
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java92
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java455
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java51
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java457
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java46
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java46
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java496
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java664
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java683
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java687
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java44
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java155
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java1497
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java642
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java1028
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java214
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java167
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java198
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java190
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java70
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java66
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java72
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java70
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java126
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java42
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java72
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java364
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java348
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java164
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java2847
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java227
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java244
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java241
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java110
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java630
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java32
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java48
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java68
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java126
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java76
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java294
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java48
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java275
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java41
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java123
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java70
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java36
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java54
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java73
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java20
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java115
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java1692
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java912
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java1108
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java448
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java440
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java276
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java2177
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java708
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java117
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java61
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java325
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java192
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java21
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java238
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java1132
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java412
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java55
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java706
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java258
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java307
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java517
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java716
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java257
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java78
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java221
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java257
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java1214
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java243
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java1373
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java36
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java98
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java150
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java511
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java789
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java496
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java18
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java45
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java1081
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java2894
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java268
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java2307
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java32
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java158
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java74
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java62
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java392
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java78
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java88
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java114
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java96
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java28
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java62
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java78
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java124
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/IUserBusinessLogic.java22
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java64
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java1175
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java7
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java60
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java19
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java17
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java185
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java112
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java56
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java120
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java40
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java46
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java99
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java86
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java130
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java536
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java40
-rw-r--r--catalog-be/src/main/resources/application-context.xml58
-rw-r--r--catalog-be/src/main/resources/config/DME2preferredRouter.txt0
-rw-r--r--catalog-be/src/main/resources/config/configuration.yaml72
-rw-r--r--catalog-be/src/main/resources/config/distribution-engine-configuration.yaml39
-rw-r--r--catalog-be/src/main/resources/config/error-configuration.yaml162
-rw-r--r--catalog-be/src/main/resources/config/logback.xml10
-rw-r--r--catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml12
-rw-r--r--catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zipbin1676 -> 1735 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml3
-rw-r--r--catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zipbin6601 -> 6315 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml59
-rw-r--r--catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zipbin1088 -> 1356 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json (renamed from asdc-tests/src/test/resources/CI/importResource/root/root.json)9
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml15
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zipbin0 -> 678 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zipbin460 -> 462 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zipbin762 -> 767 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml24
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zipbin0 -> 509 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml2
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zipbin1245 -> 1183 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml35
-rw-r--r--catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zipbin673 -> 905 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml5
-rw-r--r--catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zipbin1396 -> 1421 bytes
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py39
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py18
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py51
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py30
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py43
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py46
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py27
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py35
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py63
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json15
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py37
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py51
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py39
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py13
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py49
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py21
-rw-r--r--catalog-be/src/main/webapp/WEB-INF/web.xml14
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java44
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java447
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java56
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java40
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java132
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java4
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java132
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java200
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java236
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java127
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java191
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java387
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java156
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java368
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java432
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java395
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java71
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java355
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java)23
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java157
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java379
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java82
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java143
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java319
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java608
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java112
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java1749
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java202
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java64
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java48
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java77
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java91
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java198
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java205
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java448
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java95
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java37
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java190
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java310
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java12
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java135
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java661
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactResolverTest.java21
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java108
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java127
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java559
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java402
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java242
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java18
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java165
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java879
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java36
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java87
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java493
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java148
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java110
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java3342
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java497
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java15
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java258
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java20
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java152
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java127
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java80
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java266
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java425
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java259
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java295
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java358
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java131
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java20
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java17
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java24
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java11
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java113
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java14
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java19
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java68
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java10
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java70
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java275
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java19
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java19
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java25
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java378
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java101
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java31
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java25
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java16
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java25
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java65
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java328
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java208
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java104
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java107
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java60
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java74
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java23
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java186
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java151
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java15
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java15
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java21
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java68
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java61
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java15
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java45
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java16
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java218
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java15
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java166
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java115
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java238
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java172
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java69
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java138
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java4
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java51
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java155
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java38
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java22
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java38
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java43
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java12
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java35
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java70
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java84
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java94
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java65
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java14
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java113
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java29
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java53
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java153
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java7
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java74
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java477
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java144
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java293
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java219
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java62
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServletTest.java254
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java603
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java288
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java117
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java45
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java27
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java208
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java179
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java197
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java45
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java338
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java101
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java419
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java233
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java292
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java340
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java124
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java159
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java27
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java84
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java222
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java769
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java15
-rw-r--r--catalog-be/src/test/resources/application-context-test.xml17
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt0
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/configuration.yaml67
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml39
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml228
-rw-r--r--catalog-be/src/test/resources/cucumber/tenantIsolation.feature42
-rw-r--r--catalog-be/src/test/resources/logback-test.xml2
-rw-r--r--catalog-be/src/test/resources/paths/elasticsearch.yml392
-rw-r--r--catalog-be/src/test/resources/paths/path-context.xml71
-rw-r--r--catalog-dao/pom.xml33
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java142
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java26
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java37
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java89
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java14
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java20
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java43
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java76
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java47
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java38
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java51
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java45
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java41
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java76
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java79
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java34
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java35
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java32
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java18
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java7
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java1816
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java7
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java22
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java116
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java2
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java390
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java110
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java44
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java2
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java27
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java11
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java13
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java12
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java12
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ComponentMetadataData.java13
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java13
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java137
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java137
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java13
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java12
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java6
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java10
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java11
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java11
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java319
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java2
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java20
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java23
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java304
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java236
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java184
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java450
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java82
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java25
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java164
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java691
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java300
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java309
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java36
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java27
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java21
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java75
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionData.java20
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/OperationalEnvAuditData.java26
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java60
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java13
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java8
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java13
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java4
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java291
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfoTest.java132
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java105
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java3
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/resources/data/PolicyTypeDataTest.java11
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/utils/FixtureHelpers.java50
-rw-r--r--catalog-dao/src/test/java/org/openecomp/sdc/be/utils/JsonTester.java42
-rw-r--r--catalog-dao/src/test/resources/fixtures/ListCapabilityDataDefinition.json19
-rw-r--r--catalog-fe/pom.xml23
-rw-r--r--catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb11
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/client/BackendClient.java179
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java11
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java2
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java627
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/PortalServlet.java1
-rw-r--r--catalog-fe/src/main/resources/config/configuration.yaml7
-rw-r--r--catalog-fe/src/test/java/org/openecomp/sdc/fe/client/BackendClientTest.java26
-rw-r--r--catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/PortalServletTest.java29
-rw-r--r--catalog-fe/src/test/java/org/openecomp/sdc/servlets/PortalServletTest.java2
-rw-r--r--catalog-model/pom.xml10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java109
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java84
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java170
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java53
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java79
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java113
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java66
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java31
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java43
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java129
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java34
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java107
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java50
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java146
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java63
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java261
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java122
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java40
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java72
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java63
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java222
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java172
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java2380
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java229
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java54
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java71
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java17
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java36
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java16
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java67
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java662
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java128
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java437
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java171
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java43
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java67
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java11
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java306
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java14
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java9
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java178
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java1
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java133
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java93
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java199
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java199
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java125
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java6
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java144
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java118
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java7
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java346
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java12
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java291
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java25
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java460
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java16
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java73
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java16
-rw-r--r--catalog-model/src/test/resources/application-context-test.xml3
-rw-r--r--catalog-ui/configurations/dev.js10
-rw-r--r--catalog-ui/configurations/menu.js14
-rw-r--r--catalog-ui/configurations/prod.js9
-rw-r--r--catalog-ui/package.json3
-rw-r--r--catalog-ui/pom.xml2
-rw-r--r--catalog-ui/src/app/app.ts16
-rw-r--r--catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts1
-rw-r--r--catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts1
-rw-r--r--catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts1
-rw-r--r--catalog-ui/src/app/directives/file-opener/file-opener.ts1
-rw-r--r--catalog-ui/src/app/directives/file-upload/file-upload.ts1
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts251
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts22
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.directive.ts225
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html33
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less24
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts1
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts41
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts28
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-service-path-utils.ts80
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-zone-utils.ts55
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts3
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts3
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts1
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts97
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/palette.html18
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts1
-rw-r--r--catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts1
-rw-r--r--catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts1
-rw-r--r--catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts1
-rw-r--r--catalog-ui/src/app/filters/category-type-filter.ts1
-rw-r--r--catalog-ui/src/app/filters/entity-filter.ts15
-rw-r--r--catalog-ui/src/app/filters/resource-name-filter.ts2
-rw-r--r--catalog-ui/src/app/models/app-config.ts1
-rw-r--r--catalog-ui/src/app/models/artifacts.ts1
-rw-r--r--catalog-ui/src/app/models/attributes.ts1
-rw-r--r--catalog-ui/src/app/models/capability.ts1
-rw-r--r--catalog-ui/src/app/models/components/component.ts67
-rw-r--r--catalog-ui/src/app/models/components/displayComponent.ts74
-rw-r--r--catalog-ui/src/app/models/components/resource.ts3
-rw-r--r--catalog-ui/src/app/models/components/service.ts3
-rw-r--r--catalog-ui/src/app/models/componentsInstances/componentInstance.ts3
-rw-r--r--catalog-ui/src/app/models/forwarding-path-link.ts20
-rw-r--r--catalog-ui/src/app/models/forwarding-path.ts30
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link.ts (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java)47
-rw-r--r--catalog-ui/src/app/models/graph/graph-links/links-factory.ts1
-rw-r--r--catalog-ui/src/app/models/graph/match-relation.ts1
-rw-r--r--catalog-ui/src/app/models/graph/nodes-and-links-map.ts7
-rw-r--r--catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts1
-rw-r--r--catalog-ui/src/app/models/graph/relationship.ts1
-rw-r--r--catalog-ui/src/app/models/graph/zones/policy-instance.ts43
-rw-r--r--catalog-ui/src/app/models/graph/zones/zone-child.ts48
-rw-r--r--catalog-ui/src/app/models/group-metadata.ts33
-rw-r--r--catalog-ui/src/app/models/instance-inputs-properties-map.ts1
-rw-r--r--catalog-ui/src/app/models/member.ts1
-rw-r--r--catalog-ui/src/app/models/modal.ts4
-rw-r--r--catalog-ui/src/app/models/modules/base-module.ts2
-rw-r--r--catalog-ui/src/app/models/path-elements.ts5
-rw-r--r--catalog-ui/src/app/models/policy-metadata.ts33
-rw-r--r--catalog-ui/src/app/models/properties-inputs/derived-fe-property.ts40
-rw-r--r--catalog-ui/src/app/models/properties-inputs/input-be-model.ts3
-rw-r--r--catalog-ui/src/app/models/properties-inputs/input-fe-model.ts39
-rw-r--r--catalog-ui/src/app/models/properties-inputs/property-fe-model.ts205
-rw-r--r--catalog-ui/src/app/models/properties.ts1
-rw-r--r--catalog-ui/src/app/models/requirement.ts4
-rw-r--r--catalog-ui/src/app/modules/directive-module.ts67
-rw-r--r--catalog-ui/src/app/modules/service-module.ts10
-rw-r--r--catalog-ui/src/app/ng2/app.module.ts22
-rw-r--r--catalog-ui/src/app/ng2/components/layout/top-nav/top-nav.component.ts5
-rw-r--r--catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.html2
-rw-r--r--catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.ts1
-rw-r--r--catalog-ui/src/app/ng2/components/logic/hierarchy-navigtion/hierarchy-navigation.component.ts2
-rw-r--r--catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.html6
-rw-r--r--catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.less7
-rw-r--r--catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.ts7
-rw-r--r--catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.html19
-rw-r--r--catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.ts113
-rw-r--r--catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.html2
-rw-r--r--catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.ts6
-rw-r--r--catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.html3
-rw-r--r--catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.ts44
-rw-r--r--catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.module.ts5
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.html11
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.less24
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.ts134
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.module.ts21
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.html22
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.less51
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.ts83
-rw-r--r--catalog-ui/src/app/ng2/components/logic/service-path/service-path.module.ts (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java)42
-rw-r--r--catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.html11
-rw-r--r--catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.less62
-rw-r--r--catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.ts25
-rw-r--r--catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.html8
-rw-r--r--catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.less110
-rw-r--r--catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.ts28
-rw-r--r--catalog-ui/src/app/ng2/components/ui/dynamic-element/dynamic-element.component.ts99
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.html2
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.ts5
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.html2
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.ts6
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.html2
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.ts7
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/popover-input/ui-element-popover-input.component.ts9
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/radio-buttons/radio-buttons.component.ts6
-rw-r--r--catalog-ui/src/app/ng2/components/ui/form-components/ui-element-base.component.ts27
-rw-r--r--catalog-ui/src/app/ng2/components/ui/loader/loader.component.ts8
-rw-r--r--catalog-ui/src/app/ng2/components/ui/modal/modal.component.html14
-rw-r--r--catalog-ui/src/app/ng2/components/ui/modal/modal.component.less20
-rw-r--r--catalog-ui/src/app/ng2/components/ui/modal/modal.component.ts1
-rw-r--r--catalog-ui/src/app/ng2/components/ui/modal/modal.module.ts3
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.html4
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.less5
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.ts64
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.module.ts16
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.html9
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.less37
-rw-r--r--catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.ts87
-rw-r--r--catalog-ui/src/app/ng2/components/ui/popover/popover-content.component.html3
-rw-r--r--catalog-ui/src/app/ng2/components/ui/tabs/tabs.component.ts2
-rw-r--r--catalog-ui/src/app/ng2/components/ui/ui-elements.module.ts23
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/connection-wizard.service.ts1
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.html3
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.ts4
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.html2
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.ts5
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.html3
-rw-r--r--catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.ts4
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts3
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html86
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less12
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts329
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/services/hierarchy-nav.service.ts1
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/services/inputs.utils.ts (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java)31
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts83
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.html5
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less21
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts110
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link.model.ts (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java)35
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html43
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less45
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts137
-rw-r--r--catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.module.ts25
-rw-r--r--catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html21
-rw-r--r--catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less21
-rw-r--r--catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts66
-rw-r--r--catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts17
-rw-r--r--catalog-ui/src/app/ng2/pipes/global-pipes.module.ts1
-rw-r--r--catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts49
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts41
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/component.service.ts28
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/service.service.ts119
-rw-r--r--catalog-ui/src/app/ng2/services/config.service.ts4
-rw-r--r--catalog-ui/src/app/ng2/services/data-type.service.ts1
-rw-r--r--catalog-ui/src/app/ng2/services/dynamic-component.service.ts28
-rw-r--r--catalog-ui/src/app/ng2/services/modal.service.ts37
-rw-r--r--catalog-ui/src/app/ng2/services/policies.service.ts (renamed from asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java)48
-rw-r--r--catalog-ui/src/app/ng2/services/properties.service.ts1
-rw-r--r--catalog-ui/src/app/ng2/services/responses/component-generic-response.ts5
-rw-r--r--catalog-ui/src/app/ng2/services/responses/service-generic-response.ts22
-rw-r--r--catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts11
-rw-r--r--catalog-ui/src/app/services/components/component-service.ts32
-rw-r--r--catalog-ui/src/app/services/components/resource-service.ts1
-rw-r--r--catalog-ui/src/app/services/components/service-service.ts1
-rw-r--r--catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts106
-rw-r--r--catalog-ui/src/app/services/entity-service.ts4
-rw-r--r--catalog-ui/src/app/services/event-listener-service.ts1
-rw-r--r--catalog-ui/src/app/services/onboarding-service.ts2
-rw-r--r--catalog-ui/src/app/utils/artifacts-utils.ts2
-rw-r--r--catalog-ui/src/app/utils/common-utils.ts14
-rw-r--r--catalog-ui/src/app/utils/component-factory.ts2
-rw-r--r--catalog-ui/src/app/utils/constants.ts22
-rw-r--r--catalog-ui/src/app/utils/menu-handler.ts53
-rw-r--r--catalog-ui/src/app/utils/modals-handler.ts5
-rw-r--r--catalog-ui/src/app/utils/validation-utils.ts2
-rw-r--r--catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/catalog/catalog-view-model.ts3
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts7
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard-view.html1
-rw-r--r--catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts3
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts12
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html3
-rw-r--r--catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts1
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts6
-rw-r--r--catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html4
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts95
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html21
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less45
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts3
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts52
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/properties-and-attributes/properties-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html20
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts2
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view-model.ts50
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view.html21
-rw-r--r--catalog-ui/src/assets/languages/en_US.json6
-rw-r--r--catalog-ui/src/assets/styles/app.less3
-rw-r--r--catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding.svg48
-rw-r--r--catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_group.svg33
-rw-r--r--catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_policy.svg33
-rw-r--r--catalog-ui/src/assets/styles/images/canvas-tagging-icons/group_added.svg33
-rw-r--r--catalog-ui/src/assets/styles/images/canvas-tagging-icons/indication.svg26
-rw-r--r--catalog-ui/src/assets/styles/images/canvas-tagging-icons/policy_added.svg33
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/monitoring_template.pngbin0 -> 16351 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-policy-groups-icons.pngbin0 -> 13071 bytes
-rw-r--r--catalog-ui/src/assets/styles/sprite-group-icons.less11
-rw-r--r--catalog-ui/src/assets/styles/sprite-policy-icons.less12
-rw-r--r--catalog-ui/src/assets/styles/sprite-resource-icons.less8
-rw-r--r--catalog-ui/src/assets/styles/sprite.less4
-rw-r--r--catalog-ui/src/assets/styles/tables.less54
-rw-r--r--catalog-ui/webpack.server.js136
-rw-r--r--common-app-api/pom.xml18
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java14
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java117
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java62
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java269
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java27
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java57
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java19
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java2
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java85
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java5
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java9
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java4
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java27
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java10
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java207
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java184
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java79
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java51
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java77
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java34
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java207
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java290
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java24
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java13
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java23
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java23
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java14
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java61
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java42
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java14
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java75
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java11
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java92
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java35
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java27
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java71
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java198
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java8
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java147
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java154
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java51
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java117
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java24
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java136
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java114
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java48
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java10
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java16
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java24
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java101
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java100
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java35
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java99
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java40
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java102
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java103
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java76
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java108
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java133
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java427
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java48
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java (renamed from catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java)21
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java34
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java23
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java3
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java30
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java749
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java59
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java2
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArrayTest.java99
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseTest.java88
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/test/E2EHttpClientTest.java83
-rw-r--r--common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml32
-rw-r--r--common-be/pom.xml56
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java5
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ArtifactDataDefinition.java16
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityTypeDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/DataTypeDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathDataDefinition.java94
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathElementDataDefinition.java107
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetInputValueDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java12
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupTypeDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/HeatParameterDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListCapabilityDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java14
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListRequirementDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java7
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapComponentInstanceExternalRefs.java83
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java10
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyDataDefinition.java204
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTargetType.java29
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTypeDataDefinition.java215
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertiesOwner.java11
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java9
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/SchemaDefinition.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ConnectionPointEnum.java25
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/EnvironmentStatusEnum.java27
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java32
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java25
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java52
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java13
-rw-r--r--common/pom.xml2
-rw-r--r--mvn-be.cmd1
-rw-r--r--openecomp-ui/yarn.lock63
-rw-r--r--pom.xml162
-rw-r--r--sdc-os-chef/pom.xml2
-rwxr-xr-xsdc-os-chef/scripts/docker_run.sh34
-rw-r--r--sdc-os-chef/scripts/docker_run_csit.sh386
-rw-r--r--sdc-os-chef/scripts/sanity_run.sh220
-rw-r--r--sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/recipes/sanityTests_3_sanity_execution.rb14
-rw-r--r--sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/templates/default/sdc-sanity.yaml.erb11
-rw-r--r--security-utils/logback-test.xml (renamed from asdc-tests/src/test/resources/logback-test.xml)6
-rw-r--r--security-utils/pom.xml20
-rw-r--r--security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java36
-rw-r--r--security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java155
-rw-r--r--security-utils/src/test/java/org/openecomp/sdc/security/PasswordTest.java48
-rw-r--r--security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java75
-rw-r--r--security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java27
-rw-r--r--test-apis-ci/pom.xml781
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java43
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java12
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java6
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java438
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java22
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java9
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java12
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyObject.java90
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObjectReqDetails.java32
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/GroupPropertyEnum.java46
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java5
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java897
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java3
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java5
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java3
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java9
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupPropertyDefinition.java112
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java33
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java10
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java5
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java14
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java6
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java18
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java372
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java150
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java88
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java13
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java3
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java63
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java1018
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java50
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java285
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java697
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java137
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java61
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AutomationUtils.java14
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java7
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java6
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java16
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java44
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java3
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java13
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java6
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java58
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java29
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java162
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java25
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java30
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java621
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/AssetLifeCycle.java198
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java342
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/DeploymentValiditaion.java269
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java182
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java82
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java584
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java100
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/SearchFilterCategoryExternalAPI.java50
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java112
-rw-r--r--test-apis-ci/src/main/resources/ci/conf/attsdc.yaml2
-rw-r--r--test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh4
-rw-r--r--test-apis-ci/src/main/resources/ci/scripts/sendMail.sh6
-rw-r--r--test-apis-ci/src/main/resources/ci/scripts/startTest.sh4
-rw-r--r--test-apis-ci/src/main/resources/ci/testSuites/ExternalApiSanity.xml68
-rw-r--r--test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml2
-rw-r--r--test-apis-ci/src/main/resources/ci/testSuites/onap.xml11
-rw-r--r--test-apis-ci/src/test/java/org/openecomp/sdc/conf/TestAPIConfDependentTest.java13
-rw-r--r--test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationCucumberCI.java31
-rw-r--r--test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/spring/ImportTableConfig.java19
-rw-r--r--test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/PrecannedTestExpectationCallback.java31
-rw-r--r--test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/StepsTenantIsolationCI.java597
-rw-r--r--test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/utils/RunnerSession.java61
-rw-r--r--test-apis-ci/src/test/resources/CI/tests/tenantIsolationCI/aai_error.properties10
-rw-r--r--test-apis-ci/src/test/resources/catalogMgmtTest.properties34
-rw-r--r--test-apis-ci/src/test/resources/catalogMgmtTest.yaml6
-rw-r--r--test-apis-ci/src/test/resources/config/configuration1.yaml17
-rw-r--r--test-apis-ci/src/test/resources/config/elasticsearch.yml387
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/DME2preferredRouter.txt0
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml677
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/distribution-engine-configuration.yaml77
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/ecomp-error-configuration.yaml383
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/error-configuration.yaml (renamed from asdc-tests/src/test/resources/CI/error-configuration.yaml)749
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/neo4j-errors-configuration.yaml60
-rw-r--r--test-apis-ci/src/test/resources/config/test-apis-ci/users-configuration.yaml2
-rw-r--r--test-apis-ci/src/test/resources/cucumber/tenantIsolation.feature38
-rw-r--r--test-apis-ci/src/test/resources/preferredRouter.txt0
-rw-r--r--ui-ci-dev/.gitignore2
-rw-r--r--ui-ci-dev/pom.xml272
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/scripts/CreateVfsFromOnboarding.java67
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasElement.java33
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasManager.java206
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CleanTypeEnum.java28
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndImportButtonsEnum.java7
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndUpdateStepsEnum.java25
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java477
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/MenuOptionsEnum.java17
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/UserCredentials.java29
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java419
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/generalTests/GeneralTests.java26
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceBasicTests.java147
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceInputsTests.java124
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java333
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfCanvasTests.java80
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfDeploymentTests.java340
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfOnboardingTests.java63
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java270
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java252
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ArtifactUIUtils.java70
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/FileHandling.java30
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java344
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/MethodManipulationUtils.java15
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/OnboardUtility.java477
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ResourceUIUtils.java299
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/RestCDUtils.java167
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ServiceUIUtils.java147
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/ServiceVerificator.java55
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VerificatorUtil.java27
-rw-r--r--ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VfVerificator.java143
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/attsdc-packages.yaml2
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml80
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/log4j.properties34
-rw-r--r--ui-ci-dev/src/main/resources/ci/conf/titan.properties7
-rw-r--r--ui-ci-dev/src/main/resources/ci/scripts/startTest.sh123
-rw-r--r--ui-ci-dev/src/main/resources/ci/testSuites/fullTests.xml26
-rw-r--r--ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml55
-rw-r--r--ui-ci-dev/src/main/resources/images/gizmorambo.jpgbin16605 -> 0 bytes
-rw-r--r--ui-ci-dev/src/test/Completetheform.js3
-rw-r--r--ui-ci/pom.xml110
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/AddComponentInstancesArtifactsInCsar.java25
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java132
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/LocalGeneralUtilities.java17
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java3
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java10
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java3
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/VfModule.java49
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/businesslogic/ArtifactBusinessLogic.java7
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java17
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasElement.java6
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/CanvasManager.java125
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java91
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirrioringConfigurationObject.java74
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirroringEnum.java48
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/UserManagementTab.java3
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java4
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/CreatePath.java997
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/PathValidations.java23
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/AdminUserManagment.java14
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java25
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java6
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java9
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java62
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlows.java)142
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsUI.java (renamed from ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java)97
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PNF.java48
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PortMirroring.java648
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignment.java43
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java85
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ToscaValidationTest.java434
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java76
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java21
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfAPI.java738
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java52
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java42
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java16
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentManager.java39
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/ExtentTestManager.java7
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java33
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java37
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/DeploymentArtifactPage.java9
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java83
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/ArtifactUIUtils.java3
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java14
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java113
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/HomeUtils.java28
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java833
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java132
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/RestCDUtils.java25
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/DeploymentViewVerificator.java21
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PortMirroringVerificator.java85
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PropertiesAssignmentVerificator.java18
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java17
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ToscaValidation.java295
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfModuleVerificator.java16
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/VfVerificator.java37
-rw-r--r--ui-ci/src/main/resources/META-INF/aop-ajc.xml15
-rw-r--r--ui-ci/src/main/resources/ci/conf/attsdc.yaml2
-rw-r--r--ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh4
-rw-r--r--ui-ci/src/main/resources/ci/scripts/sendMail.sh5
-rw-r--r--ui-ci/src/main/resources/ci/scripts/startTest.sh34
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/PortMirroring.xml9
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/andreyPara.xml29
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/devOnboardE2EOneFileSanity.xml2
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml13
-rw-r--r--ui-ci/src/main/resources/log4j2.xml38
-rw-r--r--ui-ci/src/main/resources/reportportal.properties5
-rw-r--r--utils/DmaapPublisher/pom.xml131
-rw-r--r--utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/CliArgs.java59
-rw-r--r--utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublishTool.java97
-rw-r--r--utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublisher.java149
-rw-r--r--utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/RequestManager.java19
-rw-r--r--utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/TopicConfig.java52
-rw-r--r--utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/Util.java19
-rw-r--r--utils/DmaapPublisher/src/main/resources/catalogMgmt.properties35
-rw-r--r--utils/DmaapPublisher/src/main/resources/catalogMgmt.yaml7
-rw-r--r--utils/DmaapPublisher/src/main/resources/catalogWfMgmt.properties32
-rw-r--r--utils/DmaapPublisher/src/main/resources/catalogWfMgmt.yaml6
-rw-r--r--utils/DmaapPublisher/src/main/resources/preferredRouter.txt0
-rw-r--r--utils/DmaapPublisher/src/test/java/org/openecomp/sdc/dmaap/DmaapPublisherTest.java22
-rw-r--r--utils/DmaapPublisher/src/test/resources/catalogMgmtTest.properties34
-rw-r--r--utils/DmaapPublisher/src/test/resources/catalogMgmtTest.yaml7
-rw-r--r--utils/DmaapPublisher/src/test/resources/preferredRouter.txt0
-rw-r--r--utils/webseal-simulator/pom.xml23
-rw-r--r--utils/webseal-simulator/scripts/simulator_docker_run.sh6
-rw-r--r--utils/webseal-simulator/sdc-simulator/startup.sh5
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java15
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java7
-rw-r--r--utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java50
-rw-r--r--utils/webseal-simulator/src/main/resources/webseal.conf29
2300 files changed, 127811 insertions, 202609 deletions
diff --git a/.gitignore b/.gitignore
index e765d09bdd..400ccd0275 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,15 +13,24 @@
/out/
*.iml
+# Logs
+#------------------------------------------------------------
+*.log
+*/logs/*
+*/*/logs/*
+/utils/DmaapPublisher/logs/*
+
+
+#Excluded Script Folder
+xFolder
+
# IntelliJ IDE
#------------------------------------------------------------
**/.idea/
/out/
*.iml
-!catalog-fe/src/main/webapp/META-INF/
-!catalog-fe/src/main/webapp/WEB-INF/
-# Eclipse
+
# Maven
#------------------------------------------------------------
**/target/
@@ -29,7 +38,7 @@ pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
version.properties
-dependency-reduced-pom.xml
+*dependency-reduced-pom.xml
## sdc-os-chef
*.class
@@ -40,27 +49,36 @@ dependency-reduced-pom.xml
*.ear
*.iml
*.jar
+*.war
#Gradle
-build.gradle
.gradle/*
-/log
#Gradle
-build.gradle
.gradle/*
+*/*.gradle
+*/settings.gradle
+*/gradlew.bat
+*/gradlew
+gradlew.bat
+gradlew
+settings.gradle
/log
+/log
*.kpf
*.orig
-*.war
-.classpath
-.delivery
-.idea/*
# catalog-ui
#------------------------------------------------------------
-
+#------------------------------------------------------------
+catalog-ui/app/dist/*
+catalog-ui/package-lock.json
+catalog-ui/dist
+catalog-ui/*.tmp.txt
+catalog-ui/tests/Coverage/*
+catalog-ui/Chrome*
+catalog-ui/PhantomJS_1.9.8_(Windows_7_0.0.0)/*
catalog-ui/app/dist/*
.metadata/
@@ -76,8 +94,6 @@ asdctool/tosca/*
bin/
catalog-be/.pydevproject
catalog-be/.checkstyle
-catalog-be/.pydevproject
-catalog-be/bin/
catalog-be/data/*
catalog-be/src/main/java/META-INF/MANIFEST.MF
catalog-be/test-output/*
@@ -101,16 +117,13 @@ catalog-ui/app/scripts/**/*.js.map
catalog-ui/app/scripts/references.ts
catalog-ui/app/scripts/tsconfig.json
catalog-ui/app/tsconfig.json
-catalog-ui/bower_components/
catalog-ui/package-lock.json
catalog-ui/dist
catalog-ui/*.tmp.txt
catalog-ui/tests/Coverage/*
catalog-ui/Chrome*
catalog-ui/PhantomJS_1.9.8_(Windows_7_0.0.0)/*
-catalog-ui/*.tmp.txt
catalog-ui/tests/Coverage/*
-catalog-ui/Chrome*
catalog-ui/PhantomJS_1.9.8_(Windows_7_0.0.0)/*
catalog-ui/node/*
catalog-ui/node_modules/
@@ -153,6 +166,10 @@ distribution-ci/logs/wordnik.log.8
distribution-ci/logs/wordnik.log.9
dox-sequence-diagram-ui/node/*
+
+
+
+
log.home_IS_UNDEFINED/ASDC/ASDC-BE/Error.log
log.home_IS_UNDEFINED/ASDC/ASDC-BE/audit.log
log.home_IS_UNDEFINED/ASDC/ASDC-BE/debug.log
@@ -224,3 +241,24 @@ sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/files/default/testSuites/*
/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/vsp_*
+sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/files/default/testSuites/*
+
+
+utils/DmaapPublisher/logs/*
+
+
+sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/files/default/testSuites/*
+
+
+utils/DmaapPublisher/logs/*
+
+*.xls
+
+
+sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/files/default/testSuites/*
+
+
+
+/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz
+
+/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz
diff --git a/asdc-tests/.gitignore b/asdc-tests/.gitignore
deleted file mode 100644
index 9b563712b6..0000000000
--- a/asdc-tests/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-/target
-/build/
-/bin/
-/target/
diff --git a/asdc-tests/pom.xml b/asdc-tests/pom.xml
deleted file mode 100644
index a1af441320..0000000000
--- a/asdc-tests/pom.xml
+++ /dev/null
@@ -1,336 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>asdc-tests</artifactId>
-
- <parent>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-main</artifactId>
- <version>1.2.0-SNAPSHOT</version>
- </parent>
-
- <properties>
- <sonar.skip>true</sonar.skip>
- </properties>
-
- <dependencies>
-
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>${testng.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.relevantcodes</groupId>
- <artifactId>extentreports</artifactId>
- <version>2.41.0</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.typesafe</groupId>
- <artifactId>config</artifactId>
- <version>1.0.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.jcraft.jsch</groupId>
- <artifactId>com.springsource.com.jcraft.jsch</artifactId>
- <version>0.1.41</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>common-app-api</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>common-be</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- CHECK CATLOG MODEL -->
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>catalog-model</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- catalog dao -->
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>catalog-dao</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
- <!-- functional java -->
- <dependency>
- <groupId>org.functionaljava</groupId>
- <artifactId>functionaljava</artifactId>
- <version>${functionaljava.version}</version>
- <scope>compile</scope>
- </dependency>
- <!-- CASSANDRA -->
- <dependency>
- <groupId>com.datastax.cassandra</groupId>
- <artifactId>cassandra-driver-core</artifactId>
- <version>${cassandra.driver.version}</version>
- <scope>compile</scope>
- </dependency>
- <!-- CASSANDRA END -->
-
- <!-- slf4j + logback -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>${logback.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.googlecode.json-simple</groupId>
- <artifactId>json-simple</artifactId>
- <version>${json-simple.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- File changes listener -->
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jci-core</artifactId>
- <version>${commons-jci-core.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>${commons-codec}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Gson -->
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>${gson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Snake Yaml -->
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>${snakeyaml.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- http client -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpmime</artifactId>
- <version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.5</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>${commons-logging}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- http core -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- TITAN -->
- <dependency>
- <groupId>com.thinkaurelius.titan</groupId>
- <artifactId>titan-core</artifactId>
- <version>${titan.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc.sdc-titan-cassandra</groupId>
- <artifactId>sdc-titan-cassandra</artifactId>
- <version>${titan.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- <!--<version>2.3.1</version>-->
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- <!--<version>2.3.1</version>-->
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
- <artifactId>sdc-distribution-client</artifactId>
- <version>1.1.32</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.ecompsdkos</groupId>
- <artifactId>epsdk-fw</artifactId>
- <version>${ecomp.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20090211</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <version>2.7</version>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
-
- <!-- ============================================= -->
- <!-- Create the JAR file with its dependencies -->
- <!-- ============================================= -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>create.jar.with.dependencies</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <archive>
- <manifest>
- <mainClass>org.openecomp.sdc.ci.tests.run.StartTest</mainClass>
- </manifest>
- </archive>
- <descriptorRefs>
- <descriptorRef>jar-with-dependencies</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
-
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java
deleted file mode 100644
index b0627b8cfc..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/AttSdcTest.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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.execute.artifacts.CrudArt;
-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 static boolean displayException = false;
- static Logger logger = LoggerFactory.getLogger(CrudArt.class.getName());
-
-
- public AttSdcTest(TestName testName, String className) {
- super();
-
- StartTest.enableLogger();
-
- this.testName = testName;
-
- 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(
- "<Html><head><style>th{background-color: gray;color: white;height: 30px;}td {color: black;height: 30px;}.fail {background-color: #FF5555;width: 100px;text-align: center;}.success {background-color: #00FF00;width: 100px;text-align: center;}.name {width: 200px;background-color: #F0F0F0;}.message {width: 300px;background-color: #F0F0F0;}</style>");
-
- doc.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
- doc.append(
- "<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">");
-
- doc.append("</head><body>");
-
- doc.append("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>");
- doc.append("<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>");
-
- doc.append("<table>");
-
- doc.append("<tr>");
- doc.append("<th>").append("Test Name").append("</th>");
- doc.append("<th>").append("Status").append("</th>");
- doc.append("<th>").append("Message").append("</th>");
-
- if (displayException) {
- doc.append("<th>").append("Exception").append("</th>");
- }
- doc.append("</tr>");
- }
-
- @AfterClass
- public static void afterClass() {
- doc.append("<table>");
- // 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);
-
- logger.info("Start running test {}", testName.getMethodName());
- }
-
- @After
- public void afterTest() throws FileNotFoundException {
-
- logger.info("Finish running test {}", testName.getMethodName());
- }
-
- 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("<tr>");
- doc.append("<td class=\"name\">").append(testName).append("</td>");
- doc.append("<td class=\"" + result + "\">").append(result).append("</td>");
- doc.append("<td class=\"message\">").append(message).append("</td>");
-
- if (displayException) {
- // doc.append("<td
- // class=\"message\">").append(convertExceptionToString(exception)).append("</td>");
- doc.append("<td class=\"message\">");
-
- doc.append("<button type=\"button\" class=\"btn btn-info\" data-toggle=\"collapse\" data-target=\"#demo"
- + testName + "\">Simple collapsible</button>");
- doc.append("<div id=\"demo" + testName + "\" class=\"collapse out\">");
-
- doc.append(convertExceptionToString(exception));
-
- doc.append("</div>");
- doc.append("</td>");
- }
-
- doc.append("</tr>");
-
- 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<String> bugs = config.getBugs();
-
- if (bugs != null && bugs.size() > 0) {
- for (String bugNumber : bugs) {
- if (bugNumber.startsWith(bug)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
deleted file mode 100644
index 18824876cb..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
+++ /dev/null
@@ -1,518 +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.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.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.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.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.Logger;
-import org.slf4j.LoggerFactory;
-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 com.relevantcodes.extentreports.ExtentReports;
-import com.relevantcodes.extentreports.ExtentTest;
-import com.relevantcodes.extentreports.LogStatus;
-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());
-
- // public ComponentBaseTest(TestName testName, String className) {
- // super(testName, className);
- // }
-
- protected static ExtentReports extentReport;
- protected static ExtentTest extendTest;
- public static final String REPORT_FOLDER = "./ExtentReport/";
- private static final String REPORT_FILE_NAME = "ASDC_CI_Extent_Report.html";
- protected static TitanGraph titanGraph;
- private static Config myconfig;
- public static Config config;
-
- 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() throws Exception {
-
- File dir = new File(REPORT_FOLDER);
- try {
- FileUtils.deleteDirectory(dir);
- } catch (IOException e) {
- }
- extentReport = new ExtentReports(REPORT_FOLDER + REPORT_FILE_NAME);
- // extentReport = new ExtentReports(REPORT_FOLDER +
- // REPORT_FILE_NAME,true , NetworkMode.ONLINE);
- // extentReport.x();
-
- openTitanLogic();
- }
-
- protected static void openTitanLogic() throws Exception {
- initGraph();
- cleanComponents();
- // DbUtils.deleteFromEsDbByPattern("_all");
- CassandraUtils.truncateAllKeyspaces();
- }
-
- protected static void initGraph() throws FileNotFoundException {
- myconfig = Utils.getConfig();
- config = Utils.getConfig();
- logger.trace(config.toString());
- String titanConfigFilePath = myconfig.getTitanPropertiesFile();
- titanGraph = TitanFactory.open(titanConfigFilePath);
- assertNotNull(titanGraph);
- }
-
- @AfterSuite(alwaysRun = true)
- public static void shutdownTitan() throws Exception {
- shutdownTitanLogic();
- extentReport.flush();
- }
-
- protected static void shutdownTitanLogic() {
- if (titanGraph.isOpen()) {
- titanGraph.close();
- }
- CassandraUtils.close();
- }
-
- @BeforeMethod(alwaysRun = true)
- public void beforeState(java.lang.reflect.Method method) throws Exception {
-
- // deleteCreatedComponents(getCatalogAsMap());
-
- performeClean();
- extendTest = extentReport.startTest(method.getName());
- extendTest.log(LogStatus.INFO, "Test started");
-
- }
-
- @AfterMethod(alwaysRun = true)
- public void afterState(ITestResult result) throws Exception {
- performeClean();
-
- if (result.isSuccess()) {
- extendTest.log(LogStatus.PASS, "Test Result : <span class='label success'>Success</span>");
- } else {
- extendTest.log(LogStatus.ERROR, "ERROR - The following exepction occured");
- extendTest.log(LogStatus.ERROR, result.getThrowable());
- extendTest.log(LogStatus.FAIL, "<span class='label failure'>Failure</span>");
- }
-
- extentReport.endTest(extendTest);
-
- }
-
- protected void performeClean() throws Exception, FileNotFoundException {
- cleanComponents();
- 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<String> vfResourcesToDelete = new ArrayList<String>();
- List<String> nonVfResourcesToDelete = new ArrayList<String>();
- List<String> servicesToDelete = new ArrayList<String>();
- List<String> productsToDelete = new ArrayList<String>();
-
- // Categories to delete
- List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
- List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
- List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
- List<String> productCategoriesToDelete = new ArrayList<>();
- List<String> resourceCategoriesToDelete = new ArrayList<String>();
- List<String> serviceCategoriesToDelete = new ArrayList<String>();
-
- List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
- List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
- List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
-
- Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
- if (vertices != null) {
- Iterator<TitanVertex> 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<TitanVertex> 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<TitanVertex> 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<TitanVertex> 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<Vertex> 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<String, String>(catId, subCatId));
- }
- }
- }
- }
-
- vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
- if (vertices != null) {
- Iterator<TitanVertex> 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<TitanVertex> iter = vertices.iterator();
- while (iter.hasNext()) {
- Vertex category = iter.next();
- String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- productCategoriesToDelete.add(catId);
- Iterator<Vertex> 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<String, String>(catId, subCatId));
- Iterator<Vertex> 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<String, String, String>(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<String, String, String> triple : productGroupingsToDelete) {
- CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
- }
- for (ImmutablePair<String, String> 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<String, String> 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 void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
- final String userId = UserRoleEnum.DESIGNER.getUserId();
- List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
-
- // List<String> collect = resourcesArrayList.stream().filter(s ->
- // s.getName().startsWith("ci")).map(e ->
- // e.getUniqueId()).collect(Collectors.toList());
-
- // List<Map<String, String>> collect =
- // resourcesArrayList.stream().filter(s ->
- // s.getName().startsWith("ci")).map(e ->
- // e.getAllVersions()).collect(Collectors.toList());
- /*
- * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
- */
-
- if (!CollectionUtils.isEmpty(resourcesArrayList)) {
- List<String> collect = buildCollectionUniqueId(resourcesArrayList);
- for (String uId : collect) {
- ResourceRestUtils.deleteResource(uId, userId);
- }
- }
-
- resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
- if (resourcesArrayList.size() > 0) {
- List<String> collect = buildCollectionUniqueId(resourcesArrayList);
- for (String uId : collect) {
- ServiceRestUtils.deleteServiceById(uId, userId);
- }
- }
- resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
- if (resourcesArrayList.size() > 0) {
- List<String> collect = buildCollectionUniqueId(resourcesArrayList);
- for (String uId : collect) {
- ProductRestUtils.deleteProduct(uId, userId);
- }
- }
-
- }
-
- private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
-
- if (componentArrayList.size() > 0) {
- List<String> collect = buildCollectionUniqueId(componentArrayList);
- for (String uId : collect) {
- deleteHandler.accept(uId);
- // ProductRestUtils.deleteProduct(uId, userId);
- }
- }
- }
-
- private List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
-
- // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
- // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
- // e.values()).flatMap( e -> e.stream());
-
- // List<String> 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<String> 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<String> genericCollection = new ArrayList<String>();
- resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
- try {
- switch (componentTypeEnum) {
- case RESOURCE:
- RestResponse resource = ResourceRestUtils.getResource(i);
- Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
- Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
- Collection<String> 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();
- }
- });
- //
-
- // List<String> collect =
- // genericCollection.stream().collect(Collectors.toList());
-
- return genericCollection;
- }
-
- private Map<String, List<Component>> getCatalogAsMap() throws Exception {
- RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
- Map<String, List<Component>> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
deleted file mode 100644
index 90d818af77..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
+++ /dev/null
@@ -1,806 +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.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.Set;
-import java.util.function.Function;
-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.RelationshipInfo;
-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<String, List<CapabilityDefinition>> expectedContainerCapabilities;
- protected Map<String, List<RequirementDefinition>> expectedContainerRequirements;
- protected Map<String, Map<String, List<RequirementDefinition>>> removedRequirements;
- protected Map<String, ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>> 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 resourceDetailsPNF_01;
- 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<String, List<CapabilityDefinition>>();
- expectedContainerRequirements = new LinkedHashMap<String, List<RequirementDefinition>>();
- 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());
- resourceDetailsPNF_01 = ElementFactory.getDefaultResourceByType("ciPNF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.PNF.toString());
- resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("ciCP100", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
- resourceDetailsCP_02 = ElementFactory.getDefaultResourceByType("ciCP200", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
- resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("ciVL100", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
- 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<String> compInstKeysToChange = new HashSet<>();
-
- for (String expKey : expectedContainerCapabilities.keySet()) {
- List<CapabilityDefinition> 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<RequirementDefinition> 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<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> 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<String, List<RequirementDefinition>> map = removedRequirements.get(oldKey);
- if (map != null) {
- removedRequirements.remove(oldKey);
- String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
- Collection<List<RequirementDefinition>> values = map.values();
- if (values != null) {
- for (List<RequirementDefinition> list : values) {
- for (RequirementDefinition reqDef : list) {
- reqDef.setOwnerId(reqDef.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
- }
- }
- }
- removedRequirements.put(newKey, map);
- }
- }
- }
-
- private void verifyCompInstReqCap(Component actualComponent) {
- List<ComponentInstance> 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<String, List<RequirementDefinition>> actualCompInstReq = compInst.getRequirements();
- if (actualCompInstReq == null) {
- actualCompInstReq = new HashMap<>();
- }
- Map<String, List<CapabilityDefinition>> actualCompInstCap = compInst.getCapabilities();
- if (actualCompInstCap == null) {
- actualCompInstCap = new HashMap<>();
- }
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> 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<String, List<RequirementDefinition>> actualContainerRequirements = actualComponent.getRequirements();
- if (actualContainerRequirements == null) {
- actualContainerRequirements = new HashMap<>();
- }
- Map<String, List<CapabilityDefinition>> 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 <T> void compareReqCapMaps(Map<String, List<T>> expectedMap, Map<String, List<T>> 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<String, List<RequirementDefinition>> resourceRequirements = component.getRequirements();
- if (resourceRequirements == null) {
- resourceRequirements = new HashMap<>();
- }
-
- Function<Entry<String, List<RequirementDefinition>>, List<RequirementDefinition>> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList()));
- Map<String, List<RequirementDefinition>> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper));
-
- Map<String, List<CapabilityDefinition>> resourceCapabilities = component.getCapabilities();
- if (resourceCapabilities == null) {
- resourceCapabilities = new HashMap<>();
- }
-
- Function<? super Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
- Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
-
- setupContainerExpectedReqCap(uniqueId, name, originComponentId, resourceRequirements, resourceCapabilities);
- if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
- setupConstInstExpectedReqCap(uniqueId, name, originComponentId, reqCopy, capCopy);
- }
-
- // adding entry for expected componentInstance
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> compInstReqCapPair = new ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>(capCopy, reqCopy);
- expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
- }
-
- private void setupContainerExpectedReqCap(String uniqueId, String name, String componentId, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
- for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
- List<RequirementDefinition> reqListToAdd = resReq.getValue();
- for (RequirementDefinition requirementDefinition : reqListToAdd) {
- requirementDefinition.setOwnerId(uniqueId);
- requirementDefinition.setOwnerName(name);
- requirementDefinition.addToPath(uniqueId);
- requirementDefinition.setSource(componentId);
- requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
- }
- List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
- if (expectedReqList == null) {
- expectedReqList = reqListToAdd;
- } else {
- expectedReqList.addAll(reqListToAdd);
- }
- expectedContainerRequirements.put(resReq.getKey(), expectedReqList);
- }
-
- for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
- List<CapabilityDefinition> capListToAdd = resCap.getValue();
- for (CapabilityDefinition capDefinition : capListToAdd) {
- capDefinition.setOwnerId(uniqueId);
- capDefinition.setOwnerName(name);
- capDefinition.addToPath(uniqueId);
- capDefinition.setSource(componentId);
- capDefinition.setLeftOccurrences(capDefinition.getMaxOccurrences());
- }
- List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
- if (expectedCapList == null) {
- expectedCapList = capListToAdd;
- } else {
- expectedCapList.addAll(capListToAdd);
- }
- expectedContainerCapabilities.put(resCap.getKey(), expectedCapList);
- }
- }
-
- private void setupConstInstExpectedReqCap(String uniqueId, String name, String componentId, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
- for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
- List<RequirementDefinition> reqListToAdd = resReq.getValue();
- for (RequirementDefinition requirementDefinition : reqListToAdd) {
- requirementDefinition.setOwnerId(uniqueId);
- requirementDefinition.setOwnerName(name);
- requirementDefinition.addToPath(uniqueId);
- requirementDefinition.setSource(componentId);
- requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
- }
- }
-
- for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
- List<CapabilityDefinition> capListToAdd = resCap.getValue();
- for (CapabilityDefinition capDefinition : capListToAdd) {
- capDefinition.setOwnerId(uniqueId);
- capDefinition.setOwnerName(name);
- capDefinition.addToPath(uniqueId);
- capDefinition.setSource(componentId);
- }
- }
- }
-
- 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<String> entriesRequirementsToRemove = new ArrayList<>();
- List<String> entriesCapabilitiesToRemove = new ArrayList<>();
- for (Entry<String, List<RequirementDefinition>> reqEntry : expectedContainerRequirements.entrySet()) {
- List<RequirementDefinition> reqList = reqEntry.getValue();
- List<RequirementDefinition> 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<String, List<CapabilityDefinition>> capEntry : expectedContainerCapabilities.entrySet()) {
- List<CapabilityDefinition> capList = capEntry.getValue();
- List<CapabilityDefinition> 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 Component getComponentAndValidateRIsOnly(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
-
- RestResponse getResponse = null;
- Component component = null;
- if (componentDetails instanceof ResourceReqDetails) {
- getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
- } else if (componentDetails instanceof ServiceReqDetails) {
- getResponse = ServiceRestUtils.getService((ServiceReqDetails) componentDetails, sdncAdminDetails);
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
- } else if (componentDetails instanceof ProductReqDetails) {
- getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
- component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
- } else {
- Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
- }
- ResourceRestUtils.checkSuccess(getResponse);
- int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size() : 0;
- int numberOfActualRelations = component.getComponentInstancesRelations() != null ? component.getComponentInstancesRelations().size() : 0;
- assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
- assertEquals("Check number of RI relations meet the expected number", numberOfRelations, numberOfActualRelations);
-
- return component;
- }
-
- protected void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws IOException, Exception {
- updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
- getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations);
- }
-
- 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 createPNF(ResourceReqDetails resourceDetails) throws Exception {
- createVF(resourceDetails, sdncDesignerDetails);
- }
-
- 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
- RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
- String type = relationship.getRelationship().getType();
- String fromId = requirementDef.getFromNode();
- List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
- List<CapabilityDefinition> 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<String, List<RequirementDefinition>> map = removedRequirements.get(ownerId);
- if (map == null) {
- map = new HashMap<>();
- removedRequirements.put(ownerId, map);
- }
- List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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
- RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
- String type = relationship.getRelationship().getType();
- String fromId = requirementDef.getFromNode();
- Map<String, List<RequirementDefinition>> map = removedRequirements.get(fromId);
- if (map != null) {
- List<RequirementDefinition> list = map.get(type);
- if (list != null && !list.isEmpty()) {
- List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
- if (reqList == null) {
- reqList = new ArrayList<>();
- expectedContainerRequirements.put(type, reqList);
- }
- reqList.add(list.remove(0));
- }
- }
-
- List<CapabilityDefinition> 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/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
deleted file mode 100644
index 3e4411b06e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
+++ /dev/null
@@ -1,366 +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.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";
-
- final String GET_RESOURCE_METADATA_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/latestversion/notabstract/metadata";
-
- // Get resource artifact list:
- // http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts
- final String GET_RESOURCE_ARTIFACTS_LIST = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts";
-
- // 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_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";
- 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";
-
- final String CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/sdc/v1/catalog/resources/%s/lifecycleState/%s";
- final String CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/sdc/v1/catalog/services/%s/lifecycleState/%s";
-
- // *****************************************************************************************************
-
- 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/<serviceName>/<0.1>/artifacts/aaa.hh"
- final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s";
- // "/sdc2/v1/services/<serviceName>/<0.1>/resources/{resourceName}/{resourceVersion}/artifacts/<opeartion_name>_aaa.hh"
- final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
- final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL = "/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 VALIDATE_CONFORMANCE_LEVEL = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/conformanceLevelValidation";
-
- 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";
- //{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";
- 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
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
deleted file mode 100644
index 0675dc11ba..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
+++ /dev/null
@@ -1,609 +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.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";
-
- String catalogBeHost;
- String esHost;
- String esPort;
- String neoHost;
- String neoPort;
- String disributionClientHost;
- String disributionClientPort;
- Boolean isDistributionClientRunning;
-
-
- String errorConfigurationFile;
- String resourceConfigDir;
- String componentsConfigDir;
- String importResourceConfigDir;
- String importResourceTestsConfigDir;
- String importTypesConfigDir;
-
- String testSuites;
-
- String catalogFeHost;
- String catalogFePort;
- String catalogBePort;
- String catalogBeTlsPort;
-
- String neoDBusername;
- String neoDBpassword;
-
- String titanPropertiesFile;
- List<String> packages;
- List<String> bugs;
- List<String> resourcesNotToDelete;
- List<String> resourceCategoriesNotToDelete;
- List<String> serviceCategoriesNotToDelete;
- Boolean stopOnClassFailure = false;
-
- private String outputFolder;
- private String reportName;
- private String url;
- private String remoteTestingMachineIP;
- private String remoteTestingMachinePort;
- private String webSealSimulatorUrl;
- 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 static Config configIt = null;
-
- private static Yaml yaml = new Yaml();
-
-
- private Config() {
- super();
- }
-
- public static class TestPackages {
-
- List<String> packages;
- List<String> bugs;
-
- public List<String> getPackages() {
- return packages;
- }
-
- public void setPackages(List<String> packages) {
- this.packages = packages;
- }
-
- public List<String> getBugs() {
- return bugs;
- }
-
- public void setBugs(List<String> 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<String> bugs = testPackages.getBugs();
- List<String> 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 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<String> getPackages() {
- return packages;
- }
-
- public void setPackages(List<String> packages) {
- this.packages = packages;
- }
-
- public List<String> getBugs() {
- return bugs;
- }
-
- public void setBugs(List<String> 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<String> getResourcesNotToDelete() {
- return resourcesNotToDelete;
- }
-
- public void setResourcesNotToDelete(List<String> resourcesNotToDelete) {
- this.resourcesNotToDelete = resourcesNotToDelete;
- }
-
- public List<String> getResourceCategoriesNotToDelete() {
- return resourceCategoriesNotToDelete;
- }
-
- public void setResourceCategoriesNotToDelete(List<String> resourceCategoriesNotToDelete) {
- this.resourceCategoriesNotToDelete = resourceCategoriesNotToDelete;
- }
-
- public List<String> getServiceCategoriesNotToDelete() {
- return serviceCategoriesNotToDelete;
- }
-
- public void setServiceCategoriesNotToDelete(List<String> 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;
- }
-
- @Override
- public String toString() {
- return "Config [catalogBeHost=" + catalogBeHost + ", esHost=" + esHost + ", esPort=" + esPort + ", neoHost="
- + neoHost + ", neoPort=" + neoPort + ", disributionClientHost=" + disributionClientHost
- + ", disributionClientPort=" + disributionClientPort + ", errorConfigurationFile="
- + errorConfigurationFile + ", resourceConfigDir=" + resourceConfigDir + ", componentsConfigDir="
- + componentsConfigDir + ", importResourceConfigDir=" + importResourceConfigDir
- + ", importResourceTestsConfigDir=" + importResourceTestsConfigDir + ", importTypesConfigDir="
- + importTypesConfigDir + ", 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 + ", configurationFile=" + configurationFile + "]";
- }
-
- public String getWebSealSimulatorUrl() {
- return webSealSimulatorUrl;
- }
-
- public void setWebSealSimulatorUrl(String webSealSimulatorUrl) {
- this.webSealSimulatorUrl = webSealSimulatorUrl;
- }
-
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java
deleted file mode 100644
index fbc493ffd6..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java
+++ /dev/null
@@ -1,63 +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.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<String, Integer> methodFailCount = new HashMap<String, Integer>();
-
- @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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java
deleted file mode 100644
index 41936e2c30..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java
+++ /dev/null
@@ -1,135 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java
deleted file mode 100644
index 28606af14d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java
+++ /dev/null
@@ -1,226 +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.datatypes;
-
-import java.util.List;
-
-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<HeatParameterDefinition> 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 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<HeatParameterDefinition> getHeatParameters() {
- return heatParameters;
- }
-
- public void setHeatParameters(List<HeatParameterDefinition> heatParameters) {
- this.heatParameters = heatParameters;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java
deleted file mode 100644
index 8820b05772..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java
+++ /dev/null
@@ -1,122 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java
deleted file mode 100644
index 549700f384..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java
+++ /dev/null
@@ -1,121 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java
deleted file mode 100644
index 8546732414..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java
+++ /dev/null
@@ -1,272 +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.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<String> 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<CategoryDefinition> 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<String> getTags() {
- return tags;
- }
-
- public void setTags(List<String> 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<CategoryDefinition> getCategories() {
- return categories;
- }
-
- public void setCategories(List<CategoryDefinition> 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<SubCategoryDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java
deleted file mode 100644
index 690f63955d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java
+++ /dev/null
@@ -1,60 +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.datatypes;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class GroupHeatMetaDefinition {
-
- int group = 0;
- List<String> artifactList = new ArrayList<String>();
- PropertyHeatMetaDefinition propertyHeatMetaDefinition;
-
- 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<String> getArtifactList() {
- return artifactList;
- }
-
- public void setArtifactList(List<String> artifactList) {
- this.artifactList = artifactList;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java
deleted file mode 100644
index 0089eec5a7..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java
+++ /dev/null
@@ -1,332 +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.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.Iterator;
-import java.util.List;
-import java.util.Map;
-
-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<String, Object> requirements;
- private Map<String, Object> capabilities;
-
- private List<String> derivedList;
- private String derivedFromField;
-
- public ImportReqDetails(String resourceName, String description, List<String> tags, List<String> 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<String> getDerivedList() {
- return derivedList;
- }
-
- public void setDerivedList(List<String> derivedList) {
- this.derivedList = derivedList;
- }
-
- public String getDerivedFromField() {
- return derivedFromField;
- }
-
- public void setDerivedFromField(String derivedFromField) {
- this.derivedFromField = derivedFromField;
- }
-
- public Map<String, Object> getRequirements() {
- return requirements;
- }
-
- public void setRequirements(String path, String fileName, User user, String derivedFromSource) throws Exception {
- Map<String, Object> requirementsFromFile = getRequirementsMapFromFile(path + File.separator + fileName,
- toscaResourceName, "requirements");
- Map<String, Object> requirements = organizeRequirementsMap(requirementsFromFile);
- getDerivedReqCap(user, requirements, "requirements", derivedFromSource);
- this.requirements = requirements;
- }
-
- private void getDerivedReqCap(User user, Map<String, Object> reqCapMap, String field, String derivedFromResource)
- throws IOException, JSONException {
-
- if (derivedFromResource == null) {
- derivedFromResource = "Root";
- }
-
- RestResponse rest = getResourceSource(user, derivedFromResource);
- Map<String, Object> parsedFieldFromResponseAsMap = ResponseParser.getJsonValueAsMap(rest, field);
- Iterator<String> iterator = parsedFieldFromResponseAsMap.keySet().iterator();
- Map<String, Object> convertListToMap = null;
- while (iterator.hasNext()) {
- String type = iterator.next();
- List<Object> lst = (List<Object>) parsedFieldFromResponseAsMap.get(type);
- convertListToMap = convertListToMap(lst);
-
- if (field.equals("capabilities")) {
- convertListToMap.replace("capabilitySources", derivedList);
- lst = new ArrayList<Object>(Arrays.asList(convertListToMap));
- }
-
- Object existingValue = reqCapMap.get(type);
- if (existingValue != null) {
- Map<String, Object> convertedExistingValue = convertListToMap((List<Object>) existingValue);
- if (convertedExistingValue.get("name").toString().toLowerCase()
- .equals(convertListToMap.get("name").toString().toLowerCase())) {
- lst = new ArrayList<Object>(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<String, Object> getCapabilities() {
- return capabilities;
- }
-
- public void setCapabilities(String path, String fileName, User user, String derivedFromSource) throws Exception {
- Map<String, Object> capabilitiesFromFile = getCapabilitiesMapFromFile(path + File.separator + fileName,
- toscaResourceName, "capabilities");
- Map<String, Object> capabilities = organizeCapabilitiesMap(capabilitiesFromFile);
- getDerivedReqCap(user, capabilities, "capabilities", derivedFromSource);
- this.capabilities = capabilities;
- }
-
- private Map<String, Object> organizeCapabilitiesMap(Map<String, Object> capabilitiesFromFile) {
- Iterator<String> iterator = capabilitiesFromFile.keySet().iterator();
- Map<String, Object> capMap = new HashMap<String, Object>();
- while (iterator.hasNext()) {
- List<Object> valueList = new ArrayList<Object>();
- String next = iterator.next();
- Map<String, Object> valuesMap = (Map<String, Object>) 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<String, Object> convertValue = convertListToMap((List<Object>) tempValue);
- valueList = new ArrayList<Object>(Arrays.asList(convertValue, valuesMap));
- }
- capMap.put(key, valueList);
- }
- return capMap;
- }
-
- private Map<String, Object> getCapabilitiesMapFromFile(String fileName, String toscaResourceName,
- String fieldToTest) throws Exception {
- Map<String, Object> resourceToscaMap = getToscaResourceFromFile(fileName, toscaResourceName);
- Object capMap = resourceToscaMap.get(fieldToTest);
- if (capMap == null) {
- return new HashMap<String, Object>();
- }
- return (Map<String, Object>) capMap;
- }
-
- private Map<String, Object> organizeRequirementsMap(Map<String, Object> requirementsFromFile) {
- Map<String, Object> reqMap = new HashMap<String, Object>();
- List<Object> valueList = new ArrayList<Object>();
- Iterator<String> iterator = requirementsFromFile.keySet().iterator();
- while (iterator.hasNext()) {
- String key = iterator.next();
- Map<String, Object> valuesMap = (Map<String, Object>) requirementsFromFile.get(key);
- valuesMap.put("name", key);
- String capability = valuesMap.get("capability").toString();
-
- List<Object> occurencesList = (List<Object>) 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<String, Object> getRequirementsMapFromFile(String fileName, String toscaResourceName,
- String fieldToTest) throws Exception {
- Map<String, Object> resourceToscaMap = getToscaResourceFromFile(fileName, toscaResourceName);
- List<Object> reqListFromFile = (List<Object>) resourceToscaMap.get(fieldToTest);
- if (reqListFromFile == null) {
- return new HashMap<String, Object>();
- }
- Map<String, Object> testedMapFromFile = convertListToMap(reqListFromFile);
- return testedMapFromFile;
- }
-
- private Map<String, Object> getToscaResourceFromFile(String fullFileName, String toscaResourceName)
- throws Exception {
- Map<String, Object> nodesTypesMap = getNodesTypesMapFromFile(fullFileName);
- Map<String, Object> resourceToscaMap = (Map<String, Object>) nodesTypesMap.get(toscaResourceName);
-
- derivedFromField = resourceToscaMap.get("derived_from").toString();
-
- return resourceToscaMap;
- }
-
- private Map<String, Object> 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<String, Object> nodesTypesMap = (Map<String, Object>) mapFromFile.get("node_types");
- return nodesTypesMap;
- }
-
- private Map<String, Object> convertListToMap(List<Object> testedListFromFile) {
- Map<String, Object> testedMapFromFile = new HashMap<String, Object>();
- for (int i = 0; i < testedListFromFile.size(); i++) {
- Object req = testedListFromFile.get(i);
- ObjectMapper m = new ObjectMapper();
- Map<? extends String, ? extends String> mappedObject = m.convertValue(req, Map.class);
- testedMapFromFile.putAll(mappedObject);
- }
- return testedMapFromFile;
- }
-
- public void compareRequirementsOrCapabilities(Map<String, Object> exepectedReq, Map<String, Object> actualReq) {
- Iterator<String> iterator = exepectedReq.keySet().iterator();
- while (iterator.hasNext()) {
- String key = iterator.next();
- List<Object> expectedValues = (List<Object>) exepectedReq.get(key);
- List<Object> actualValues = (List<Object>) actualReq.get(key);
- assertNotNull(actualValues);
-
- List<Map<String, Object>> expectedMapsList = convertListToMapList(expectedValues);
- List<Map<String, Object>> actualMapsList = convertListToMapList(actualValues);
- assertEquals(expectedMapsList.size(), actualMapsList.size());
-
- for (int i = 0; i < expectedMapsList.size(); i++) {
- Map<String, Object> expectedMap = expectedMapsList.get(i);
- Map<String, Object> actualdMap = actualMapsList.get(i);
- if (expectedMap.get("name").equals(actualdMap.get("name"))) {
- Iterator<String> 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<Map<String, Object>> convertListToMapList(List<Object> testedListFromFile) {
- List<Map<String, Object>> listOfMaps = new ArrayList<Map<String, Object>>();
- for (int i = 0; i < testedListFromFile.size(); i++) {
- Object req = testedListFromFile.get(i);
- ObjectMapper m = new ObjectMapper();
- Map<? extends String, ? extends String> mappedObject = m.convertValue(req, Map.class);
- mappedObject.remove("uniqueId");
- Map<String, Object> testedMapFromFile = new HashMap<String, Object>();
- testedMapFromFile.putAll(mappedObject);
- listOfMaps.add(testedMapFromFile);
- }
- return listOfMaps;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java
deleted file mode 100644
index f2484e274d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java
+++ /dev/null
@@ -1,88 +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.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<String> contacts;
- private String isActive;
-
- public ProductReqDetails(String name, List<CategoryDefinition> 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<String> getContacts() {
- return contacts;
- }
-
- public void setContacts(List<String> contacts) {
- this.contacts = contacts;
- }
-
- public List<CategoryDefinition> getCategories() {
- return categories;
- }
-
- public void setCategories(List<CategoryDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java
deleted file mode 100644
index 208e4aa3ea..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java
+++ /dev/null
@@ -1,145 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java
deleted file mode 100644
index 62f5e0c8f0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java
+++ /dev/null
@@ -1,76 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java
deleted file mode 100644
index b521b4bf08..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.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.ci.tests.datatypes;
-
-import java.util.List;
-
-public class ResourceDetailedAssetStructure extends ResourceAssetStructure {
-
- private List<ResourceInstanceAssetStructure> resources;
- private List<ArtifactAssetStructure> artifacts;
-
- public ResourceDetailedAssetStructure() {
- super();
- }
-
- public ResourceDetailedAssetStructure(String lastUpdaterFullName, String toscaResourceName,
- List<ResourceInstanceAssetStructure> resources, List<ArtifactAssetStructure> artifacts) {
- super();
- this.lastUpdaterFullName = lastUpdaterFullName;
- this.toscaResourceName = toscaResourceName;
- this.resources = resources;
- this.artifacts = artifacts;
- }
-
- public List<ResourceInstanceAssetStructure> getResources() {
- return resources;
- }
-
- public void setResources(List<ResourceInstanceAssetStructure> resources) {
- this.resources = resources;
- }
-
- public List<ArtifactAssetStructure> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<ArtifactAssetStructure> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java
deleted file mode 100644
index 4d5806b90f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceExternalReqDetails.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.datatypes;
-
-import java.util.List;
-
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-
-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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java
deleted file mode 100644
index 6a69120a05..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java
+++ /dev/null
@@ -1,116 +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.datatypes;
-
-import java.util.List;
-
-public class ResourceInstanceAssetStructure {
-
- String resourceInstanceName;
- String resourceName;
- String resourceInvariantUUID;
- String resourceVersion;
- String resoucreType;
- String resourceUUID;
- List<ArtifactAssetStructure> artifacts;
-
- public ResourceInstanceAssetStructure() {
- super();
- }
-
- public ResourceInstanceAssetStructure(String resourceInstanceName, String resourceName,
- String resourceInvariantUUID, String resourceVersion, String resoucreType, String resourceUUID,
- List<ArtifactAssetStructure> 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<ArtifactAssetStructure> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<ArtifactAssetStructure> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
deleted file mode 100644
index d8bd80115e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
+++ /dev/null
@@ -1,222 +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.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<String> derivedFrom;
- String vendorName;
- String vendorRelease;
- String resourceVendorModelNumber;
-
- // 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.resourceVendorModelNumber = resource.getResourceVendorModelNumber();
- 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<String> tags, String category,
- List<String> 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<String> tags, String category,
- List<String> 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<String> 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<String> getDerivedFrom() {
- return derivedFrom;
- }
-
- public void setDerivedFrom(List<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java
deleted file mode 100644
index eb473ab39f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java
+++ /dev/null
@@ -1,337 +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.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<String> tags;
- String isHighestVersion;
- String creationDate;
- String lastUpdateDate;
- // String category;
- String lifecycleState;
- List<String> derivedFrom;
- String vendorName;
- String vendorRelease;
- String contactId;
- String abstractt;
- String highestVersion;
- List<String> artifacts;
- List<String> interfaces;
- String uuid;
- String cost;
- String licenseType;
- String resourceType;
- List<CategoryDefinition> 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<String> tags, String isHighestVersion, String creationDate, String lastUpdateDate,
- String category, String lifecycleState, List<String> derivedFrom, String vendorName, String vendorRelease,
- String contactId, String abstractt, String highestVersion, List<String> artifacts, List<String> 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<String> getInterfaces() {
- return interfaces;
- }
-
- public void setInterfaces(List<String> interfaces) {
- this.interfaces = interfaces;
- }
-
- public List<String> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<String> artifacts) {
- this.artifacts = artifacts;
- }
-
- public ResourceRespJavaObject() {
- super();
- }
-
- 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<String> getTags() {
- return tags;
- }
-
- public void setTags(List<String> 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<String> getDerivedFrom() {
- return derivedFrom;
- }
-
- public void setDerivedFrom(List<String> 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<CategoryDefinition> getCategories() {
- return categories;
- }
-
- public void setCategories(List<CategoryDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java
deleted file mode 100644
index cc283a3169..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.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.ci.tests.datatypes;
-
-import java.util.List;
-
-public class ServiceDetailedAssetStructure extends ServiceAssetStructure {
-
- String lastUpdaterFullName;
- List<ResourceInstanceAssetStructure> resources;
- List<ArtifactAssetStructure> 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<ResourceInstanceAssetStructure> resources,
- List<ArtifactAssetStructure> 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<ResourceInstanceAssetStructure> getResources() {
- return resources;
- }
-
- public void setResources(List<ResourceInstanceAssetStructure> resources) {
- this.resources = resources;
- }
-
- public List<ArtifactAssetStructure> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<ArtifactAssetStructure> artifacts) {
- this.artifacts = artifacts;
- }
-
- @Override
- public String toString() {
- return "ServiceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", resources=" + resources
- + ", artifacts=" + artifacts + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java
deleted file mode 100644
index dde1f27cca..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDistributionStatus.java
+++ /dev/null
@@ -1,80 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
deleted file mode 100644
index 4be171eff0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
+++ /dev/null
@@ -1,106 +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.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 {
-
- String serviceType;
- String serviceRole;
- String environmentContext;
-
- public ServiceReqDetails(String serviceName, String category, ArrayList<String> 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;
- this.serviceType = "";
- this.serviceRole = "";
- projectCode = "12345";
- CategoryDefinition categoryDefinition = new CategoryDefinition();
- categoryDefinition.setName(category);
- categories = new ArrayList<>();
- categories.add(categoryDefinition);
- this.environmentContext = "";
- }
-
- 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();
- this.serviceType = service.getServiceType();
- this.serviceRole = service.getServiceRole();
- this.environmentContext = service.getEnvironmentContext();
- }
-
- 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<String>) 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;
- }
-
- public String getEnvironmentContext() {
- return environmentContext;
- }
-
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java
deleted file mode 100644
index 4aeb0ce589..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java
+++ /dev/null
@@ -1,267 +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.datatypes;
-
-import java.util.ArrayList;
-
-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<String> tags;
- String uniqueId;
- String lastUpdateDate;
- String contactId;
- String vendorName;
- String vendorRelease;
- String lifecycleState;
- String highestVersion;
- ArrayList<String> artifacts;
- ArrayList<String> ResourceInstances;
- ArrayList<String> 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<String> tags, String uniqueId,
- String lastUpdateDate, String contactId, String vendorName, String vendorRelease, String lifecycleState,
- String highestVersion, ArrayList<String> artifacts, ArrayList<String> resourceInstances,
- ArrayList<String> 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<String> getTags() {
- return tags;
- }
-
- public void setTags(ArrayList<String> 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<String> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(ArrayList<String> artifacts) {
- this.artifacts = artifacts;
- }
-
- public ArrayList<String> getResourceInstances() {
- return ResourceInstances;
- }
-
- public void setResourceInstances(ArrayList<String> resourceInstances) {
- ResourceInstances = resourceInstances;
- }
-
- public ArrayList<String> getResourceInstancesRelations() {
- return ResourceInstancesRelations;
- }
-
- public void setResourceInstancesRelations(ArrayList<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java
deleted file mode 100644
index d0f029242f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java
+++ /dev/null
@@ -1,57 +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.datatypes;
-
-import java.util.List;
-
-public class TypeHeatMetaDefinition {
-
- String typeName;
-
- List<GroupHeatMetaDefinition> groupHeatMetaDefinition;
-
- public TypeHeatMetaDefinition() {
- super();
- }
-
- public String getTypeName() {
- return typeName;
- }
-
- public void setTypeName(String typeName) {
- this.typeName = typeName;
- }
-
- public List<GroupHeatMetaDefinition> getGroupHeatMetaDefinition() {
- return groupHeatMetaDefinition;
- }
-
- public void setGroupHeatMetaDefinition(List<GroupHeatMetaDefinition> groupHeatMetaDefinition) {
- this.groupHeatMetaDefinition = groupHeatMetaDefinition;
- }
-
- @Override
- public String toString() {
- return "TypeHeatMetaDefinition [typeName=" + typeName + ", groupHeatMetaDefinition=" + groupHeatMetaDefinition
- + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java
deleted file mode 100644
index 724fca2b4d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.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.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"), LIFECYCLE_OPERATIONS("LIFECYCLE_OPERATIONS"),
- VES_EVENTS("VES_EVENTS"), PERFORMANCE_COUNTER("PERFORMANCE_COUNTER"), UCPE_LAYER_2_CONFIGURATION("UCPE_LAYER_2_CONFIGURATION"),
- // 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<String> getAllTypes() {
- List<String> types = new ArrayList<String>();
- for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) {
- types.add(ate.getType());
- }
- return types;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java
deleted file mode 100644
index c1b9fd4747..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java
+++ /dev/null
@@ -1,40 +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.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");
-
- private String auditJsonKeyName;
-
- private AuditJsonKeysEnum(String auditJsonKeyName) {
- this.auditJsonKeyName = auditJsonKeyName;
- }
-
- public String getAuditJsonKeyName() {
- return auditJsonKeyName.toLowerCase();
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java
deleted file mode 100644
index 7042a954e7..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/DistributionNotificationStatusEnum.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java
deleted file mode 100644
index c2a28a1edf..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java
deleted file mode 100644
index 6bfbd8af7d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java
+++ /dev/null
@@ -1,64 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java
deleted file mode 100644
index 59d1dec453..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java
deleted file mode 100644
index 21901e4635..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java
+++ /dev/null
@@ -1,95 +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.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<String> errorParams;
- private Boolean validateYaml;
-
- // private enum ActionStatus;
-
- private ImportTestTypesEnum(String resourceName, String folderName, ActionStatus actionStatus,
- List<String> 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<String> getErrorParams() {
- return errorParams;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java
deleted file mode 100644
index 7c330a3d10..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.datatypes.enums;
-
-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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java
deleted file mode 100644
index 58892439b0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java
deleted file mode 100644
index b73d5a8fee..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java
+++ /dev/null
@@ -1,66 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java
deleted file mode 100644
index 389b962f1c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java
deleted file mode 100644
index d85a496241..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/OriginTypeEnum.java
+++ /dev/null
@@ -1,74 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java
deleted file mode 100644
index 7e98d52109..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java
+++ /dev/null
@@ -1,106 +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.datatypes.enums;
-
-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("defaultFloatPropName1", "float", "12.34", "default f;oat 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java
deleted file mode 100644
index 47123a61e7..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java
+++ /dev/null
@@ -1,57 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java
deleted file mode 100644
index 2f2af97fd8..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java
+++ /dev/null
@@ -1,40 +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.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_USER_ID("creatorUserId"), CREATOR_FULL_NAME("creatorFullName"),
- LAST_UPDATER_USER_ID("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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java
deleted file mode 100644
index f26423a35d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/SearchCriteriaEnum.java
+++ /dev/null
@@ -1,38 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java
deleted file mode 100644
index 4cfcc8a558..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java
+++ /dev/null
@@ -1,35 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java
deleted file mode 100644
index 61d4e487e2..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java
+++ /dev/null
@@ -1,37 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java
deleted file mode 100644
index b8635b3bda..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java
deleted file mode 100644
index fb04f6a68b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java
+++ /dev/null
@@ -1,77 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java
deleted file mode 100644
index 344f353348..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java
+++ /dev/null
@@ -1,166 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java
deleted file mode 100644
index 0d6a5f3b3c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java
+++ /dev/null
@@ -1,90 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java
deleted file mode 100644
index b11f7f585a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java
deleted file mode 100644
index 4b135f66f6..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java
deleted file mode 100644
index 1414742423..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java
+++ /dev/null
@@ -1,88 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java
deleted file mode 100644
index e689a3921b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java
+++ /dev/null
@@ -1,179 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java
deleted file mode 100644
index 561b92a317..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java
+++ /dev/null
@@ -1,88 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java
deleted file mode 100644
index b481cb77af..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java
+++ /dev/null
@@ -1,121 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java
deleted file mode 100644
index 40b86fa528..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java
+++ /dev/null
@@ -1,142 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java
deleted file mode 100644
index cc78709888..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java
+++ /dev/null
@@ -1,300 +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.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;
-
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java
deleted file mode 100644
index 2bc8625057..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java
+++ /dev/null
@@ -1,98 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java
deleted file mode 100644
index 2c23b08717..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java
+++ /dev/null
@@ -1,114 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java
deleted file mode 100644
index 4a2ad9ab82..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java
+++ /dev/null
@@ -1,38 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java
deleted file mode 100644
index cd3beee150..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java
deleted file mode 100644
index 5801536973..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java
+++ /dev/null
@@ -1,888 +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.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.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<String, String> headers) throws IOException {
-
- RestResponse restResponse = new RestResponse();
- 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<String, String> 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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
- con.disconnect();
-
- return restResponse;
- }
-
- public RestResponse httpsSendGet(String url, Map<String, String> 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<String, String> 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", e);
- }
-
- 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<String, List<String>> 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<String, String> 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<String, String> 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", e);
- }
-
- 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<String, List<String>> 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<String, String> 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<String, String> 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<String, List<String>> 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<String, String> headers) throws IOException {
- return httpSendPost(url, body, headers, "POST");
- }
-
- public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
- return httpSendPost(url, body, headers, "PUT");
- }
-
- public RestResponse httpSendPost(String url, String body, Map<String, String> 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<String, String> 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<String, List<String>> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
- con.disconnect();
- return restResponse;
-
- }
-
- public RestResponse httpSendPostWithOutBody(String url, Map<String, String> 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<String, String> 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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
- con.disconnect();
- return restResponse;
-
- }
-
- public RestResponse httpSendPostMultipart(String url, Map<String, String> 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<String, String> 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<String, String> 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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
- con.disconnect();
- return restResponse;
-
- }
-
- public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
-
- RestResponse restResponse = new RestResponse();
- URL obj = new URL(url);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
-
- if (headers != null) {
- for (Entry<String, String> 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<String, List<String>> 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<String, String> headers)
- throws IOException, ClientProtocolException {
- CloseableHttpResponse response = null;
- CloseableHttpClient client = HttpClients.createDefault();
- try {
- HttpPost httpPost = new HttpPost(url);
- RestResponse restResponse = new RestResponse();
- for (Entry<String, String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java
deleted file mode 100644
index 6937608d2a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java
+++ /dev/null
@@ -1,53 +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.datatypes.http;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class MustHeaders {
-
- private Map<String, String> headers = new HashMap<String, String>();
-
- 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<String, String> getMap() {
- return headers;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java
deleted file mode 100644
index f11d35a646..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java
+++ /dev/null
@@ -1,84 +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.datatypes.http;
-
-import java.util.List;
-import java.util.Map;
-
-public class RestResponse {
-
- Integer errorCode;
- String response;
- Map<String, List<String>> headerFields;
- String responseMessage;
-
- public RestResponse() {
- super();
- }
-
- public RestResponse(Integer errorCode, String response, Map<String, List<String>> 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<String, List<String>> getHeaderFields() {
- return headerFields;
- }
-
- public void setHeaderFields(Map<String, List<String>> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java
deleted file mode 100644
index 3af40c5bb8..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java
+++ /dev/null
@@ -1,135 +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.TODO;
-
-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.DbUtils.TitanState;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.testng.AssertJUnit;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.Test;
-
-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<Vertex, Boolean> 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<Vertex, Boolean> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java
deleted file mode 100644
index 49b556fc28..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java
+++ /dev/null
@@ -1,656 +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.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.general.AtomicOperationUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.openecomp.sdc.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<Resource, RestResponse> resourceDetailsVFCcompE = AtomicOperationUtils
- .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE,
- ResourceCategoryEnum.APPLICATION_L4_APP_SERVER, UserRoleEnum.DESIGNER, true);
- resourceDetailsVFCcomp = resourceDetailsVFCcompE.left().value();
- Either<Service, RestResponse> 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<String, Object> jsonBody = new HashMap<String, Object>();
- 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<String, Object> jsonBody = new HashMap<String, Object>();
- 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.calculateMD5Base64EncodedByString(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<String, Object> json = new HashMap<String, Object>();
- 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<String, Object> json = new HashMap<String, Object>();
- 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<String, Object> json = new HashMap<String, Object>();
- 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<String, Object> json = new HashMap<String, Object>();
- 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<String, ArtifactDefinition> artifacts = resource.getArtifacts();
- boolean isExist = false;
- for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) {
- isExist = true;
-
- }
- }
- AssertJUnit.assertTrue(isExist);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java
deleted file mode 100644
index 28c346efc9..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java
+++ /dev/null
@@ -1,1789 +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.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<String> 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<String, ArtifactDefinition> artifactsMap = resourceJavaObject.getDeploymentArtifacts();
- boolean flag = false;
- if (artifactsMap != null) {
- for (Entry<String, ArtifactDefinition> 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<Component, RestResponse> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
-
- // Add HEAT
- logger.debug("listFileName: {}", listFileName);
- 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<String, ArtifactDefinition> 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<String> 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<String> 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 {
- ArtifactReqDetails otherArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
-
- 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String, ArtifactDefinition> artifactsMap = resourceJavaObject.getDeploymentArtifacts();
- boolean flag = false;
- if (artifactsMap != null) {
- for (Entry<String, ArtifactDefinition> 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<String> 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType());
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name(), variables, addInformationalArtifactToService.getResponse());
-
- }
-
- @Test(enabled = false)
- public void addHeatArtifactInvalidYamlFormatToService() throws Exception, Exception {
-
- String fileName = yamlInvalidFormat;
- List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<String> 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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<String> 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<Component, RestResponse> 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<String> 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<String> 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<String> 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<String> 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<String> 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<Component, RestResponse> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filesPath);
- logger.debug("listFileName: {}", listFileName);
-
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
deleted file mode 100644
index 65c0bba6a0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
+++ /dev/null
@@ -1,661 +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.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.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 com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-
-import fj.data.Either;
-
-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<Resource, RestResponse> 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<Resource, RestResponse> 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<Service, RestResponse> 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<Resource, RestResponse> 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<Service, RestResponse> 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<String, ArtifactDefinition> artifacts = resource.getArtifacts();
- boolean isExist = false;
- for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) {
- isExist = true;
-
- }
- }
- AssertJUnit.assertTrue(isExist);
- }
-
-
- protected String createUploadArtifactBodyJson() {
- Map<String, Object> jsonBody = new HashMap<String, Object>();
- 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.calculateMD5Base64EncodedByString(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<String, Object> json = new HashMap<String, Object>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java
deleted file mode 100644
index 2ca09b36f3..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/HeatEnvArtifact.java
+++ /dev/null
@@ -1,331 +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.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.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.be.model.heat.HeatParameterType;
-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.DataProvider;
-import org.testng.annotations.Test;
-import org.yaml.snakeyaml.Yaml;
-
-import com.google.gson.Gson;
-
-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<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(1, componentInstances.size());
-
- ComponentInstance vfi = componentInstances.get(0);
- Map<String, ArtifactDefinition> deploymentArtifacts = vfi.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
- assertEquals(4, deploymentArtifacts.size());
- ArtifactDefinition heatEnv = deploymentArtifacts.get("heat0env");
- assertNotNull(heatEnv);
-
- Map<String, Object> yaml = downloadComponentInstanceYamlFile(service.getUniqueId(), vfi.getUniqueId(), sdncModifierDetails, heatEnv.getUniqueId());
- assertNotNull(yaml);
- Map<String, Object> paramters = (Map<String, Object>) yaml.get("parameters");
- assertNotNull(paramters);
- assertEquals(8, paramters.size());
- assertEquals(null, paramters.get("param8"));
- List<HeatParameterDefinition> heatParameters = heatEnv.getListHeatParameters();
- 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<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(1, componentInstances.size());
-
- ComponentInstance vfi = componentInstances.get(0);
- Map<String, ArtifactDefinition> deploymentArtifacts = vfi.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
- assertEquals(4, deploymentArtifacts.size());
- ArtifactDefinition heatEnv = deploymentArtifacts.get("heat0env");
- assertNotNull(heatEnv);
-
- Map<String, Object> yaml = downloadComponentInstanceYamlFile(service.getUniqueId(), vfi.getUniqueId(), sdncModifierDetails, heatEnv.getUniqueId());
- assertNotNull(yaml);
- Map<String, Object> paramters = (Map<String, Object>) 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<HeatParameterDefinition> heatParameters = heatEnv.getListHeatParameters();
- heatParameters.forEach(p -> {
- assertEquals(p.getCurrentValue(), paramters.get(p.getName()));
- });
-
- }
-
- @DataProvider(name = "vfModuleCsar")
- public static Object[][] csarNames() {
- return new Object[][] { { "VSPPackage" }, { "csar_1" }, { "csarHeatEnv.csar" } };
- }
-
- @Test(dataProvider = "vfModuleCsar")
- public void heatEnvOnVfDownloadNoChangesTest(String vfName) throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- System.out.println("Run for vf " + vfName);
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, vfName);
- assertNotNull(createdResource);
- Map<String, ArtifactDefinition> deploymentArtifacts = createdResource.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
-
- for (ArtifactDefinition artifact : deploymentArtifacts.values()) {
- if (artifact.getArtifactType().equals("HEAT")) {
-
- ArtifactDefinition heatArtifact = artifact;
- assertNotNull(heatArtifact);
-
- ArtifactDefinition heatEnvArtifact = deploymentArtifacts.get(artifact.getArtifactLabel() + "env");
- assertNotNull(heatEnvArtifact);
-
- String heatEnvId = heatEnvArtifact.getUniqueId();
- downloadHeatEnvAndValidate(sdncModifierDetails, createdResource, heatArtifact, heatEnvId);
- }
- }
- System.out.println("Finished for vf " + vfName);
-
- }
-
- private void downloadHeatEnvAndValidate(User sdncModifierDetails, Resource createdResource, ArtifactDefinition heatArtifact, String heatEnvId) throws Exception {
- RestResponse downloadResult = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdResource.getUniqueId(), sdncModifierDetails, heatEnvId);
- BaseRestUtils.checkSuccess(downloadResult);
-
- ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(downloadResult.getResponse(), ArtifactUiDownloadData.class);
- byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes();
- byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload);
- Yaml yaml = new Yaml();
-
- InputStream inputStream = new ByteArrayInputStream(decodeBase64);
-
- Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- Map<String, Object> paramters = (Map<String, Object>) load.get("parameters");
- assertNotNull(paramters);
-
- List<HeatParameterDefinition> heatParameters = heatArtifact.getListHeatParameters();
- assertNotNull(heatParameters);
- assertEquals("Validate heat parameters size", heatParameters.size(), paramters.size());
- Gson gson = new Gson();
- heatParameters.forEach(hpInResource -> {
- Object valueInFile = paramters.get(hpInResource.getName());
- Object valueInResource;
- if (hpInResource.getCurrentValue() == null) {
- valueInResource = hpInResource.getDefaultValue();
- } else {
- valueInResource = hpInResource.getCurrentValue();
- }
- if (valueInResource == null) {
- assertEquals("Validate null value for parameter " + hpInResource.getName(), valueInResource, valueInFile);
- } else {
- HeatParameterType type = HeatParameterType.isValidType(hpInResource.getType());
- // if (type != null && (HeatParameterType.JSON == type || HeatParameterType.COMMA_DELIMITED_LIST == type)){
- // String jsonValue = gson.toJson(valueInFile).toString();
- //
- // assertEquals("Validate value as json string for parameter " +hpInResource.getName() ,valueInResource, jsonValue);
- // }else{
- assertEquals("Validate value for parameter " + hpInResource.getName(), valueInResource, valueInFile.toString());
- // }
- }
- });
- }
-
- @Test(enabled = true)
- public void heatEnvOnVfFailedTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
- assertNotNull(createdResource);
- Map<String, ArtifactDefinition> deploymentArtifacts = createdResource.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
- String heatEnvId = "wrongId";
- RestResponse downloadResult = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdResource.getUniqueId(), sdncModifierDetails, heatEnvId);
-
- assertEquals("Validate error code", 404, downloadResult.getErrorCode().intValue());
-
- // BaseRestUtils.checkErrorResponse(downloadResult, ActionStatus.ARTIFACT_NOT_FOUND);
-
- }
-
- @Test(dataProvider = "vfModuleCsar")
- public void heatEnvOnVfDownloadChangeParamTest(String vfName) throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, vfName);
- assertNotNull(createdResource);
- Map<String, ArtifactDefinition> deploymentArtifacts = createdResource.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
-
- ArtifactDefinition heatArt = deploymentArtifacts.get("heat0");
- assertNotNull(heatArt);
-
- List<HeatParameterDefinition> heatParameters = heatArt.getListHeatParameters();
- assertNotNull(heatParameters);
- HeatParameterDefinition paramForChange = null;
- for (HeatParameterDefinition hp : heatParameters) {
- if (hp.getType().equals("string")) {
- paramForChange = hp;
- break;
- }
- }
- assertNotNull(paramForChange);
- paramForChange.setCurrentValue("newValueForTest");
- RestResponse updateResult = ArtifactRestUtils.updateDeploymentArtifactToResource(heatArt, sdncModifierDetails, createdResource.getUniqueId());
- BaseRestUtils.checkSuccess(updateResult);
-
- RestResponse getResourceResult = ResourceRestUtils.getResource(createdResource.getUniqueId());
- BaseRestUtils.checkSuccess(getResourceResult);
-
- Resource resource = ResponseParser.convertResourceResponseToJavaObject(getResourceResult.getResponse());
- assertNotNull(resource);
- deploymentArtifacts = resource.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
-
- heatArt = deploymentArtifacts.get("heat0");
- assertNotNull(heatArt);
- ArtifactDefinition heatEnvArt = deploymentArtifacts.get("heat0env");
- assertNotNull(heatEnvArt);
-
- downloadHeatEnvAndValidate(sdncModifierDetails, createdResource, heatArt, heatEnvArt.getUniqueId());
-
- }
-
- // ****************************************
- private Map<String, Object> 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<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
-
- return load;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java
deleted file mode 100644
index 63d0221d32..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java
+++ /dev/null
@@ -1,696 +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.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.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-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.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.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.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.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<String, ArtifactDefinition> deploymentArtifacts = resourceObject.getDeploymentArtifacts();
- assertNotNull("deploymentArtifacts list is null", deploymentArtifacts);
- List<String> 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<String, ArtifactDefinition> 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<Pair<String, String>> fields = new ArrayList();
- fields.add(new Pair<String, String>("id", artifact.getEsId()));
- List<Row> 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<Component> 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<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- assertNotNull("toscaArtifacts list is null", toscaArtifacts);
- List<String> 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<String, Object> mapOfDepResArtTypesObjects = getMapOfDepResArtTypesObjects();
- assertNotNull("deployment artifact types list is null", mapOfDepResArtTypesObjects);
- Object object = mapOfDepResArtTypesObjects.get("heat");
- if (object instanceof Map<?, ?>) {
- Map<String, Object> map = (Map<String, Object>) 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<String> 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<String> 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<String> 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<String> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String> 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<String> 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<Service, RestResponse> createServiceResponse = AtomicOperationUtils
- .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true);
- Map<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String, Object> getMapOfDepResArtTypesObjects() throws FileNotFoundException {
-
- return (Map<String, Object>) 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
deleted file mode 100644
index 4c50932709..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
+++ /dev/null
@@ -1,631 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.artifacts;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-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<String, String> 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
-
- Map<String, 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<String, String> extractSingleParameter(Map<String, String> curr) {
- Map<String, String> innerMap = new HashMap<String, String>();
- 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<String, Map> createMapFromYaml(String payload) {
- ArrayList<String> parametersList = new ArrayList<String>();
-
- Yaml yaml = new Yaml();
-
- Map<String, Map> result = (Map<String, Map>) yaml.load(payload);
- Map<String, Map> paramters = (Map<String, Map>) result.get("parameters");
-
- for (Map.Entry<String, Map> entry : paramters.entrySet()) {
- Map<String, String> origInnerMap = (Map<String, String>) entry.getValue();
-
- if (origInnerMap.containsKey("label")) {
- origInnerMap.remove("label");
- paramters.remove(entry);
- paramters.put(entry.getKey(), origInnerMap);
- }
- }
- return paramters;
- }
-
- public Map<String, Map<String, String>> jsonToMap(RestResponse addInformationalArtifactToResource,
- String section2extract, String createKeyMapBy) {
- Map<String, Object> JsonToMap = new HashMap<String, Object>();
- JsonToMap = (Map<String, Object>) ResponseParser.parseToObject(addInformationalArtifactToResource.getResponse(),
- JsonToMap.getClass());
-
- List<Map<String, String>> listOfParamters = (List<Map<String, String>>) JsonToMap.get(section2extract);
- Map<String, Map<String, String>> mapOfActualParameters = new HashMap<String, Map<String, String>>();
-
- for (Map<String, String> curr : listOfParamters) {
- Map<String, String> innerMap = extractSingleParameter(curr);
-
- mapOfActualParameters.put(curr.get(createKeyMapBy), innerMap);
- }
- return mapOfActualParameters;
- }
-
- public Map<String, String> selectFileToUpload(String pathToFile, String fileName) throws IOException {
- String sourceDir = config.getResourceConfigDir();
- String testResourcesPath = sourceDir + File.separator + pathToFile;
- String file = fileName;
- Map<String, String> filePayload = new HashMap<String, String>();
- 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<String, String> 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
-
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
-
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
- @Test
- public void missingDefaultParam() throws Exception {
-
- // select file to upload
-
- Map<String, String> 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
-
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
-
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
- @Test
- public void missingTypeParam() throws Exception {
-
- // select file to upload
-
- Map<String, String> 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<String, String> 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<HeatParameterDefinition> 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<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
- for (HeatParameterDefinition 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<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
- deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
- for (HeatParameterDefinition 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
-
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
-
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
- @Test
- public void updateValueParamMissingDefault() throws Exception {
-
- String updateValueParam = "changed";
-
- Map<String, String> 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<HeatParameterDefinition> 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<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
- for (HeatParameterDefinition 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<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
- deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
- for (HeatParameterDefinition 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
-
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
-
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
- @Test
- public void updateValueParamNull() throws Exception {
-
- String updateValueParam = null;
-
- Map<String, String> 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<HeatParameterDefinition> 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<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
- for (HeatParameterDefinition 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<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
- deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
- for (HeatParameterDefinition 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
- @Test
- public void updateValueParamEmpty() throws Exception {
-
- String updateValueParam = "";
-
- Map<String, String> 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<HeatParameterDefinition> 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<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getListHeatParameters();
- for (HeatParameterDefinition 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<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
- deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
- for (HeatParameterDefinition 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
- @Test
- public void onlyValueParamPermited() throws Exception {
-
- Map<String, String> 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<HeatParameterDefinition> 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<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
- section2extract, createKeyMapBy);
-
- // Prepare map to validate JS
-
- Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
-
- // compare MAPs
-
- ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java
deleted file mode 100644
index a00fceba49..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java
+++ /dev/null
@@ -1,176 +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.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.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<String> 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<String> 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<HeatParameterDefinition> heatParameters = artifactDefinitionJavaObject.getListHeatParameters();
- String currentValue = null;
- for (HeatParameterDefinition 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<String> 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<String> 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<String> 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/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
deleted file mode 100644
index b1d04ba88d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
+++ /dev/null
@@ -1,94 +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.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<Resource, ComponentInstanceProperty> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
deleted file mode 100644
index 11c80d4a61..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
+++ /dev/null
@@ -1,301 +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.category;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.OriginTypeEnum;
-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.testng.AssertJUnit;
-import org.testng.annotations.AfterClass;
-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";
- protected boolean isInitialized = false;
-
- @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 {
- if (isInitialized)
- return;
- user = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
- resourceDetails1 = buildResourceDetails(user, "TestResource1");
- resourceDetails1.setResourceType(ResourceTypeEnum.VFCMT.name());
- resourceDetails2 = buildResourceDetails(user, "TestResource2");
- svcDetails1 = buildServiceDetails("TestService1");
-
- // VFCMT
- res1 = createResource(user, resourceDetails1);
- AssertJUnit.assertEquals("create resorce failed", 201, res1.getErrorCode().intValue());
- resourceDetails1.setUniqueId(ResponseParser.getUniqueIdFromResponse(res1));
-
- resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res1));
-
- // VFC
- res2 = createResource(user, resourceDetails2);
- AssertJUnit.assertEquals("create resorce failed", 201, res2.getErrorCode().intValue());
- resourceDetails2.setUniqueId(ResponseParser.getUniqueIdFromResponse(res2));
- resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res2));
-
- // SERVICE
- svc1 = createService(user, svcDetails1);
- AssertJUnit.assertEquals("create resorce failed", 201, svc1.getErrorCode().intValue());
- svcDetails1.setUniqueId(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getUniqueId());
- svcDetails1.setVersion(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getVersion());
- isInitialized = true;
- }
-
- @AfterClass
- 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));
-
- }
-
- @Test
- public void getCatalogDataNoVFCMT() throws Exception {
-
- List<String> excludeTyps = Arrays.asList(OriginTypeEnum.VFCMT.name());
- RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
- String json = res.getResponse();
- JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
- JSONArray resources = (JSONArray) jsonResp.get("resources");
- JSONArray services = (JSONArray) jsonResp.get("services");
-
- // Verify all the expected resources received except of resource1 which is VFCMT
- AssertJUnit.assertFalse("check resource1 is in response",
- isComponentInArray(resourceDetails1.getUniqueId(), resources));
- AssertJUnit.assertTrue("check resource2 is in response",
- isComponentInArray(resourceDetails2.getUniqueId(), resources));
- AssertJUnit.assertTrue("check service1 is in response",
- isComponentInArray(svcDetails1.getUniqueId(), services));
-
- }
-
- @Test
- public void getCatalogDataNoVFCandVFCMT() throws Exception {
-
- List<String> excludeTyps = Arrays.asList(OriginTypeEnum.VFCMT.name(), OriginTypeEnum.VFC.name());
- RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
- String json = res.getResponse();
- JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
- JSONArray resources = (JSONArray) jsonResp.get("resources");
- JSONArray services = (JSONArray) jsonResp.get("services");
-
- // Verify all the expected resources received except of VFCMT & VFC
- AssertJUnit.assertFalse("check resource1 is in response",
- isComponentInArray(resourceDetails1.getUniqueId(), resources));
- AssertJUnit.assertFalse("check resource2 is in response",
- isComponentInArray(resourceDetails2.getUniqueId(), resources));
- AssertJUnit.assertTrue("check service1 is in response",
- isComponentInArray(svcDetails1.getUniqueId(), services));
-
- }
-
- @Test
- public void getCatalogDataNoServiceAndVFC() throws Exception {
-
- List<String> excludeTyps = Arrays.asList(OriginTypeEnum.SERVICE.name(), OriginTypeEnum.VFC.name());
- RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
- String json = res.getResponse();
- JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
- JSONArray resources = (JSONArray) jsonResp.get("resources");
- JSONArray services = (JSONArray) jsonResp.get("services");
-
- // Verify all the expected resources received except of VFC & SERVICE
- AssertJUnit.assertTrue("check resource1 is in response",
- isComponentInArray(resourceDetails1.getUniqueId(), resources));
- AssertJUnit.assertFalse("check resource2 is in response",
- isComponentInArray(resourceDetails2.getUniqueId(), resources));
- AssertJUnit.assertFalse("check service1 is in response",
- isComponentInArray(svcDetails1.getUniqueId(), services));
-
- }
-
- protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception {
- RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId);
-
- }
-
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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 {
-
- deleteService(svcDetails1.getUniqueId(), user);
- Config config = Utils.getConfig();
-
- Map<String, String> 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<String, String> getHeadersMap(User user) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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<String> serviceTags = new ArrayList<String>();
- 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 {
- RestResponse deleteServiceResponse = ResourceRestUtils.deleteResource(serviceId, user.getUserId());
- return deleteServiceResponse;
- }
-
- public class NewObject {
- private String _name;
-
- public String getName() {
- return _name;
- }
-
- public void setName(String name) {
- this._name = name;
- }
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java
deleted file mode 100644
index d68f3f5582..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java
deleted file mode 100644
index ade662a20c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java
+++ /dev/null
@@ -1,2301 +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.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.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.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<CategoryDefinition> categoryList;
- private List<SubCategoryDefinition> subCategoryList;
- private Map<String, List<String>> subCategoriesToDeleteMap;
-
- @BeforeMethod
- public void init() throws Exception {
- subCategoriesToDeleteMap = new HashMap<String, List<String>>();
- 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<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
- 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<CategoryDefinition> 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<CategoryDefinition> categoryList = new ArrayList<CategoryDefinition>();
- 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<String> subCategorieUniqueIdList = new ArrayList<String>();
- 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<SubCategoryDefinition> defineSubCategories(int catListSize) {
- List<SubCategoryDefinition> subCatList = new ArrayList<SubCategoryDefinition>();
- 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<CategoryDefinition> 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<CategoryDefinition> 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<CategoryDefinition> 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<String>(),
- 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<String>(),
- 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<String>(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<String>(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<String>(), 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<String, Object> map = ResponseParser.parseToObjectUsingMapper(importResult.getResponse(), Map.class);
- assertEquals("Check entries count", 2, map.size());
-
- List<Map<String, Object>> resources = (List<Map<String, Object>>) map.get("resources");
- assertEquals("Check resource category entries count", 1, resources.size());
-
- List<Map<String, Object>> services = (List<Map<String, Object>>) map.get("services");
- assertEquals("Check resource category entries count", 2, services.size());
-
- RestResponse allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "resources");
- List<CategoryDefinition> resourceCategories = ResponseParser.parseCategories(allCategories);
- for (Map<String, Object> 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<CategoryDefinition> servicesCategories = ResponseParser.parseCategories(allCategories);
- for (Map<String, Object> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java
deleted file mode 100644
index 7f30f8ca92..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.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.category;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-
-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.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<String, Object> artifacts = (HashMap<String, Object>) 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java
deleted file mode 100644
index 7858b3259f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java
+++ /dev/null
@@ -1,2003 +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.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 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.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<GroupingDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java
deleted file mode 100644
index dd96ebfc2f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java
+++ /dev/null
@@ -1,1907 +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.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.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=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
- // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = "&AbcD123" GROUPING_NAME
- // = "" RESOURCE_TYPE = "Resource" STATUS = "400" DESC = "SVC4556: Error:
- // Invalid Resource sub-category name format.">
- // 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=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
- // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = " AbdfghBCVa jQ234 @@___
- // +++ At and T " GROUPING_NAME = "" RESOURCE_TYPE = "Resource" STATUS =
- // "400" DESC = "SVC4555: Error: Invalid Resource sub-category name
- // length.">
- @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=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
- // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = " A and T " GROUPING_NAME
- // = "" RESOURCE_TYPE = "Resource" STATUS = "400" DESC = "SVC4555: Error:
- // Invalid Resource sub-category name length.">
- @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=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
- // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = "AbcD123~" GROUPING_NAME
- // = "" RESOURCE_TYPE = "Resource" STATUS = "400" DESC = "SVC4556: Error:
- // Invalid Resource sub-category name format.">
- @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<SubCategoryDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
deleted file mode 100644
index 52db5bcb36..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
+++ /dev/null
@@ -1,3514 +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.devCI;
-
-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.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.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.datastructure.AuditingFieldsKeysEnum;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.Assert;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.relevantcodes.extentreports.LogStatus;
-
-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;
-
-
- @BeforeMethod
- public void init() throws Exception{
- AtomicOperationUtils.createDefaultConsumer(true);
- }
-
-
- @Rule
- public static TestName name = new TestName();
-
- public CRUDExternalAPI() {
- super(name, CRUDExternalAPI.class.getName());
-
- }
-
-
-
- @DataProvider(name="uploadArtifactOnVfcVlCpViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s, resourceTypeEnum: %s", chosenLifeCycleState, artifactType, resourceTypeEnum));
- uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, chosenLifeCycleState, artifactType, resourceTypeEnum);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- @DataProvider(name="uploadArtifactOnVFViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
- uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE, chosenLifeCycleState, artifactType, null);
- }
-
-
-
-
-
- @DataProvider(name="uploadArtifactOnServiceViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
- uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.SERVICE, chosenLifeCycleState, artifactType, null);
- }
-
-
- @DataProvider(name="uploadArtifactOnServiceViaExternalAPIIncludingDistribution")
- public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPIIncludingDistribution() {
- return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- };
- }
-
- @Test(dataProvider="uploadArtifactOnServiceViaExternalAPIIncludingDistribution")
- public void uploadArtifactOnServiceViaExternalAPIIncludingDistribution(LifeCycleStatesEnum chosenLifeCycleState, String artifactType) throws Exception {
- extendTest.log(LogStatus.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<String> 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);
-
- if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == chosenLifeCycleState) && (!component.getComponentType().toString().equals(ComponentTypeEnum.RESOURCE.toString()))) {
- numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size()) + 1;
- } else {
- numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size()) + 1;
- }
- } 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<String, ArtifactDefinition> 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
- protected 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
-
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
- 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 <AuditingFieldsKeysEnum, String> 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 <AuditingFieldsKeysEnum, String> 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")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
- uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState, artifactType, null);
- }
-
-
-
- @DataProvider(name="uploadArtifactOnVfcVlCpRIViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
- uploadArtifactOnAssetViaExternalAPI(ComponentTypeEnum.RESOURCE_INSTANCE, chosenLifeCycleState, artifactType, resourceTypeEnum);
- }
-
-
-
-
- @DataProvider(name="uploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.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<String> variables = asList(artifactReqDetails.getArtifactType());
-
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
- // 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<String> variables = asList(artifactReqDetails.getArtifactType());
-
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
- // 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<String> 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<String> variables = asList("artifact name", "255");
- artifactReqDetails.setArtifactName("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
- // 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<String> variables = asList();
-
- artifactReqDetails.setArtifactName("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
- // 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<String> variables = asList("artifact label", "25");
- artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
- // 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<String> variables = asList("artifact label");
- artifactReqDetails.setArtifactLabel("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
- // 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<String> variables = asList("artifact description", "256");
- artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
- // 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<String> variables = asList("artifact description");
- artifactReqDetails.setDescription("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
-
-
- // 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<String> variables = asList(artifactDefinition.getArtifactDisplayName());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null);
- }
-
-
-
-
-
-
-
-
- protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
- Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum) 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
- if(componentResourceInstanceDetails != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
- } else {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
- 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<String> 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<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
- if(componentResourceInstanceDetails != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
- } else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
- }
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
-
- return restResponse;
-
- }
-
-
-
-
-
-
-
-
- @DataProvider(name="uploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
- 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 {
- extendTest.log(LogStatus.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<String> variables = asList();
-
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(userRoleEnum),
- artifactReqDetails, 409, componentResourceInstanceDetails, errorInfo, variables, lifeCycleStatesEnum);
-
- if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKIN)) {
- performeClean();
- }
- }
-
-
-
-
-
- @DataProvider(name="uploadArtifactOnAssetWhichNotExist")
- 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 {
- extendTest.log(LogStatus.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");
- }
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name());
- List<String> variables = asList("null");
-
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 404, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.CHECKIN);
-
- performeClean();
-
- }
-
-
- @DataProvider(name="uploadArtifactOnAssetWhichInInvalidStateForUploading")
- public static Object[][] dataProviderUploadArtifactOnAssetWhichInInvalidStateForUploading() {
- return new Object[][] {
- {ComponentTypeEnum.SERVICE},
- {ComponentTypeEnum.RESOURCE},
- {ComponentTypeEnum.RESOURCE_INSTANCE},
- };
- }
-
-
- @Test(dataProvider="uploadArtifactOnAssetWhichInInvalidStateForUploading")
- public void uploadArtifactOnAssetWhichInInvalidStateForUploading(ComponentTypeEnum componentTypeEnum) throws Exception {
- extendTest.log(LogStatus.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<String> 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);
-
- performeClean();
- }
-
-
- ////////////////////////////////////////////////////////////////////////////////////
- ////////////////////////////////////////////////////////////////////////////////////
- ////////////////////////////////////////////////////////////////////////////////////
- // Update External API //
- ////////////////////////////////////////////////////////////////////////////////////
- ////////////////////////////////////////////////////////////////////////////////////
- ////////////////////////////////////////////////////////////////////////////////////
-
- @DataProvider(name="updateArtifactForServiceViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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<String, ArtifactDefinition> 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<String> variables = asList(artifactUUID);
- updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", errorInfo, variables, UserRoleEnum.DESIGNER, 404);
-
- }
-
-
-
-
-
- @DataProvider(name="updateArtifactOnRIViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("componentTypeEnum: %s, userRoleEnum: %s, lifeCycleStatesEnum: %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType));
- Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null);
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
- List<String> variables = asList();
- updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, lifeCycleStatesEnum, artifactType, errorInfo, variables, userRoleEnum, 409);
- }
-
-
- @DataProvider(name="updateArtifactOnAssetWhichNotExist")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType));
- Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, resourceTypeEnum);
-
- // get updated artifact data
- Map<String, ArtifactDefinition> 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<String> 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);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null);
-
- }
-
- // 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);
- } 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);
- }
- }
-
-
- @DataProvider(name="updateArtifactOnAssetWhichInInvalidStateForUploading")
- 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 {
- extendTest.log(LogStatus.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<String> variables = asList(component.getName(), component.getComponentType().toString().toLowerCase(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getFirstName(),
- ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getLastName(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId());
- updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, LifeCycleStatesEnum.STARTCERTIFICATION, artifactType, errorInfo, variables, UserRoleEnum.DESIGNER, 403);
-
- }
-
-
-
-
-
- @DataProvider(name="updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.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<String> 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<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
- List<String> 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);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null);
-
- }
- }
-
-
- // 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<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_ARTIFACT_NAME.name());
- List<String> variables = asList();
- artifactReqDetails.setArtifactName("");
-
- if(componentInstance != null) {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null);
-
- }
- }
-
-
- // 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<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
- List<String> variables = asList();
- artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
-
- if(componentInstance != null) {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null);
-
- }
- }
-
-
- // 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<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
- List<String> 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);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null);
-
- }
- }
-
-
- // 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<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
- List<String> variables = asList();
- artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
-
- if(componentInstance != null) {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null);
-
- }
- }
-
-
- // 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<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
-
-
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
- List<String> 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);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null);
-
- }
- }
-
- // 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<String> 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<String, ArtifactDefinition> 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);
- } else {
- updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- expectedResponseCode, null, artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState);
- }
-
- 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<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum) 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
- if(componentInstance != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
- } else {
- expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
- if((lifeCycleStatesEnum == LifeCycleStatesEnum.CHECKIN) || (lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
- } 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<String, ArtifactDefinition> getDeploymentArtifactsOfAsset(Component component, ComponentTypeEnum componentTypeEnum) {
- Map<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
-
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
-// 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 <AuditingFieldsKeysEnum, String> 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")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.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")
- public static Object[][] dataProviderDeleteArtifactOnVfcVlCpRIViaExternalAPI() {
- return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC, null},
-
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL, null},
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP, null},
-
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC, null},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC, null},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL, null},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL, null},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP, null},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP, null},
-
- {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 {
- extendTest.log(LogStatus.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")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("componentTypeEnum: %s, userRoleEnum %s, lifeCycleStatesEnum %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType));
- Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, lifeCycleStatesEnum, artifactType, null);
- Map<String, ArtifactDefinition> 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<String> variables = asList();
-
- if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- 409, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum);
- } else {
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- 409, null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum);
- }
-
- //TODO
-// downloadResourceDeploymentArtifactExternalAPI(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, componentTypeEnum);
- }
-
-
- @DataProvider(name="deleteArtifactOnAssetWhichNotExist")
- 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 {
- extendTest.log(LogStatus.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType));
- Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, resourceTypeEnum);
-
- Map<String, ArtifactDefinition> 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<String> variables = asList(invalidArtifactUUID);
-
- if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null);
- } else {
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, invalidArtifactUUID, errorInfo, variables, null);
-
- }
-
-
- // 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);
- } else {
- component.setUUID("invalidComponentUUID");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name());
- variables = asList("null");
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN);
- }
-
-
-
-
- }
-
- @DataProvider(name="deleteArtifactOnAssetWhichInInvalidStateForUploading")
- 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 {
- extendTest.log(LogStatus.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<String, ArtifactDefinition> 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<String> 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);
- } else {
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 403, null, artifactUUID, errorInfo, variables, null);
-
- }
-
- }
-
-
- @DataProvider(name="deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI")
- 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 {
- extendTest.log(LogStatus.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<String, ArtifactDefinition> deploymentArtifacts;
- deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE);
- String artifactUUID = null;
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci") && !key.endsWith("env")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
- List<String> variables = asList(artifactUUID);
- deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null);
- }
-
- protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails,
- Integer expectedResponseCode, ComponentInstance componentInstance, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum) 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
- if(componentInstance != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
- } 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)) {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
- } else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
- }
- }
-
- 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;
- Map<String, ArtifactDefinition> deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactName = key;
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- 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 deletecd 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 - 2, 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
-
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
-// 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 <AuditingFieldsKeysEnum, String> 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 <AuditingFieldsKeysEnum, String> 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<Resource, RestResponse> 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<Service, RestResponse> 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<String, Object> jsonBody = new HashMap<String, Object>();
- 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().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.calculateMD5Base64EncodedByString(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<String, Object> json = new HashMap<String, Object>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java
deleted file mode 100644
index 5155562e35..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.openecomp.sdc.ci.tests.execute.devCI;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.CommonRestUtils;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.api.HealthCheckInfo;
-import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
-import org.openecomp.sdc.common.api.HealthCheckWrapper;
-import org.testng.annotations.Test;
-
-import com.google.gson.Gson;
-
-public class HealthCheckAPI extends ComponentBaseTest {
-
- @Rule
- public static TestName name = new TestName();
-
- public HealthCheckAPI() {
- super(name, HealthCheckAPI.class.getName());
- }
-
- @Test
- public void checkAmdocsHealthCheckAPI() throws Exception {
- RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
- BaseRestUtils.checkSuccess(healthCheckInfoResponse);
-
- Gson gson = new Gson();
- HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
- assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
- HealthCheckInfo amdocsHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent().equals(Constants.HC_COMPONENT_ON_BOARDING)).findFirst().orElse(null);
- assertNotNull("Amdocs health check not exists in Health Check info", amdocsHC);
- assertEquals("Amdocs health check is down", HealthCheckInfo.HealthCheckStatus.UP, amdocsHC.getHealthCheckStatus());
- assertNotNull("Amdocs componentsInfo not exists in health check", amdocsHC.getComponentsInfo());
- Map<String, HealthCheckStatus> amdocsHCComponents = amdocsHC.getComponentsInfo().stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
- assertNotNull(amdocsHCComponents);
- assertTrue("Amdocs health check ZU component is down or not exists", amdocsHCComponents.get("ZU") != null && amdocsHCComponents.get("ZU").equals(HealthCheckStatus.UP));
- assertTrue("Amdocs health check BE component is down or not exists", amdocsHCComponents.get("BE") != null && amdocsHCComponents.get("BE").equals(HealthCheckStatus.UP));
- assertTrue("Amdocs health check CAS component is down or not exists", amdocsHCComponents.get("CAS") != null && amdocsHCComponents.get("CAS").equals(HealthCheckStatus.UP));
- assertTrue("Amdocs health check FE component is down or not exists", amdocsHCComponents.get("FE") != null && amdocsHCComponents.get("FE").equals(HealthCheckStatus.UP));
- }
-
- @Test
- public void checkDcaeHealthCheckAPI() throws Exception {
- RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
- BaseRestUtils.checkSuccess(healthCheckInfoResponse);
-
- Gson gson = new Gson();
- HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
- assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
- HealthCheckInfo dcaeHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent().equals(Constants.HC_COMPONENT_DCAE)).findFirst().orElse(null);
- assertNotNull("DCAE health check not exists in Health Check info", dcaeHC);
- assertEquals("DCAE health check is down", HealthCheckInfo.HealthCheckStatus.UP, dcaeHC.getHealthCheckStatus());
- assertNotNull("DCAE componentsInfo not exists in health check", dcaeHC.getComponentsInfo());
- Map<String, HealthCheckStatus> dcaeHCComponents = dcaeHC.getComponentsInfo().stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
- assertNotNull(dcaeHCComponents);
- assertTrue("DCAE health check BE component is down or not exists", dcaeHCComponents.get("BE") != null && dcaeHCComponents.get("BE").equals(HealthCheckStatus.UP));
- assertTrue("DCAE health check FE component is down or not exists", dcaeHCComponents.get("FE") != null && dcaeHCComponents.get("FE").equals(HealthCheckStatus.UP));
- }
-
- @Test
- public void checkCassandraHealthCheck() throws Exception {
- RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
- BaseRestUtils.checkSuccess(healthCheckInfoResponse);
-
- Gson gson = new Gson();
- HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
- assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
- HealthCheckInfo cassandraHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent().equals(Constants.HC_COMPONENT_CASSANDRA)).findFirst().orElse(null);
- assertNotNull("Cassandra health check not exists in Health Check info", cassandraHC);
- assertEquals("Cassandra health check is down", HealthCheckInfo.HealthCheckStatus.UP, cassandraHC.getHealthCheckStatus());
- }
-
-} \ No newline at end of file
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java
deleted file mode 100644
index 87eb6dc696..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java
+++ /dev/null
@@ -1,307 +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.devCI;
-
-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.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.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.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 updateVFsearchByCsarStartCertificationState() 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java
deleted file mode 100644
index 49e5950db5..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java
+++ /dev/null
@@ -1,103 +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.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.Resource;
-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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/OpsRejectDistribution.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/OpsRejectDistribution.java
deleted file mode 100644
index 989158ca1e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/OpsRejectDistribution.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.devCI;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-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.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.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.testng.annotations.Test;
-
-public class OpsRejectDistribution extends ComponentBaseTest {
-
- @Rule
- public static TestName name = new TestName();
-
- public OpsRejectDistribution() {
- super(name, OpsRejectDistribution.class.getName());
- }
-
- @Test
- public void testOpsRejectDistribution() throws Exception {
- User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- ServiceReqDetails service = ElementFactory.getDefaultService();
- RestResponse createdService = ServiceRestUtils.createService(service, designer);
- BaseRestUtils.checkCreateResponse(createdService);
- Service serviceFirstImport = ResponseParser.parseToObjectUsingMapper(createdService.getResponse(), Service.class);
- Component serviceObject = AtomicOperationUtils.changeComponentState(serviceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- AtomicOperationUtils.approveAndRejectServiceForDistribution(serviceObject);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/SearchFilterCategoryExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/SearchFilterCategoryExternalAPI.java
deleted file mode 100644
index 3f804a31b1..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/SearchFilterCategoryExternalAPI.java
+++ /dev/null
@@ -1,285 +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.devCI;
-
-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.BeforeMethod;
-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<String> 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 <AuditingFieldsKeysEnum, String> 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")
- 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<String> 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 <AuditingFieldsKeysEnum, String> 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<String> createdResoucesName = new ArrayList<String>();
- 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 <AuditingFieldsKeysEnum, String> 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 {
- for(ResourceTypeEnum resourceTypeEnum: ResourceTypeEnum.values()) {
- List<String> createdResoucesName = new ArrayList<String>();
- 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 <AuditingFieldsKeysEnum, String> 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 {
- Random random = new Random();
- int numberOfResouceToCreate = random.nextInt(5) + 1;
- List<String> createdResoucesName = new ArrayList<String>();
-
- for(int i=0; i<numberOfResouceToCreate; i++) {
-
- Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFCMT, 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.VFCMT.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.VFCMT.toString());
- AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
-
-
- @DataProvider(name="normativeResourceCategory")
- public static Object[][] dataProviderNormativeResourceCategory() {
- return new Object[][] {
- {ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE},
- {ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE},
- };
- }
-
- // Verify exist of normative resource category from data provider
- @Test(dataProvider="normativeResourceCategory")
- public void normativeResourceCategory(ResourceCategoryEnum resourceCategoryEnum) throws Exception {
- RestResponse restResponse = CategoryRestUtils.getAllCategories(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "resources");
- validateJsonContainResourceCategory(restResponse.getResponse(), resourceCategoryEnum);
-
- Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, resourceCategoryEnum, UserRoleEnum.DESIGNER, true).left().value();
- List<String> createdResoucesName = new ArrayList<String>();
- 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);
- }
-
- protected void validateJsonContainResource(String json, List<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java
deleted file mode 100644
index bb86f8f336..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java
+++ /dev/null
@@ -1,578 +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.devCI;
-
-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<Component, RestResponse> 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<String, String> 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<String, String> prepareHeadersMap(String userId) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/VFCMTExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/VFCMTExternalAPI.java
deleted file mode 100644
index ce6103e7c2..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/VFCMTExternalAPI.java
+++ /dev/null
@@ -1,388 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.devCI;
-
-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.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.annotations.BeforeMethod;
-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;
-
-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 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 <AuditingFieldsKeysEnum, String> 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 <AuditingFieldsKeysEnum, String> 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<String> 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")
- 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"},
- {"contact_id_missing"},
- {"contact_id_invalid"},
- };
- }
-
- // Various failure flows
- @Test(dataProvider="createVfcmtVariousFailureFlows")
- public void createVfcmtVariousFailureFlows(String flow) throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
-
- ErrorInfo errorInfo = null;
- List<String> variables = null;
- AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API;
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(defaultResource.getName());
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, defaultResource.getName());
-
- switch (flow) {
- case "name_missing":
- defaultResource.setName("");
- List<String> 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("invalid");
- 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_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY.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 "att_contact_missing":
- defaultResource.setContactId("");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CONTACT.name());
- variables = asList(ComponentTypeEnum.RESOURCE.getValue());
- break;
- case "att_contact_invalid":
- default:
- defaultResource.setContactId("abcderfffdfdfd");
- 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/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
deleted file mode 100644
index d9548bd4f8..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ValidateConformanceLevel.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.execute.devCI;
-
-import static org.testng.Assert.assertTrue;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-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.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.ComponentRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.testng.annotations.Test;
-
-public class ValidateConformanceLevel extends ComponentBaseTest {
-
- @Rule
- public static TestName name = new TestName();
-
- public ValidateConformanceLevel() {
- super(name, ValidateConformanceLevel.class.getName());
- }
-
- @Test
- public void testValidateServiceConformanceLevel() 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.CHECKIN, true).getLeft();
-
- 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);
- RestResponse apiRes = ComponentRestUtils.validateConformanceLevel("fake-uuid-for-test", user.getUserId());
- assertTrue(apiRes.getErrorCode() == 404);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java
deleted file mode 100644
index cd0332e768..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/test1.java
+++ /dev/null
@@ -1,95 +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.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.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<String> distributionStatusList = Arrays.asList(DistributionNotificationStatusEnum.DOWNLOAD_OK.toString(), DistributionNotificationStatusEnum.DEPLOY_OK.toString(), DistributionNotificationStatusEnum.NOTIFIED.toString());
- DistributionValidationUtils.validateDistributedArtifactsByAudit(service, distributionStatusList);
- }
- }
-
-
- public static Map<String, String> addVNF_ModuleDeploymentArtifactToMap(Service service, Map<String, String> distributionArtifactMap){
-
-
- return distributionArtifactMap;
- }
-
- public Component getComponentInTargetLifeCycleState(String componentType, UserRoleEnum creatorUser, LifeCycleStatesEnum targetLifeCycleState) throws Exception {
- Component component = null;
-
- if(componentType.toLowerCase().equals("vf")) {
- Either<Resource, RestResponse> 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<Service, RestResponse> createdResource = AtomicOperationUtils.createDefaultService(creatorUser, true);
- component = createdResource.left().value();
- component = AtomicOperationUtils.changeComponentState(component, creatorUser, targetLifeCycleState, true).getLeft();
- }
-
- return component;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java
deleted file mode 100644
index b4a9bb87ce..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java
+++ /dev/null
@@ -1,186 +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.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<String, String> 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<String> 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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java
deleted file mode 100644
index 4dbc374e35..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java
+++ /dev/null
@@ -1,596 +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.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.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.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.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.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.ArtifactUtils;
-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.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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String> 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<String> 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.calculateMD5Base64EncodedByByteArray(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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String> 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<String> 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.calculateMD5Base64EncodedByByteArray(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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String, String> authorizationHeaders = new HashMap<String, String>();
- 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);
- }
-
- @Test
- public void downloadServiceToscaArtifactSuccess() throws Exception {
- // Creates service
- RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
- assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue());
- Service service = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
- service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
- // Approves service distribution
- RestResponse serviceDistributionApproveRes = ServiceRestUtils.approveServiceDistribution(service.getUniqueId(), UserRoleEnum.GOVERNOR.getUserId());
- service = ResponseParser.convertServiceResponseToJavaObject(serviceDistributionApproveRes.getResponse());
- // Distributes service
- RestResponse serviceDistributionRes = AtomicOperationUtils.distributeService(service, true);
- service = ResponseParser.convertServiceResponseToJavaObject(serviceDistributionRes.getResponse());
- // Gets tosca template artifact from service
- ArtifactDefinition toscaTemplateArtifact = service.getToscaArtifacts().get("assettoscatemplate");
- String expectedPayloadChecksum = toscaTemplateArtifact.getArtifactChecksum();
- String artifactName = toscaTemplateArtifact.getArtifactName();
- ArtifactReqDetails artifactDetails = ArtifactUtils.convertArtifactDefinitionToArtifactReqDetails(toscaTemplateArtifact);
- // Downloads tosca template artifact
- Map<String, String> authorizationHeaders = new HashMap<String, String>();
- 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<String> 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<String> contTypeHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_TYPE_HEADER);
- assertNotNull(contTypeHeaderList);
- assertEquals("Check content type", "application/octet-stream", contTypeHeaderList.get(0));
- String actualContents = restResponse.getResponse();
-
- // validating checksum
- byte[] bytes = actualContents.getBytes();
- String actualPayloadChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(bytes);
- AssertJUnit.assertEquals(expectedPayloadChecksum, actualPayloadChecksum);
-
- // validating valid zip
- InputStream is = new ByteArrayInputStream(bytes);
- InputStream zis = new ZipInputStream(is);
- zis.close();
-
- // validate audit
- String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
- ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion, artifactName));
- String auditAction = "DArtifactDownload";
- ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
- ResourceRestUtils.ecomp, encodeUrlForDownload(relativeUrl), "200", "OK");
- AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java
deleted file mode 100644
index 80b70d675e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java
+++ /dev/null
@@ -1,385 +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.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<String, ArtifactDefinition> deploymentArtifacts;
- List<ComponentInstance> 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<String, ArtifactDefinition> 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/LifeCycleExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/LifeCycleExternalAPI.java
deleted file mode 100644
index 510d8076be..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/LifeCycleExternalAPI.java
+++ /dev/null
@@ -1,270 +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.externalapi;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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.User;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-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.ServiceAssetStructure;
-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.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.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.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.Assert;
-import org.testng.AssertJUnit;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.gson.Gson;
-
-public class LifeCycleExternalAPI extends ComponentBaseTest{
- @Rule
- public static final TestName name = new TestName();
- protected Gson gson = new Gson();
-
- public LifeCycleExternalAPI() {
- super(name, LifeCycleExternalAPI.class.getName());
- }
-
- @BeforeMethod
- public void setup() {
- AtomicOperationUtils.createDefaultConsumer(true);
- }
-
- @Test
- public void testReseourceSuccsesfullTransition() throws Exception{
- ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
- resourceDetails.setName("ciResource1");
- resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
- defaultUser);
- ResourceAssetStructure parsedCreatedResponse = gson.fromJson(createResource.getResponse(), ResourceAssetStructure.class);
- BaseRestUtils.checkCreateResponse(createResource);
-
- //CHECKIN
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,defaultUser,
- LifeCycleStatesEnum.CHECKIN,null);
- //testAudit(defaultUser,parsedCreatedResponse,"0.1",LifeCycleStatesEnum.CHECKOUT.name(),"201","OK");
-
- //CERTIFICATIONREQUEST
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,defaultUser,
- LifeCycleStatesEnum.CERTIFICATIONREQUEST,null);
-
- //CERTIFICATIONREQUEST
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.TESTER),
- LifeCycleStatesEnum.STARTCERTIFICATION,null);
-
- //CERTIFICATIONREQUEST
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.TESTER),
- LifeCycleStatesEnum.CERTIFY,"1.0");
- }
-
- @Test
- public void testVFCMTSuccsesfullTransitionDesigner() throws Exception{
- User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ResourceExternalReqDetails resourceDetails = ElementFactory.getDefaultResourceByType("ci1", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
-
- RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(resourceDetails, defaultUser);
- ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class);
-
- BaseRestUtils.checkCreateResponse(restResponse);
-
- //CHECKIN
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CHECKIN,null);
-
- //CERTIFICATIONREQUEST
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CERTIFY,"1.0");
- }
-
- @Test
- public void testVFCMTSuccsesfullTransitionTester() throws Exception{
- User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ResourceExternalReqDetails resourceDetails = ElementFactory.getDefaultResourceByType("ci1", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
-
- RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(resourceDetails, defaultUser);
- ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class);
-
- BaseRestUtils.checkCreateResponse(restResponse);
-
- //CHECKIN
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CHECKIN,null);
-
- //CERTIFICATIONREQUEST
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.TESTER),
- LifeCycleStatesEnum.CERTIFY,"1.0");
- }
-
- @Test
- public void testVFCMTFailSubmitForTesting() throws Exception{
- User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ResourceExternalReqDetails resourceDetails = ElementFactory.getDefaultResourceByType("ci1", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
-
- RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(resourceDetails, defaultUser);
- ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class);
-
- BaseRestUtils.checkCreateResponse(restResponse);
-
- //CHECKIN
- testResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CHECKIN,null);
-
- //CERTIFICATIONREQUEST
- testFailResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CERTIFICATIONREQUEST,400,ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID.name(),Arrays.asList(LifeCycleStatesEnum.CERTIFICATIONREQUEST.getState()));
-
- //CERTIFICATIONREQUEST
- testFailResourceTransitionOfLifeCycle(parsedCreatedResponse,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.STARTCERTIFICATION,400,ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID.name(),Arrays.asList(LifeCycleStatesEnum.STARTCERTIFICATION.getState()));
- }
-
- //@Test
- public void testServiceSuccsesfullTransition() throws Exception{
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
- serviceDetails.setName("ciService1");
- RestResponse createService = ServiceRestUtils.createService(serviceDetails,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- ServiceAssetStructure parsedCreatedService = gson.fromJson(createService.getResponse(), ServiceAssetStructure.class);
- BaseRestUtils.checkCreateResponse(createService);
-
- //CHECKIN
- testServiceTransitionOfLifeCycle(serviceDetails, parsedCreatedService,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CHECKIN,null);
-
- //CERTIFICATIONREQUEST
- testServiceTransitionOfLifeCycle(serviceDetails, parsedCreatedService,ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- LifeCycleStatesEnum.CERTIFICATIONREQUEST,null);
-
- //CERTIFICATIONREQUEST
- testServiceTransitionOfLifeCycle(serviceDetails, parsedCreatedService,ElementFactory.getDefaultUser(UserRoleEnum.TESTER),
- LifeCycleStatesEnum.STARTCERTIFICATION,null);
-
- //CERTIFICATIONREQUEST
- testServiceTransitionOfLifeCycle(serviceDetails, parsedCreatedService,ElementFactory.getDefaultUser(UserRoleEnum.TESTER),
- LifeCycleStatesEnum.CERTIFY,"1.0");
- }
-
- private void testFailResourceTransitionOfLifeCycle(ResourceAssetStructure parsedCreatedResponse, User user,
- LifeCycleStatesEnum lifeCycleStatesEnum,int errorCode, String error,List<String> variables) throws IOException, JSONException {
- RestResponse response = LifecycleRestUtils.changeExternalResourceState(parsedCreatedResponse.getUuid(),user, lifeCycleStatesEnum);
- AssertJUnit.assertNotNull("check response object is not null", response);
- AssertJUnit.assertNotNull("check error code exists in response", response.getErrorCode());
- AssertJUnit.assertEquals("Check response code is succses", errorCode, response.getErrorCode().intValue());
-
- ErrorValidationUtils.checkBodyResponseOnError(error, variables,response.getResponse());
- }
-
- private void testResourceTransitionOfLifeCycle(ResourceAssetStructure parsedCreatedResponse, User user,
- LifeCycleStatesEnum lifeCycleStatesEnum,String version) throws IOException {
- RestResponse response = LifecycleRestUtils.changeExternalResourceState(parsedCreatedResponse.getUuid(),user, lifeCycleStatesEnum);
- AssertJUnit.assertNotNull("check response object is not null", response);
- AssertJUnit.assertNotNull("check error code exists in response", response.getErrorCode());
- AssertJUnit.assertEquals("Check response code is succses", 201, response.getErrorCode().intValue());
- ResourceAssetStructure parsedMetadata = gson.fromJson(response.getResponse(), ResourceAssetStructure.class);
-
- Assert.assertEquals(parsedMetadata.getUuid(),parsedCreatedResponse.getUuid());
- Assert.assertEquals(parsedMetadata.getInvariantUUID(),parsedCreatedResponse.getInvariantUUID());
- Assert.assertEquals(parsedMetadata.getName(),parsedCreatedResponse.getName());
- if (version==null){
- Assert.assertEquals(parsedMetadata.getVersion(),parsedCreatedResponse.getVersion());
- } else {
- Assert.assertEquals(parsedMetadata.getVersion(),version);
- }
- Assert.assertEquals(parsedMetadata.getResourceType(),parsedCreatedResponse.getResourceType());
- Assert.assertEquals(parsedMetadata.getLifecycleState(),lifeCycleStatesEnum.getComponentState());
- Assert.assertEquals(parsedMetadata.getLastUpdaterUserId(),user.getUserId());
- Assert.assertEquals(parsedMetadata.getLastUpdaterFullName(),user.getFullName());
- }
-
- private void testServiceTransitionOfLifeCycle(ServiceReqDetails resourceDetails,
- ServiceAssetStructure parsedCreatedResponse, User user, LifeCycleStatesEnum lifeCycleStatesEnum,String version) throws IOException {
- RestResponse response = LifecycleRestUtils.changeExternalServiceState(resourceDetails,user, lifeCycleStatesEnum);
- AssertJUnit.assertNotNull("check response object is not null", response);
- AssertJUnit.assertNotNull("check error code exists in response", response.getErrorCode());
- AssertJUnit.assertEquals("Check response code is succses", 201, response.getErrorCode().intValue());
- ServiceAssetStructure parsedMetadata = gson.fromJson(response.getResponse(), ServiceAssetStructure.class);
-
- Assert.assertEquals(parsedMetadata.getUuid(),parsedCreatedResponse.getUuid());
- Assert.assertEquals(parsedMetadata.getInvariantUUID(),parsedCreatedResponse.getInvariantUUID());
- Assert.assertEquals(parsedMetadata.getName(),parsedCreatedResponse.getName());
- if (version==null){
- Assert.assertEquals(parsedMetadata.getVersion(),parsedCreatedResponse.getVersion());
- } else {
- Assert.assertEquals(parsedMetadata.getVersion(),version);
- }
- Assert.assertEquals(parsedMetadata.getLifecycleState(),lifeCycleStatesEnum.getComponentState());
- Assert.assertEquals(parsedMetadata.getLastUpdaterUserId(),user.getUserId());
- }
-
- private void testAudit(User modifier,ResourceAssetStructure resource,String prevVersion,String prevLifecycle,
- String errorCode, String error) throws Exception{
- DbUtils.cleanAllAudits();
-
- //ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
- String auditAction = "ChangeLyfecycleByAPI";
- expectedResourceAuditJavaObject.setAction(auditAction);
- expectedResourceAuditJavaObject.setModifierUid(modifier.getUserId());
- expectedResourceAuditJavaObject.setModifierName(modifier.getFullName());
- expectedResourceAuditJavaObject.setResourceName(resource.getName());
- expectedResourceAuditJavaObject.setResourceType("Resource");
- expectedResourceAuditJavaObject.setPrevVersion(prevVersion);
- expectedResourceAuditJavaObject.setCurrVersion(resource.getVersion());
- expectedResourceAuditJavaObject.setPrevState(prevLifecycle);
- expectedResourceAuditJavaObject.setCurrState(resource.getLifecycleState());
- expectedResourceAuditJavaObject.setStatus(errorCode);
-// List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>());
-// String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
- expectedResourceAuditJavaObject.setDesc(error);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
- AuditValidationUtils.validateAuditExternalChangeLifecycle(expectedResourceAuditJavaObject, auditAction,body);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/UserAPIs.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/UserAPIs.java
deleted file mode 100644
index 3083188fa3..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/UserAPIs.java
+++ /dev/null
@@ -1,468 +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.externalapi;
-
-import static org.testng.AssertJUnit.assertFalse;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.IOException;
-import java.lang.reflect.Type;
-import java.math.BigInteger;
-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.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 createUserAllPosibleRoles() throws Exception {
-
- EcompUser ecompUser = new EcompUser();
- EcompRole ecompRole = new EcompRole();
-
- List<EcompRole> allRoles = getAllRoles();
-
- for (EcompRole ecompRole2 : allRoles) {
- try {
-
- ///get list of users
- List<EcompUser> 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<EcompRole> setRoles = new HashSet<EcompRole>();
- 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 createSameUserTwiceTest() throws Exception {
-
- EcompUser ecompUser = new EcompUser();
- EcompRole ecompRole = new EcompRole();
- try {
-
- ///get list of users
- List<EcompUser> allusersList = getAllusersList();
- int sizeBeforeChange = allusersList.size();
-
- //create user
- ecompUser.setLoginId(getUser());
- ecompRole.setId((long) 1);
- ecompRole.setName("TESTER");
- Set<EcompRole> setRoles = new HashSet<EcompRole>();
- 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<EcompUser> allusersList = getAllusersList();
- int sizeBeforeChange = allusersList.size();
-
- //create user
- ecompUser.setLoginId(getUser());
- ecompRole.setId((long) 1);
- ecompRole.setName("TESTER");
- Set<EcompRole> setRoles = new HashSet<EcompRole>();
- 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<EcompRole>();
- 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<EcompRole> setRoles = new HashSet<EcompRole>();
- setRoles.add(ecompRole);
- ecompUser.setRoles(setRoles);
- RestResponse pushUser = EcompUserRestUtils.pushUser(ecompUser);
- BaseRestUtils.checkSuccess(pushUser);
-
- List<EcompRole> userRolesBefore = getUserRoles(ecompUser);
-
- //update role
- ecompRole = new EcompRole();
- ecompRole.setId((long) 2);
- ecompRole.setName("DESIGNER");
- List<EcompRole> list= new ArrayList<EcompRole>();
- list.add(ecompRole);
-
- EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list);
-
- List<EcompRole> 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<EcompRole> setRoles = new HashSet<EcompRole>();
- 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());
- }
-
- }
-
- @Test
- public void changeUserRoleWithCheckOutResource() 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<EcompRole> setRoles = new HashSet<EcompRole>();
- 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();
-
- //update role
- ecompRole = new EcompRole();
- ecompRole.setId((long) 1);
- ecompRole.setName("TESTER");
- List<EcompRole> list= new ArrayList<EcompRole>();
- list.add(ecompRole);
-
- RestResponse pushUserRoles = EcompUserRestUtils.pushUserRoles(ecompUser.getLoginId(), list);
-// assertTrue("wrong response code :" , pushUserRoles.getErrorCode() == BaseRestUtils.STATUS_CODE_ALREADY_EXISTS);
-
- } 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<EcompRole> setRoles = new HashSet<EcompRole>();
- 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<EcompRole> list= new ArrayList<EcompRole>();
- 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<EcompUser> 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<EcompRole> setRoles = new HashSet<EcompRole>();
- 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<EcompUser> 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<EcompRole> setRoles = new HashSet<EcompRole>();
- 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<EcompRole> getUserRoles(EcompUser ecompUser) throws IOException {
- RestResponse userRoles = EcompUserRestUtils.getUserRoles(ecompUser.getLoginId());
- Type listType = new TypeToken<List<EcompRole>>() {}.getType();
- List<EcompRole> 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<EcompUser> getAllusersList() throws IOException {
- RestResponse allUsers = EcompUserRestUtils.getAllUsers();
-
- Type listType = new TypeToken<List<EcompUser>>() {}.getType();
- List<EcompUser> usersList = new Gson().fromJson(allUsers.getResponse(), listType);
-
- return usersList;
- }
-
- private List<EcompRole> getAllRoles() throws IOException {
- RestResponse allRoles = EcompUserRestUtils.getAllAvailableRoles();
-
- Type listType = new TypeToken<List<EcompRole>>() {}.getType();
- List<EcompRole> availableRoles = new Gson().fromJson(allRoles.getResponse(), listType);
-
- return availableRoles;
- }
-
- private String getUser() {
-
- String returnMe = "ci"+ new BigInteger(getRandomNumber(4));
- 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=0; i < digCount; i++)
- sb.append((char)('0' + rnd.nextInt(10)));
- return sb.toString();
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
deleted file mode 100644
index b820c7d803..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
+++ /dev/null
@@ -1,441 +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=========================================================
- */
-
-//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.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<String, String> 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<String, String>());
- assertEquals("Check response code after download artifact", 401, restResponse.getErrorCode().intValue());
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_REQUIRED.name(), new ArrayList<String>(),
- restResponse.getResponse());
- assertTrue(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
- List<String> getAuthenticateHeader = restResponse.getHeaderFields().get(WWW_AUTHENTICATE);
- assertEquals("www-authenticate header contains more then one value", 1, getAuthenticateHeader.size());
- assertTrue(getAuthenticateHeader.get(0).equals("Basic realm=" + "\"ASDC\""));
-
- validateAuditAuthentication("", AUTH_REQUIRED, ComponentTypeEnum.SERVICE);
- }
-
- @Test
- public void sendAuthenticatedRequestTest_userIsNotProvsioned() throws Exception, Exception {
- String userName = "shay";
- Map<String, String> 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<String>(),
- 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<String, String> 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<String>(),
- 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<String, String> 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<String>(),
- 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<String, String> 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<String>(),
- 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<String, String> authorizationHeader = new HashMap<String, String>();
- 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java
deleted file mode 100644
index e4f7d396be..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java
+++ /dev/null
@@ -1,53 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java
deleted file mode 100644
index 12390eb2fc..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java
+++ /dev/null
@@ -1,1419 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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.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);
- }
-
- // UserId (UserId is taken from USER_ID header)
-
- @Test
- public void createEcompCredentialsHttpCspUserIdIsEmpty() throws Exception {
- // UserId 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 { // UserId
- // 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 UserId in json body
- @Test
- public void createEcompCredentiaJsonBodyContainLastModfierAtuid() throws Exception {
- // Add UserId (not admin) to json - we will ignore and create the user
- HashMap<String, String> jsonMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java
deleted file mode 100644
index acb7e15c6c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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<String> 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<String> 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<String> 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
deleted file mode 100644
index a58ec18840..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
+++ /dev/null
@@ -1,646 +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.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.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.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.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.AtomicOperationUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.openecomp.sdc.common.util.YamlToObjectConverter;
-import org.testng.annotations.Test;
-import org.yaml.snakeyaml.Yaml;
-
-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();
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- resourceVF = (Resource) AtomicOperationUtils
- .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
-
- csarBasicValidation(resourceVF, downloadCSAR);
-
- validateVFCsar(resourceVF, downloadCSAR, 1, 0, 0, 0, 0, 0, 0);
-
-
- }
-
- @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, 3, 1, 0);
- }
-
- @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, 0, 0, 0);
- }
-
- @Test(enabled = true)
- public void createResourceCsarInclInformationalArtTest() throws Exception {
-
- Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
-
- AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceVF1, UserRoleEnum.DESIGNER, false, true);
- AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceVF1, UserRoleEnum.DESIGNER, false, true);
-
- 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, 0, 0, 1, 1, 0);
- }
-
- @Test(enabled = true)
- public void createServiceCsarNotMandatoryMetadataFieldsTest() throws Exception {
-
- Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- service.setServiceType("serviceTypeTest");
- service.setServiceRole("serviceRoleTest");
- ServiceRestUtils.updateService(new ServiceReqDetails(service), sdncModifierDetails);
-
- Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
- Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
-
- resourceVF1 = (Resource) AtomicOperationUtils
- .changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- resourceVF2 = (Resource) AtomicOperationUtils
- .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF1, service, UserRoleEnum.DESIGNER, true);
- AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true);
-
- service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
-
- csarBasicValidation(service, downloadCSAR);
-
- validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 3, 0, 0);
- }
-
- @Test(enabled = true)
- public void createResourceCsarNotMandatoryMetadataFieldsTest() throws Exception {
-
- Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- resourceVF.setResourceVendorModelNumber("modelNumberTest");
- ResourceRestUtils.updateResourceMetadata(new ResourceReqDetails(resourceVF), sdncModifierDetails, resourceVF.getUniqueId());
-
- resourceVF = (Resource) AtomicOperationUtils
- .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
-
- csarBasicValidation(resourceVF, downloadCSAR);
-
- validateVFCsar(resourceVF, downloadCSAR, 1, 0, 0, 0, 0, 0, 0);
-
-
- }
-
-
- private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) {
- try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR);
- ZipInputStream zip = new ZipInputStream(ins);) {
-
- 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("csar.meta"));
-
- readNextEntry(sb, len, buffer, zip);
-
- nextEntry = zip.getNextEntry();
- assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
-
- readNextEntry(sb, len, buffer, zip);
- nextEntry = zip.getNextEntry();
- 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, int informationalArtifactIndexToPass) {
-
- // 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("csar.meta"));
- readNextEntry(sb, len, buffer, zip);
- nextEntry = zip.getNextEntry();
- assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
- readNextEntry(sb, len, buffer, zip);
-
-
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
-
- int toscaEntryIndex = 0;
- int generatorEntryIndex = 0;
- int deploymentArtifactIndex = 0;
- int informationalArtifactIndex = 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.startsWith("Artifacts/Deployment/MODEL_INVENTORY_PROFILE") && entryName.contains("AAI")) {
- ++generatorEntryIndex;
- continue;
- }
-
- if (entryName.contains(".xml") && entryName.startsWith("Artifacts/Deployment/") && !entryName.contains("AAI")) {
- ++deploymentArtifactIndex;
- continue;
- }
-
- if (entryName.contains(".xml") && entryName.startsWith("Artifacts/Informational/") && !entryName.contains("AAI")) {
- ++informationalArtifactIndex;
- 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 Deployment artifacts entries", deploymentArtifactIndexToPass,
- deploymentArtifactIndex);
- assertEquals("Validate amount of Informational artifacts entries", informationalArtifactIndexToPass,
- informationalArtifactIndex);
-
- ins.close();
- zip.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- private void validateVFCsar(Component certifiedVF, byte[] resultByte, int toscaEntryIndexToPass,
- int ymlDeploymentArtifactIndexToPass, int xmlDeploymentArtifactIndexToPass, int heatDeploymentArtifactIndexToPass,
- int ymlInformationalArtifactIndexToPass, int xmlInformationalArtifactIndexToPass, int heatInformationalArtifactIndexToPass) {
-
- // 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("csar.meta"));
-
- readNextEntry(sb, len, buffer, zip);
- nextEntry = zip.getNextEntry();
- assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
-
- readNextEntry(sb, len, buffer, zip);
-
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
-
- int toscaEntryIndex = 0;
- int ymlDeploymentArtifactsIndex = 0;
- int xmlDeploymentArtifactsIndex = 0;
- int heatDeploymentArtifactIndex = 0;
- int ymlInformationalArtifactsIndex = 0;
- int xmlInformationalArtifactsIndex = 0;
- int heatInformationalArtifactIndex = 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) {
-
- readNextEntry(sb, len, buffer, zip);
-
- 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.contains("YANG_XML")) {
- if(entryName.startsWith("Artifacts/Deployment")){
- ++xmlDeploymentArtifactsIndex;
- continue;
- }else if(entryName.startsWith("Artifacts/Informational")){
- ++xmlInformationalArtifactsIndex;
- continue;
- }
- }
-
- if (entryName.contains(".sh") && entryName.contains("HEAT_ARTIFACT")) {
- if(entryName.startsWith("Artifacts/Deployment")){
- ++heatDeploymentArtifactIndex;
- continue;
- }else if(entryName.startsWith("Artifacts/Informational")){
- ++heatInformationalArtifactIndex;
- continue;
- }
- }
-
- if ((entryName.contains(".yml") || entryName.contains(".yaml")) && entryName.contains("HEAT")) {
- if(entryName.startsWith("Artifacts/Deployment")){
- ++ymlDeploymentArtifactsIndex;
- continue;
- }else if(entryName.startsWith("Artifacts/Informational")){
- ++ymlInformationalArtifactsIndex;
- continue;
- }
- }
-
- if(entryName.contains("Definitions/") && entryName.contains("template-interface.yml")){
- validateInterfaceContent(resourceYaml, certifiedVF);
- continue;
- }
- if(entryName.contains("Definitions/")) {
- if(isImportsFileValidation(entryName))
- continue;
- }
-
- assertTrue("Unexpected entry: " + entryName, false);
- }
-
- //Definitions folder
- assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex);
-
- //Deployment folder
- assertEquals("Validate amount of YAML Deployment artifacts", ymlDeploymentArtifactIndexToPass, ymlDeploymentArtifactsIndex);
- assertEquals("Validate amount of XML Deployment artifacts", xmlDeploymentArtifactIndexToPass,
- xmlDeploymentArtifactsIndex);
- assertEquals("Validate amount of HEAT Deployment artifacts", heatDeploymentArtifactIndexToPass,
- heatDeploymentArtifactIndex);
-
- //Informational folder
- assertEquals("Validate amount of YAML Informational artifacts", ymlInformationalArtifactIndexToPass, ymlInformationalArtifactsIndex);
- assertEquals("Validate amount of XML Informational artifacts", xmlInformationalArtifactIndexToPass,
- xmlInformationalArtifactsIndex);
- assertEquals("Validate amount of HEAT Informational artifacts", heatInformationalArtifactIndexToPass,
- heatInformationalArtifactIndex);
-
- 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<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- @SuppressWarnings("unchecked")
- Map<String, Object> metadata = (Map<String, Object>) 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 UUID", component.getUUID(), UUID);
-
- String type = (String) metadata.get("type");
- assertNotNull(type);
- if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
- assertEquals("Validate component type", component.getComponentType().getValue(), type);
- String serviceType = (String) metadata.get("serviceType");
- assertNotNull(serviceType);
- assertEquals("Validate service type", ((Service )component).getServiceType(), serviceType);
- String serviceRole = (String) metadata.get("serviceRole");
- assertNotNull(serviceRole);
- assertEquals("Validate service role", ((Service )component).getServiceRole(), serviceRole);
- } else {
- assertEquals("Validate component type", ((Resource) component).getResourceType(),
- ResourceTypeEnum.valueOf(type));
- String resourceVendorModelNumber = (String) metadata.get("resourceVendorModelNumber");
- assertNotNull(resourceVendorModelNumber);
- assertEquals("Validate resource vendor model number", ((Resource )component).getResourceVendorModelNumber(), resourceVendorModelNumber);
- }
- }
-
- 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;
- }
-
- private void validateInterfaceContent(String content, Component component) {
- Yaml yaml = new Yaml();
-
- InputStream inputStream = new ByteArrayInputStream(content.getBytes());
- @SuppressWarnings("unchecked")
- Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- @SuppressWarnings("unchecked")
- Map<String, Object> node_types = (Map<String, Object>) load.get("node_types");
- assertNotNull(node_types);
-
- String toscaInterfaceName = node_types.keySet().stream().filter(p -> p.startsWith("org.openecomp.")).findAny().get();
- Map<String, Object> toscaInterface = (Map<String, Object>) node_types.get(toscaInterfaceName);
- assertNotNull(toscaInterface);
- String derived_from = (String) toscaInterface.get("derived_from");
- assertNotNull(derived_from);
- assertEquals("Validate derived from generic", component.getDerivedFromGenericType(), derived_from);
-
- }
-
- private void readNextEntry(StringBuffer sb, int len, byte[] buffer, ZipInputStream zip) throws IOException {
- sb.setLength(0);
-
- while ((len = zip.read(buffer)) > 0) {
- sb.append(new String(buffer, 0, len));
- }
- }
-
- private boolean isImportsFileValidation(String fileName) {
-
- switch(fileName){
- case "Definitions/artifacts.yml":
- case "Definitions/capabilities.yml":
- case "Definitions/data.yml":
- case "Definitions/groups.yml":
- case "Definitions/interfaces.yml":
- case "Definitions/nodes.yml":
- case "Definitions/policies.yml":
- case "Definitions/relationships.yml":
- return true;
-
- }
- return false;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
deleted file mode 100644
index 828326e3da..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
+++ /dev/null
@@ -1,657 +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.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 static org.openecomp.sdc.ci.tests.utils.ToscaParserUtils.downloadAndParseToscaTemplate;
-
-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.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-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.ComponentInstancePropInput;
-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.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.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.DataProvider;
-import org.testng.annotations.Test;
-
-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();
- String rootPath = System.getProperty("user.dir");
- private static final String CSARS_PATH = "/src/test/resources/CI/csars/";
- public static String userDefinedNodeYaml = "CustomVL.yml";
-
- public ExportToscaTest() {
- super(name, ExportToscaTest.class.getName());
- }
-
- @DataProvider(name = "vfModuleCsar")
- public static Object[][] csarNames() {
- return new Object[][] { { "VSPPackage", true }, { "csar_1", true }, { "noArtifact", false }, {"noVfModule", false} };
-// return new Object[][] { { "VSPPackage", true }, { "csar_1", true }, { "noArtifact", false } };
- }
-
- @Test(dataProvider = "vfModuleCsar")
- public void exportVfModuleTest(String csarname, boolean includeGroups) throws Exception {
- System.out.println("run for csar " + csarname);
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, csarname);
-
- validateGroupsInResource(sdncModifierDetails, createdResource, includeGroups);
- }
-
- @Test(dataProvider = "vfModuleCsar")
- public void exportVfModuleInstanceTest(String csarname, boolean includeGroups) throws Exception {
- System.out.println("run for csar " + csarname);
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- // create resource
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, csarname);
-
- // change state to check in
- 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);
-
- List<GroupDefinition> groupsInResource = createdResource.getGroups();
- int vfModuleCount = 0;
- List<GroupDefinition> vfModulesInRes = groupsInResource.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
-
- ComponentInstance componentInstance = service.getComponentInstances().get(0);
- String normalizedName = componentInstance.getNormalizedName();
-
- Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, service);
- assertNotNull(load);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- assertNotNull(topology_template);
- Map<String, Object> groups = (Map<String, Object>) topology_template.get("groups");
- if (includeGroups) {
- assertNotNull(vfModulesInRes);
- assertNotNull(groups);
-
- assertEquals("Validate count of vf module instances", vfModulesInRes.size(), groups.size());
-
- vfModulesInRes.forEach(modInRes -> {
- validateVfModuleVsInstance(normalizedName, groups, modInRes);
- });
- }else{
- assertNull(groups);
- }
- }
-
- private void validateVfModuleVsInstance(String normalizedName, Map<String, Object> groups, GroupDefinition modInRes) {
- String instName = normalizedName + ".." + modInRes.getName();
- Map<String, Object> group = (Map<String, Object>) groups.get(instName);
- assertNotNull(group);
-
- String type = (String) group.get("type");
- assertNotNull(type);
- assertEquals("Validate group instance type", modInRes.getType(), type);
-
- Map<String, Object> metadata = (Map<String, Object>) group.get("metadata");
- assertNotNull(metadata);
-
- String invariantUUID = (String) metadata.get("vfModuleModelInvariantUUID");
- String name = (String) metadata.get("vfModuleModelName");
- String UUID = (String) metadata.get("vfModuleModelUUID");
- String version = (String) metadata.get("vfModuleModelVersion");
-
- String customizationUUID = (String) metadata.get("vfModuleModelCustomizationUUID");
- assertNotNull("Validate group instance customizationUUID", customizationUUID);
-
- assertEquals("Validate group instance InvariantUUID", modInRes.getInvariantUUID(), invariantUUID);
- assertEquals("Validate group instance name", modInRes.getName(), name);
- assertEquals("Validate group instance UUID", modInRes.getGroupUUID(), UUID);
- assertEquals("Validate group instance version", modInRes.getVersion(), version);
-
- Map<String, Object> propertiesInInst = (Map<String, Object>) group.get("properties");
- assertNotNull(propertiesInInst);
-
- List<GroupProperty> propertiesInGroup = modInRes.convertToGroupProperties();
- // property isBase not exist in tosca
- assertEquals("Validate group instance properties size", propertiesInGroup.size() - 1, propertiesInInst.size());
- propertiesInGroup.forEach(propInGroup -> {
- String propName = propInGroup.getName();
- if (!propName.equals("isBase")) {
- Object propValue = propertiesInInst.get(propName);
- String valueInGroup = propInGroup.getValue();
- if (valueInGroup != null && !valueInGroup.isEmpty()) {
- assertNotNull(propValue);
- assertEquals("Validate group instance property value for " + propName, valueInGroup, propValue.toString());
- } else {
- assertNull(propValue);
- }
- }
- });
- }
-
- private void validateGroupsInResource(User sdncModifierDetails, Resource createdResource, boolean includeGroups) throws Exception {
- Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
- assertNotNull(load);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- assertNotNull(topology_template);
- Map<String, Object> groups = (Map<String, Object>) topology_template.get("groups");
- if (includeGroups) {
- assertNotNull(groups);
- List<GroupDefinition> groupsOrigin = createdResource.getGroups();
-
- assertEquals("Validate groups size", groupsOrigin.size(), groups.size());
- for (GroupDefinition group : groupsOrigin) {
- Map<String, Object> groupTosca = (Map<String, Object>) groups.get(group.getName());
- assertNotNull(groupTosca);
-
- Map<String, Object> metadata = (Map<String, Object>) groupTosca.get("metadata");
- assertNotNull(metadata);
-
- String invariantUUID;
- String name;
- String UUID;
- String version;
- Map<String, Object> properties = (Map<String, Object>) 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);
-
- validateVfModuleProperties(createdResource, group, properties);
- } 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);
- }
- } else {
- assertEquals(null, groups);
- }
- }
-
- private void validateVfModuleProperties(Resource createdResource, GroupDefinition group, Map<String, Object> properties) {
- // vf_module_type
- String vf_module_type = (String) properties.get("vf_module_type");
- List<GroupProperty> props = group.convertToGroupProperties();
-
- GroupProperty isBaseProp = getGroupPropertyByName(group, Constants.IS_BASE);
- assertNotNull(isBaseProp);
-
- String value = isBaseProp.getValue() == null ? isBaseProp.getDefaultValue() : isBaseProp.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);
- }
-
- // vf_module_description
- String vf_module_description = (String) properties.get("vf_module_description");
- assertEquals("Validate vf_module_description", group.getDescription(), vf_module_description);
-
- // volume_group
- Boolean volume_group = (Boolean) properties.get("volume_group");
- boolean isVolume = false;
- List<String> artifactsList = group.getArtifacts();
- List<ArtifactDefinition> 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);
-
- // min_vf_module_instances
- Integer min_vf_module_instances = (Integer) properties.get("min_vf_module_instances");
- GroupProperty minInstProp = getGroupPropertyByName(group, "min_vf_module_instances");
- assertNotNull(minInstProp);
- assertEquals("Validate min_vf_module_instances", minInstProp.getValue(), min_vf_module_instances.toString());
-
- // vf_module_label
- String vf_module_label = (String) properties.get("vf_module_label");
- GroupProperty labelProp = getGroupPropertyByName(group, "vf_module_label");
- assertNotNull(labelProp);
- assertEquals("Validate vf_module_label", labelProp.getValue(), vf_module_label);
-
- // vf_module_label
- Integer initial_count = (Integer) properties.get("initial_count");
- GroupProperty initCountProp = getGroupPropertyByName(group, "initial_count");
- assertNotNull(initCountProp);
- assertEquals("Validate initial_count", initCountProp.getValue(), initial_count.toString());
-
- // max_vf_module_instances
- Integer max_vf_module_instances = (Integer) properties.get("max_vf_module_instances");
- GroupProperty maxInstProp = getGroupPropertyByName(group, "max_vf_module_instances");
- assertNotNull(maxInstProp);
- if (max_vf_module_instances != null) {
- assertEquals("Validate max_vf_module_instances", maxInstProp.getValue(), max_vf_module_instances.toString());
- } else {
- assertEquals("Validate max_vf_module_instances", maxInstProp.getValue(), max_vf_module_instances);
- }
- }
-
- private GroupProperty getGroupPropertyByName(GroupDefinition group, String name) {
- List<GroupProperty> props = group.convertToGroupProperties();
- for (GroupProperty prop : props) {
- if (prop.getName().equals(name)) {
- return prop;
- }
- }
- return null;
- }
-
- @Test(enabled = true)
- public void exportCsarInputsTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
- Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
- assertNotNull(load);
-
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- assertNotNull(topology_template);
-
- Map<String, Object> inputs = (Map<String, Object>) topology_template.get("inputs");
- assertNotNull(inputs);
-
- List<InputDefinition> inputsFromResource = createdResource.getInputs();
- assertEquals("validate inputs size", inputsFromResource.size(), inputs.size());
- for (InputDefinition inputDef : inputsFromResource) {
- Map<String, Object> inputInFile = (Map<String, Object>) inputs.get(inputDef.getName());
- assertNotNull(inputInFile);
- validateInput(inputDef, inputInFile);
- }
- List<ComponentInstance> componentInstances = createdResource.getComponentInstances();
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = createdResource.getComponentInstancesProperties();
- Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
- assertNotNull(node_templates);
-
- JsonParser jsonParser = new JsonParser();
-
- for (Entry<String, List<ComponentInstanceProperty>> entry : componentInstancesProperties.entrySet()) {
-
- Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(entry.getKey())).findFirst();
- assertTrue(findFirst.isPresent());
- String resourceName = findFirst.get().getName();
- Map<String, Object> instance = (Map<String, Object>) node_templates.get(resourceName);
- assertNotNull(instance);
- Map<String, Object> properties = (Map<String, Object>) 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<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, resource);
- assertNotNull(load);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- assertNotNull(topology_template);
- Map<String, Object> nodes = (Map<String, Object>) topology_template.get("node_templates");
- assertNotNull(nodes);
- Map<String, Object> pmaaServerObj = (Map<String, Object>) nodes.get("pmaa_server_0");
- assertNotNull(pmaaServerObj);
- Map<String, Object> props = (Map<String, Object>) pmaaServerObj.get("properties");
- assertNotNull(props);
- Map<String, Object> jsonPropObj = (Map<String, Object>) 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<String, Object> tosca = downloadAndParseToscaTemplate(sdncModifierDetails, service);
- assertNotNull(tosca);
- Map<String, Object> topology_template = (Map<String, Object>) tosca.get("topology_template");
- assertNotNull(topology_template);
-
- // 5 validate no inputs in service
- Map<String, Object> inputs = (Map<String, Object>) tosca.get("inputs");
- assertNull(inputs);
-
- List<ComponentInstance> 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<ComponentInstancePropInput> instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken<ArrayList<ComponentInstancePropInput>>() {
- }.getType());
- // Take only the 2 first inputs
- List<ComponentInstancePropInput> 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<String, Object>) tosca.get("topology_template");
- assertNotNull(topology_template);
-
- // 8.2 validate inputs in service
- inputs = (Map<String, Object>) topology_template.get("inputs");
- assertNotNull(inputs);
- assertEquals(2, inputs.size());
-
- // validate created inputs vs inputs in Tosca inputs section
- final Map<String, Object> inputsFinal = inputs;
- buildComponentInstInputsMap.getComponentInstanceInputsMap().values().forEach(listPerInstance -> {
- listPerInstance.forEach(input -> {
- Map<String, Object> inputInMap = (Map<String, Object>) inputsFinal.get(input.getName());
- assertNotNull(inputInMap);
- });
- });
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = service.getComponentInstancesInputs();
-
- // validate created inputs vs inputs in Tosca instance input value
- List<ComponentInstanceInput> vfiInputs = componentInstancesInputs.get(vfi.getUniqueId());
- assertNotNull(vfiInputs);
- assertEquals(2, vfiInputs.size());
-
- Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
- assertNotNull(node_templates);
-
- Map<String, Object> instance = (Map<String, Object>) node_templates.get(vfi.getName());
- assertNotNull(instance);
- Map<String, Object> properties = (Map<String, Object>) instance.get("properties");
- assertNotNull(properties);
-
- vfiInputs.forEach(vfiInput -> {
- Map<String, Object> inputPropValueInTosca = (Map<String, Object>) properties.get(vfiInput.getName());
- assertNotNull(inputPropValueInTosca);
- String instaneInputName = (String) inputPropValueInTosca.get("get_input");
- assertNotNull(instaneInputName);
- Map<String, Object> inputInMap = (Map<String, Object>) inputsFinal.get(instaneInputName);
- assertNotNull(inputInMap);
- });
-
- }
-
- @Test(enabled = true)
- public void exportComponentInstancesTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
-
- Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
- assertNotNull(load);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- assertNotNull(topology_template);
-
- Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
- assertNotNull(node_templates);
-
- RestResponse getResource = ResourceRestUtils.getResource(createdResource.getUniqueId());
- BaseRestUtils.checkSuccess(getResource);
- Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
- List<ComponentInstance> componentInstances = resource.getComponentInstances();
-
- assertEquals(componentInstances.size(), node_templates.size());
-
- for (ComponentInstance ci : componentInstances) {
- Map<String, Object> instance = (Map<String, Object>) node_templates.get(ci.getName());
- assertNotNull(instance);
- Map<String, Object> metadata = (Map<String, Object>) instance.get("metadata");
- assertNotNull(metadata);
- String customizationUUD = (String) metadata.get("customizationUUID");
- assertTrue(ci.getCustomizationUUID().equals(customizationUUD));
- }
-
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void extendNodeTemplateWithDefaultPropertyValuesTest() throws Exception {
-
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
- String payloadCsarName = "ToscaTemplateCsar.csar";
- Path path = Paths.get(rootPath + CSARS_PATH + "ToscaTemplateCsar.csar");
- byte[] data = Files.readAllBytes(path);
- String payloadData = Base64.encodeBase64String(data);
- resourceDetails.setPayloadData(payloadData);
- resourceDetails.setPayloadName(payloadCsarName);
- resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
- BaseRestUtils.checkCreateResponse(createResource);
- Resource createdResource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
-
- Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
- assertNotNull(load);
-
- Map<String, Object> nodeTemplateProperties = findNodeTemplateProperties(load, "custom_vl");
-
- assertTrue(nodeTemplateProperties != null);
- assertTrue(nodeTemplateProperties.get("dhcp_enabled").equals(true));
- assertTrue(nodeTemplateProperties.get("ip_version").equals(4));
- assertTrue(nodeTemplateProperties.get("vl_name").equals("customvl"));
- }
-
- private Map<String, Object> findNodeTemplateProperties(Map<String, Object> load, String riName) {
- // find properties of node template (RI)
- return findToscaElement(
- // find node template (RI) by name
- findToscaElement(
- // find node templates
- findToscaElement(
- // find topology template
- findToscaElement(load, "topology_template"), "node_templates"),
- riName),
- "properties");
- }
-
- @SuppressWarnings("unchecked")
- private Map<String, Object> findToscaElement(Map<String, Object> load, String elementName) {
- return (Map<String, Object>) load.get(elementName);
- }
-
- // ----------------------------------------
- private void validateInput(InputDefinition inputDef, Map<String, Object> 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"));
- }
-
- public ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) {
- for (String artifactUid : artifactsList) {
- for (Entry<String, ArtifactDefinition> 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<ComponentInstancePropInput> inputs) {
- Map<String, List<ComponentInstancePropInput>> map = new HashMap<>();
- map.put(addToInput, inputs);
- ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
- componentInstInputsMap.setComponentInstanceInputsMap(map);
- return componentInstInputsMap;
- }
-
-}
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
deleted file mode 100644
index c1b3181600..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/FilteredDataByParamsComponentServletTest.java
+++ /dev/null
@@ -1,135 +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.imports;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.rules.TestName;
-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.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.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 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<String> 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<String> 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<ArtifactDefinition> deploymentArtifactsFromResource = new ArrayList<ArtifactDefinition>(resource.getDeploymentArtifacts().values());
- List<ArtifactDefinition> deploymentArtifactsFromUiComponent = new ArrayList<ArtifactDefinition>(uiComponentWithArtifacts.getDeploymentArtifacts().values());
- List<ArtifactDefinition> informationalArtifactsFromResource = new ArrayList<ArtifactDefinition>(resource.getArtifacts().values());
- List<ArtifactDefinition> informationalArtifactsFromUiComponent = new ArrayList<ArtifactDefinition>(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<String> 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
deleted file mode 100644
index f3b134f6a9..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java
+++ /dev/null
@@ -1,1829 +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.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.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.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.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.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.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();
- private static final String CSARS_PATH = "/src/test/resources/CI/csars/";
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String>();
- 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<String>();
- 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<String>();
- 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<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String> variables = new ArrayList<String>();
- 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<String, String> allVersions = resource.getAllVersions();
- assertEquals(2, allVersions.keySet().size());
- assertEquals(2, allVersions.values().size());
- Set<String> 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<String, ArtifactDefinition> informationalArtifacts = resource.getArtifacts();
- assertEquals(1, informationalArtifacts.keySet().size());
- Set<String> keySet = informationalArtifacts.keySet();
- assertTrue(keySet.contains(firstArtifactLabel.toLowerCase()));
- Collection<ArtifactDefinition> values = informationalArtifacts.values();
- assertEquals(1, values.size());
- Iterator<ArtifactDefinition> 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<String, ArtifactDefinition> updatedArtifacts = updatedResource.getDeploymentArtifacts(); for
- * (Entry<String, ArtifactDefinition> 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<GroupDefinition> 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<String> 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<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> compNameToUniqueId = resource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId()));
-
- // Verify 2 members on group1
- // members: [ app_server, mongo_server ]
- List<GroupDefinition> 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<String, String> createdMembers = groupDefinition1.get(0).getMembers();
- verifyMembers(createdMembers, compNameToUniqueId);
-
- List<GroupProperty> properties = groupDefinition1.get(0).convertToGroupProperties();
- assertEquals("Verify number of members", 2, properties.size());
-
- GroupProperty heatFiles = properties.stream().filter(p -> p.getName().equals("heat_files")).findFirst().get();
- assertNotNull("check heat files not empty", heatFiles);
- List<String> 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());
-
- GroupProperty 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 {
- Resource resource = ResourceRestUtils.importResourceFromCsar("vmmc_relate_by_cap_name.csar");
- // 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 + CSARS_PATH + "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<String, ComponentInstance> nodes = resource.getComponentInstances().stream().collect(Collectors.toMap(n -> n.getName(), n -> n));
- Map<String, CapabilityDefinition> 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<String, List<RequirementCapabilityRelDef>> mappedByReqOwner = resource.getComponentInstancesRelations().stream().collect(Collectors.groupingBy(e -> e.getFromNode()));
- assertEquals(mappedByReqOwner.get(cp1Uid).get(0).getRelationships().get(0).getRelation().getCapabilityUid(), capabilities.get("virtual_linkable").getUniqueId());
- assertEquals(mappedByReqOwner.get(cp2Uid).get(0).getRelationships().get(0).getRelation().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<String, ArtifactDefinition> 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<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
-
- assertEquals(1, componentInstances.size());
- ComponentInstance ci = componentInstances.get(0);
- Map<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<GroupDefinition> 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<String, ArtifactDefinition> 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 + CSARS_PATH + "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<ComponentInstance> componentInstances = resource.getComponentInstances();
- List<ComponentInstance> 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 + CSARS_PATH + "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()))
- );
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void importInnerVfcWithArtifactsUpdateSucceed() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- String rootPath = System.getProperty("user.dir");
- ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
-
- String payloadName = "vfc_artifacts.csar";
- Path path = Paths.get(rootPath + CSARS_PATH + payloadName);
- byte[] data = Files.readAllBytes(path);
- String payloadData = Base64.encodeBase64String(data);
- resourceDetails.setPayloadData(payloadData);
- resourceDetails.setPayloadName(payloadName);
- resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
-
- Map<String,String> validCreatedInformationalArtifactVersions = new HashMap<>();
- validCreatedInformationalArtifactVersions.put("GuideInfoDelete.mib","1");
- validCreatedInformationalArtifactVersions.put("GuideInfoUpdate.mib","1");
- validCreatedInformationalArtifactVersions.put("OtherInfoIgnore.mib","1");
-
- Map<String,String> validCreatedDeploymentArtifactVersions = new HashMap<>();
- validCreatedDeploymentArtifactVersions.put("PollDelete.mib","1");
- validCreatedDeploymentArtifactVersions.put("PollUpdate.mib","1");
- validCreatedDeploymentArtifactVersions.put("TrapDelete.mib","1");
- validCreatedDeploymentArtifactVersions.put("TrapUpdate.mib","1");
-
- Map<String,String> validUpdatedInformationalArtifactVersions = new HashMap<>();
- validUpdatedInformationalArtifactVersions.put("GuideInfoNew.mib","1");
- validUpdatedInformationalArtifactVersions.put("GuideInfoUpdate.mib","2");
- validUpdatedInformationalArtifactVersions.put("OtherInfoIgnore.mib","1");
-
- Map<String,String> validUpdatedDeploymentArtifactVersions = new HashMap<>();
- validUpdatedDeploymentArtifactVersions.put("PollNew.mib","1");
- validUpdatedDeploymentArtifactVersions.put("PollUpdate.mib","2");
- validUpdatedDeploymentArtifactVersions.put("TrapNew.mib","1");
- validUpdatedDeploymentArtifactVersions.put("TrapUpdate.mib","2");
-
- RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
- BaseRestUtils.checkCreateResponse(createResource);
- Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
-
- List<ComponentInstance> componentInstances = resource.getComponentInstances().stream()
- .filter(ci->ci.getNormalizedName().contains("ltm_server"))
- .collect(Collectors.toList());
- assertTrue(!componentInstances.isEmpty() && componentInstances.size() == 1);
- ComponentInstance componentInstance = componentInstances.get(0);
- assertTrue(!componentInstance.getArtifacts().isEmpty() && componentInstance.getArtifacts().size() == 3);
- componentInstance.getArtifacts().values().stream()
- .forEach(a->assertTrue(validCreatedInformationalArtifactVersions.containsKey(a.getArtifactName()) &&
- validCreatedInformationalArtifactVersions.get(a.getArtifactName()).equals(a.getArtifactVersion())));
-
- assertTrue(!componentInstance.getDeploymentArtifacts().isEmpty() && componentInstance.getDeploymentArtifacts().size() == 4);
- componentInstance.getDeploymentArtifacts().values().stream()
- .forEach(a->assertTrue(validCreatedDeploymentArtifactVersions.containsKey(a.getArtifactName()) &&
- validCreatedDeploymentArtifactVersions.get(a.getArtifactName()).equals(a.getArtifactVersion())));
-
- payloadName = "vfc_artifacts_update.csar";
- path = Paths.get(rootPath + CSARS_PATH + payloadName);
- data = Files.readAllBytes(path);
- payloadData = Base64.encodeBase64String(data);
- resourceDetails.setPayloadData(payloadData);
- resourceDetails.setPayloadName(payloadName);
-
- RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
- BaseRestUtils.checkSuccess(updateResource);
- resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
-
- componentInstances = resource.getComponentInstances().stream()
- .filter(ci->ci.getNormalizedName().contains("ltm_server"))
- .collect(Collectors.toList());
- assertTrue(!componentInstances.isEmpty() && componentInstances.size() == 1);
- componentInstance = componentInstances.get(0);
- assertTrue(!componentInstance.getArtifacts().isEmpty() && componentInstance.getArtifacts().size() == 3);
- componentInstance.getArtifacts().values().stream()
- .forEach(a->assertTrue(validUpdatedInformationalArtifactVersions.containsKey(a.getArtifactName()) &&
- validUpdatedInformationalArtifactVersions.get(a.getArtifactName()).equals(a.getArtifactVersion())));
-
- assertTrue(!componentInstance.getDeploymentArtifacts().isEmpty() && componentInstance.getDeploymentArtifacts().size() == 4);
- componentInstance.getDeploymentArtifacts().values().stream()
- .forEach(a->assertTrue(validUpdatedDeploymentArtifactVersions.containsKey(a.getArtifactName()) &&
- validUpdatedDeploymentArtifactVersions.get(a.getArtifactName()).equals(a.getArtifactVersion())));
-
-
- payloadName = "vfc_artifacts_delete_all.csar";
- path = Paths.get(rootPath + CSARS_PATH + payloadName);
- data = Files.readAllBytes(path);
- payloadData = Base64.encodeBase64String(data);
- resourceDetails.setPayloadData(payloadData);
- resourceDetails.setPayloadName(payloadName);
-
- updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
- BaseRestUtils.checkSuccess(updateResource);
- resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
-
- componentInstances = resource.getComponentInstances().stream()
- .filter(ci->ci.getNormalizedName().contains("ltm_server"))
- .collect(Collectors.toList());
- assertTrue(!componentInstances.isEmpty() && componentInstances.size() == 1);
- componentInstance = componentInstances.get(0);
- assertTrue(componentInstance.getArtifacts() == null || componentInstance.getArtifacts().isEmpty());
- assertTrue(componentInstance.getDeploymentArtifacts() == null || componentInstance.getDeploymentArtifacts().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<String, String> createdMembers, Map<String, String> compNameToUniqueId) {
- for (Map.Entry<String, String> 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<String, String> prepareHeadersMap(String userId) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java
deleted file mode 100644
index aa02a3e8c7..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java
+++ /dev/null
@@ -1,618 +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.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.PropertyDefinition;
-import org.openecomp.sdc.be.model.Resource;
-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.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";
- private static final String FILE_NAME_USER_VFC = "Derived_VFC";
- @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<NormativeTypesEnum, Boolean> removeAllNormativeTypeResources() throws ClientProtocolException, IOException {
- Map<NormativeTypesEnum, Boolean> normativeExistInDB = new HashMap<>();
-
- for (NormativeTypesEnum current : NormativeTypesEnum.values()) {
- Boolean existedBeforeDelete = ImportRestUtils.removeNormativeTypeResource(current);
- normativeExistInDB.put(current, existedBeforeDelete);
- }
- return normativeExistInDB;
- }
-
- public static Either<String, Boolean> 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<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>());
- String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
- expectedResourceAuditJavaObject.setDesc(auditDesc);
- AuditValidationUtils.validateAuditImport(expectedResourceAuditJavaObject, auditAction);
- }
- }
- }
-
- // -----------------------------------------------------------------------------------
- protected void validateMyComputeCapabilities(Map<String, Object> map) {
- assertTrue(map.containsKey("capabilities"));
- Map<String, Object> capabilities = (Map<String, Object>) map.get("capabilities");
- assertTrue(capabilities.containsKey("tosca.capabilities.Container"));
- List<Object> hostCapList = (List<Object>) capabilities.get("tosca.capabilities.Container");
- assertFalse(hostCapList.isEmpty());
- Map<String, Object> hostCap = (Map<String, Object>) 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<Object> endPointCapList = (List<Object>) capabilities.get("tosca.capabilities.Endpoint.Admin");
- assertFalse(endPointCapList.isEmpty());
- Map<String, Object> endPointCap = (Map<String, Object>) endPointCapList.get(0);
- validateField(endPointCap, "name", "endpoint");
- validateField(endPointCap, "type", "tosca.capabilities.Endpoint.Admin");
-
- assertTrue(capabilities.containsKey("tosca.capabilities.OperatingSystem"));
- List<Object> osCapList = (List<Object>) capabilities.get("tosca.capabilities.OperatingSystem");
- assertFalse(osCapList.isEmpty());
- Map<String, Object> osCap = (Map<String, Object>) osCapList.get(0);
- validateField(osCap, "name", "os");
- validateField(osCap, "type", "tosca.capabilities.OperatingSystem");
-
- assertTrue(capabilities.containsKey("tosca.capabilities.Scalable"));
- List<Object> scalableCapList = (List<Object>) capabilities.get("tosca.capabilities.Scalable");
- assertFalse(scalableCapList.isEmpty());
- Map<String, Object> scalableCap = (Map<String, Object>) scalableCapList.get(0);
- validateField(scalableCap, "name", "scalable");
- validateField(scalableCap, "type", "tosca.capabilities.Scalable");
-
- assertTrue(capabilities.containsKey("tosca.capabilities.network.Bindable"));
- List<Object> bindingCapList = (List<Object>) capabilities.get("tosca.capabilities.network.Bindable");
- assertFalse(bindingCapList.isEmpty());
- Map<String, Object> bindingCap = (Map<String, Object>) 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<String, Boolean> eitherMyCompute = getResource(resourceName, resourceVersion);
- assertTrue(eitherMyCompute.isLeft());
- String testComputeYml = eitherMyCompute.left().value();
-
- Map<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) 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<String, Boolean> eitherMyCompute = getResource(resourceName,
- // resourceVersion);
- // assertTrue( eitherMyCompute.isLeft() );
- // String testComputeYml = eitherMyCompute.left().value();
-
- Map<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) 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<String, Boolean> eitherMyCompute = getResource(resourceName,
- // resourceVersion);
- // assertTrue( eitherMyCompute.isLeft() );
-
- // String testComputeYml = eitherMyCompute.left().value();
-
- Map<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) 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<String, Object> capabilities = (Map<String, Object>)
- // map.get("capabilities");
- // AssertJUnit.assertTrue(capabilities.containsKey("host"));
- // Map<String, Object> hostCap = (Map<String, Object>)
- // 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<String, Object> endPointCap = (Map<String, Object>)
- // capabilities.get("endpoint");
- // validateField(endPointCap, "type",
- // "tosca.capabilities.Endpoint.Admin");
-
- assertTrue(map.containsKey("capabilities"));
- Map<String, Object> capabilities = (Map<String, Object>) map.get("capabilities");
- assertTrue(capabilities.containsKey("tosca.capabilities.Container"));
- List<Object> hostCapList = (List<Object>) capabilities.get("tosca.capabilities.Container");
- assertFalse(hostCapList.isEmpty());
- Map<String, Object> hostCap = (Map<String, Object>) 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<Object> endPointCapList = (List<Object>) capabilities.get("tosca.capabilities.Endpoint.Admin");
- assertFalse(endPointCapList.isEmpty());
- Map<String, Object> endPointCap = (Map<String, Object>) 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<String, Object> map) {
- assertTrue(map.containsKey("requirements"));
- Map<String, Object> requirements = (Map<String, Object>) map.get("requirements");
-
- assertTrue(requirements.containsKey("tosca.capabilities.Attachment"));
- List<Object> localStorageReqList = (List<Object>) requirements.get("tosca.capabilities.Attachment");
- assertFalse(localStorageReqList.isEmpty());
- Map<String, Object> localStorageReq = (Map<String, Object>) 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<String, Object> 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<String, Object> 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<String, Object> foundMap = (Map<String, Object>) foundValue;
- Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
- assertTrue(foundMap.size() == excpectedMap.size());
- Iterator<String> 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<Object> foundList = (List<Object>) foundValue;
- List<Object> excpectedList = (List<Object>) 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<String, Object> actCat = (Map<String, Object>) 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<NormativeTypesEnum, Boolean> originalState, UserRoleEnum userRole) throws IOException {
- removeAllNormativeTypeResources();
-
- Iterator<Entry<NormativeTypesEnum, Boolean>> iterator = originalState.entrySet().iterator();
- while (iterator.hasNext()) {
- Entry<NormativeTypesEnum, Boolean> 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<String, Boolean> 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<String, Boolean> 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(String.format("Expected code %s and got code %s",ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS,statusCode),statusCode == ImportRestUtils.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<String, Boolean> 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(String.format("Expected code %s and got code %s",ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS,statusCode),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);
- }
-
- @Test
- public void testImportVFCDerivedFromGeneric() throws IOException {
-
- RestResponse response = ImportRestUtils.importNewResourceByName(FILE_NAME_USER_VFC, UserRoleEnum.ADMIN);
- Integer statusCode = response.getErrorCode();
- assertTrue(String.format("Expected code %s and got code %s",ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS,statusCode),statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
- String uid = ResponseParser.getUniqueIdFromResponse(response);
- response = ResourceRestUtils.getResource(uid);
- Resource VFC = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
- List<PropertyDefinition> props = VFC.getProperties();
- for (PropertyDefinition prop : props) {
- assertTrue(null != prop.getOwnerId() && !uid.equals(prop.getOwnerId()));
-
- }
-
- }
-
-}
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
deleted file mode 100644
index 61c846242c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java
+++ /dev/null
@@ -1,1524 +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.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.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.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.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.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<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
- : new ArrayList<String>());
- 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.calculateMD5Base64EncodedByString(json);
-
- Map<String, String> headers = new HashMap<String, String>();
- 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> artifacts = new ArrayList<String>();
- //
- // artifacts.add(resourceId+":"+artifactName1);
- // artifacts.add(resourceId+":"+artifactName2);
- // resourceRespJavaObject.setArtifacts(artifacts);
- // ArrayList<String> interfaces = new ArrayList<String>();
- //
- // 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<PropertyDefinition> 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<PropertyDefinition> 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<PropertyDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java
deleted file mode 100644
index 3d7c81abae..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java
+++ /dev/null
@@ -1,416 +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.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<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
- assertEquals(capabilities.size(), 6);
-
- CapabilityDefinition capability = capabilities.get(scalable).get(0);
- List<ComponentInstanceProperty> 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<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
- assertEquals(capabilities.size(), 6);
-
- CapabilityDefinition capability = capabilities.get(scalable).get(0);
- List<ComponentInstanceProperty> 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<ImmutablePair<String, String>> propertyNamesValues = new ArrayList<>();
- propertyNamesValues.add(new ImmutablePair<String, String>("num_cpus", "2"));
- propertyNamesValues.add(new ImmutablePair<String, String>("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<ImmutablePair<String, String>> propertyNamesValues = new ArrayList<>();
- propertyNamesValues.add(new ImmutablePair<String, String>("num_cpus", "2"));
- propertyNamesValues.add(new ImmutablePair<String, String>("mem_size", "2000 MB"));
- checkResource(createResource, 8, container, "DBMS", propertyNamesValues);
-
- List<ImmutablePair<String, String>> propertyNamesValues1 = new ArrayList<>();
- propertyNamesValues1.add(new ImmutablePair<String, String>(propertyForTestName, "success_again"));
- propertyNamesValues1.add(new ImmutablePair<String, String>(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<ImmutablePair<String, String>> propertyNamesValues) {
- Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
-
- Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
- // TODO Tal: Since Cashing change partial resource returned that causes
- // null pointer exception
- /* assertEquals(capabilities.size(), capNum); */
- /*
- * List<CapabilityDefinition> 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<String, String> propValuePair : propertyNamesValues) {
- // TODO Tal: Since Cashing change partial resource returned that
- // causes null pointer exception
- /*
- * Map<String, ComponentInstanceProperty> propertiesFromContainer =
- * capabilityFromContainer.getProperties()
- * .stream().filter(p->p.getName().equalsIgnoreCase(propValuePair.
- * getLeft())) .collect(Collectors.toMap(p->p.getName(), p->p));
- */
-
- List<ComponentInstanceProperty> 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/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
deleted file mode 100644
index 7a8a764e2e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
+++ /dev/null
@@ -1,2893 +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.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.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.CapabilityRequirementRelationship;
-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.RelationshipInfo;
-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;
-
-/**
- *
- * @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 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;
- 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<String>(),
- 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<String>(),
- 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<String> derivedFrom = new ArrayList<String>() ;
- // 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> tags = new ArrayList<String>();
- 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<String> 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<String> 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<String, String> headersMap = new HashMap<String, String>();
- 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<String> 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<String> 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<String> tags = new ArrayList<String>();
- 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> 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());
-
- RelationshipInfo pair = new RelationshipInfo();
- 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);
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- capReqRel.setRelation(pair);
- List<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- relationships.add(capReqRel);
- 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<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> 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<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> 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<String> 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<String, Object> requirements = importReqDetailsFather.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetailsFather,
- expectedNumOfRequirements);
- assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
- importReqDetailsFather.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
-
- importReqDetailsFather.setCapabilities(testResourcesPath, fatherFileName, sdncUserDetails, "Compute");
- Map<String, Object> capabilities = importReqDetailsFather.getCapabilities();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
- expectedNumOfRequirements);
- assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
- importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
-
- importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
- derivedFromName);
- Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
- expectedNumOfRequirements);
- assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
- importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
-
- importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
- derivedFromName);
- Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> 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<String> 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<String, Object> requirements = importReqDetailsFather.getRequirements();
- Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetailsFather,
- expectedNumOfRequirements);
- assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
- importReqDetailsFather.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
-
- importReqDetailsFather.setCapabilities(testResourcesPath, fatherFileName, sdncUserDetails, "Root");
- Map<String, Object> capabilities = importReqDetailsFather.getCapabilities();
- Map<String, Object> 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<String> 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<String, Object> childRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
- expectedNumOfRequirements);
- Map<String, Object> 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<String, Object> requirements = importReqDetails.getRequirements();
- Map<String, Object> twinRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails,
- expectedNumOfRequirements);
- assertEquals(requirements.keySet().size(), twinRequirementsFromResponse.keySet().size());
- importReqDetails.compareRequirementsOrCapabilities(requirements, twinRequirementsFromResponse);
-
- importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails,
- derivedFromName);
- Map<String, Object> capabilities = importReqDetails.getCapabilities();
- Map<String, Object> 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<String, Object> parseReqOrCapFromResponse(String parsedFieldName, ImportReqDetails importReqDetails,
- int expectedNumOfReqCap) throws ClientProtocolException, IOException {
- RestResponse getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId());
- assertTrue(getResource.getErrorCode().equals(STATUS_CODE_SUCCESS));
- Map<String, Object> parsedFieldFromResponseToMap = ResponseParser.getJsonValueAsMap(getResource,
- parsedFieldName);
- Iterator<String> iterator = parsedFieldFromResponseToMap.keySet().iterator();
- actualNumOfReqOrCap = 0;
- while (iterator.hasNext()) {
- String next = iterator.next();
- List<Object> object = (List<Object>) parsedFieldFromResponseToMap.get(next);
- actualNumOfReqOrCap += object.size();
- }
- assertEquals(expectedNumOfReqCap, actualNumOfReqOrCap);
- return parsedFieldFromResponseToMap;
- }
-
- // ---------------------------------
-
- private void verifyResourcePropertiesList(Resource resourceJavaObject) { // use
- // importListPropertySuccessFlow.yml
- boolean isPropertyAppear = false;
- List<PropertyDefinition> 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<RequirementDefinition> requerments =
- // resourceJavaObject.getRequirements().get("tosca.capabilities.Attachment");
- List<RequirementDefinition> 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<CapabilityDefinition> capabilities =
- // resourceJavaObject.getCapabilities().get("tosca.capabilities.Endpoint.Admin");
- List<CapabilityDefinition> 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<PropertyDefinition> 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<String, PropertyDefinition> 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);
-
- 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<String, PropertyDefinition> attr) {
- List<PropertyDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java
deleted file mode 100644
index 9e8b94e5a8..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java
+++ /dev/null
@@ -1,282 +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.imports;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-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<GroupDefinition> 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<GroupDefinition> 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<GroupDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ToscaTemplateVersionTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ToscaTemplateVersionTest.java
deleted file mode 100644
index 4a9e9beff4..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ToscaTemplateVersionTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.openecomp.sdc.ci.tests.execute.imports;
-
-import static org.junit.Assert.assertEquals;
-
-import java.nio.file.Paths;
-import java.util.Map;
-
-import org.junit.rules.TestName;
-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.ImportReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-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.ToscaParserUtils;
-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.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class ToscaTemplateVersionTest extends ComponentBaseTest {
-
- private static final String EXPECTED_EXPORT_TOSCA_VERSION = "tosca_simple_yaml_1_1";
- private static final String YML_110_VERSION = "loadBalancerTestVersion.yml";
- public static TestName name = new TestName();
- private String SOURCE_DIR;
- private static String WORK_DIR = "importToscaResourceByCreateUrl";
-
- public ToscaTemplateVersionTest() {
- super(name, ToscaTemplateVersionTest.class.getName());
- }
-
- @BeforeMethod
- public void setUp() throws Exception {
- SOURCE_DIR = config.getResourceConfigDir();
- }
-
- @Test
- public void verifyExportYamlVersion() throws Exception {
- User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciYamlVersionTest", ServiceCategoriesEnum.MOBILITY, defaultUser.getUserId());
- RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, defaultUser);
- BaseRestUtils.checkCreateResponse(serviceResponse);
- Service service = ResponseParser.parseToObjectUsingMapper(serviceResponse.getResponse(), Service.class);
- Map<String, Object> load = ToscaParserUtils.downloadAndParseToscaTemplate(defaultUser, service);
- assertEquals(ToscaParserUtils.getToscaVersion(load), EXPECTED_EXPORT_TOSCA_VERSION);
- }
-
- @Test
- public void testVerifyImportYamlVersion_1_1_0() throws Exception {
- String testResourcesPath = Paths.get(SOURCE_DIR, WORK_DIR).toString();
- ImportReqDetails importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(ElementFactory.getDefaultImportResource(), testResourcesPath,
- YML_110_VERSION);
- RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- null);
- BaseRestUtils.checkCreateResponse(importResourceResponse);
-
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java
deleted file mode 100644
index 633ce45178..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java
+++ /dev/null
@@ -1,407 +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.inputs;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-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.codec.binary.Base64;
-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.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.ComponentInstancePropInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.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.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.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 org.yaml.snakeyaml.Yaml;
-
-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
- * <ul>
- * <li>Create service with VF instance that has inputs)</li>
- * <li>Get all inputs of VF instance</li>
- * <li>Add inputs to service</li>
- * <li>Get service inputs</li>
- * <li>Delete service inputs</li>
- * </ul>
- *
- * @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<ComponentInstance> serviceInstances = new Gson().fromJson(getInstancesResponse.getResponse(), new TypeToken<ArrayList<ComponentInstance>>(){}.getType());
-
- // Get all inputs of first instance
- ComponentInstance vfInstance = serviceInstances.get(0);
- RestResponse getComponentInstanceInputsResponse = InputsRestUtils.getComponentInstanceInputs(service, vfInstance);
- BaseValidationUtils.checkSuccess(getComponentInstanceInputsResponse);
- List<ComponentInstancePropInput> instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken<ArrayList<ComponentInstancePropInput>>(){}.getType());
-
- // Take only the 2 first inputs
- List<ComponentInstancePropInput> 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<InputDefinition> serviceInputsAfterAdd = new Gson().fromJson(getComponentInputsResponse.getResponse(), new TypeToken<ArrayList<InputDefinition>>(){}.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<InputDefinition> serviceInputsAfterDelete = new Gson().fromJson(getComponentInputsResponseAfterDelete.getResponse(), new TypeToken<ArrayList<InputDefinition>>(){}.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);
- }
-
- /**
- * Test to check deletion of inputs related to CP/VL property values
- * @throws Exception
- */
- @Test
- public void testDeleteInputsRelatedToPropertyValues() throws Exception {
- Service service = createServiceWithVLinstance();
- User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- String simplePropName = "network_technology";
- String complexPropName = "network_assignments";
- String propertiesName = "network_assignments#ipv6_subnet_default_assignment#ip_network_address_plan";
- String vlInstanceId = service.getComponentInstances().get(0).getUniqueId();
-
- // Take a simple property type and a complex property type
- List<ComponentInstanceProperty> inputsToAdd = service.getComponentInstancesProperties().get(vlInstanceId)
- .stream()
- .filter(p -> simplePropName.equals(p.getName()) || complexPropName.equals(p.getName()))
- .collect(Collectors.toList());
-
- List<ComponentInstancePropInput> propInputList = new ArrayList<>();
- for (ComponentInstanceProperty prop : inputsToAdd) {
- if (simplePropName.equals(prop.getName())) {
- propInputList.add(new ComponentInstancePropInput(prop));
- } else {
- propInputList.add(buildComponentInstNetworkAssignmentIpv6AssignmentComplexPropertyInput(prop, propertiesName));
- }
- }
- // Set component instance property input map and add to inputs service
- ComponentInstInputsMap componentInstInputsMap = buildComponentInstPropertyInputsMap(vlInstanceId, propInputList);
- RestResponse addInputResponse = InputsRestUtils.addInput(service, componentInstInputsMap, UserRoleEnum.DESIGNER);
- BaseValidationUtils.checkSuccess(addInputResponse);
-
- // Get the updated service
- ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
- RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, user);
- service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
-
- // validate instance get_input property values in service and tosca template
- ComponentInstance vlInstance = service.getComponentInstances().get(0);
- String simplePropValue = "{\"get_input\":\"" + vlInstance.getNormalizedName() + "_" + simplePropName + "\"}";
- String complexPropValue = "{\"ipv6_subnet_default_assignment\":{\"ip_network_address_plan\":{\"get_input\":\"" + vlInstance.getNormalizedName() + "_" + propertiesName.replaceAll("#", "_") + "\"}}}";
- // download and compare
- Map<String, Object> load = downloadAndParseServiceToscaTemplate(user, service);
- validateGetInputInstancePropertyValues(load, service, simplePropName, simplePropValue, complexPropName, complexPropValue, vlInstance);
-
- // Delete inputs from service
- RestResponse deleteInputResponse = InputsRestUtils.deleteInputFromComponent(service, service.getInputs().get(0).getUniqueId());
- BaseValidationUtils.checkSuccess(deleteInputResponse);
- deleteInputResponse = InputsRestUtils.deleteInputFromComponent(service, service.getInputs().get(1).getUniqueId());
- BaseValidationUtils.checkSuccess(deleteInputResponse);
-
- // Get the updated service
- getServiceResponse = ServiceRestUtils.getService(serviceDetails, user);
- service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
-
- // download and compare (get_input property values removed)
- load = downloadAndParseServiceToscaTemplate(user, service);
- simplePropValue = "{}";
- complexPropValue = "{\"ipv6_subnet_default_assignment\":{\"ip_network_address_plan\":{}}}";
- validateGetInputInstancePropertyValues(load, service, simplePropName, simplePropValue, complexPropName, complexPropValue, vlInstance);
-
- }
-
- /**
- * 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<Service, RestResponse> 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<Component, RestResponse> 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<ComponentInstance, RestResponse> 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;
- }
-
-
- private Service createServiceWithVLinstance() throws Exception, IOException {
- // Create default service
- Either<Service, RestResponse> createDefaultServiceEither = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
- if (createDefaultServiceEither.isRight()){
- assertTrue("Error creating default service", false);
- }
- Service service = createDefaultServiceEither.left().value();
-
- Resource vl = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, "ExtVL", "1.0");
-
- // add VL instance to service
- Either<ComponentInstance, RestResponse> vlInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vl, service, UserRoleEnum.DESIGNER, true);
- if (vlInstDetails.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 instances from service
- ComponentInstance instance = service.getComponentInstances().get(0);
- if (instance != 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<ComponentInstancePropInput> inputs) {
- Map<String, List<ComponentInstancePropInput>> map = new HashMap<>();
- map.put(addToInput, inputs);
- ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
- componentInstInputsMap.setComponentInstanceInputsMap(map);
- return componentInstInputsMap;
- }
-
- private ComponentInstInputsMap buildComponentInstPropertyInputsMap (String instanceId, List<ComponentInstancePropInput> props) {
- Map<String, List<ComponentInstancePropInput>> map = new HashMap<>();
- map.put(instanceId, props);
- ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
- componentInstInputsMap.setComponentInstancePropInput(map);
- return componentInstInputsMap;
- }
-
-
- private ComponentInstancePropInput buildComponentInstNetworkAssignmentIpv6AssignmentComplexPropertyInput (ComponentInstanceProperty prop, String propertiesName) {
- ComponentInstancePropInput componentInstancePropInput = new ComponentInstancePropInput(prop);
- componentInstancePropInput.setPropertiesName(propertiesName);
- PropertyDefinition input = new PropertyDefinition();
- input.setUniqueId("org.openecomp.datatypes.network.SubnetAssignments.datatype.ip_network_address_plan");
- input.setName("ip_network_address_plan");
- input.setParentUniqueId("org.openecomp.datatypes.network.SubnetAssignments.datatype");
- input.setType("string");
- componentInstancePropInput.setInput(input);
- return componentInstancePropInput;
-
- }
-
- private Map<String, Object> downloadAndParseServiceToscaTemplate(User user, Service service) throws Exception {
- String artifactUniqeId = service.getToscaArtifacts().get("assettoscatemplate").getUniqueId();
- RestResponse toscaTemplate = ArtifactRestUtils.downloadServiceArtifactInternalApi(service.getUniqueId(), user, 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<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- return load;
- }
-
- private void validateGetInputInstancePropertyValues (Map<String, Object> load, Service service, String simplePropName, String simplePropValue, String complexPropName, String complexPropValue, ComponentInstance instance) {
-
- String instanceName = instance.getName();
- String instanceId = instance.getUniqueId();
- ComponentInstanceProperty simpleProp = service.getComponentInstancesProperties().get(instanceId).stream().filter(p -> p.getName().equals(simplePropName)).findAny().get();
- ComponentInstanceProperty complexProp = service.getComponentInstancesProperties().get(instanceId).stream().filter(p -> p.getName().equals(complexPropName)).findAny().get();
-
- assertEquals(simpleProp.getValue(), simplePropValue);
- assertEquals(complexProp.getValue(), complexPropValue);
- // compare with downloaded tosca template
- assertNotNull(load);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- assertNotNull(topology_template);
- Map<String, Object> nodes = (Map<String, Object>) topology_template.get("node_templates");
- assertNotNull(nodes);
- Map<String, Object> vlInstanceObj = (Map<String, Object>) nodes.get(instanceName);
- assertNotNull(vlInstanceObj);
- Map<String, Object> props = (Map<String, Object>) vlInstanceObj.get("properties");
- assertNotNull(props);
- Map<String, Object> complexPropObj = (Map<String, Object>) props.get(complexPropName);
- assertNotNull(complexPropObj);
- Gson gson = new Gson();
- assertEquals(gson.toJson(complexPropObj), complexProp.getValue());
-
- // if simpleProp has an empty value it will not be generated in the tosca map
- if (!simpleProp.getValue().equals("{}")){
- Map<String, Object> simplePropObj = (Map<String, Object>) props.get(simplePropName);
- assertNotNull(simplePropObj);
- assertEquals(gson.toJson(simplePropObj), simpleProp.getValue());
- }
-
-
-
-
-
-
- }
-
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java
deleted file mode 100644
index 84bb5421ab..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java
+++ /dev/null
@@ -1,274 +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.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 alitvinsky
- *
- * 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/ServiceCertWithoutDeploymentArtifacts.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/ServiceCertWithoutDeploymentArtifacts.java
deleted file mode 100644
index 53f1fd20d5..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/ServiceCertWithoutDeploymentArtifacts.java
+++ /dev/null
@@ -1,65 +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.lifecycle;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-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.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.testng.annotations.Test;
-
-public class ServiceCertWithoutDeploymentArtifacts extends LCSbaseTest {
- protected ServiceReqDetails serviceDetails;
- protected User sdncDesignerDetails;
- protected User sdncAdminDetails;
- protected Service serviceServ;
-
- @Rule
- public static TestName testName = new TestName();
-
- public ServiceCertWithoutDeploymentArtifacts() {
- super(testName, ServiceCertWithoutDeploymentArtifacts.class.getName());
- }
-
- @Test
- /**
- * checks possibility to certify service without of deployment artifacts
- * @throws Exception
- */
- public void testDeploymentArtifactsRestriction() throws Exception {
-
- sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
- assertTrue(serviceServ.getDeploymentArtifacts() == null || serviceServ.getDeploymentArtifacts().isEmpty());
- assertTrue(serviceServ.getComponentInstances() == null || serviceServ.getComponentInstances().isEmpty());
- serviceDetails = new ServiceReqDetails(serviceServ);
- RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
- assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
- changeServiceState.getErrorCode() == 200);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java
deleted file mode 100644
index 1cf16978e4..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java
+++ /dev/null
@@ -1,2021 +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.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<PropertyConstraint>() {
- }.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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String> tags = new ArrayList<String>();
- 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 = "<b>Bold<</b>";
-
- 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&amp;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 = "<b>Bold<</b>";
-
- 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&amp;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<String> 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 = "----<b></b><>;";
-
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java
deleted file mode 100644
index fdde5e571a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java
+++ /dev/null
@@ -1,1022 +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.property;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.http.HttpStatus;
-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.PropertyDefinition.PropertyNames;
-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.ServiceReqDetails;
-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.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
-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<ComponentInstanceProperty> expectedPropertyList;
- private List<ComponentInstanceProperty> 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 = "<second string
- // value>";
- protected String newStringPropValue = "second string value";
- protected String newIntegerPropValue = "888";
- protected String newBooleanPropValue = "false";
-
- @BeforeMethod
- public void init() {
- expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- }
-
- @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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty, RestResponse> 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<String> 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<ComponentInstanceProperty>();
- actualPropertyList = new ArrayList<ComponentInstanceProperty>();
- 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<String> 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));
- }
-
- @Test // US833308
- public void serviceWithVLINetworkRoleProperty() throws Exception {
-
- String propName = PropertyNames.NETWORK_ROLE.getPropertyName();
- String propType = "string";
- String propValue = "myValue";
-
- // create service
- Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
- Resource vl = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, "ExtVL", "1.0");
- // add ExtVL instance
- ComponentInstance vlInstDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(vl, service, UserRoleEnum.DESIGNER, true).left().value();
- // fetch updated service
- service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
-
- // update ExtVL network_role property value
- ComponentInstanceProperty propDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(service, vlInstDetails, propName, propType);
- propDetails.setValue(propValue);
- RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils.updatePropertyValueOnResourceInstance(service, vlInstDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), propDetails);
- assertTrue("expected updatePropertyValueOnResourceInstance response code: " + HttpStatus.SC_OK, updatePropertyValueOnResourceInstance.getErrorCode() == HttpStatus.SC_OK);
-
- service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
- // expected property value after update has service systemName prefixed to user defined value.
- ComponentInstanceProperty updatedPropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(service, vlInstDetails, propName, propType);
- String generatedValue = service.getSystemName() + "." + propValue;
- assertTrue("property value was updated properly", updatedPropDetails.getValue().equals(generatedValue));
-
- // update service name
- ServiceReqDetails updatedServiceDetails = new ServiceReqDetails(service);
- String newServiceName = "ciServiceWithVLIPropertyValueTest";
- updatedServiceDetails.setName(newServiceName);
- RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- service = ResponseParser.convertServiceResponseToJavaObject(updateServiceResponse.getResponse());
- // expected property value after update has service (updated) systemName prefixed to user defined value.
- generatedValue = newServiceName + "." + propValue;
- updatedPropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(service, vlInstDetails, propName, propType);
- assertTrue("property value was updated properly", updatedPropDetails.getValue().equalsIgnoreCase(generatedValue));
- }
-
-
- // -------------------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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java
deleted file mode 100644
index 7ecdcf457f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java
+++ /dev/null
@@ -1,1796 +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.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<br>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", "[ <b>AAA</b> ]", "[\"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" ,
- // "[\"<b>xxx</b>\", \"<b>yyy</b>\"]" , "[\"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<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
- "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
- "tosca.datatypes.Credential",
- "{\"key1\":{\"protocol\":\"protocol<br>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<br>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\":\"<b>AAAA</b>\" }", "{\"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<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
- "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
- "tosca.datatypes.Credential",
- "{\"key1\":{\"protocol\":\"protocol<br>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<String> 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String> 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<String> 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<String> 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<String> 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<String> 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<String>(),
- 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<String>(),
- 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<String> 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<String> 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<String> 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<String> 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<String> 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<String>(),
- 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<String>(),
- 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<String> 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<String> 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<PropertyDefinition> 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<String> 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<String> 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<String>(),
- 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java
deleted file mode 100644
index 9f0dff9b42..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java
+++ /dev/null
@@ -1,379 +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.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.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.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;
-
-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<String, String> headersMap = new HashMap<String, String>();
-
- @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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- // String category = ResourceCategoryEnum.DATABASE.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> variables = Arrays.asList();
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables,
- propertyErrorResponse.getResponse());
- }
-
- // --------------------------------------------------------------------------------------
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java
deleted file mode 100644
index 85dfe4e13a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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 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<byte[], Boolean> serialize = SerializationUtils.serializeExt(resource);
-
- SerializationUtils.deserializeExt(serialize.left().value(), Resource.class, "ffff");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java
deleted file mode 100644
index 903ffbaca7..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java
+++ /dev/null
@@ -1,1395 +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.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.CapabilityRequirementRelationship;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.RelationshipImpl;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.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 ResourceReqDetails resourceDetailsReq;
- private ResourceReqDetails resourceDetailsCap;
-
- @BeforeMethod
- public void before() throws Exception {
- designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- 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("ciMyCompute", 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());
-
- RelationshipInfo pair = new RelationshipInfo();
- 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<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- capReqRel.setRelation(pair);
- relationships.add(capReqRel);
- 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get("tosca.capabilities.Container");
- List<RequirementDefinition> reqList = capReqDef.getRequirements().get("tosca.capabilities.Container");
-
- RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
- requirementDef.setFromNode(riReq.getUniqueId());
- requirementDef.setToNode(riCap.getUniqueId());
-
- RelationshipInfo pair = new RelationshipInfo();
- 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<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- capReqRel.setRelation(pair);
- relationships.add(capReqRel);
- 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<RequirementDefinition> 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<RequirementCapabilityRelDef> 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<RequirementCapabilityRelDef> getComponentInstancesRelations(String resourceUniqueId)
- throws ClientProtocolException, IOException {
- Resource resource = getVfAsResourceObject(resourceUniqueId);
- List<RequirementCapabilityRelDef> 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<ComponentInstance> getComponentInstancesList(String resourceUniqueId) throws Exception {
- Resource resource = getVfAsResourceObject(resourceUniqueId);
- List<ComponentInstance> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
- for (CapabilityDefinition cap : list) {
- cap.setMinOccurrences("0");
- }
-
- Map<String, List<CapabilityDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
- for (CapabilityDefinition cap : list) {
- cap.setMinOccurrences("0");
- }
-
- Map<String, List<CapabilityDefinition>> 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());
-
- createComponentInstance(resourceDetailsCap, designerUser, resourceDetailsVF);
- createComponentInstance(resourceDetailsReq, designerUser, resourceDetailsVF);
-
- ResourceReqDetails vfHigh = new ResourceReqDetails(resourceDetailsVF, "0.1");
- vfHigh.setName("vfHigh");
- vfHigh.setTags(new ArrayList<String>(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<String>(),
- 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<String>(), 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();
-
- 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();
-
- 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(),
- associateInstances.getResponse());
-
- CapReqDef capReqDef = getResourceReqCap();
-
- Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(),
- associateInstances.getResponse());
-
- CapReqDef capReqDef = getResourceReqCap();
-
- Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(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<String>(), 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<String>(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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
- for (CapabilityDefinition cap : list) {
- cap.setMinOccurrences("0");
- }
-
- Map<String, List<CapabilityDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(),
- 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<String, List<CapabilityDefinition>> capabilitiesAfterFirstCheckout = capReqDefAfterFirstCheckout
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesAfterFirstAssociate = capReqDefAfterFirstAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> requirementsAfterFirstAssociate = capReqDefAfterFirstAssociate
- .getRequirements();
-
- requirementsAfterFirstCheckout.remove("tosca.capabilities.Container");
- assertTrue(requirementsAfterFirstAssociate.equals(requirementsAfterFirstCheckout));
- assertTrue(capabilitiesAfterFirstAssociate.equals(capabilitiesAfterFirstCheckout));
-
- resourceDetailsVF.setUniqueId(firstUniqueId);
- CapReqDef capReqDefOfFirstVersion = getResourceReqCap();
- Map<String, List<CapabilityDefinition>> capabilitiesOfFirstVersion = capReqDefOfFirstVersion.getCapabilities();
- Map<String, List<RequirementDefinition>> 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<RequirementCapabilityRelDef> componentInstancesRelations = getComponentInstancesRelations(
- resourceDetailsVF.getUniqueId());
- assertFalse(componentInstancesRelations.isEmpty());
- assertEquals(1, componentInstancesRelations.size());
- List<ComponentInstance> 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<ComponentInstance> componentInstances =
- // resource_0_2.getComponentInstances();
- List<ComponentInstance> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<RequirementDefinition> expectedList = requirementsBeforeAssociate.get("tosca.capabilities.Container");
- for (RequirementDefinition req : expectedList) {
- if (req.getOwnerName().equals(riReq2.getName())) {
- expectedList = new ArrayList<RequirementDefinition>(Arrays.asList(req));
- break;
- }
- }
- requirementsBeforeAssociate.put("tosca.capabilities.Container", expectedList);
- assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
-
- List<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
- for (CapabilityDefinition cap : list) {
- cap.setMinOccurrences("0");
- }
-
- Map<String, List<CapabilityDefinition>> 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<String, List<CapabilityDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesAfterDissociate = capReqDefAfterDissociation
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
- .getRequirements();
-
- RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
- capReqDefBeforeAssociate);
- assertTrue(requirementDef.getRelationships().size() == 1);
- String requirement = requirementDef.getRelationships().get(0).getRelation().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<String>(Arrays.asList(riReq.getName(), riCap.getName(), requirement)),
- associateInstances.getResponse());
-
- CapReqDef capReqDef = getResourceReqCap();
-
- Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<RequirementDefinition> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<RequirementDefinition> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<RequirementDefinition> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
- .getRequirements();
- String requirementName = requirementDef.getRelationships().get(0).getRelation().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<String>(Arrays.asList(riReq.getName(), riCap.getName(), requirementName)),
- dissociateInstances.getResponse());
-
- CapReqDef capReqDefAfterDissociate = getResourceReqCap();
-
- List<RequirementDefinition> 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);
-
- 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<String>(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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(),
- dissociateInstances.getResponse());
-
- CapReqDef capReqDefAfterDissociate = getResourceReqCap();
-
- List<RequirementDefinition> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(),
- dissociateInstances.getResponse());
-
- CapReqDef capReqDefAfterDissociate = getResourceReqCap();
-
- List<RequirementDefinition> 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<String>(Arrays.asList("")), dissociateInstances.getResponse());
-
- CapReqDef capReqDefAfterDissociate = getResourceReqCap();
-
- List<RequirementDefinition> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
- for (CapabilityDefinition cap : list) {
- cap.setMinOccurrences("0");
- }
-
- Map<String, List<CapabilityDefinition>> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
- .getRequirements();
-
- 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<RequirementDefinition> 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<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
- .getCapabilities();
- Map<String, List<RequirementDefinition>> 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<String>(),
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java
deleted file mode 100644
index b2e81fea75..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java
+++ /dev/null
@@ -1,2212 +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.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 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.ComponentTypeEnum;
-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.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.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.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.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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add(resourceName);
- resourceTags.add("tag2");
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String> variables = Arrays.asList();
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
- createResourceResponse2.getResponse());
-
- }
-
- private ResourceReqDetails createRandomResource() {
- String resourceName = "CISCO4";
- String description = "description";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> 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();
-
- // 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
-
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- // resourceTags.add(resourceName);
- // resourceTags.add("tag2");
- // String category = ResourceServiceCategoriesEnum.VOIP.getValue();
- // ArrayList<String> derivedFrom = new ArrayList<String>();
- // 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add("");
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.VOIP.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CustomizationUUIDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CustomizationUUIDTest.java
deleted file mode 100644
index cd87ea5265..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CustomizationUUIDTest.java
+++ /dev/null
@@ -1,433 +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.resource;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-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.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.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-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;
-
-public class CustomizationUUIDTest extends ComponentBaseTest {
-
- @Rule
- public static TestName name = new TestName();
-
- public CustomizationUUIDTest() {
- super(name, CustomizationUUIDTest.class.getName());
- }
-
- @Test(enabled = true)
- public void resourceCustomUUIDTestUpdateMeta() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- // create resource in checkin status
- Resource resource1 = createVfFromCSAR(sdncModifierDetails, "csar_1");
-
- RestResponse checkinState = LifecycleRestUtils.changeComponentState(resource1, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
- BaseRestUtils.checkSuccess(checkinState);
-
- // create service
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
- RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
- ResourceRestUtils.checkCreateResponse(createServiceResponse);
- Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
-
- // create instance 1
- ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(resource1);
- RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
- ResourceRestUtils.checkCreateResponse(createComponentInstance);
-
- ComponentInstance ci1 = ResponseParser.parseToObjectUsingMapper(createComponentInstance.getResponse(), ComponentInstance.class);
- assertNotNull(ci1.getCustomizationUUID());
- String ci1CustUUID = ci1.getCustomizationUUID();
-
- // get service with 1 instance
- RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(1, componentInstances.size());
-
- // change name of instance 1 and check custom UUID
- String newCi1Name = "newCi1Name";
- ci1.setName(newCi1Name);
- RestResponse updateComponentInstance = ComponentInstanceRestUtils.updateComponentInstance(ci1, sdncModifierDetails, service.getUniqueId(), ComponentTypeEnum.SERVICE);
- ResourceRestUtils.checkSuccess(updateComponentInstance);
- ComponentInstance ci1AfterChange = ResponseParser.parseToObjectUsingMapper(updateComponentInstance.getResponse(), ComponentInstance.class);
-
- // must be different
- assertFalse(ci1.getCustomizationUUID().equals(ci1AfterChange.getCustomizationUUID()));
-
- // change position of instance 1 and check UUID
- ci1.setPosX("151");
- ci1.setPosY("20");
- updateComponentInstance = ComponentInstanceRestUtils.updateComponentInstance(ci1, sdncModifierDetails, service.getUniqueId(), ComponentTypeEnum.SERVICE);
- ResourceRestUtils.checkSuccess(updateComponentInstance);
- ci1AfterChange = ResponseParser.parseToObjectUsingMapper(updateComponentInstance.getResponse(), ComponentInstance.class);
- // must be same
- assertTrue(ci1.getCustomizationUUID().equals(ci1AfterChange.getCustomizationUUID()));
- }
-
- @Test(enabled = true)
- public void resourceCustomUUIDPropertyTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- // create resource
- Resource resource1 = createVfFromCSAR(sdncModifierDetails, "csar_1");
-
- RestResponse checkinState = LifecycleRestUtils.changeComponentState(resource1, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
- BaseRestUtils.checkSuccess(checkinState);
-
- // 2 create service
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
- RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
- ResourceRestUtils.checkCreateResponse(createServiceResponse);
- Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
-
- // create instance
- ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(resource1);
- RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
- ResourceRestUtils.checkCreateResponse(createComponentInstance);
-
- ComponentInstance ci1 = ResponseParser.parseToObjectUsingMapper(createComponentInstance.getResponse(), ComponentInstance.class);
- assertNotNull(ci1.getCustomizationUUID());
- String ci1CustUUID = ci1.getCustomizationUUID();
-
- // get service with 1 instance
- RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(1, componentInstances.size());
-
- // instance property values
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = service.getComponentInstancesProperties();
- assertNotNull(componentInstancesProperties);
- List<ComponentInstanceProperty> listProps = componentInstancesProperties.get(ci1.getUniqueId());
- assertNotNull(listProps);
-
- ComponentInstanceProperty updatedInstanceProperty = null;
- for (ComponentInstanceProperty cip : listProps) {
- if (cip.getType().equals("string")) {
- updatedInstanceProperty = cip;
- break;
- }
- }
- assertNotNull(updatedInstanceProperty);
- updatedInstanceProperty.setValue("newValue");
-
- RestResponse updatePropRes = ComponentInstanceRestUtils.updatePropertyValueOnResourceInstance(service, ci1, sdncModifierDetails, updatedInstanceProperty);
- BaseRestUtils.checkSuccess(updatePropRes);
-
- getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- ComponentInstance ciAfterUpdateProp = componentInstances.get(0);
-
- assertFalse(ci1.getCustomizationUUID().equals(ciAfterUpdateProp.getCustomizationUUID()));
- }
-
- @Test(enabled = true)
- public void resourceCustomUUIDChangeVersionTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- // create resource in checkin status
- Resource resource1 = createVfFromCSAR(sdncModifierDetails, "csar_1");
-
- RestResponse checkinState = LifecycleRestUtils.changeComponentState(resource1, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
- BaseRestUtils.checkSuccess(checkinState);
-
- // create service
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
- RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
- ResourceRestUtils.checkCreateResponse(createServiceResponse);
- Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
-
- // create instance 1
- ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(resource1);
- RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
- ResourceRestUtils.checkCreateResponse(createComponentInstance);
-
- ComponentInstance ci1 = ResponseParser.parseToObjectUsingMapper(createComponentInstance.getResponse(), ComponentInstance.class);
- assertNotNull(ci1.getCustomizationUUID());
- String ci1CustUUID = ci1.getCustomizationUUID();
-
- // create 0.2 version of resource( check out and check in)
- RestResponse checkoutState = LifecycleRestUtils.changeComponentState(resource1, sdncModifierDetails, LifeCycleStatesEnum.CHECKOUT);
- BaseRestUtils.checkSuccess(checkoutState);
- resource1 = ResponseParser.parseToObjectUsingMapper(checkoutState.getResponse(), Resource.class);
- assertNotNull(resource1);
-
- checkinState = LifecycleRestUtils.changeComponentState(resource1, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
- BaseRestUtils.checkSuccess(checkinState);
-
- // change version of instance
- RestResponse changeComponentInstanceVersion = ComponentInstanceRestUtils.changeComponentInstanceVersion(service, ci1, resource1, sdncModifierDetails);
- BaseRestUtils.checkSuccess(changeComponentInstanceVersion);
- RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(1, componentInstances.size());
- assertFalse(ci1CustUUID.equals(componentInstances.get(0).getCustomizationUUID()));
-
- }
-
- @Test(enabled = true)
- public void resourceCustomUUIDChangeArtifactsTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- // create resource in checkin status
- Resource resource1 = createVfFromCSAR(sdncModifierDetails, "csar_1");
-
- RestResponse checkinState = LifecycleRestUtils.changeComponentState(resource1, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
- BaseRestUtils.checkSuccess(checkinState);
-
- // create service
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
- RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
- ResourceRestUtils.checkCreateResponse(createServiceResponse);
- Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
-
- // create instance 1
- ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(resource1);
- RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
- ResourceRestUtils.checkCreateResponse(createComponentInstance);
-
- ComponentInstance ci1 = ResponseParser.parseToObjectUsingMapper(createComponentInstance.getResponse(), ComponentInstance.class);
- assertNotNull(ci1.getCustomizationUUID());
- String lastUUID = ci1.getCustomizationUUID();
-
- RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
-
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(1, componentInstances.size());
- ComponentInstance ci = componentInstances.get(0);
- Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
- // find artifact for update
- ArtifactDefinition artifactForUpdate = null;
- for (ArtifactDefinition ad : deploymentArtifacts.values()) {
- if (ad.getArtifactType().equals("HEAT_ENV")) {
- artifactForUpdate = ad;
- break;
- }
- }
-
- assertNotNull(artifactForUpdate);
- // update heat env on instance
- RestResponse updateArtifact = ArtifactRestUtils.updateDeploymentArtifactToRI(artifactForUpdate, sdncModifierDetails, ci.getUniqueId(), service.getUniqueId());
- BaseRestUtils.checkSuccess(updateArtifact);
- getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertFalse(lastUUID.equals(componentInstances.get(0).getCustomizationUUID()));
- lastUUID = componentInstances.get(0).getCustomizationUUID();
-
- // add artifact to instance
- ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact();
- RestResponse addArtifactToResourceInstance = ArtifactRestUtils.addArtifactToResourceInstance(artifactDetails, sdncModifierDetails, ci.getUniqueId(), service.getUniqueId());
- BaseRestUtils.checkSuccess(addArtifactToResourceInstance);
- ArtifactDefinition artifactDef = ResponseParser.parseToObjectUsingMapper(addArtifactToResourceInstance.getResponse(), ArtifactDefinition.class);
- assertNotNull(artifactDef);
-
- getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
-
- componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertFalse(lastUUID.equals(componentInstances.get(0).getCustomizationUUID()));
- lastUUID = componentInstances.get(0).getCustomizationUUID();
-
- //update artifact
- //not supported now!!!!!
-// artifactDef.setDescription("new description");
-// RestResponse updateArtifactRes = ArtifactRestUtils.updateArtifactToResourceInstance(artifactDef, sdncModifierDetails, ci.getUniqueId(), service.getUniqueId());
-// BaseRestUtils.checkSuccess(updateArtifactRes);
-// artifactDef = ResponseParser.parseToObjectUsingMapper(addArtifactToResourceInstance.getResponse(), ArtifactDefinition.class);
-// assertNotNull(artifactDef);
-//
-// getService = ServiceRestUtils.getService(service.getUniqueId());
-// BaseRestUtils.checkSuccess(getService);
-// service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
-//
-// componentInstances = service.getComponentInstances();
-// assertNotNull(componentInstances);
-// assertFalse(lastUUID.equals(componentInstances.get(0).getCustomizationUUID()));
-// lastUUID = componentInstances.get(0).getCustomizationUUID();
-//
-// //delete artifact
-// RestResponse deleteArtifactRes = ArtifactRestUtils.deleteArtifactFromResourceInstance (artifactDef, sdncModifierDetails, ci.getUniqueId(), service.getUniqueId());
-// BaseRestUtils.checkSuccess(deleteArtifactRes);
-// getService = ServiceRestUtils.getService(service.getUniqueId());
-// BaseRestUtils.checkSuccess(getService);
-// service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
-//
-// componentInstances = service.getComponentInstances();
-// assertNotNull(componentInstances);
-// assertFalse(lastUUID.equals(componentInstances.get(0).getCustomizationUUID()));
- }
-
- @Test(enabled = true)
- public void resourceCustomUUIDRelationTest() throws Exception {
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-
- // create resource in checkin status
- Resource resource = createVfFromCSAR(sdncModifierDetails, "csar_1");
-
- RestResponse checkinState = LifecycleRestUtils.changeComponentState(resource, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
- BaseRestUtils.checkSuccess(checkinState);
-
- // create service
- ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncModifierDetails.getUserId());
- RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifierDetails);
- ResourceRestUtils.checkCreateResponse(createServiceResponse);
- Service service = ResponseParser.parseToObjectUsingMapper(createServiceResponse.getResponse(), Service.class);
-
- // create instance 1
- ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(resource);
- RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
- ResourceRestUtils.checkCreateResponse(createComponentInstance);
-
- ComponentInstance ci1 = ResponseParser.parseToObjectUsingMapper(createComponentInstance.getResponse(), ComponentInstance.class);
- assertNotNull(ci1.getCustomizationUUID());
- String ci1LastUUID = ci1.getCustomizationUUID();
-
- // create instance 2
- createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, sdncModifierDetails, service);
- ResourceRestUtils.checkCreateResponse(createComponentInstance);
-
- ComponentInstance ci2 = ResponseParser.parseToObjectUsingMapper(createComponentInstance.getResponse(), ComponentInstance.class);
- assertNotNull(ci2.getCustomizationUUID());
- String ci2LastUUID = ci2.getCustomizationUUID();
-
- // get service with 2 instances
- RestResponse getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
- assertEquals(2, componentInstances.size());
-
- ComponentInstance ciFrom = componentInstances.get(0);
- ComponentInstance ciTo = componentInstances.get(1);
-
- Map<String, List<RequirementDefinition>> requirements = ciFrom.getRequirements();
- assertNotNull(requirements);
- List<RequirementDefinition> listReq = requirements.get("tosca.capabilities.network.Bindable");
- assertNotNull(listReq);
- RequirementDefinition req = listReq.get(0);
-
-
- Map<String, List<CapabilityDefinition>> capabilities = ciTo.getCapabilities();
- assertNotNull(capabilities);
- List<CapabilityDefinition> listCap = capabilities.get("tosca.capabilities.network.Bindable");
- assertNotNull(listCap);
- CapabilityDefinition cap = listCap.get(0);
-
- List<CapabilityDefinition> capList = new ArrayList<>();
- capList.add(cap);
- List<RequirementDefinition> reqList = new ArrayList<>();
- reqList.add(req);
-
- RequirementCapabilityRelDef relation = ElementFactory.getReqCapRelation(ciFrom.getUniqueId(),ciTo.getUniqueId(), req.getOwnerId(), cap.getOwnerId(), cap.getType(), req.getName(), capList, reqList );
-
- RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(relation, sdncModifierDetails,service.getUniqueId(), ComponentTypeEnum.SERVICE);
- ResourceRestUtils.checkSuccess(associateInstances);
-
- getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
-
- for ( ComponentInstance ci : componentInstances){
- if ( ci.getUniqueId().equals(ci1.getUniqueId()) ){
- assertFalse( ci1LastUUID.equals(ci.getCustomizationUUID()) );
- ci1LastUUID = ci.getCustomizationUUID();
- }else{
- assertFalse( ci2LastUUID.equals(ci.getCustomizationUUID()) );
- ci2LastUUID = ci.getCustomizationUUID();
- }
- }
- associateInstances = ComponentInstanceRestUtils.dissociateInstances(relation, sdncModifierDetails,service.getUniqueId(), ComponentTypeEnum.SERVICE);
- ResourceRestUtils.checkSuccess(associateInstances);
-
- getService = ServiceRestUtils.getService(service.getUniqueId());
- BaseRestUtils.checkSuccess(getService);
- service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
- componentInstances = service.getComponentInstances();
- assertNotNull(componentInstances);
-
- for ( ComponentInstance ci : componentInstances){
- if ( ci.getUniqueId().equals(ci1.getUniqueId()) ){
- assertFalse( ci1LastUUID.equals(ci.getCustomizationUUID()) );
- }else{
- assertFalse( ci2LastUUID.equals(ci.getCustomizationUUID()) );
- }
- }
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java
deleted file mode 100644
index a3372098a0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java
+++ /dev/null
@@ -1,580 +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.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.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.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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- // String category = ServiceCategoriesEnum.MOBILITY.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> 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<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> 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<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
-
- }
-
- @Test
- public void getResourceAllVersions_version25() throws Exception {
-
- Map<String, String> origVersionsMap = new HashMap<String, String>();
-
- // 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
-
- }
-
- @Test
- public void getResourceAllVersions_ReadyForCertification_version05() throws Exception {
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- // 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
-
- }
-
- @Test
- public void getResourceAllVersions_CertifactionInProgress_version05() throws Exception {
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- // 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
-
- }
-
- @Test
- public void getResourceAllVersions_Certified_version10() throws Exception {
-
- Map<String, String> origVersionsMap = new HashMap<String, String>();
-
- // 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
-
- }
-
- @Test
- public void getResourceAllVersions_Certified_version20() throws Exception {
-
- Map<String, String> origVersionsMap = new HashMap<String, String>();
-
- // 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<String, String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java
deleted file mode 100644
index b6d9058c92..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java
+++ /dev/null
@@ -1,193 +0,0 @@
-package org.openecomp.sdc.ci.tests.execute.resource;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.IOException;
-import java.util.Arrays;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.AssertJUnit;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-/**
- * Created by chaya on 6/15/2017.
- */
-public class GetLeftPaletteTest extends ComponentBaseTest {
-
- private static Logger logger = LoggerFactory.getLogger(GetLeftPaletteTest.class.getName());
- protected User designerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- protected ResourceReqDetails vlResourceDetails;
- protected ResourceReqDetails cpResourceDetails;
- protected ResourceReqDetails vfcResourceDetails;
- protected ResourceReqDetails vfcmtResourceDetails;
- protected ResourceReqDetails vfResourceDetails;
-
-
- public static TestName name = new TestName();
-
- public GetLeftPaletteTest() {
- super(name, GetLeftPaletteTest.class.getName());
- }
-
- @BeforeClass
- public void setUp() throws Exception {
- // create VL
- vlResourceDetails = createResource(vlResourceDetails, "vlRes", ResourceTypeEnum.VL);
- checkInResource(vlResourceDetails);
-
- // create CP
- cpResourceDetails = createResource(cpResourceDetails, "cpRes", ResourceTypeEnum.CP);
- checkInResource(cpResourceDetails);
-
- // create VFC
- vfcResourceDetails = createResource(vfcResourceDetails, "vfcRes", ResourceTypeEnum.VFC);
- checkInResource(vfcResourceDetails);
-
- // create VFCMT
- vfcmtResourceDetails = createResource(vfcmtResourceDetails, "vfcmtRes", ResourceTypeEnum.VFCMT);
- checkInResource(vfcmtResourceDetails);
-
- // create VF
- vfResourceDetails = createResource(vfResourceDetails, "vfRes", ResourceTypeEnum.VF);
- checkInResource(vfResourceDetails);
- }
-
-
-
- @Test
- public void testGetLeftPaletteForPNF() throws IOException {
-
- RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "PNF");
- assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
- getResourceLatestVersionResponse.getErrorCode() == 200);
-
- String json = getResourceLatestVersionResponse.getResponse();
- JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
-
- AssertJUnit.assertTrue("check vlResource is in response",
- isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertTrue("check cpResource is in response",
- isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfcResource is not in response",
- isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfResource is not in response",
- isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfcmtResource is not in response",
- isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
-
- }
-
- @Test
- public void testGetLeftPaletteForVF() throws IOException {
-
- RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "VF");
- assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
- getResourceLatestVersionResponse.getErrorCode() == 200);
-
- String json = getResourceLatestVersionResponse.getResponse();
- JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
-
- AssertJUnit.assertTrue("check vlResource is in response",
- isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertTrue("check cpResource is in response",
- isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertTrue("check vfcResource is not in response",
- isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfResource is not in response",
- isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfcmtResource is not in response",
- isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
-
- }
-
- @Test
- public void testGetLeftPaletteForService() throws IOException {
-
- RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "SERVICE");
- assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
- getResourceLatestVersionResponse.getErrorCode() == 200);
-
- String json = getResourceLatestVersionResponse.getResponse();
- JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
-
- AssertJUnit.assertTrue("check vlResource is in response",
- isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertTrue("check cpResource is in response",
- isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfcResource is not in response",
- isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertTrue("check vfResource is not in response",
- isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
-
- AssertJUnit.assertFalse("check vfcmtResource is not in response",
- isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
-
- }
-
- private ResourceReqDetails createResource(ResourceReqDetails resDetails, String name, ResourceTypeEnum resType) throws Exception {
- resDetails = new ResourceReqDetails(name, "desc",Arrays.asList(name), "Generic", Arrays.asList("tosca.nodes.Root"), "c", "1", "111", "myIcon", resType.name());
- resDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getCategory(),
- ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory());
- RestResponse response = ResourceRestUtils.createResource(resDetails, designerDetails);
- assertTrue("response code is not 200, returned :" + response.getErrorCode(),
- response.getErrorCode() == 201);
- resDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(response));
- return resDetails;
- }
-
- private void checkInResource(ResourceReqDetails resDetails) throws IOException {
- RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resDetails, designerDetails, "0.1",
- LifeCycleStatesEnum.CHECKIN);
- AssertJUnit.assertEquals("check in operation failed", 200, checkInResponse.getErrorCode().intValue());
-
- }
-
- protected boolean isComponentInArray(String id, JSONArray component) {
- for (int i = 0; i < component.size(); i++) {
- JSONObject jobject = (JSONObject) component.get(i);
- if (jobject.get("uniqueId").toString().equals(id.toLowerCase())) {
- return true;
- }
- }
- return false;
- }
-
- @AfterClass
- public void tearDown() throws IOException {
- ResourceRestUtils.deleteResource(vlResourceDetails.getUniqueId(), designerDetails.getUserId());
- ResourceRestUtils.deleteResource(cpResourceDetails.getUniqueId(), designerDetails.getUserId());
- ResourceRestUtils.deleteResource(vfcResourceDetails.getUniqueId(), designerDetails.getUserId());
- ResourceRestUtils.deleteResource(vfcmtResourceDetails.getUniqueId(), designerDetails.getUserId());
- ResourceRestUtils.deleteResource(vfResourceDetails.getUniqueId(), designerDetails.getUserId());
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java
deleted file mode 100644
index cdfd3ec650..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java
+++ /dev/null
@@ -1,326 +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.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.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.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<NormativeTypes, Boolean> 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<String> expectedNotAbstractResourcesUniqueIdArray = new ArrayList<String>(Arrays.asList(computeUid,
- databaseUid, objectStorageUid, blockStorageUid, loadBalancerUid, portUid, networkUid));
-
- List<String> actualNotAbstarctResourcesUniqueIdArray = restResponseToListByHeader(
- getResourceNotAbstarctResponse, "name");
-
- // Collections.sort(actualNotAbstarctResourcesUniqueIdArray);
- // Collections.sort(expectedNotAbstractResourcesUniqueIdArray);
-
- List<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- String category = ServiceCategoriesEnum.MOBILITY.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String>(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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
-
- RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap);
-
- return getResourceNotAbstarctResponse;
- }
-
- protected List<String> restResponseToListByHeader(RestResponse restResponse, String restResponseHeader) {
- JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
- JsonArray jsonArray = jelement.getAsJsonArray();
-
- List<String> 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<NormativeTypesEnum, Boolean> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java
deleted file mode 100644
index df8ff58ba8..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java
+++ /dev/null
@@ -1,371 +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.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.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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- // set resource details
- ResourceReqDetails resourceDetails = new ResourceReqDetails();
- resourceDetails.setDescription("updatedDescription");
- ArrayList<String> resourceTags = new ArrayList<String>();
- // 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- // String category = ResourceCategoriesEnum.MOBILITY.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add("tag1");
- String category = ServiceCategoriesEnum.MOBILITY.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
-
- // set resource details
- String resourceName = "ResForUpdate";
- String description = "updatedDescription";
- ArrayList<String> resourceTags = new ArrayList<String>();
- resourceTags.add("tag1");
- resourceTags.add("tag2");
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java
deleted file mode 100644
index f4a4fa108a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java
deleted file mode 100644
index 3002523ccb..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java
+++ /dev/null
@@ -1,124 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java
deleted file mode 100644
index 5b68b0fa84..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java
+++ /dev/null
@@ -1,2301 +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.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.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<String> Empty_List = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add("tag2");
- String category = ServiceCategoriesEnum.MOBILITY.getValue();
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
- // 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<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String> tagsList = Arrays.asList(resourceDetails.getName());
- List<String> 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<String> 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<String> 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<String> resourceTag = new ArrayList<String>();
- 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<String> resourceList = new ArrayList<String>();
- 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<String> tags = updatedResourceDetails.getTags();
-
- for (Iterator<String> 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<String> resourceList = new ArrayList<String>();
- 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<String> resource_Name = new ArrayList<String>();
- List<String> resourceList = new ArrayList<String>();
-
- ArrayList<String> resourceTags = new ArrayList<String>();
- 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<String> resourceList = new ArrayList<String>();
-
- 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<String> resourceList = new ArrayList<String>();
- 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<String> resourceList = new ArrayList<String>();
- 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<String> resourceList = new ArrayList<String>();
- 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<String> tagList = new ArrayList<String>();
- tagList.add(0, "updatedResourceName");
- resourceDetails.setTags(tagList);
-
- RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
- // validate response
- List<String> resourceList = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- 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<String> drivenFrom = new ArrayList<String>();
- drivenFrom.add(0, "tosca.nodes.Container.Application");
- updatedResourceDetails.setDerivedFrom(drivenFrom);
-
- RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
- // validate response
- List<String> resourceList = new ArrayList<String>();
- 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<String> myList = new ArrayList<String>();
- 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<String> myList = new ArrayList<String>();
- 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());
- // contactId norm
- 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());
- // contactId norm
- 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());
- // contactId norm
- 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());
- // contactId norm
- resourceDetails.setContactId(updatedContactId.toLowerCase());
- parseResponseAndValidate(resourceDetails, updatedRestResponse);
-
- ////////////////////////////// **************//////////////////////////////
- List<String> 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(updatedTagField);
- // set description
- resourceDetails.setTags(resourceTags);
- List<String> 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<String>();
- // 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<String>();
- 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<String>();
- 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<String> myArray = new ArrayList<String>();
- 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<String>();
- 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<String> 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<String> resourceTags = new ArrayList<String>();
-
- String updatedTagField;
- RestResponse updatedRestResponse;
- List<String> variables = Arrays.asList("Resource", "tag");
-
- for (int i = 0; i < notValidCharsArray.length; i++) {
- updatedTagField = "UpdatedTag" + notValidCharsArray[i];
- resourceTags = new ArrayList<String>();
- 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<String> resourceList = new ArrayList<String>();
- 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<String>();
- 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<String>();
- 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<String> 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<String> 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<String> 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<String> variables = new ArrayList<>();
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, updatedRestResponse.getResponse());
-
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java
deleted file mode 100644
index 895390f764..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java
+++ /dev/null
@@ -1,480 +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.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.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<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> resourceDetailsVF_01e = AtomicOperationUtils
- .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true);
- resourceDetailsVF = new ResourceReqDetails(resourceDetailsVF_01e.left().value());
- Either<Resource, RestResponse> 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<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<String> variables = Arrays.asList("Resource Instance");
- // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_COMPONENT_NAME.name(),
- // variables, updateResourceInstanceResponse.getResponse());
-
- resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
-
- // validate RI name
- List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<String> variables = Arrays.asList("Resource Instance", "50");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), variables,
- updateResourceInstanceResponse.getResponse());
-
- resourceInstanceReqDetailsCP.setName(prevName);
- // validate RI name
- List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<String> variables = Arrays.asList("Resource Instance");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), variables,
- updateResourceInstanceResponse.getResponse());
-
- resourceInstanceReqDetailsCP.setName(prevValue);
-
- // validate RI name
- List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
- List<String> resourceInstanceListName = new ArrayList<String>();
- for (int i = 0; i < resourceInstances.size(); i++) {
- resourceInstanceListName.add(resourceInstances.get(i).getName());
- }
- List<String> resourceInstanceExpectedListName = new ArrayList<String>();
- 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<String> tags = new ArrayList<String>();
- 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<String> tags = new ArrayList<String>();
- // 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java
deleted file mode 100644
index 37e7539fd9..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java
+++ /dev/null
@@ -1,315 +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.resource;
-
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-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.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.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<Resource, RestResponse> resourceDetailsVFe = AtomicOperationUtils
- .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true);
- resourceDetailsVF = resourceDetailsVFe.left().value();
- Either<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource> 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<Resource> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java
deleted file mode 100644
index dddab57873..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java
+++ /dev/null
@@ -1,1795 +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.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.CapabilityRequirementRelationship;
-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.RelationshipInfo;
-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<CapabilityDefinition> capList = capReqDef.getCapabilities().get("tosca.capabilities.Container");
- List<RequirementDefinition> reqList = capReqDef.getRequirements().get("tosca.capabilities.Container");
-
- RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
- requirementDef.setFromNode(riReq.getUniqueId());
- requirementDef.setToNode(riCap.getUniqueId());
-
- RelationshipInfo pair = new RelationshipInfo();
- 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<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- relationships.add(capReqRel);
- capReqRel.setRelation(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<RequirementDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java
deleted file mode 100644
index c8a20cf44a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java
+++ /dev/null
@@ -1,1008 +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.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.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.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;
-
-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<String> 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<String>();
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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<String>(),
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java
deleted file mode 100644
index 56cfeb54ea..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java
+++ /dev/null
@@ -1,1300 +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.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 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.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.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.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<String> 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<String> 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<String> 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<String> 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<String> tags = new ArrayList<String>();
- 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<String> 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<String> 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<String> tags = new ArrayList<String>();
- 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<String> 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<String> 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<String> 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<String> tags = new ArrayList<String>();
- 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<String> 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<String> 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<String> 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<String> 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<String, String> 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<String> variables = new ArrayList<String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java
deleted file mode 100644
index 760d002856..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java
+++ /dev/null
@@ -1,350 +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.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.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<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
-
- }
-
- @Test
- public void GetAllServiceVersions_Version01() throws Exception {
-
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
-
- RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
- Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
- Map<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
- }
-
- @Test
- public void GetAllServiceVersions_Version15() throws Exception {
- // addMandatoryArtifactsToService();
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
- }
-
- @Test
- public void GetAllServiceVersions_Version25() throws Exception {
- // addMandatoryArtifactsToService();
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
- }
-
- @Test
- public void GetAllServiceVersions_ReadyForCertification_version05() throws Exception {
- // addMandatoryArtifactsToService();
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
- }
-
- @Test
- public void GetAllServiceVersions_CertifactionInProgress_version05() throws Exception {
- // addMandatoryArtifactsToService();
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
- }
-
- @Test
- public void GetAllServiceVersions_Certified_version10() throws Exception {
- // addMandatoryArtifactsToService();
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- // 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<String, String> getVersionsMap = res.getAllVersions();
- assertTrue(origVersionsMap.equals(getVersionsMap));
- }
-
- @Test
- public void GetAllServiceVersions_Certified_version20() throws Exception {
- // addMandatoryArtifactsToService();
- Map<String, String> origVersionsMap = new HashMap<String, String>();
- // 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<String, String> 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<String> variables = Arrays.asList("123456789");
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables,
- serviceGetResponse.getResponse());
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java
deleted file mode 100644
index 846b5d24d3..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java
+++ /dev/null
@@ -1,368 +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.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 org.apache.http.HttpStatus;
-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 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<String, Exception> 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<String> versionZeroOneIDWrapper = new Wrapper<String>(),
- versionZeroTwoIDWrapper = new Wrapper<String>();
-
- 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<String> 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<String, String> headers = new HashMap<String, String>() {
- {
- 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<String> versionZeroOneIDWrapper,
- Wrapper<String> 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<String> 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<String> versionZeroOneIDWrapper = new Wrapper<String>(),
- versionZeroTwoIDWrapper = new Wrapper<String>();
-
- 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<String> versionZeroOneIDWrapper = new Wrapper<String>(),
- versionZeroTwoIDWrapper = new Wrapper<String>();
-
- 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<String> versionOnePointTwoIDWrapper = new Wrapper<String>();
-
- 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<String> versionOnePointTwoIDWrapper = new Wrapper<String>();
-
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java
deleted file mode 100644
index 19bed4d380..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java
+++ /dev/null
@@ -1,684 +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.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.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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<Service> 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<String>(),
- 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<String>(),
- 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<Service> 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<Service> 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<Service> restResponseToResourceObjectList(RestResponse restResponse) {
- JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
- JsonArray jsonArray = jelement.getAsJsonArray();
- List<Service> 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<Service> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java
deleted file mode 100644
index fdec8346fc..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java
+++ /dev/null
@@ -1,1194 +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.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.CapabilityRequirementRelationship;
-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.RelationshipInfo;
-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<String, List<CapabilityDefinition>>();
- expectedContainerRequirements = new LinkedHashMap<String, List<RequirementDefinition>>();
- 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<String> varibales = new ArrayList<String>();
- 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<String> varibales = new ArrayList<String>();
- 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<String> varibales = new ArrayList<String>();
- 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<String> varibales = new ArrayList<String>();
- 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<String> varibales = new ArrayList<String>();
- 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<RequirementCapabilityRelDef> 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<RequirementCapabilityRelDef> getComponentInstancesRelations(String resourceUniqueId)
- throws ClientProtocolException, IOException {
- Resource resource = getVfAsResourceObject(resourceUniqueId);
- List<RequirementCapabilityRelDef> 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());
-
- RelationshipInfo pair = new RelationshipInfo();
- 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<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- relationships.add(capReqRel);
- capReqRel.setRelation(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<RequirementDefinition> requirements;
- List<CapabilityDefinition> 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<ComponentInstance> listOfComponentInstances = component.getComponentInstances();
-
- for (ComponentInstance instance : listOfComponentInstances) {
- if (instance.getComponentUid().equals(vfWithCapabilities.getUniqueId())) {
- List<CapabilityDefinition> capFromResource = vfWithCapabilities.getCapabilities()
- .get(CapabilitiesAndRequirementsType);
- List<CapabilityDefinition> 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<RequirementDefinition> reqFromAtomicResource = vfWithRequirements.getRequirements()
- .get(CapabilitiesAndRequirementsType);
- List<RequirementDefinition> 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<CapabilityDefinition> capList, List<RequirementDefinition> reqList,
- String vfc1UniqueId, String vfc2UniqueId) {
- return ElementFactory.getReqCapRelation(reqCompInstId, capCompInstId, vfc1UniqueId, vfc2UniqueId, capType,
- reqName, capList, reqList);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
deleted file mode 100644
index ce2c996cc6..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
+++ /dev/null
@@ -1,1407 +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.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.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.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.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);
- LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncAdminDetails, "0.1",
- LifeCycleStatesEnum.CHECKIN);
- createAtomicResource(resourceDetailsVL_01);
- createAtomicResource(resourceDetailsVL_02);
- createVF(resourceDetailsVF_01);
- createVF(resourceDetailsVF_02);
- createPNF(resourceDetailsPNF_01);
- createService(serviceDetails_01);
- certifyResource(resourceDetailsVFC_01);
- certifyResource(resourceDetailsVFC_02);
- 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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 createCheckedinPNFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
- return createCheckedinVFInstance(containerDetails, compInstOriginDetails, modifier);
- }
-
- private RestResponse createCheckedinAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
- changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN);
- return createAtomicInstanceForService(containerDetails, compInstOriginDetails, modifier);
- }
-
- 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 createPNFInstanceSuccessfullyTest() throws Exception {
- RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createPNFInstResp);
- getComponentAndValidateRIs(serviceDetails_01, 1, 0);
-// createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
-// ResourceRestUtils.checkCreateResponse(createVFInstResp);
-// getComponentAndValidateRIs(serviceDetails_01, 2, 0);
- }
-
- @Test
- public void createVFAndAtomicInstanceTest() throws Exception {
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createVFInstResp);
- 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 createPNFAndAtomicInstanceTest() throws Exception {
- RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createPNFInstResp);
- RestResponse createVLInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createVLInstResp);
- getComponentAndValidateRIs(serviceDetails_01, 2, 0);
-
-
- }
-
- private String createCpInstance() throws Exception {
- // Create CP instance
- RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsPNF_01,
- resourceDetailsCP_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
- getComponentAndValidateRIs(resourceDetailsPNF_01, 1, 0);
- return ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
- }
-
- @Test
- public void createPNFAndAtomicInstanceAssociatedTest() throws Exception {
- reqOwnerId = createCpInstance();
- RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createPNFInstResp);
- String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createPNFInstResp);
- RestResponse createVLInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(createVLInstResp);
- capOwnerId = ResponseParser.getUniqueIdFromResponse(createVLInstResp);
- String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVLInstResp);
-
- String capType = "tosca.capabilities.network.Linkable";
- String reqName = "link";
-
- RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- ResourceRestUtils.checkSuccess(getResourceResponse);
- CapReqDef capReqDef = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), CapReqDef.class);
- List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
-
- RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, capList, reqList);
-
- associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
- getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- capReqDef = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), CapReqDef.class);
- List<RequirementDefinition> list = capReqDef.getRequirements().get(capType);
-// AssertJUnit.assertEquals("Check requirement", null, list);
- getComponentAndValidateRIsOnly(serviceDetails_01, 2, 1);
- }
-
- @Test
- public void deleteAtomicInstanceTest() throws Exception {
- RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
- // 1 rel
- 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
-
- RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, capList, reqList);
-
- associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
- getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
- List<RequirementDefinition> 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<CapabilityDefinition> capList, List<RequirementDefinition> reqList) {
- return ElementFactory.getReqCapRelation(reqCompInstId, capCompInstId, reqOwnerId, capOwnerId, capType, reqName, capList, reqList);
- }
-
- @Test
- public void createResourceInstanceByDifferentDesignerTest() throws Exception {
- createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409);
- createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(), resourceDetailsVF_01, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409);
- createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(), resourceDetailsVF_01, sdncDesignerDetails, 409);
- createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsCP_01, sdncDesignerDetails, 409);
- getComponentAndValidateRIs(serviceDetails_01, 0, 0);
- }
-
- @Test
- public void createResourceInstanceWithEmptyUserIdTest() throws Exception {
- sdncDesignerDetails.setUserId("");
- createVFInstanceFail(ActionStatus.MISSING_INFORMATION, new ArrayList<String>(), resourceDetailsVF_01, sdncDesignerDetails, 403);
- createAtomicResourceInstanceFail(ActionStatus.MISSING_INFORMATION, new ArrayList<String>(), 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<String>(Arrays.asList("")), resourceDetailsVF_01, sdncDesignerDetails, 404);
- createAtomicResourceInstanceFailWithoutChangeState(ActionStatus.RESOURCE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")), resourceDetailsCP_01, sdncDesignerDetails, 404);
- }
-
- @Test
- public void createResourceInstanceInServiceNotExistsTest() throws Exception {
- serviceDetails_01.setUniqueId("1234");
- createVFInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")), resourceDetailsVF_01, sdncDesignerDetails, 404);
- createAtomicResourceInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")), resourceDetailsCP_01, sdncDesignerDetails, 404);
- }
-
- @Test
- public void createResourceInstanceInCheckedinServiceTest() throws Exception {
- changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
-
- createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01, sdncDesignerDetails, 409);
- createAtomicResourceInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(Arrays.asList(vfResource.getName())));
- createVF(vfResource, designer2);
-
- RestResponse atomicInstanceForService = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01, sdncDesignerDetails);
- ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
- createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<ComponentInstance> 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<String>(Arrays.asList(unsupportedType)), 400, createResourceInstanceResponse);
- }
-
- @Test
- public void deleteResourceInstanceByDifferentDesignerTest() throws Exception {
-
- createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
-
- deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409);
- deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(), resourceDetailsVF_01, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409);
- deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(), resourceDetailsVF_01, notASDCUser, 409);
- deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(), resourceDetailsVF_01, sdncDesignerDetails, 409);
- deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<String>(Arrays.asList("")), resourceDetailsVF_01, sdncDesignerDetails, 404);
- deleteAtomicResourceInstanceFail(ActionStatus.RESOURCE_NOT_FOUND, new ArrayList<String>(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<String>(Arrays.asList("")), resourceDetailsVF_01, sdncDesignerDetails, 404);
- deleteAtomicResourceInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(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<String>(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<String>(), resourceDetailsVF_01, sdncDesignerDetails, 409);
- deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), 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<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements().get(CAPABILITY_TYPE);
- List<CapabilityDefinition> capListBeforeAssociate = new ArrayList<CapabilityDefinition>();
- 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<String>(Arrays.asList(capCompInstId)));
-
- CapReqDef capReqDefAfterAssociate = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>(Arrays.asList(capCompInstId)));
- //////////////////////////////////////////////
-
- CapReqDef capReqDefAfterAssociate = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- List<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>(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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
-
- // for (CapabilityDefinition capabilityDefinition :
- // capListBeforeAssociate) {
- // if (capabilityDefinition.getType().equals(CAPABILITY_TYPE)){
- // capabilityDefinition.setMinOccurrences("0");
- // }
- // }
- //
- // List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>());
-
- CapReqDef capReqDefAfterAssociate = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>());
-
- CapReqDef capReqDefAfterAssociate = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>());
- assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
- assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
- assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.OPS), ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
- assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1), ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
-
- CapReqDef capReqDefAfterAssociate = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
- List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String> 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<String> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements().get(CAPABILITY_TYPE);
-
- RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
-
- List<String> variables = new ArrayList<String>();
- 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<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeSeconderyAssociate = capReqDefBeforeSeconderyAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListAfterSeconderyAssociate = capReqDefAfterSeconderyAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> reqList = capReqDef.getRequirements().get(CAPABILITY_TYPE);
-
- RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capList, reqList);
-
- List<String> variables = new ArrayList<String>();
- 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<CapabilityDefinition> capListAfterDissociate = capReqDefAfterDissociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>(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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements().get(CAPABILITY_TYPE);
-
- RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
-
- List<String> variables = new ArrayList<String>();
- 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<CapabilityDefinition> capListAfterDissociate = capReqDefAfterDissociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String>());
- }
-
- @Test
- public void dissoicateWithEmptyUserIdHeaderTest() throws Exception {
- sdncDesignerDetails.setUserId("");
- RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
- dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
- }
-
- @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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<String> variables = new ArrayList<String>();
- 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<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities().get(CAPABILITY_TYPE);
- List<RequirementDefinition> 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<CapabilityDefinition> capListAfterAssociate =
- // capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
- // List<RequirementDefinition> 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<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
- List<RequirementDefinition> 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<RequirementDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java
deleted file mode 100644
index def34958eb..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java
+++ /dev/null
@@ -1,2164 +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.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.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<String> listForMessage = new ArrayList<String>();
-
- 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<String> 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<String> 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<String> 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<String> arrList, RestResponse response)
- throws Exception, JSONException {
- ErrorValidationUtils.checkBodyResponseOnError(actionStatus.name(), arrList, response.getResponse());
- }
-
- protected List<String> addServiceNameToTagsList(String serviceName, List<String> 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<String> 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 <html></html>";
- // serviceDetails.setDescription(newDescription);
- // List<String> 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<String> 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<String>(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<CategoryDefinition> 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);
- }
-
- @Test
- public void environmentContextService() throws Exception {
- updatedServiceDetails.setEnvironmentContext("General_Revenue-Bearing");
- RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
- validateResponse(updateServiceResponse, 200, null, listForMessage);
- Service actualService = ResponseParser.convertServiceResponseToJavaObject(updateServiceResponse.getResponse());
- assertEquals(updatedServiceDetails.getEnvironmentContext(), actualService.getEnvironmentContext());
- }
-
- // 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<String>());
- 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<CategoryDefinition> 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<String> 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<String> 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<String> 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("<html>Hello, <b>world!</b></html>");
- 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("&amp;&lt;&gt;");
- 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<String> 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<String> 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<String> variables = new ArrayList<String>();
- // 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<String> variables = new ArrayList<String>();
- // 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java
deleted file mode 100644
index e1bc3c9dde..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java
+++ /dev/null
@@ -1,756 +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.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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<List<User>> typeToken = new TypeToken<List<User>>() {
- };
- List<User> listOfUsersOnResponse = gson.fromJson(getAllAdminUsers.getResponse(), typeToken.getType());
- logger.debug("listOfUsers: {}", listOfUsersOnResponse);
-
- // build map of all Admin users from listOfUsersOnResponse from
- // response
- Map<String, User> mapAllUsersOnResponse = new HashMap<String, User>();
- 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<String, User> 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<String> 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<String> 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<String> resourceExpectedUniqIdList = new ArrayList<String>();
- 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<String> 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<String> resourceExpectedUniqIdList = new ArrayList<String>();
- 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<String> 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<ServiceReqDetails> serviceReqDetailsListOnResponse = new ArrayList<ServiceReqDetails>();
- 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<String> 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<ResourceReqDetails> resourceReqDetailsListOnResponse = new ArrayList<ResourceReqDetails>();
- 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<String> resourceActualUniqIdList = new ArrayList<String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java
deleted file mode 100644
index 2a79539443..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java
+++ /dev/null
@@ -1,1693 +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.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 - UserId
- // @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 - UserId
- // @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 - UserId
- // @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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java
deleted file mode 100644
index 7d0ef75cf5..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java
+++ /dev/null
@@ -1,317 +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.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.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.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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java
deleted file mode 100644
index c80f6c612d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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<String> 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<String>();
- 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<String> getRelevantArtifactTypes() {
- return relevantArtifactTypes;
- }
-
- public void setRelevantArtifactTypes(List<String> 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/postupgrade/AttKeyPropertiesRenameTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/postupgrade/AttKeyPropertiesRenameTest.java
deleted file mode 100644
index 4ae4c17bea..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/postupgrade/AttKeyPropertiesRenameTest.java
+++ /dev/null
@@ -1,95 +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.migration.v1707.postupgrade;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-import static org.testng.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.migration.v1707.CommonMigrationUtils;
-import org.openecomp.sdc.ci.tests.utils.graph.GraphFileUtils;
-import org.testng.annotations.Test;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-public class AttKeyPropertiesRenameTest extends ComponentBaseTest {
-
- @Rule
- public static TestName name = new TestName();
-
-
- public AttKeyPropertiesRenameTest() {
- super(name, AttKeyPropertiesRenameTest.class.getName());
- }
-
- @Test
- public void verifyAttPropertyKeys() throws Exception {
- initGraph();
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "attContact");
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "attCreator");
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "attuid");
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "pmatt");
-
- CommonMigrationUtils.assertKeyExists(titanGraph, "userId");
- CommonMigrationUtils.assertKeyExists(titanGraph, "projectCode");
- CommonMigrationUtils.assertKeyExists(titanGraph, "contactId");
- CommonMigrationUtils.assertKeyExists(titanGraph, "creatorId");
-
- verifyPropertyKeysVerticesSameAsPreUpgrade("attuid", "userId");
- verifyPropertyKeysVerticesSameAsPreUpgrade("pmatt", "projectCode");
- verifyPropertyKeysVerticesSameAsPreUpgrade("attContact", "contactId");
- verifyPropertyKeysVerticesSameAsPreUpgrade("attCreator", "creatorId");
-
- }
-
- private void assertKeyNotExist(String key) {
- assertNotNull(titanGraph.getPropertyKey(key));
- }
-
- private void assertKeyExists(String key) {
- assertNull(titanGraph.getPropertyKey(key));
- }
-
- private void verifyPropertyKeysVerticesSameAsPreUpgrade(String oldPropertyKEyName, String newPropertyKeyName) throws IOException {
- List<String> verticesIdsFromGraph = getVerticesIdsFromGRaph(newPropertyKeyName);
- List<String> verticesIdsFromFile = GraphFileUtils.getVerticesIdsFromFile(oldPropertyKEyName);
- Collections.sort(verticesIdsFromFile);
- Collections.sort(verticesIdsFromGraph);
- assertEquals(verticesIdsFromFile, verticesIdsFromGraph);
- }
-
- private List<String> getVerticesIdsFromGRaph(String newPropertyKeyName) {
- Iterable<TitanVertex> vertices = titanGraph.query().has(newPropertyKeyName).vertices();
- assertTrue(vertices.iterator().hasNext());
- List<String> verticesIdsFromGraph = new ArrayList<>();
- vertices.forEach(vertex -> verticesIdsFromGraph.add(vertex.id().toString()));
- return verticesIdsFromGraph;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/preupgrade/AttKeyPropertiesBeforeRenameTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/preupgrade/AttKeyPropertiesBeforeRenameTest.java
deleted file mode 100644
index 4369d75a74..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/preupgrade/AttKeyPropertiesBeforeRenameTest.java
+++ /dev/null
@@ -1,70 +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.migration.v1707.preupgrade;
-
-import static org.testng.Assert.assertTrue;
-
-import java.io.IOException;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.migration.v1707.CommonMigrationUtils;
-import org.openecomp.sdc.ci.tests.utils.graph.GraphFileUtils;
-import org.testng.annotations.Test;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-public class AttKeyPropertiesBeforeRenameTest extends ComponentBaseTest {
-
-
- @Rule
- public static TestName name = new TestName();
-
- public AttKeyPropertiesBeforeRenameTest() {
- super(name, AttKeyPropertiesBeforeRenameTest.class.getName());
- }
-
- @Test
- public void verifyAttPropertyKeys() throws Exception {
- initGraph();
- CommonMigrationUtils.assertKeyExists(titanGraph, "attContact");
- CommonMigrationUtils.assertKeyExists(titanGraph, "attCreator");
- CommonMigrationUtils.assertKeyExists(titanGraph, "attuid");
- CommonMigrationUtils.assertKeyExists(titanGraph, "pmatt");
-
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "userId");
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "projectCode");
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "contactId");
- CommonMigrationUtils.assertKeyNotExist(titanGraph, "creatorId");
-
- saveVerticesWithPropertyKeyToFile("attContact");
- saveVerticesWithPropertyKeyToFile("attCreator");
- saveVerticesWithPropertyKeyToFile("attuid");
- saveVerticesWithPropertyKeyToFile("pmatt");
- }
-
- private void saveVerticesWithPropertyKeyToFile(String propertyKey) throws IOException {
- Iterable<TitanVertex> vertices = titanGraph.query().has(propertyKey).vertices();
- assertTrue(vertices.iterator().hasNext());
- GraphFileUtils.writeVerticesUIDToFile(propertyKey, vertices);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java
deleted file mode 100644
index 14c7a37101..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java
+++ /dev/null
@@ -1,177 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java
deleted file mode 100644
index bde68528bf..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java
deleted file mode 100644
index add06a587c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java
+++ /dev/null
@@ -1,96 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java
deleted file mode 100644
index 799309e55d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java
+++ /dev/null
@@ -1,82 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java
deleted file mode 100644
index 338adfd094..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java
+++ /dev/null
@@ -1,273 +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.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.testng.TestNG;
-
-public class StartTest {
-
- // private List<Class<? extends AttSdcTest>> testClasses = new
- // ArrayList<Class<? extends AttSdcTest>>();
- 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<String> suites = new ArrayList<String>();
- 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<Class> getClassesForPackage(String pkgname) {
-
- List<Class> classes = new ArrayList<Class>();
-
- // 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<JarEntry> 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("<tr>");
- results.append("<th>").append("Unit Test").append("</th>");
- results.append("<th>").append("Result").append("</th>");
- results.append("</tr>");
- }
-
- // private void addUnitTestResult(StringBuilder results,
- // Class<? extends AttSdcTest> testClass, Result unitTestResult) {
- //
- // boolean isSuccess = unitTestResult.wasSuccessful();
- //
- // String result = (isSuccess) ? "success" : "fail";
- // String fileName = FileUtils.getFileName(testClass.getName());
- // results.append("<tr>");
- // //
- // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
- // results.append("<td class=\"name\">")
- // .append("<a href=\"" + fileName + timeOfTest + ".html\">"
- // + fileName + "</a>").append("</td>");
- // results.append("<td class=\"" + result + "\">").append(result)
- // .append("</td>");
- // results.append("</tr>");
- // }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java
deleted file mode 100644
index 56ddc196cb..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java
+++ /dev/null
@@ -1,410 +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.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<Class<? extends AttSdcTest>> testClasses = new ArrayList<Class<? extends AttSdcTest>>();
- 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<String> 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<String> packages, boolean exitOnFailure) {
-
- boolean success = true;
- StringBuilder results = new StringBuilder();
- Result result;
-
- if (packages == null) {
- return;
- }
-
- for (String packageName : packages) {
- // List<Class> classesForPackage =
- // getClassesForPackage("org.openecomp.sdc.ci.tests.execute");
- List<Class> 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(
- "<Html><head><style>th{background-color: gray;color: white;height: 30px;}td {color: black;height: 30px;}.fail {background-color: #FF5555;width: 100px;text-align: center;}.success {background-color: #00FF00;width: 100px;text-align: center;}.name {width: 200px;background-color: #F0F0F0;}.message {width: 300px;background-color: #F0F0F0;}</style></head><body>");
-
- Calendar calendar = Calendar.getInstance();
- timeOfTest = calendar.getTimeInMillis();
- SimpleDateFormat date_format = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
- results.append("<br/><h2> This report generated on " + date_format.format(calendar.getTime()) + "</h2><br/>");
-
- results.append("<table>");
- addTableHead(results);
-
- int size = testClasses.size();
- int index = 0;
-
- int totalRunTests = 0;
- int totalFailureTests = 0;
- int totalIgnoreTests = 0;
- int numOfFailureClasses = 0;
- for (Class<? extends AttSdcTest> 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<Failure> 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<Failure> 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("</table>");
- results.append("<br/><h2> Tests Summary: </h2><br/>");
- results.append("Total Runs : " + totalRunTests + "<br/>");
- results.append("Total Failure : " + totalFailureTests + "<br/>");
- results.append("Total: " + totalFailureTests + "/" + totalRunTests + "<br/>");
- results.append("</html>");
-
- 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<Class> getClassesForPackage(String pkgname) {
-
- List<Class> classes = new ArrayList<Class>();
-
- // 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<JarEntry> 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("<tr>");
- results.append("<th>").append("Unit Test").append("</th>");
- results.append("<th>").append("Result").append("</th>");
- results.append("</tr>");
- }
-
- private void addUnitTestResult(StringBuilder results, Class<? extends AttSdcTest> testClass,
- Result unitTestResult) {
-
- boolean isSuccess = unitTestResult.wasSuccessful();
-
- String result = (isSuccess) ? "success" : "fail";
- String fileName = FileUtils.getFileName(testClass.getName());
- results.append("<tr>");
- // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
- results.append("<td class=\"name\">")
- .append("<a href=\"" + fileName + timeOfTest + ".html\">" + fileName + "</a>").append("</td>");
- results.append("<td class=\"" + result + "\">").append(result).append("</td>");
- results.append("</tr>");
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java
deleted file mode 100644
index b676b29bda..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java
+++ /dev/null
@@ -1,287 +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.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<String> variablesAsList = new ArrayList<String>();
-
- @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<Service, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> 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<ArtifactDefinition> artifacts = resourceDetailsVF_01.getDeploymentArtifacts().values();
- List<String> 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<List<ComponentInstanceProperty>> componentInstancesProperties = resourceDetailsVF_01.getComponentInstancesProperties().values();
- List<String> 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<Pair<Component, ComponentInstance>, 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<Resource, RestResponse> 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<HeatParameterDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
deleted file mode 100644
index 1cc4626f49..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.sanity;
-
-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.enums.ResourceTypeEnum;
-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;
-
-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<ComponentInstanceReqDetails> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java
deleted file mode 100644
index 76c0c86680..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.tosca.datatypes;
-
-public class ToscaCapabilitiesNodeTemplatesDefinition {
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
deleted file mode 100644
index 766d4d9fd5..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.tosca.datatypes;
-
-import java.util.List;
-
-/**
- * First Level tosca yml structure
- * @author al714h
- *
- */
-public class ToscaDefinition {
-
- String toscaDefinitionVersion;
- List<ToscaImportsDefinition> toscaImports;
- List<ToscaNodeTypesDefinition> toscaNodeTypes;
- ToscaTopologyTemplateDefinition toscaTopologyTemplate;
-
- public ToscaDefinition() {
- super();
- }
-
- public String getToscaDefinitionVersion() {
- return toscaDefinitionVersion;
- }
-
- public void setToscaDefinitionVersion(String toscaDefinitionVersion) {
- this.toscaDefinitionVersion = toscaDefinitionVersion;
- }
-
- public List<ToscaImportsDefinition> getToscaImports() {
- return toscaImports;
- }
-
- public void setToscaImports(List<ToscaImportsDefinition> toscaImports) {
- this.toscaImports = toscaImports;
- }
-
- public List<ToscaNodeTypesDefinition> getToscaNodeTypes() {
- return toscaNodeTypes;
- }
-
- public void setToscaNodeTypes(List<ToscaNodeTypesDefinition> toscaNodeTypes) {
- this.toscaNodeTypes = toscaNodeTypes;
- }
-
- public ToscaTopologyTemplateDefinition getToscaTopologyTemplate() {
- return toscaTopologyTemplate;
- }
-
- public void setToscaTopologyTemplate(ToscaTopologyTemplateDefinition toscaTopologyTemplate) {
- this.toscaTopologyTemplate = toscaTopologyTemplate;
- }
-
- @Override
- public String toString() {
- return "ToscaDefinition [toscaDefinitionVersion=" + toscaDefinitionVersion + ", toscaImports=" + toscaImports
- + ", toscaNodeTypes=" + toscaNodeTypes + ", toscaTopologyTemplate=" + toscaTopologyTemplate + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java
deleted file mode 100644
index e19fcb3aba..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.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.ci.tests.tosca.datatypes;
-
-import java.util.List;
-
-// spec page 102
-public class ToscaGroupsTopologyTemplateDefinition {
-
- String type; // required
- String description;
- // List<ToscaGroupsProperiesDefinition> toscaGroupsProperiesDefinition;
- List<String> targets; // required
- // List<ToscaGroupsInterfacesDefinition> toscaGroupsInterfacesDefinition;
- List<String> members;
-
- public ToscaGroupsTopologyTemplateDefinition() {
- super();
- // TODO Auto-generated constructor stub
- }
-
- 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 List<String> getTargets() {
- return targets;
- }
-
- public void setTargets(List<String> targets) {
- this.targets = targets;
- }
-
- public List<String> getMembers() {
- return members;
- }
-
- public void setMembers(List<String> members) {
- this.members = members;
- }
-
- @Override
- public String toString() {
- return "ToscaGroupsTopologyTemplateDefinition [type=" + type + ", description=" + description + ", targets="
- + targets + ", members=" + members + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java
deleted file mode 100644
index 5363223c38..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java
+++ /dev/null
@@ -1,59 +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.tosca.datatypes;
-
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
-
-public class ToscaImportsDefinition {
-
- String typeName;
-
- List<GroupHeatMetaDefinition> groupHeatMetaDefinition;
-
- public ToscaImportsDefinition() {
- super();
- }
-
- public String getTypeName() {
- return typeName;
- }
-
- public void setTypeName(String typeName) {
- this.typeName = typeName;
- }
-
- public List<GroupHeatMetaDefinition> getGroupHeatMetaDefinition() {
- return groupHeatMetaDefinition;
- }
-
- public void setGroupHeatMetaDefinition(List<GroupHeatMetaDefinition> groupHeatMetaDefinition) {
- this.groupHeatMetaDefinition = groupHeatMetaDefinition;
- }
-
- @Override
- public String toString() {
- return "TypeHeatMetaDefinition [typeName=" + typeName + ", groupHeatMetaDefinition=" + groupHeatMetaDefinition
- + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java
deleted file mode 100644
index 62f859c567..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.tosca.datatypes;
-
-public class ToscaInputsTopologyTemplateDefinition {
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java
deleted file mode 100644
index 8970467e9c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.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.tosca.datatypes;
-
-import java.util.List;
-
-public class ToscaNodeTemplatesTopologyTemplateDefinition {
-
- String name;
- String type;
- List<ToscaPropertiesNodeTemplatesDefinition> properties;
- List<ToscaRequirementsNodeTemplatesDefinition> requirements;
- List<ToscaCapabilitiesNodeTemplatesDefinition> capabilities;
-
- public ToscaNodeTemplatesTopologyTemplateDefinition() {
- super();
- }
-
- 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 List<ToscaPropertiesNodeTemplatesDefinition> getProperties() {
- return properties;
- }
-
- public void setProperties(List<ToscaPropertiesNodeTemplatesDefinition> properties) {
- this.properties = properties;
- }
-
- public List<ToscaRequirementsNodeTemplatesDefinition> getRequirements() {
- return requirements;
- }
-
- public void setRequirements(List<ToscaRequirementsNodeTemplatesDefinition> requirements) {
- this.requirements = requirements;
- }
-
- public List<ToscaCapabilitiesNodeTemplatesDefinition> getCapabilities() {
- return capabilities;
- }
-
- public void setCapabilities(List<ToscaCapabilitiesNodeTemplatesDefinition> capabilities) {
- this.capabilities = capabilities;
- }
-
- @Override
- public String toString() {
- return "ToscaNodeTemplatesTopologyTemplateDefinition [name=" + name + ", type=" + type + ", properties="
- + properties + ", requirements=" + requirements + ", capabilities=" + capabilities + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java
deleted file mode 100644
index 148e99c58c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java
+++ /dev/null
@@ -1,54 +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.tosca.datatypes;
-
-// spec page 88
-public class ToscaNodeTypesDefinition {
-
- String name;
- String derivedFrom;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDerivedFrom() {
- return derivedFrom;
- }
-
- public void setDerivedFrom(String derivedFrom) {
- this.derivedFrom = derivedFrom;
- }
-
- public ToscaNodeTypesDefinition() {
- super();
- }
-
- @Override
- public String toString() {
- return "CsarNodeTypesDefinition [name=" + name + ", derivedFrom=" + derivedFrom + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java
deleted file mode 100644
index cf0add050d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java
+++ /dev/null
@@ -1,53 +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.tosca.datatypes;
-
-public class ToscaPropertiesNodeTemplatesDefinition {
-
- String name;
- Object value;
-
- public ToscaPropertiesNodeTemplatesDefinition() {
- super();
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Object getValue() {
- return value;
- }
-
- public void setValue(Object value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return "ToscaPropertyNodeTemplatesTopologyTemplateDefinition [name=" + name + ", value=" + value + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java
deleted file mode 100644
index bd9f0f0f5e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java
+++ /dev/null
@@ -1,72 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java
deleted file mode 100644
index 549867a562..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java
+++ /dev/null
@@ -1,77 +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.tosca.datatypes;
-
-import java.util.List;
-
-// spec page 104
-public class ToscaTopologyTemplateDefinition {
-
- String description;
- List<ToscaInputsTopologyTemplateDefinition> toscaInputsTopologyTemplateDefinition;
- List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition;
- // List<ToscaRelationshipTemplatesTopologyTemplateDefinition>
- List<ToscaGroupsTopologyTemplateDefinition> toscaGroupsTopologyTemplateDefinition;
- // List<ToscaPoliciesTopologyTemplateDefinition>
- // toscaPolociesTopologyTemplateDefinition;
- // List<ToscaOutputsTopologyTemplateDefinition>
- // toscaOutputsTopologyTemplateDefinition;
-
- public ToscaTopologyTemplateDefinition() {
- super();
- }
-
- public List<ToscaInputsTopologyTemplateDefinition> getToscaInputsTopologyTemplateDefinition() {
- return toscaInputsTopologyTemplateDefinition;
- }
-
- public void setToscaInputsTopologyTemplateDefinition(
- List<ToscaInputsTopologyTemplateDefinition> toscaInputsTopologyTemplateDefinition) {
- this.toscaInputsTopologyTemplateDefinition = toscaInputsTopologyTemplateDefinition;
- }
-
- public List<ToscaNodeTemplatesTopologyTemplateDefinition> getToscaNodeTemplatesTopologyTemplateDefinition() {
- return toscaNodeTemplatesTopologyTemplateDefinition;
- }
-
- public void setToscaNodeTemplatesTopologyTemplateDefinition(
- List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition) {
- this.toscaNodeTemplatesTopologyTemplateDefinition = toscaNodeTemplatesTopologyTemplateDefinition;
- }
-
- public List<ToscaGroupsTopologyTemplateDefinition> getToscaGroupsTopologyTemplateDefinition() {
- return toscaGroupsTopologyTemplateDefinition;
- }
-
- public void setToscaGroupsTopologyTemplateDefinition(
- List<ToscaGroupsTopologyTemplateDefinition> toscaGroupsTopologyTemplateDefinition) {
- this.toscaGroupsTopologyTemplateDefinition = toscaGroupsTopologyTemplateDefinition;
- }
-
- @Override
- public String toString() {
- return "ToscaTopologyTemplateDefinition [toscaInputsTopologyTemplateDefinition="
- + toscaInputsTopologyTemplateDefinition + ", toscaNodeTemplatesTopologyTemplateDefinition="
- + toscaNodeTemplatesTopologyTemplateDefinition + ", toscaGroupsTopologyTemplateDefinition="
- + toscaGroupsTopologyTemplateDefinition + "]";
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java
deleted file mode 100644
index 9ca8adee53..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java
+++ /dev/null
@@ -1,113 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java
deleted file mode 100644
index b34d474cf0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java
+++ /dev/null
@@ -1,133 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java
deleted file mode 100644
index 06320bcb5f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java
+++ /dev/null
@@ -1,59 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java
deleted file mode 100644
index 97a08479f8..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java
+++ /dev/null
@@ -1,39 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java
deleted file mode 100644
index 609ebf22b7..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java
+++ /dev/null
@@ -1,74 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java
deleted file mode 100644
index 7a26403053..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java
+++ /dev/null
@@ -1,66 +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.utils;
-
-import org.apache.commons.codec.binary.Base64;
-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 {
- /**
- * Converts ArtifactReqDetails to ArtifactDefinition
- * @param artifactReq
- * @return
- */
- 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;
- }
- /**
- * Converts ArtifactDefinition to ArtifactReqDetails
- * @param artifactDef
- * @return
- */
- public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetails( ArtifactDefinition artifactDef) {
- ArtifactReqDetails artifactReq = new ArtifactReqDetails();
- artifactReq.setArtifactLabel(artifactDef.getArtifactLabel());
- artifactReq.setArtifactDisplayName(artifactDef.getArtifactDisplayName());
- artifactReq.setArtifactGroupType(artifactDef.getArtifactGroupType().getType());
- artifactReq.setArtifactType(artifactDef.getArtifactType().toUpperCase());
- artifactReq.setArtifactName(artifactDef.getArtifactName());
- artifactReq.setDescription(artifactDef.getDescription());
- artifactReq.setUniqueId(artifactDef.getUniqueId());
- artifactReq.setTimeout(artifactDef.getTimeout());
- artifactReq.setPayload(Base64.encodeBase64String(artifactDef.getPayloadData()));
- return artifactReq;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java
deleted file mode 100644
index 41aa1a567f..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java
+++ /dev/null
@@ -1,286 +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.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.Element;
-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 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;
-
-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<Vertex, Boolean> getVertexByUId(String uid) {
- TitanGraph titanGraph = getTitanGraph();
- Either<Vertex, Boolean> result = Either.right(false);
- // Iterator<Vertex> vertexItr = titanGraph.getVertices().iterator();
-
- Iterator<TitanVertex> 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<Vertex> vertices = new ArrayList<>();
- List<Edge> edges = new ArrayList<>();
- // Iterator<Edge> edgesItr = titanGraph.getEdges().iterator();
- Iterator<TitanEdge> edgesItr = titanGraph.query().edges().iterator();
- // Iterator<Vertex> verticesItr = titanGraph.getVertices().iterator();
- Iterator<TitanVertex> 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<Vertex> verticesToRemove = new ArrayList<>(), verticesToAdd = new ArrayList<>();
- List<Edge> edgesToRemove = new ArrayList<>(), edgesToAdd = new ArrayList<>();
-
- TitanState currentTitanState = getCurrentTitanState();
-
- List<Edge> joinedEdges = new ArrayList<>();
- joinedEdges.addAll(titanStateToRestoreTo.edges);
- joinedEdges.retainAll(currentTitanState.edges);
-
- List<Vertex> 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<Vertex> verticesToRemove, List<Vertex> verticesToAdd,
- List<Edge> edgesToRemove, List<Edge> 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<String> properties = copyFrom.getPropertyKeys();
- Set<String> 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<Edge> edges;
- private List<Vertex> vertices;
-
- private TitanState(List<Edge> edges, List<Vertex> 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<String, Object> properties) {
-
- if (properties != null && false == properties.isEmpty()) {
-
- Object[] propertyKeyValues = new Object[properties.size() * 2];
- int i = 0;
- for (Entry<String, Object> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java
deleted file mode 100644
index 7d90eb0b6d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java
+++ /dev/null
@@ -1,62 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
deleted file mode 100644
index 6bfa1b8e94..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
+++ /dev/null
@@ -1,166 +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.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;
-
-//
-//
-//
-// import static org.testng.AssertJUnit.assertTrue;
-// import static org.testng.AssertJUnit.assertEquals;
-// import static org.testng.AssertJUnit.assertNotNull;
-// import java.io.IOException;
-// import java.util.HashMap;
-// import java.util.Map;
-//
-// import org.apache.log4j.Logger;
-//
-// import org.openecomp.sdc.be.model.ArtifactDefinition;
-// import org.openecomp.sdc.ci.tests.api.Urls;
-// import org.openecomp.sdc.ci.tests.config.Config;
-// import
-// org.openecomp.sdc.ci.tests.executeOnUGN.distributionClient.ClientConfiguration;
-// import org.openecomp.sdc.ci.tests.http.HttpHeaderEnum;
-// import org.openecomp.sdc.ci.tests.http.RestResponse;
-// import org.openecomp.sdc.ci.tests.run.StartTest;
-// import com.google.gson.Gson;
-//
- 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<Long, ServiceDistributionStatus> serviveDistributionStatusMap = ResponseParser.convertServiceDistributionStatusToObject(distributionServiceList.getResponse());
- if(serviveDistributionStatusMap.size() != 0){
- serviceDistributionStatus = getLatestServiceDistributionObjectFromMap(serviveDistributionStatusMap);
- return serviceDistributionStatus;
- }
-
- return null;
- }
-
- public static ServiceDistributionStatus getLatestServiceDistributionObjectFromMap(Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap) {
-
- ServiceDistributionStatus serviceDistributionStatus = null;
- if (serviceDistributionStatusMap.size() == 1 ){
- for (Entry<Long, ServiceDistributionStatus> entry : serviceDistributionStatusMap.entrySet()) {
- return entry.getValue();
- }
- }
- else{
- serviceDistributionStatus = getFilteredServiceDistributionObject(serviceDistributionStatusMap);
- }
-
- return serviceDistributionStatus;
- }
-
- private static ServiceDistributionStatus getFilteredServiceDistributionObject(Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap) {
-
- List<Long> list = new ArrayList<Long>();
- list.addAll(serviceDistributionStatusMap.keySet());
- Collections.sort(list);
- return serviceDistributionStatusMap.get(list.get(list.size() - 1));
- }
-
- public static Map<String, String> getArtifactsMapOfDistributedService(Service service) throws Exception{
-
- Map<String, String> expectedDistributionArtifactMap = new HashMap<String, String>();
- expectedDistributionArtifactMap = addServiceDeploymentArtifactToMap(service, expectedDistributionArtifactMap);
- expectedDistributionArtifactMap = addComponentInstancesDeploymentArtifactToMap(service, expectedDistributionArtifactMap);
-
- return expectedDistributionArtifactMap;
- }
-
-
- public static Map<String, String> addServiceDeploymentArtifactToMap(Service service, Map<String, String> distributionArtifactMap){
-
- Map<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts();
- if (deploymentArtifacts != null && deploymentArtifacts.size() > 0){
- for(Entry<String, ArtifactDefinition> 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<String, String> addComponentInstancesDeploymentArtifactToMap(Service service, Map<String, String> 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<String, ArtifactDefinition> artifact : componentInstance.getDeploymentArtifacts().entrySet()){
- String url = buildResourceInstanceDeploymentUrl(service, artifact.getValue().getArtifactName(), artifact.getValue().getArtifactUUID());;
- distributionArtifactMap.put(artifact.getKey(), url);
- }
- }
- }
- }
-
- return distributionArtifactMap;
- }
-
-
- }
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java
deleted file mode 100644
index 66379f18ef..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java
+++ /dev/null
@@ -1,630 +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.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.Set;
-import java.util.function.Function;
-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.RelationshipInfo;
-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<String, List<CapabilityDefinition>> expectedContainerCapabilities;
- public static Map<String, List<RequirementDefinition>> expectedContainerRequirements;
- public static Map<String, RequirementDefinition> removedRequirements;
- public static Map<String, ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>> 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<String> compInstKeysToChange = new HashSet<>();
-
- for (String expKey : expectedContainerCapabilities.keySet()) {
- List<CapabilityDefinition> 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<RequirementDefinition> 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<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> 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<ComponentInstance> 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<String, List<RequirementDefinition>> actualCompInstReq = compInst.getRequirements();
- if (actualCompInstReq == null) {
- actualCompInstReq = new HashMap<>();
- }
- Map<String, List<CapabilityDefinition>> actualCompInstCap = compInst.getCapabilities();
- if (actualCompInstCap == null) {
- actualCompInstCap = new HashMap<>();
- }
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> 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<String, List<RequirementDefinition>> actualContainerRequirements = actualComponent.getRequirements();
- if (actualContainerRequirements == null) {
- actualContainerRequirements = new HashMap<>();
- }
- Map<String, List<CapabilityDefinition>> 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 <T> void compareReqCapMaps(Map<String, List<T>> expectedMap, Map<String, List<T>> 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<String, List<RequirementDefinition>> resourceRequirements = component.getRequirements();
- if (resourceRequirements == null) {
- resourceRequirements = new HashMap<>();
- }
-
- Function<Entry<String, List<RequirementDefinition>>, List<RequirementDefinition>> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList()));
- Map<String, List<RequirementDefinition>> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper));
-
- Map<String, List<CapabilityDefinition>> resourceCapabilities = component.getCapabilities();
- if (resourceCapabilities == null) {
- resourceCapabilities = new HashMap<>();
- }
-
- Function<Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
- Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
-
- setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
- if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)
- && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
- setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
- }
-
- // adding entry for expected componentInstance
- ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> compInstReqCapPair = new ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>(
- capCopy, reqCopy);
- expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
- }
-
- private static void setupContainerExpectedReqCap(String uniqueId, String name,
- Map<String, List<RequirementDefinition>> componentRequirements,
- Map<String, List<CapabilityDefinition>> componentCapabilities) {
- for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
- List<RequirementDefinition> reqListToAdd = resReq.getValue();
- for (RequirementDefinition requirementDefinition : reqListToAdd) {
- requirementDefinition.setOwnerId(uniqueId);
- requirementDefinition.setOwnerName(name);
- }
- List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
- if (expectedReqList == null) {
- expectedReqList = reqListToAdd;
- } else {
- expectedReqList.addAll(reqListToAdd);
- }
- expectedContainerRequirements.put(resReq.getKey(), expectedReqList);
- }
-
- for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
- List<CapabilityDefinition> capListToAdd = resCap.getValue();
- for (CapabilityDefinition capDefinition : capListToAdd) {
- capDefinition.setOwnerId(uniqueId);
- capDefinition.setOwnerName(name);
- }
- List<CapabilityDefinition> 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<String, List<RequirementDefinition>> componentRequirements,
- Map<String, List<CapabilityDefinition>> componentCapabilities) {
- for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
- List<RequirementDefinition> reqListToAdd = resReq.getValue();
- for (RequirementDefinition requirementDefinition : reqListToAdd) {
- requirementDefinition.setOwnerId(uniqueId);
- requirementDefinition.setOwnerName(name);
- }
- }
-
- for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
- List<CapabilityDefinition> 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<String> entriesRequirementsToRemove = new ArrayList<>();
- List<String> entriesCapabilitiesToRemove = new ArrayList<>();
- for (Entry<String, List<RequirementDefinition>> reqEntry : expectedContainerRequirements.entrySet()) {
- List<RequirementDefinition> reqList = reqEntry.getValue();
- List<RequirementDefinition> 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<String, List<CapabilityDefinition>> capEntry : expectedContainerCapabilities.entrySet()) {
- List<CapabilityDefinition> capList = capEntry.getValue();
- List<CapabilityDefinition> 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
- RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
- String type = relationship.getRelationship().getType();
- String fromId = requirementDef.getFromNode();
- List<RequirementDefinition> 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
- RelationshipInfo relationship = requirementDef.getRelationships().get(0).getRelation();
- String type = relationship.getRelationship().getType();
- String fromId = requirementDef.getFromNode();
- String key = type + " " + fromId;
- RequirementDefinition requirementDefinition = removedRequirements.get(key);
- if (requirementDefinition != null) {
- List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
- if (reqList == null) {
- reqList = new ArrayList<>();
- expectedContainerRequirements.put(type, reqList);
- }
- reqList.add(requirementDefinition);
- }
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
deleted file mode 100644
index 5449a5fc6b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
+++ /dev/null
@@ -1,305 +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.utils;
-
-import static org.testng.AssertJUnit.assertNotNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.apache.commons.codec.binary.Base64;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTypesDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaPropertiesNodeTemplatesDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaRequirementsNodeTemplatesDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.yaml.snakeyaml.Yaml;
-
-public class ToscaParserUtils {
-
- private static Logger log = LoggerFactory.getLogger(ToscaParserUtils.class.getName());
-
- 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<String, Object> 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<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- return load;
- }
-
- 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:
- enrichToscaDefinitionWithToscaVersion(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 enrichToscaDefinitionWithToscaVersion(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
- if (toscaMap.get("tosca_definitions_version") != null) {
- toscaDefinition.setToscaDefinitionVersion(getToscaVersion(toscaMap));
- }
- }
-
- public static String getToscaVersion(Map<?, ?> toscaMap) {
- return (String) toscaMap.get("tosca_definitions_version");
- }
-
- // spec 90 page
- public static void getToscaNodeTypes(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
- @SuppressWarnings("unchecked")
- Map<String, Map<String, String>> nodeTypes = (Map<String, Map<String, String>>) toscaMap.get("node_types");
- List<ToscaNodeTypesDefinition> listToscaNodeTypes = new ArrayList<>();
- if (nodeTypes != null) {
- for (Entry<String, Map<String, String>> entry : nodeTypes.entrySet()) {
- ToscaNodeTypesDefinition toscaNodeTypes = new ToscaNodeTypesDefinition();
- String toscaNodeName = entry.getKey();
- toscaNodeTypes.setName(toscaNodeName);
-
- Map<String, String> toscaNodeType = entry.getValue();
- if (toscaNodeType != null) {
- Set<Entry<String, String>> entrySet = toscaNodeType.entrySet();
- if (entrySet != null) {
- // boolean found = false;
- for (Entry<String, String> toscaNodeTypeMap : entrySet) {
- String key = toscaNodeTypeMap.getKey();
- if (key.equals("derived_from")) {
- String derivedFrom = toscaNodeTypeMap.getValue();
- toscaNodeTypes.setDerivedFrom(derivedFrom);
- // found = true;
- break;
- } else {
- continue;
- }
-
- }
- // if (found == false) {
- // System.out.println("Tosca file not valid,
- // derived_from not found");
- // }
- }
-
- }
- listToscaNodeTypes.add(toscaNodeTypes);
- }
- toscaDefinition.setToscaNodeTypes(listToscaNodeTypes);
- }
- }
-
- public static void getToscaTopologyTemplate(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
- ToscaTopologyTemplateDefinition toscaTopologyTemplate = new ToscaTopologyTemplateDefinition();
- @SuppressWarnings("unchecked")
- Map<String, Map<String, Object>> topologyTemplateMap = (Map<String, Map<String, Object>>) toscaMap
- .get("topology_template");
- List<ToscaNodeTemplatesTopologyTemplateDefinition> listToscaNodeTemplates = new ArrayList<>();
-
- if (topologyTemplateMap != null) {
- getToscaNodeTemplates(topologyTemplateMap, listToscaNodeTemplates);
- }
- toscaTopologyTemplate.setToscaNodeTemplatesTopologyTemplateDefinition(listToscaNodeTemplates);
- toscaDefinition.setToscaTopologyTemplate(toscaTopologyTemplate);
- }
-
- public static void getToscaNodeTemplates(Map<String, Map<String, Object>> topologyTemplateMap,
- List<ToscaNodeTemplatesTopologyTemplateDefinition> listToscaNodeTemplates) {
- Map<String, Object> nodeTemplatesMap = topologyTemplateMap.get("node_templates");
- if (nodeTemplatesMap != null) {
-
- for (Entry<String, Object> nodeTemplates : nodeTemplatesMap.entrySet()) {
- ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates = new ToscaNodeTemplatesTopologyTemplateDefinition();
- getToscaNodeTemplatesName(nodeTemplates, toscaNodeTemplates);
-
- @SuppressWarnings("unchecked")
- Map<String, Object> node = (Map<String, Object>) nodeTemplates.getValue();
- getNodeTemplatesType(toscaNodeTemplates, node);
- getToscaNodeTemplateProperties(toscaNodeTemplates, node);
- getToscaNodeTemplateRequirements(toscaNodeTemplates, node);
- listToscaNodeTemplates.add(toscaNodeTemplates);
- }
- }
- }
-
- public static void getToscaNodeTemplateRequirements(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
- Map<String, Object> node) {
- List<ToscaRequirementsNodeTemplatesDefinition> toscaRequirements = new ArrayList<>();
- if (node.get("requirements") != null) {
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> requirementList = (List<Map<String, Object>>) node.get("requirements");
- for (int i = 0; i < requirementList.size(); i++) {
- for (Entry<String, Object> 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<String, String> requirementMap = (Map<String, String>) requirement.getValue();
- Set<Entry<String, String>> entrySet = requirementMap.entrySet();
- if (entrySet != null) {
- for (Entry<String, String> 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);
- }
- }
- }
- toscaNodeTemplates.setRequirements(toscaRequirements);
- }
-
- public static void getToscaNodeTemplateProperties(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
- Map<String, Object> node) {
- List<ToscaPropertiesNodeTemplatesDefinition> listToscaProperties = new ArrayList<>();
- if (node.get("properties") != null) {
- @SuppressWarnings("unchecked")
- Map<String, Object> properties = (Map<String, Object>) node.get("properties");
- for (Entry<String, Object> property : properties.entrySet()) {
- ToscaPropertiesNodeTemplatesDefinition toscaProperty = new ToscaPropertiesNodeTemplatesDefinition();
- String propertyName = property.getKey();
- Object propertyValue = property.getValue();
- toscaProperty.setName(propertyName);
- toscaProperty.setValue(propertyValue);
- listToscaProperties.add(toscaProperty);
- }
- }
- toscaNodeTemplates.setProperties(listToscaProperties);
- }
-
- protected static void getNodeTemplatesType(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
- Map<String, Object> 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<String, Object> nodeTemplates,
- ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates) {
- String name = nodeTemplates.getKey();
- toscaNodeTemplates.setName(name);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
deleted file mode 100644
index 8a8ec58217..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
+++ /dev/null
@@ -1,656 +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.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<String> getScriptList (List<UploadArtifactInfo>
- // artifactsList){
- //
- // ArrayList<String> 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<String, Object> yamlObject = (Map<String, Object>) 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<String, Object> nodeTypesMap = (Map<String, Object>) nodeTypes;
- for (Entry<String, Object> 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<UploadArtifactInfo> artifactsList = new
- // ArrayList<UploadArtifactInfo>();
- //
- //// 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<UploadArtifactInfo> createArtifactsList(String srcDir) {
- //
- // List<UploadArtifactInfo> artifactsList = new
- // ArrayList<UploadArtifactInfo>();
- // File srcFile = new File(srcDir);
- // addFileToList(srcFile, artifactsList);
- //
- // return artifactsList;
- // }
- //
- // public void addFileToList(File srcFile, List<UploadArtifactInfo>
- // 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<String> 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 <String> idArray = new ArrayList<String>();
- //
- // 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<String> buildCategoriesTagsListFromJson(String
- // categoriesTagsJson){
- //
- // ArrayList<String> 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 <String> getCategoriesFromDb() throws Exception{
- //
- // ArrayList<String> categoriesFromDbArrayList = new ArrayList<>();
- // RestResponse restResponse = new RestResponse();
- // String contentTypeHeaderData = "application/json";
- // String acceptHeaderDate = "application/json";
- //
- // Map<String, String> headersMap = new HashMap<String,String>();
- // 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<String> actualArraylList, List<String> expectedArrayList,
- String message) {
-
- ArrayList<String> actual = new ArrayList<String>(actualArraylList);
- ArrayList<String> expected = new ArrayList<String>(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<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) parseYamlConfig(
- "deploymentResourceArtifacts");
- for (Map.Entry<String, Object> 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<String> getListOfDepResArtLabels(Boolean isLowerCase) throws FileNotFoundException {
-
- List<String> listOfResDepArtTypesFromConfig = new ArrayList<String>();
- @SuppressWarnings("unchecked")
- Map<String, Object> resourceDeploymentArtifacts = (Map<String, Object>) parseYamlConfig(
- "deploymentResourceArtifacts");
- if (resourceDeploymentArtifacts != null) {
-
- if (isLowerCase) {
- for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
- listOfResDepArtTypesFromConfig.add(iter.getKey().toLowerCase());
- }
- } else {
-
- for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
- listOfResDepArtTypesFromConfig.add(iter.getKey());
- }
- }
- }
- return listOfResDepArtTypesFromConfig;
- }
-
- public static List<String> getListOfToscaArtLabels(Boolean isLowerCase) throws FileNotFoundException {
-
- List<String> listOfToscaArtTypesFromConfig = new ArrayList<String>();
- @SuppressWarnings("unchecked")
- Map<String, Object> toscaArtifacts = (Map<String, Object>) parseYamlConfig("toscaArtifacts");
- if (toscaArtifacts != null) {
-
- if (isLowerCase) {
- for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
- listOfToscaArtTypesFromConfig.add(iter.getKey().toLowerCase());
- }
- } else {
- for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
- listOfToscaArtTypesFromConfig.add(iter.getKey());
- }
- }
- }
- return listOfToscaArtTypesFromConfig;
- }
-
- public static List<String> getListOfResPlaceHoldersDepArtTypes() throws FileNotFoundException {
- List<String> listResDepArtTypesFromConfig = new ArrayList<String>();
- List<String> listOfResDepArtLabelsFromConfig = getListOfDepResArtLabels(false);
- assertNotNull("deployment artifact types list is null", listOfResDepArtLabelsFromConfig);
- Object parseYamlConfig = Utils.parseYamlConfig("deploymentResourceArtifacts");
- Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) 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<String, Object> map = (Map<String, Object>) 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java
deleted file mode 100644
index b6cc44ce36..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java
+++ /dev/null
@@ -1,225 +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.utils.cassandra;
-
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-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 com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.TableMetadata;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-import com.datastax.driver.core.querybuilder.Select.Where;
-
-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<TableMetadata> 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<Row> fetchFromTable(String keyspace, String tableName,
- List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
-
- List<Pair<String, String>> fieldsConverted = new ArrayList<>();
-
-// fields.forEach(pair -> {
-// Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
-// fieldsConverted.add(newPair);
-// });
-
- fields.forEach(pair ->{
- Pair<String, String> newPair;
- if(pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL ){
- newPair = new Pair<String, String>("RESOURE_URL", pair.getValue1());
-
- }else{
- newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
- }
- fieldsConverted.add(newPair);
-
- });
-
- return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
- }
-
- public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> 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<Entry<AuditingFieldsKeysEnum, String>> entrySet =
- // fields.entrySet();
- // fields.
- boolean multiple = (fields.size() > 1) ? true : false;
- Where where = null;
- int size = 0;
-
- for (Pair<String, String> 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<Row> 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<AuditingFieldsKeysEnum, String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java
deleted file mode 100644
index 05336c475b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java
+++ /dev/null
@@ -1,172 +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.utils.cassandra;
-
-import java.io.FileNotFoundException;
-import java.util.Collection;
-import java.util.List;
-
-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 com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.TableMetadata;
-import com.datastax.driver.core.querybuilder.QueryBuilder;
-import com.datastax.driver.core.querybuilder.Select;
-import com.datastax.driver.core.querybuilder.Select.Where;
-
-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<TableMetadata> 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<Row> fetchFromTable(String keyspace, String tableName,
- List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
-
- // List<Pair<AuditingFieldsKeysEnum, String>>
- // Map<AuditingFieldsKeysEnum, String>
-
- 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<Entry<AuditingFieldsKeysEnum, String>> entrySet =
- // fields.entrySet();
- // fields.
- boolean multiple = (fields.size() > 1) ? true : false;
- Where where = null;
- int size = 0;
-
- for (Pair<AuditingFieldsKeysEnum, String> 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<Row> 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<AuditingFieldsKeysEnum, String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
deleted file mode 100644
index 465153af14..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
+++ /dev/null
@@ -1,692 +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.utils.general;
-
-import static org.testng.Assert.assertEquals;
-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 org.apache.commons.codec.binary.Base64;
-import org.apache.commons.lang3.tuple.Pair;
-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.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.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 com.google.gson.Gson;
-
-import fj.data.Either;
-
-public final class AtomicOperationUtils {
-
- private AtomicOperationUtils() {
- throw new UnsupportedOperationException();
- }
-
- // *********** RESOURCE ****************
- /**
- * Import a vfc From tosca file
- *
- * @param filePath
- * @param fileName
- * @return
- * @throws IOException
- * @throws JSONException
- */
- public static Either<Resource, RestResponse> 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<Resource, RestResponse> 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<Resource, RestResponse> 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(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<Resource, RestResponse> 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<Service, RestResponse> 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<Service, RestResponse> 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<Product, RestResponse> 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<Component, RestResponse> 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<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
- // ArrayList<LifeCycleStatesEnum>(EnumSet.allOf(LifeCycleStatesEnum.class));
-
- ArrayList<String> lifeCycleStatesEnumList = new ArrayList<String>();
- 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;
-
- }
-
- public static RestResponse approveAndRejectServiceForDistribution(Component component) throws Exception {
-
- Service service = (Service) component;
-
- User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
- opsUser.setRole("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, "rejectService", DistributionStatusEnum.DISTRIBUTION_REJECTED);
- }
-
- assertEquals(approveDistribution.getErrorCode(), new Integer(ProductRestUtils.STATUS_CODE_SUCCESS));
- assertEquals(distributionService.getErrorCode(), new Integer(ProductRestUtils.STATUS_CODE_SUCCESS));
-
- return distributionService;
-
- }
-
- // *********** ARTIFACTS *****************
-
- public static Either<ArtifactDefinition, RestResponse> 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<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer) {
- return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false);
- }
-
- public static Either<ComponentInstance, RestResponse> 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) {
- assertTrue(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 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 RestResponse associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws IOException {
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- RestResponse associate2ResourceInstancesResponse = ResourceRestUtils.associate2ResourceInstances(containerDetails, fromNode, toNode, assocType, defaultUser);
-
- if (validateState) {
- assertTrue(associate2ResourceInstancesResponse.getErrorCode() == ServiceRestUtils.STATUS_CODE_SUCCESS);
- }
-
- return associate2ResourceInstancesResponse;
- }
-
- public static Either<Pair<Component, ComponentInstance>, 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<ComponentInstanceProperty, RestResponse> addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
- 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<ComponentInstanceProperty, RestResponse> updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
- 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<ComponentInstanceProperty, RestResponse> addDefaultPropertyToResource(PropertyTypeEnum propertyType, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
-
- User defaultUser = ElementFactory.getDefaultUser(userRole);
- PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
- 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<Resource, RestResponse> buildResourceFromResponse(RestResponse resourceResp) {
- Either<Resource, RestResponse> 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<Resource, RestResponse> 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);
- }
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java
deleted file mode 100644
index a9b8aaea15..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java
+++ /dev/null
@@ -1,341 +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.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.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.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.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<CategoryDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
deleted file mode 100644
index 076261adef..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
+++ /dev/null
@@ -1,948 +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.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.CapabilityRequirementRelationship;
-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.RelationshipInfo;
-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.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 JH0003 = "jh0003";
- private static final String CI_RES = "ciRes";
- 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.GENERIC_INFRASTRUCTURE, 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = null;
- if (derived != null) {
- derivedFrom = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- 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<String> resourceTags = new ArrayList<String>();
- resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = null;
- if (derived != null) {
- derivedFrom = new ArrayList<String>();
- derivedFrom.add(derived.normativeName);
- }
- String vendorName = "SDC 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("ciMyCompute.yaml");
- importReqDetails.setCategories(resourceReqDetails.getCategories());
- importReqDetails.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- 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("ciMyCompute.yaml");
- importReqDetails.setCategories(resourceReqDetails.getCategories());
- importReqDetails.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- 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("ciMyCompute.yaml");
- importReqDetails.setCategories(resourceReqDetails.getCategories());
- importReqDetails.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
- return importReqDetails;
- }
-
- // *** SERVICE ***
- public static ServiceReqDetails getDefaultService() {
- return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, "al1976");
- }
-
- public static ServiceReqDetails getDefaultService(String contactId) {
- return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, contactId);
- }
-
- public static ServiceReqDetails getDefaultService(User user) {
- return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, user.getUserId());
- }
-
- public static ServiceReqDetails getService(ServiceCategoriesEnum category) {
- return getDefaultService("ciService", category, "al1976");
- }
-
- public static ServiceReqDetails getDefaultService(ServiceCategoriesEnum category, User user) {
- return getDefaultService("ciService", category, user.getUserId());
- }
-
- public static ServiceReqDetails getDefaultService(String serviceName, ServiceCategoriesEnum category, String contactId) {
- serviceName = (serviceName + generateUUIDforSufix());
- ArrayList<String> tags = new ArrayList<String>();
- 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("Shay");
- sdncMechUserDetails.setLastName("Sponder");
- 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<String> 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<String> 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<String> 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 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<String> 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<String> 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("CiProduct1", null);
- }
-
- public static ProductReqDetails getDefaultProduct(String name) {
- return createDefaultProductReqDetails(name, null);
- }
-
- public static ProductReqDetails getDefaultProduct(CategoryDefinition category) {
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- return createDefaultProductReqDetails("CiProduct1", categories);
- }
-
- public static ProductReqDetails getDefaultProduct(String name, CategoryDefinition category) {
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- return createDefaultProductReqDetails(name, categories);
- }
-
- public static ProductReqDetails getDefaultProduct(List<CategoryDefinition> categories) {
- return createDefaultProductReqDetails("CiProduct1", categories);
- }
-
- public static ProductReqDetails getDefaultProduct(String name, List<CategoryDefinition> categories) {
- return createDefaultProductReqDetails(name, categories);
- }
-
- private static ProductReqDetails createDefaultProductReqDetails(String name, List<CategoryDefinition> categories) {
- ProductReqDetails product = new ProductReqDetails(name);
- ArrayList<String> tags = new ArrayList<String>();
- tags.add(name);
- product.setTags(tags);
- product.setProjectCode("12345");
- product.setIcon("myIcon");
- ArrayList<String> contacts = new ArrayList<String>();
- contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1).getUserId());
- product.setContacts(contacts);
- product.setCategories(categories);
- String fullName = "This is my full name: " + name;
- 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<CapabilityDefinition> capList,
- List<RequirementDefinition> reqList) {
- RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
- requirementDef.setFromNode(fromCompInstId);
- requirementDef.setToNode(toCompInstId);
- RelationshipInfo pair = new RelationshipInfo();
- 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<CapabilityRequirementRelationship> relationships = new ArrayList<>();
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- relationships.add(capReqRel);
- capReqRel.setRelation(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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java
deleted file mode 100644
index 5acb0e47c1..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java
+++ /dev/null
@@ -1,137 +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.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 {
- private static final 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) {
- LOGGER.debug(String.format("Failed to write to file '%s'", filePath), e);
- }
- }
-
- 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<String, Exception> getFileContentUTF8(String filePath) {
- Either<String, Exception> 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<String> getFileListFromBaseDirectoryByTestName(String testResourcesPath) {
-
- File file = new File(testResourcesPath);
- File[] listFiles = file.listFiles();
- if (listFiles != null) {
- List<String> 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<String> fileList, String pattern) {
-
- for (String filePath : fileList) {
- if (filePath.contains(pattern)) {
- return filePath;
- }
- }
- return null;
- }
-
- public static String loadPayloadFileFromListUsingPosition(List<String> listFileName, String pattern,
- Boolean isBase64, int positionInList) throws IOException {
- List<String> newList = new ArrayList<>(Arrays.asList(listFileName.get(positionInList)));
- return loadPayloadFile(newList, pattern, isBase64);
- }
-
- public static String loadPayloadFile(List<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java
deleted file mode 100644
index 7e5a7d69a2..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java
+++ /dev/null
@@ -1,57 +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.utils.general;
-
-import java.io.IOException;
-import java.util.List;
-
-import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
-
-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<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filePath);
- importReqDetails.setPayloadName(fileName);
- String payloadData = FileUtils.loadPayloadFile(listFileName, fileName, true);
- importReqDetails.setPayloadData(payloadData);
-
- return importReqDetails;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java
deleted file mode 100644
index 00c51f8fbd..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/graph/GraphFileUtils.java
+++ /dev/null
@@ -1,60 +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.utils.graph;
-
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.FileUtils;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-public class GraphFileUtils {
-
- public static final String TEMP_FILES_PATH = "src/main/resources/ci/tempFiles/%s.txt";
-
- public static void writeVerticesUIDToFile(String fileName, Iterable<TitanVertex> vertices) throws IOException {
- Path path = Paths.get(String.format(TEMP_FILES_PATH, fileName));
- Files.deleteIfExists(path);
- Path file = Files.createFile(path);
- final String newLine = System.getProperty("line.separator");
- for (TitanVertex vertex : vertices) {
- FileUtils.writeStringToFile(file.toFile(), String.valueOf(vertex.id()) + newLine, Charset.defaultCharset(), true);
- }
- }
-
- public static List<String> getVerticesIdsFromFile(String fileName) throws IOException {
- List<String> verticesUids = new ArrayList<>();
- Files.lines(Paths.get(String.format(TEMP_FILES_PATH, fileName))).forEach(verticesUids::add);
- return verticesUids;
- }
-
- private static String getUid(TitanVertex titanVertex) {
- return (String )titanVertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java
deleted file mode 100644
index ddd9209d83..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java
+++ /dev/null
@@ -1,920 +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.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.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.AssertJUnit;
-
-import com.google.gson.Gson;
-
-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<String, String> headersMap = new HashMap<String,String>();
- 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<String, String> headersMap = new HashMap<String,String>();
- 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<String, String> addionalHeaders) throws Exception
- {
-
- return downloadServiceArtifact( service, artifact, user,addionalHeaders,true);
- }
-
- public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> 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<String, String> addionalHeaders) throws Exception
- {
- return downloadResourceArtifact(service, resource, artifact, user,addionalHeaders, true);
- }
-
- public static RestResponse downloadResourceArtifact(ServiceReqDetails service,ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> 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<String, String> 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<String, String> 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<String, String> getHeadersMap(User sdncModifierDetails) {
- Map<String, String> headersMap = new HashMap<String,String>();
- 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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(ArtifactDefinition artifact, 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, artifact.getUniqueId());
-
- return updateDeploymentArtifact(artifact, 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);
- }
- public static RestResponse updateDeploymentArtifactToRI(ArtifactDefinition 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<String, String> additionalHeaders = null;
- String checksum = ResponseParser.calculateMD5Header(artifactDetails);
- additionalHeaders = new HashMap<String, String>();
- 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<String> placeHolderlst = Utils.getListOfResPlaceHoldersDepArtTypes();
- Map<String, String> additionalHeaders = null;
- String checksum = null;
- String url= null;
-//
-//
-// if (artifactDetails.getArtifactGroupType() != null
-// && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")
-// && placeHolderlst.contains(artifactDetails.getArtifactType())) {
-// Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
-// ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel());
-// artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
-// artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
-// checksum = ResponseParser.calculateMD5Header(artifactDetails);
-// additionalHeaders = new HashMap<String, String>();
-// 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<String, String>();
- 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<String, String> additionalHeaders = null;
-
- additionalHeaders = new HashMap<String, String>();
-
-
- 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<String, String> additionalHeaders = null;
- if (checksum != null && !checksum.isEmpty()) {
- additionalHeaders = new HashMap<String, String>();
- 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<String, String> additionalHeaders = null;
- additionalHeaders = new HashMap<String, String>();
- if (checksum != null && !checksum.isEmpty()) {
- additionalHeaders = new HashMap<String, String>();
- 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<String, String> additionalHeaders = null;
- additionalHeaders = new HashMap<String, String>();
- 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<String, String> additionalHeaders = null;
-
- additionalHeaders = new HashMap<String, String>();
- 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<String, String> 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<String, String> 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<String,Map<String,Object>> getArtifactsListFromResponse(String jsonResponse, String fieldOfArtifactList){
- JSONObject object = (JSONObject)JSONValue.parse(jsonResponse);
- Map<String,Map<String,Object>> map = (Map<String,Map<String,Object>>)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<String, Object> artifact = getArtifactFromRestResponse(createResponse, artifactField, requieredArtifactLabel);
- assertNotNull(artifact);
- return artifact.get("uniqueId").toString();
- }
-
- public static Map<String, Object> getArtifactFromRestResponse(RestResponse response, String artifactField, String requieredArtifactLabel)
- {
- Map<String, Map<String, Object>> 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<String, String> 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;
-
- }
-
-
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
deleted file mode 100644
index 7cee913b0d..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
+++ /dev/null
@@ -1,557 +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.utils.rest;
-
-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.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-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.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.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.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();
-
- private static Logger logger = LoggerFactory.getLogger(UserRestUtils.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 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<String, String> headersMap = new HashMap<String,String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<ResourceAssetStructure> getResourceAssetList(RestResponse assetResponse) {
- List<ResourceAssetStructure> 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<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>();
- List<ArtifactAssetStructure> 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) {
-
- 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) {
-
- 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<ArtifactAssetStructure> artifactAssetStructureList,
- Component component, AssetTypeEnum assetType) {
- Map<String, ArtifactDefinition> componentDeploymentArtifacts = component.getDeploymentArtifacts();
- validateArtifactMetadata(componentDeploymentArtifacts, artifactAssetStructureList, component.getUUID(),
- assetType, null);
- }
-
- private static void validateArtifactMetadata(Map<String, ArtifactDefinition> componentDeploymentArtifacts,
- List<ArtifactAssetStructure> artifactAssetStructureList, String componentUuid, AssetTypeEnum assetType,
- String resourceInstanceName) {
-
- for (Entry<String, ArtifactDefinition> 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);
- }
- }
-
- }
-
- private static ArtifactAssetStructure getArtifactMetadata(List<ArtifactAssetStructure> artifactAssetStructureList,
- String artifactUUID) {
- for (ArtifactAssetStructure artifactAssetStructure : artifactAssetStructureList) {
- if (artifactAssetStructure.getArtifactUUID().equals(artifactUUID)) {
- return artifactAssetStructure;
- }
- }
- return null;
- }
-
- private static void resourceInstanceAssetValidator(
- List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, Component component,
- AssetTypeEnum assetType) {
-
- List<ComponentInstance> 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()));
- assertTrue(
- "Expected RI asset resourceUUID is " + componentInstance.getComponentUid() + " actual: "
- + resourceInstanceAssetStructure.getResourceUUID(),
- componentInstance.getComponentUid()
- .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<ResourceInstanceAssetStructure>
- // resourceInstanceAssetStructures, String componentUid) {
- private static ResourceInstanceAssetStructure getResourceInstanceMetadata(
- List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, String name) {
- for (ResourceInstanceAssetStructure resourceInstanceAssetStructure : resourceInstanceAssetStructures) {
- if (resourceInstanceAssetStructure.getResourceInstanceName().equals(name)) {
- return resourceInstanceAssetStructure;
- }
- }
- return null;
- }
-
- public static ServiceDetailedAssetStructure getServiceAssetMetadata(RestResponse assetResponse) {
-
- List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>();
- List<ArtifactAssetStructure> 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<ArtifactAssetStructure> 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<ResourceInstanceAssetStructure> 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<ServiceAssetStructure> getServiceAssetList(RestResponse assetResponse) {
- List<ServiceAssetStructure> 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<String> getResourceNamesList(List<ResourceAssetStructure> resourceAssetList) {
- List<String> assetNamesList = new ArrayList<>();
- for (ResourceAssetStructure resourceAsset : resourceAssetList) {
- assetNamesList.add(resourceAsset.getName());
- }
- return assetNamesList;
- }
-
- public static List<String> getServiceNamesList(List<ServiceAssetStructure> serviceAssetList) {
- List<String> assetNamesList = new ArrayList<>();
- for (ServiceAssetStructure serviceAsset : serviceAssetList) {
- assetNamesList.add(serviceAsset.getName());
- }
- return assetNamesList;
- }
-
- public static void checkResourceTypeInObjectList(List<ResourceAssetStructure> 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<ResourceAssetStructure> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java
deleted file mode 100644
index 080583b901..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java
+++ /dev/null
@@ -1,263 +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.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<String, String> prepareHeadersMap(String userId) {
- return prepareHeadersMap(userId, acceptHeaderData);
- }
-
- protected static Map<String, String> prepareHeadersMap(String userId, String accept) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> additionalHeaders)
- throws IOException {
- Map<String, String> 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<String> headersToRemove)
- throws IOException {
- Map<String, String> 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<String, String> 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<String, String> additionalHeaders) throws IOException {
- Map<String, String> 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 {
- return sendDelete(url, userId, null);
- }
-
- protected static RestResponse sendDelete(String url, String userId, Map<String, String> additionalHeaders) throws IOException {
- Map<String, String> 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<String, String> addAuthorizeHeader(String userName, String password) {
- String userCredentials = userName + ":" + password;
- encodeBase64 = Base64.encodeBase64(userCredentials.getBytes());
- String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64);
- Map<String, String> authorizationHeader = new HashMap<String, String>();
- authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials);
- return authorizationHeader;
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
deleted file mode 100644
index 528e82a9f5..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
+++ /dev/null
@@ -1,87 +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.utils.rest;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-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 getCatalog(String userId, List<String> excludeList) throws IOException {
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
- StringBuilder sb = new StringBuilder();
- sb.append(url).append("?");
- Optional.ofNullable(excludeList).orElse(Collections.emptyList()).forEach(type -> sb.append("excludeTypes="+type+"&"));
- return sendGet(sb.toString(), userId);
- }
-
- public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException {
-
- Config config = Utils.getConfig();
- 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<String, String> additionalHeaders = new HashMap<String, String>();
- additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
-
- return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders);
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java
deleted file mode 100644
index f5791efbb3..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java
+++ /dev/null
@@ -1,308 +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.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<String, String> 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<String, String> 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 userId, 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, userId);
- 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<String, String> 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<String, String> 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<String, String> 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<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
- new TypeToken<List<CategoryDefinition>>() {
- }.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<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
- new TypeToken<List<CategoryDefinition>>() {
- }.getType());
- int subCatNum = 0;
- String subCatName = expectedSubCategoryDefinition.getName();
- for (CategoryDefinition elem : categoryDefinitions) {
- if (elem.getUniqueId().equals(parentCategoryId)) {
- List<SubCategoryDefinition> 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<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
- new TypeToken<List<CategoryDefinition>>() {
- }.getType());
- int groupingNum = 0;
- String groupingName = expectedGroupingDefinition.getName();
- for (CategoryDefinition elem : categoryDefinitions) {
- if (elem.getUniqueId().equals(parentCategoryId)) {
- List<SubCategoryDefinition> subCategories = elem.getSubcategories();
- if (subCategories != null) {
- for (SubCategoryDefinition subCategoryDataDefinition : subCategories) {
- // if
- // (subCategoryId.equals(subCategoryDataDefinition.getUniqueId()))
- // {
- if (subCategoryId.equals(subCategoryDataDefinition.getUniqueId())
- && subCategoryDataDefinition.getGroupings() != null) {
- List<GroupingDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java
deleted file mode 100644
index e691efdbca..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.openecomp.sdc.ci.tests.utils.rest;
-
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.config.Config;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CommonRestUtils extends BaseRestUtils {
-
- private static Logger logger = LoggerFactory.getLogger(CommonRestUtils.class.getName());
-
- public static RestResponse getHealthCheck() throws Exception {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_HEALTH_CHECK_VIA_PROXY, config.getCatalogFeHost(), config.getCatalogFePort());
-
- return sendGet(url, null);
-
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java
deleted file mode 100644
index 21332a253c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java
+++ /dev/null
@@ -1,304 +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.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<String, String> headersMap = new HashMap<String, String>();
- 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 getComponentInstancePropertiesByID(ComponentTypeEnum type, String componentId, String resourceInstanceId, User user)
- throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- 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_INSTANCE_PROPERTIES_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(type), componentId, resourceInstanceId);
-
- return sendGet(url, user.getUserId(), headersMap);
-
- }
-
- 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;
- }
- public static RestResponse updateComponentInstance(ComponentInstance componentInstance,
- User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws IOException {
-
- Config config = Utils.getConfig();
- String userId = sdncModifierDetails.getUserId();
- String serviceBodyJson = gson.toJson(componentInstance);
- String url = String.format(Urls.UPDATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
- ComponentTypeEnum.findParamByType(componentType), componentId,
- componentInstance.getUniqueId());
- RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
- return updateResourceInstance;
- }
-
- public static RestResponse updateMultipleComponentInstance(
- List<ComponentInstanceReqDetails> 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<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java
deleted file mode 100644
index 8237819d7a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java
+++ /dev/null
@@ -1,70 +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.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;
- }
-
- public static RestResponse validateConformanceLevel(String uuid, String userId) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.VALIDATE_CONFORMANCE_LEVEL, config.getCatalogBeHost(), config.getCatalogBePort(), "services", uuid);
-
- RestResponse res = sendGet(url, userId);
- return res;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java
deleted file mode 100644
index 71735d5a4a..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java
+++ /dev/null
@@ -1,245 +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.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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java
deleted file mode 100644
index ec40c13894..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java
+++ /dev/null
@@ -1,252 +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.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();
- private static Logger logger = LoggerFactory.getLogger(UserRestUtils.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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<EcompRole> roles) throws IOException {
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- 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);
-
- 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<String, String> headersMap = new HashMap<String, String>();
- 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.setEmail("ttes@intl.sdc.com"); ecompUser.setLoginId("tt0004");
- * ecompUser.setActive(true);
- *
- * EcompRole roleToUpdate = new EcompRole(); roleToUpdate.setId(new
- * Long(6)); roleToUpdate.setName("PRODUCT_STRATEGIST"); List<EcompRole>
- * 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"); //
- * println("\n-----------------------------\n Testing getUserRoles"); //
- * TODO Auto-generated catch block e.printStackTrace(); } }
- */
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java
deleted file mode 100644
index d79c8e002c..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
deleted file mode 100644
index 407141622e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
+++ /dev/null
@@ -1,399 +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.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.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<String, String> headers = new HashMap<String, String>();
- 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<String, String> headers = new HashMap<String, String>();
- 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<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams()
- : new ArrayList<String>());
- 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<String, String> headersMap = prepareHeadersMap(userId);
- HttpRestClient httpRestClient = new HttpRestClient();
-
- for (Map.Entry<String, String> 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<String, String> headers = new HashMap<String, String>();
- headers.put("USER_ID", userRole.getUserId());
-
- return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java
deleted file mode 100644
index de7be077d1..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java
+++ /dev/null
@@ -1,122 +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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
deleted file mode 100644
index a5b8c7a4bf..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
+++ /dev/null
@@ -1,410 +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.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.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";
-
- 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 changeExternalResourceState(String uuid, User sdncModifierDetails, LifeCycleStatesEnum lifeCycleStatesEnum) throws IOException {
- String url = String.format(Urls.CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API, "localhost", "8080", uuid, lifeCycleStatesEnum);
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = new HashMap<>();
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY=");
- headersMap.put("X-ECOMP-InstanceID", "test");
- return sendPost(url, createLifecycleCommentJson(COMMENT), userId, acceptHeaderData,headersMap);
- }
-
- public static RestResponse changeExternalServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails, LifeCycleStatesEnum lifeCycleStatesEnum) throws IOException {
- String url = String.format(Urls.CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API, "localhost", "8080", serviceDetails.getUUID(), lifeCycleStatesEnum);
- String userId = sdncModifierDetails.getUserId();
- Map<String, String> headersMap = new HashMap<>();
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
- headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY=");
- headersMap.put("X-ECOMP-InstanceID", "test");
- RestResponse lifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), userId, acceptHeaderData,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 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<String, String> 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<String, String> prepareHeadersMap(User sdncModifierDetails) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = prepareHeadersMap(user);
- Map<String, String> userRemarksMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java
deleted file mode 100644
index fad47f0178..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java
+++ /dev/null
@@ -1,196 +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.utils.rest;
-
-import java.io.IOException;
-
-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;
-
-import com.google.gson.Gson;
-
-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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java
deleted file mode 100644
index a8661830ee..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java
+++ /dev/null
@@ -1,262 +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.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<ComponentInstanceProperty> 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<ComponentInstanceProperty> propList, String propNameToUpdate, String propTypeToUpdate, List<String> 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<ComponentInstanceProperty> propList, String propId, List<String> 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<ComponentInstanceProperty> expectedList, List<ComponentInstanceProperty> 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<ComponentInstanceProperty> addResourcePropertiesToList(Resource resource, List<ComponentInstanceProperty> listToFill) {
- for (PropertyDefinition prop : resource.getProperties()) {
- listToFill.add(new ComponentInstanceProperty(prop, null, null));
- }
- return listToFill;
- }
-
- public static List<ComponentInstanceProperty> addComponentInstPropertiesToList(Component component, List<ComponentInstanceProperty> listToFill, String componentId) {
-
- if (componentId != null) {
- List<ComponentInstanceProperty> 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<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
- for (Map.Entry<String, List<ComponentInstanceProperty>> 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<ComponentInstanceProperty> propList = component.getComponentInstancesProperties().get(componentInstanceDetails.getUniqueId());
- if (propList != null) {
- return getPropFromListByPropNameAndType(propList, name, type);
- }
- return null;
- }
-
- private static void updatePropertyListWithPathParameter(Resource resource, List<String> path, List<ComponentInstanceProperty> expectedPropertyList) {
- List<PropertyDefinition> 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<String> path, List<ComponentInstanceProperty> expectedPropertyList) {
- List<ComponentInstanceProperty> 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<String> tempPathList = new ArrayList<String>();
- 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<ComponentInstanceProperty> list, Component container) {
- List<String> path = new ArrayList<>();
- if (container != null) {
- List<ComponentInstance> 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<ComponentInstanceProperty> list) {
- List<String> path = new ArrayList<>();
- path.add(componentInstDetails.getUniqueId());
- updatePropertyListWithPathParameterOnCompInst(service, path, list);
- }
-}
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
deleted file mode 100644
index 0d8a1119ad..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
+++ /dev/null
@@ -1,725 +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.utils.rest;
-
-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;
-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 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.JsonParser;
-
-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 *******
-
- 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<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resourceDetails);
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(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<String, String> 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<String, String> 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 getResourceLatestVersionListMetadata(User sdncModifierDetails, String internalComponentType) throws IOException {
-
- Config config = Utils.getConfig();
- StringBuilder sb = new StringBuilder();
- String url = String.format(Urls.GET_RESOURCE_METADATA_lATEST_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort());
- sb.append(url);
- if (internalComponentType != null && !internalComponentType.isEmpty()) {
- sb.append("?internalComponentType="+internalComponentType);
- }
- return sendGet(sb.toString(), sdncModifierDetails.getUserId());
-
- }
-
- public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion)
- throws IOException {
-
- 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<String, String> 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<String, String> 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
-
- 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<String, String> headersMap = new HashMap<String, String>();
- 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 getResourceFilteredDataByParams(User sdncModifierDetails, String uniqueId , List<String> 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 {
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
- BaseRestUtils.RESOURCE_COMPONENT_TYPE);
-
- Map<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resourceDetails);
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(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<Resource> restResponseToResourceObjectList(String restResponse) {
- JsonElement jelement = new JsonParser().parse(restResponse);
- JsonArray jsonArray = jelement.getAsJsonArray();
- List<Resource> 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<Resource> 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<String, List<CapabilityDefinition>> capabilitiesMap = component.getCapabilities();
- Map<String, List<RequirementDefinition>> requirementMap = component.getRequirements();
- List<CapabilityDefinition> capabilitiesList = capabilitiesMap.get(assocType);
- List<RequirementDefinition> 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<Object> relationships = new ArrayList<Object>(relationshipsArray);
- wrapper.put("fromNode", fromNode);
- wrapper.put("toNode", toNode);
- wrapper.put("relationships", relationships);
- return wrapper;
-
- }
-
- private static CapabilityDefinition getCapabilityDefinitionByOwnerId(
- List<CapabilityDefinition> capabilityDefinitionList, String ownerId) {
-
- for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) {
- if (capabilityDefinition.getOwnerId().equals(ownerId)) {
- return capabilityDefinition;
- }
- }
- return null;
- }
-
- private static RequirementDefinition getRequirementDefinitionByOwnerId(
- List<RequirementDefinition> 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<ComponentInstance> 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);
- }
-
- 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/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java
deleted file mode 100644
index d9b8ec3d4b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java
+++ /dev/null
@@ -1,63 +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.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.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<String, String> headersMap = prepareHeadersMap(userId);
-
- Gson gson = new Gson();
- String userBodyJson = gson.toJson(resourceDetails);
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
deleted file mode 100644
index 2d173cc151..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
+++ /dev/null
@@ -1,564 +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.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 org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
-import org.codehaus.jackson.Version;
-import org.codehaus.jackson.map.JsonDeserializer;
-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.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.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<String, Object> map = new HashMap<String, Object>();
- ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
-
- for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
- JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
-
- map = (Map<String, Object>) 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<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
- Resource resource = null;
- try {
- resource = mapper.readValue(response, Resource.class);
- logger.debug(resource.toString());
- } catch (IOException e) {
- try {
- List<Resource> 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<PropertyConstraint> 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> T parseToObject(String json, Class<T> 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> T parseToObjectUsingMapper(String json, Class<T> clazz) {
- // Generic convert
- ObjectMapper mapper = new ObjectMapper();
- T object = null;
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> 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 <T> void addDeserializer(SimpleModule module, Class<T> clazz,
- final JsonDeserializer<T> 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<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- 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();
- 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<PropertyConstraint> 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<String> getValuesFromJsonArray(RestResponse message) throws Exception {
- List<String> artifactTypesArrayFromApi = new ArrayList<String>();
-
- 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<Map<String, Object>> getAuditFromMessage(Map auditingMessage) {
- List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
- // JsonElement jElement = new JsonParser().parse(auditingMessage);
- // JsonObject jObject = jElement.getAsJsonObject();
- // JsonObject hitsObject = (JsonObject) jObject.get("hits");
- // JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
- //
- // Iterator<JsonElement> 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<String,Object> map = new HashMap<String,Object>();
- // map = (Map<String,Object>) gson.fromJson(auditUnparsed,
- // map.getClass());
-
- auditList.add(auditingMessage);
- // }
- return auditList;
- }
-
- public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
-
- List<CategoryDefinition> categories = new ArrayList<>();
- try {
- JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse());
- JsonArray cagegories = jElement.getAsJsonArray();
- Iterator<JsonElement> 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<String> getDerivedListFromJson(RestResponse res) throws JSONException {
- JSONArray listFromJson = getListFromJson(res, "derivedFrom");
- List<String> lst = new ArrayList<String>();
- for (int i = 0; i < listFromJson.length(); i++) {
- lst.add(listFromJson.getString(i));
- }
-
- return lst;
- }
-
- public static Map<String, Object> convertStringToMap(String obj) {
- Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
- return object;
- }
-
- public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- JSONArray listFromJson = getListFromJson(res, field);
- for (int i = 0; i < listFromJson.length(); i++) {
- Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
- list.add(convertStringToMap);
- }
- return list;
-
- }
-
- public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) {
- String valueField = getValueFromJsonResponse(response.getResponse(), key);
- Map<String, Object> 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<String, List<Component>> convertCatalogResponseToJavaObject(String response) {
-
- // Map<String, ArrayList<Component>> map = new HashMap<String,
- // ArrayList<Component>>();
- Map<String, List<Component>> map = new HashMap<String, List<Component>>();
-
- 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");
-
- //////// RESOURCE/////////////////////////////
- ArrayList<Component> 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);
-
- return map;
-
- }
-
-
- public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
-
- Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<Long, ServiceDistributionStatus>();
- 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<String, String> getPropertiesNameType(RestResponse restResponse)
- throws JSONException {
- Map<String, String> propertiesMap = new HashMap<String, String>();
- 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;
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
deleted file mode 100644
index 0055dbd982..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
+++ /dev/null
@@ -1,285 +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.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 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<String, String> 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<String, String> prepareHeadersMap(User sdncModifierDetails, boolean isCached) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> 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<String, String> 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<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java
deleted file mode 100644
index 6c6a66d863..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java
+++ /dev/null
@@ -1,281 +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.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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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 getAllAdminUsers(User sdncModifierDetails) throws IOException {
-
- Config config = Utils.getConfig();
-
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> headersMap = new HashMap<String, String>();
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java
deleted file mode 100644
index 50ecdd8520..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java
+++ /dev/null
@@ -1,223 +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.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.JsonElement;
-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<String, Object> 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<String, ArtifactDefinition> 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<String, ArtifactDefinition> 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<String> getListOfArtifactFromFolder(String folderName) throws IOException, Exception {
- Config config = Utils.getConfig();
- String sourceDir = config.getResourceConfigDir();
- String testResourcesPath = sourceDir + File.separator + folderName;
- List<String> 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<String> 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
deleted file mode 100644
index 0d16308e26..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
+++ /dev/null
@@ -1,1390 +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.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<String> variables) {
-
- String auditDesc = errorInfo.getMessageId() + ": " + errorInfo.getMessage();
- 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<String, Object> actualAuditRecords = new HashMap<String, Object>();
- // Andrey's comment
- // actualAuditRecords = parseAuditResourceByAction(action, body);
- actualAuditRecords = parseAuditResourceByAction(action, null);
-
- // List<Map<String, Object>> actualAuditRecords = new
- // ArrayList<Map<String, Object>>();
- // 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<String, Object> actualAuditRecords = new HashMap<String, Object>();
- // 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<AuditingFieldsKeysEnum, String> body) throws Exception {
-
- Map<String, Object> actualAuditRecord = new HashMap<String, Object>();
- 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<String, Object> map, String auditJsonKeyName,
- String expectedArtifactData, boolean checkAllFields) {
- Map<ArtifactDataFieldEnum, String> expectedArtifactDataFileds = new HashMap<ArtifactDataFieldEnum, String>();
- Map<ArtifactDataFieldEnum, String> actualAtifactDataFileds = new HashMap<ArtifactDataFieldEnum, String>();
- 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<ArtifactDataFieldEnum, String> 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<String, Object> map2 = new HashMap<String, Object>();
- 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<String, Object> map2 = new HashMap<String, Object>();
- 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<String, Object> map2 = new HashMap<String, Object>();
- 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<String, Object> map2 = new HashMap<String, Object>();
- 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<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
- Map<String, Object> 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<String, Object> map2 = new HashMap<String, Object>();
- 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<String, Object> map2 = new HashMap<String, Object>();
- 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<AuditingFieldsKeysEnum, String> body)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- 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<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- 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 validateAuditExternalChangeLifecycle(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- 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 void validateAuditDeploy(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
-
- Map<String, Object> map2 = new HashMap<String, Object>();
- 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<String, Object> map2 = new HashMap<String, Object>();
- 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<AuditJsonKeysEnum> fieldsList = Arrays.asList(additionalFields);
- if (fieldsList.contains(AuditJsonKeysEnum.COMMENT)) {
- validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), productExpectedAudit.getCOMMENT());
- }
- }
- }
-
- private static List<Map<String, Object>> getAuditListByAction(String action, int expectedNumOfAudit)
- throws Exception {
- List<Map<String, Object>> 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<Map<String, Object>> actionToList = getAuditListByAction(expectedAudit.getAction(), 1);
- assertEquals("expected number of ES action is 1", 1, actionToList.size());
-
- Map<String, Object> 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<String, Object> 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);
- }
- }
-
- private 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<String, Object> foundMap = (Map<String, Object>) foundValue;
- Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
- assertTrue(foundMap.size() == excpectedMap.size());
- Iterator<String> 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<Object> foundList = (List<Object>) foundValue;
- List<Object> excpectedList = (List<Object>) 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 Map<String, Object> parseAuditResourceByAction(String
- // action, String body) throws Exception {
- //
- // Map auditingMessage = null;
- // auditingMessage = retrieveAuditMessagesByPattern(action, null);
- //
- // return auditingMessage;
- //
- // }
-
- public static Map<String, Object> parseAuditResourceByAction(String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
-
- Map auditingMessage = null;
- auditingMessage = retrieveAuditMessagesByPattern(action, body, false);
-
- return auditingMessage;
-
- }
-
- // public static List<Map<String, Object>>
- // parseAuditResourceByActionToList(String action, String body) throws
- // Exception {
- //
- // List<Map<String, Object>> auditList = new ArrayList<Map<String,
- // Object>>();
- //
- //// 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<Map<String, Object>> parseAuditResourceByActionToList(String action,
- Map<AuditingFieldsKeysEnum, String> body) throws Exception {
-
- List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
-
- // 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<JSONObject> 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<String, String> headersMap = new HashMap<String, String>();
- 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<String, String> retrieveAuditMessagesByPattern(String action, Map<AuditingFieldsKeysEnum, String> body, Boolean retryFlag)
- throws IOException {
-
- // get cassandra table name by action
- String esType = AuditingActionEnum.getActionByName(action).getAuditingEsType();
- Map<String, String> resultsMap = new HashMap<String, String>();
-
- List<Pair<AuditingFieldsKeysEnum, String>> myFields = new ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
- Pair<AuditingFieldsKeysEnum, String> myPair = new Pair<AuditingFieldsKeysEnum, String>(
- AuditingFieldsKeysEnum.AUDIT_ACTION, action);
- myFields.add(0, myPair);
- if (body != null && !body.isEmpty()) {
- for (Map.Entry<AuditingFieldsKeysEnum, String> mapElement : body.entrySet()) {
- myFields.add(new Pair<AuditingFieldsKeysEnum, String>(mapElement.getKey(), mapElement.getValue()));
- }
- }
-
- List<Row> 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 = 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<AuditingFieldsKeysEnum, String> myFields= new
- // HashMap<AuditingFieldsKeysEnum, String>();
- //// myFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION , pattern);
- //
- // List<Pair<AuditingFieldsKeysEnum, String>> myFields = new
- // ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
- // Pair<AuditingFieldsKeysEnum, String> myPair = new
- // Pair<AuditingFieldsKeysEnum, String>(AuditingFieldsKeysEnum.AUDIT_ACTION
- // , pattern);
- // myFields.add(0, myPair);
- //
- //
- // List<Row> 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<String> metaDataList = new
- // ArrayList<String>(Arrays.asList(metaData.split(", ")));
- //
- //
- //
- // Map<String, String> resultsMap = new HashMap<String, String>();
- //
- //
- // 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<String> dataArray = new
- // ArrayList<String>(Arrays.asList(dataString.split(", ")));
- ////
- ////
- //// Map<String, String> resultsMap = new HashMap<String, String>();
- //// for (int i=0 ; i<metaDataList.size() ; i++) {
- //// resultsMap.put(metaDataList.get(i), dataArray.get(i));
- //// }
- ////
- //// return restResponse.getResponse();
- // return resultsMap;
- // }
-
- public static void categoryAuditSuccess(String action, CategoryDefinition categoryDefinition, User user, int status,
- String resourceType) throws Exception {
- categoryAuditSuccessInternal(action, categoryDefinition, null, null, user, status, resourceType);
- }
-
- public static void categoryAuditFailure(String action, CategoryDefinition categoryDataDefinition, User user,
- ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
- categoryAuditFailureInternal(action, categoryDataDefinition, null, null, user, errorMessage, status,
- resourceType, variables);
- }
-
- public static void subCategoryAuditSuccess(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, User user, int status, String resourceType) throws Exception {
- categoryAuditSuccessInternal(action, categoryDefinition, subCategoryDefinition, null, user, status,
- resourceType);
- }
-
- public static void groupingAuditSuccess(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, int status,
- String resourceType) throws Exception {
- categoryAuditSuccessInternal(action, categoryDefinition, subCategoryDefinition, groupingDefinition, user,
- status, resourceType);
- }
-
- public static void subCategoryAuditFailure(String action, CategoryDefinition categoryDataDefinition,
- SubCategoryDefinition subCategoryDefinition, User user, ActionStatus errorMessage, int status,
- String resourceType, Object... variables) throws Exception {
- categoryAuditFailureInternal(action, categoryDataDefinition, subCategoryDefinition, null, user, errorMessage,
- status, resourceType, variables);
- }
-
- // NEW Benny
- public static void groupingAuditFailure(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
- ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
- groupingAuditFailureInternal(action, categoryDefinition, subCategoryDefinition, groupingDefinition, user,
- errorMessage, status, resourceType, variables);
- }
-
- private static void groupingAuditFailureInternal(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);
- }
-
- ///
- private static void categoryAuditSuccessInternal(String action, CategoryDefinition categoryDefinition,
- SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, int status,
- String resourceType) throws Exception {
- // resourceType = Service/Resource/Product
- ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
- expectedCatrgoryAuditJavaObject.setAction(action);
- expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
- expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.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("OK");
- AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
- }
-
- ///////////////////////////
- ///// BENNNNNNNNY
- public enum UserAuditJsonKeysEnum {
- ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER(
- "USER_AFTER"), USER_BEFORE("USER_BEFORE");
- private String auditJsonKeyName;
-
- private UserAuditJsonKeysEnum(String auditJsonKeyName) {
- this.auditJsonKeyName = auditJsonKeyName;
- }
-
- public String getAuditJsonKeyName() {
- return auditJsonKeyName.toLowerCase();
- }
- }
-
- public static void validateAddUserAudit(ExpectedUserCRUDAudit expectedAddUserAuditJavaObject, String action)
- throws Exception {
-
- List<Map<String, Object>> actionToList = getAuditListByAction(expectedAddUserAuditJavaObject.getAction(), 1);
- Map<String, Object> 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<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
- Map<String, Object> 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<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
- Map<String, Object> 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<String>()));
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedComponentNotFoundAuditObject(String Action,
- String resourceUid, ComponentType resourceType, String artifactUid, User user,
- ArrayList<String> 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<String>());
-
- 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<String>());
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(String Action, String resourceName,
- ComponentType resourceType, String artifactUid, User user, String currVersion, String currState,
- ArrayList<String> 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<String> 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<String, String> actionMap = new HashMap<String, String>();
- actionMap.put("ACTION", action);
- JSONObject actionJsonObject = new JSONObject(actionMap);
- Map<String, String> uuidMap = new HashMap<String, String>();
- uuidMap.put("SERVICE_INSTANCE_ID", uuid);
- JSONObject uuidJsonObject = new JSONObject(uuidMap);
-
- List<JSONObject> filters = new ArrayList<JSONObject>(Arrays.asList(actionJsonObject, uuidJsonObject));
- JSONObject body = buildElasticQueryBody(filters);
- return body;
- }
-
- public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
- List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
- Map<String, Object> 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<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java
deleted file mode 100644
index eb3ee331ed..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java
+++ /dev/null
@@ -1,116 +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.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.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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java
deleted file mode 100644
index cd2297fd19..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java
+++ /dev/null
@@ -1,126 +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.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertNotNull;
-import static org.testng.AssertJUnit.assertTrue;
-
-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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
deleted file mode 100644
index 05e3874fc0..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
+++ /dev/null
@@ -1,298 +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.utils.validation;
-
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-import org.json.simple.parser.JSONParser;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.PropertyHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaRequirementsNodeTemplatesDefinition;
-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;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CsarValidationUtils {
- private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName());
-
- public static String getCsarPayload(String csarName, String fileLocation) throws Exception {
-
- RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName,
- ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertTrue("Return response code different from 200",
- csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- Map<String, byte[]> readZip = null;
- byte[] data = csar.getResponse();
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
-
- }
-
- byte[] artifactsBs = readZip.get(fileLocation);
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
-
- return str;
-
- }
-
- public static List<TypeHeatMetaDefinition> 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<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
- listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
- return listHeatMetaDefenition;
- }
- return null;
-
- }
-
- protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure,
- List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
-
- @SuppressWarnings("unchecked")
- Set<Object> 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<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<GroupHeatMetaDefinition>();
- heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroup(array, groupHeatMetaDefinitions, true));
- listHeatMetaDefenition.add(heatMetaDefenition);
- }
- return listHeatMetaDefenition;
- }
-
- protected static List<GroupHeatMetaDefinition> fetchArtifactByGroup(JSONArray array,
- List<GroupHeatMetaDefinition> 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<Object> 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<String> 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<TypeHeatMetaDefinition> listHeatMetaDefenition,
- Boolean isEnvIncluded) {
- int count = 0;
- List<String> 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<TypeHeatMetaDefinition> 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<TypeHeatMetaDefinition> 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.getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition().size();
- }
-
- public static Integer getResourceInstanceRelationCount(ToscaDefinition toscaDefinition) {
- int count = 0;
- List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition
- .getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition();
- for (int i = 0; i < toscaNodeTemplatesTopologyTemplateDefinition.size(); i++) {
- List<ToscaRequirementsNodeTemplatesDefinition> requirements = toscaNodeTemplatesTopologyTemplateDefinition
- .get(i).getRequirements();
- 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<GroupDefinition> groups = resource.getGroups();
- for (GroupDefinition groupDefinition : groups) {
- List<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java
deleted file mode 100644
index 46948d8f5b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/DistributionValidationUtils.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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<String, String> verifyDistributedArtifactDownloadUsingDB(String distributionID, Map<String, String> expectedArtifactsMapOfDistributedService, List<String> 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<String, String> url : expectedArtifactsMapOfDistributedService.entrySet()){
- Map <AuditingFieldsKeysEnum, String> 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<String, String> actualAuditRecord = new HashMap<String, String>();
- 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<String> distributionStatusList) throws Exception, IOException, ParseException {
- String distributionID;
- AtomicOperationUtils.distributeService(service, true);
- distributionID = DistributionUtils.getLatestServiceDistributionObject(service).getDistributionID();
- if(distributionID != null){
- Map<String, String> expectedArtifactsMapOfDistributedService = DistributionUtils.getArtifactsMapOfDistributedService(service);
- DistributionValidationUtils.verifyDistributedArtifactDownloadUsingDB(distributionID, expectedArtifactsMapOfDistributedService, distributionStatusList);
- }
- else{
- assertNotNull("distributionID is null", distributionID);
- }
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java
deleted file mode 100644
index 9bf8bd9230..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java
+++ /dev/null
@@ -1,121 +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.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.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;
-import org.yaml.snakeyaml.Yaml;
-
-public class ErrorValidationUtils {
-
- static Logger logger = LoggerFactory.getLogger(Utils.class.getName());
-
- public static void checkBodyResponseOnError(String errorType, List<String> 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<String> 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<String, ErrorInfo> errorMap = (Map<String, ErrorInfo>) map.get("errors");
- @SuppressWarnings("unchecked")
- Map<String, Object> errorInfo = (Map<String, Object>) 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java
deleted file mode 100644
index ba5114c1bc..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java
+++ /dev/null
@@ -1,239 +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.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<String> expectedContacts = expectedProduct.getContacts();
- List<String> 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<String> expectedTags = expectedProduct.getTags();
- List<String> 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<String, String> 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<CategoryDefinition> expectedCategories = expectedProduct.getCategories();
- List<CategoryDefinition> 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<SubCategoryDefinition> actualSubcategories = actualDefinition.getSubcategories();
- List<SubCategoryDefinition> 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<GroupingDefinition> actualGroupings = actualSub.getGroupings();
- List<GroupingDefinition> 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<SubCategoryDefinition> actualSubcategories = actualDefinition.getSubcategories();
- List<SubCategoryDefinition> 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<GroupingDefinition> actualGroupings = actualSub.getGroupings();
- List<GroupingDefinition> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java
deleted file mode 100644
index 7bbadc5c1b..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java
+++ /dev/null
@@ -1,358 +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.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<String> expectedTags = resourceDetails.getTags();
- if (expectedTags != null) {
- Set<String> hs = new LinkedHashSet<>(expectedTags);
- expectedTags.clear();
- expectedTags.addAll(hs);
- List<String> 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<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) gson.fromJson(response, map.getClass());
-
- // De-duplicating the tags list for comparison
- List<String> tags = resourceRespJavaObject.getTags();
- if (tags != null) {
- Set<String> hs = new LinkedHashSet<>(tags);
- tags = new ArrayList<String>(hs);
- resourceRespJavaObject.setTags(tags);
- tags = new ArrayList<String>(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_USER_ID.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorUserId());
- validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorFullName());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_USER_ID.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<String, Object> map) {
- assertTrue(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName() + " is missing",
- map.containsKey(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName()));
- Object foundValue = map.get(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName());
- List<Map<String, Object>> foundList = (List<Map<String, Object>>) foundValue;
- List<CategoryDefinition> excpectedList = resourceRespJavaObject.getCategories();
-
- assertTrue(foundList.size() == excpectedList.size());
- for (int i = 0; i < foundList.size(); i++) {
- CategoryDefinition expCat = excpectedList.get(i);
- Map<String, Object> foun = foundList.get(i);
- assertTrue("expected " + expCat.getName() + " not equal to actual " + foundValue,
- foun.get("name").equals(expCat.getName()));
- }
- }
-
- public static void validateField(Map<String, Object> 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<String, Object> foundMap = (Map<String, Object>) foundValue;
- Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
- assertTrue(foundMap.size() == excpectedMap.size());
- Iterator<String> 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<Object> foundList = (List<Object>) foundValue;
- List<Object> excpectedList = (List<Object>) 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<String, Object> map = new HashMap<String, Object>();
- map = (Map<String, Object>) gson.fromJson(response, map.getClass());
-
- Resource resource = gson.fromJson(response, Resource.class);
-
- Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
- Map<String, InterfaceDefinition> interfaces = null;
-
- if (interfaze != null) {
- interfaces = resource.getInterfaces();
- Map<String, Operation> 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_USER_ID.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorUserId());
- validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
- resourceRespJavaObject.getCreatorFullName());
- validateField(map, RespJsonKeysEnum.LAST_UPDATER_USER_ID.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<String> myArtifacats = new ArrayList<String>();
- 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<Resource> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java
deleted file mode 100644
index 2f8a0dffc4..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.ci.tests.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertFalse;
-
-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<String> expectedTags = expectedService.getTags();
- expectedTags.add(expectedService.getName());
- List<String> receivedTags = service.getTags();
- if (expectedTags != null) {
- Set<String> 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java
deleted file mode 100644
index dde27d5cbd..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/TestYamlParser.java
+++ /dev/null
@@ -1,92 +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.utils.validation;
-
-import java.io.File;
-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.Map;
-import java.util.Set;
-
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.common.util.ZipUtil;
-import org.testng.annotations.Test;
-import org.yaml.snakeyaml.Yaml;
-
-
-
-
-public class TestYamlParser extends ComponentBaseTest{
-
-
-
-
- @Rule
- public static TestName name = new TestName();
-
- public TestYamlParser() {
- super(name, TestYamlParser.class.getName());
- }
-
-
-
-
-
- @Test
- public void testYaml() throws IOException{
-
- System.out.println("");
-
- File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
-
-
- //read file
-
-
- Map<String, byte[]> 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<String, Object> load = (Map<String, Object>) yaml.load(str);
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
-
- Set<String> keySet = node_templates.keySet();
- }
-
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java
deleted file mode 100644
index 31e2327e40..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java
+++ /dev/null
@@ -1,275 +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.utils.validation;
-
-import static org.testng.AssertJUnit.assertEquals;
-import static org.testng.AssertJUnit.assertTrue;
-
-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<String> variables) {
-
- validateAuditDataAgainstAuditDbInAccess(sdncUserDetails, auditJavaObject, restResponse, errorInfo, variables);
-
- }
-
- public static void validateAuditDataAgainstAuditDbInAccess(User sdncUserDetails,
- UserAuditJavaObject auditJavaObject, RestResponse restResponse, ErrorInfo errorInfo,
- List<String> 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());
- }
-
- 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/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java
deleted file mode 100644
index 0c19627bda..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.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/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
deleted file mode 100644
index 9b98688036..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
+++ /dev/null
@@ -1,352 +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.externalApis;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-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.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.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);
- // consumerDataDefinition =
- // ConsumerRestUtils.getDefaultConsumerDetails();
- // 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 // (enabled = false)
- public void getResourceAssetSuccess() throws Exception {
-
- List<String> 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<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
- List<String> 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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), null);
-
- }
-
- @Test // (enabled = false)
- public void getServiceAssetSuccess() throws Exception {
-
- List<String> 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<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList);
- Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
-
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_ASSET_LIST);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), null);
-
- }
-
- @Test
- public void getToscaModelSuccess() throws Exception {
-
- CloseableHttpClient httpclient = HttpClients.createDefault();
- ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
- resourceDetails.setName("ciResource1");
- 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/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java
deleted file mode 100644
index 3886c5aa3e..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java
+++ /dev/null
@@ -1,438 +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.externalApis;
-
-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.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.ServiceAssetStructure;
-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.ServiceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
-import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class GetFilteredAssetServlet extends ComponentBaseTest {
-
- 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";
-
- @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<String> 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<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
- List<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- // 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<String> 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<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @Test // (enabled = false)
- public void getResourceAssetBySpecifiedSubCategoryAndCategory() throws Exception {
- String[] filter = { subCategoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory(), categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), };
- List<String> 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<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- // 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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> variables = Arrays.asList(subCategoryFilterKey + "1", "[" + subCategoryFilterKey + ", " + categoryFilterKey + "]");
- 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- // ---------------------------------------------------------------------------------------------------------
- // SERVICE
- // Success
- @Test // (enabled = false)
- public void getServiceAssetBySpecifiedCategory() throws Exception {
- String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue() };
- List<String> 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<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
-
- }
-
- @Test // (enabled = false)
- public void getServiceAssetBySpecifiedCategoryAndDistributionStatus() throws Exception {
- String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue(), distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED };
- List<String> 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<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @Test // (enabled = false)
- public void getServiceAssetByDistributionStatus() throws Exception {
- String[] filter = { distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED };
- List<String> 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<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- // 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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
- }
-
- @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<String> 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));
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
-
- }
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java
deleted file mode 100644
index 791a490288..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java
+++ /dev/null
@@ -1,773 +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.externalApis;
-
-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.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.ResourceDetailedAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure;
-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.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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
- private static Logger log = LoggerFactory.getLogger(GetAssetServlet.class.getName());
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- // 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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
-
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
-
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
-
- }
-
- @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);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
- }
-
- @Test // (enabled = false)
- public void getServiceAssetMetadataServiceNotFound() throws Exception {
-
- String serviceUuid = "notExistingServiceUuid";
- RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
- serviceUuid);
-
- // Validate audit message
- ArrayList<String> variables = new ArrayList<>();
- variables.add(serviceUuid);
- ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables,
- assetResponse.getResponse());
- }
-
- // Add to service VF instance imported from CSAR
-
- @Test
- public void getFilteredResourceAssetSuccess() throws Exception {
-
- List<String> expectedAssetNamesList = new ArrayList<>();
-
- ResourceReqDetails resourceDetails = ElementFactory
- .getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_APP_SERVER);
- 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 = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_BORDER);
- resourceDetails.setName("ciResource2");
- 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("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();
-
- resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_FIREWALL);
- 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.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<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
- List<String> getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList);
- Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
-
- AssetRestUtils.checkResourceTypeInObjectList(resourceAssetList, ResourceTypeEnum.VF);
-
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory
- .getDefaultFilteredAssetListAudit(AssetTypeEnum.RESOURCES, "?" + query);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
-
- }
-
- @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+");
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
-
- }
-
- @Test
- public void getFilteredServiceAssetSuccess() throws Exception {
-
- List<String> 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);
-
- 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();
-
- 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("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();
- 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("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();
-
- 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();
-
- String query = "distributionStatus=Distributed";
- RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.SERVICES, query);
- BaseRestUtils.checkSuccess(assetResponse);
-
- List<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
- Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
-
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory
- .getDefaultFilteredAssetListAudit(AssetTypeEnum.SERVICES, "?" + query);
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
- AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
-
- }
-
-}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java b/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java
deleted file mode 100644
index 5e9e02c479..0000000000
--- a/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java
+++ /dev/null
@@ -1,70 +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.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/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml b/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml
deleted file mode 100644
index fae7ab7ece..0000000000
--- a/asdc-tests/src/main/resources/ci/conf/attsdc-packages.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-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 \ No newline at end of file
diff --git a/asdc-tests/src/main/resources/ci/conf/attsdc.yaml b/asdc-tests/src/main/resources/ci/conf/attsdc.yaml
deleted file mode 100644
index 10bf38f89d..0000000000
--- a/asdc-tests/src/main/resources/ci/conf/attsdc.yaml
+++ /dev/null
@@ -1,91 +0,0 @@
-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
-
-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
- - 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
diff --git a/asdc-tests/src/main/resources/ci/conf/log4j.properties b/asdc-tests/src/main/resources/ci/conf/log4j.properties
deleted file mode 100644
index d313e92b55..0000000000
--- a/asdc-tests/src/main/resources/ci/conf/log4j.properties
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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/asdc-tests/src/main/resources/ci/conf/testngLifeCycle.xml b/asdc-tests/src/main/resources/ci/conf/testngLifeCycle.xml
deleted file mode 100644
index aa390dc213..0000000000
--- a/asdc-tests/src/main/resources/ci/conf/testngLifeCycle.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="lifeCycle" parallel="none">
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_cerificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceResourceLCSTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_UndoCheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_UndoCheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_StartCertificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_CheckinCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_CheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceCertWithResourceInstances"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CrossCheckOutTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CertifyVFWithNotCertRIs"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_request4CerCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CleanupIntermediateReources"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_CheckOutCIT"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_cerificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CertifyServiceWithNotCertRI"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_CheckInCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_request4CerCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_StartCertificationCITest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- lifeCycle -->
diff --git a/asdc-tests/src/main/resources/ci/conf/titan.properties b/asdc-tests/src/main/resources/ci/conf/titan.properties
deleted file mode 100644
index 0fe7888b9e..0000000000
--- a/asdc-tests/src/main/resources/ci/conf/titan.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-storage.backend=cassandra
-#storage.hostname=cassandrahost
-storage.hostname=localhost
-storage.port=9160
-
-cache.db-cache = false
-storage.cassandra.keyspace=sdctitan
-
diff --git a/asdc-tests/src/main/resources/ci/conf/truststore b/asdc-tests/src/main/resources/ci/conf/truststore
deleted file mode 100644
index bdec93d862..0000000000
--- a/asdc-tests/src/main/resources/ci/conf/truststore
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/main/resources/ci/scripts/startTest.sh b/asdc-tests/src/main/resources/ci/scripts/startTest.sh
deleted file mode 100644
index 01b8979781..0000000000
--- a/asdc-tests/src/main/resources/ci/scripts/startTest.sh
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <jar file>"
-}
-
-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
-CONF_FILE=${FULL_PATH}/conf/attsdc.yaml
-DEBUG=true
-MainClass=org.openecomp.sdc.ci.tests.run.StartTest
-
-JAR_FILE=$1
-SUITE_FILE=$2
-
-#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
-TARGET_LOG_DIR="${TARGET_DIR}/"
-
-# 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 -DdisplayException=true -Dtargetlog=${TARGET_LOG_DIR} -Dconfig.resource=${CONF_FILE} -Ddebug=${DEBUG} -Dlog4j.configuration=${LOGS_PROP_FILE} -cp $JAR_FILE ${MainClass} $SUITE_FILE"
-
-#echo $cmd
-#console=`$cmd`
-
-if [ $DEBUG == "true" ]
-then
- $cmd
-else
- $cmd >> /dev/null
-fi
-status=`echo $?`
-
-
-
-echo "##################################################"
-echo "################# status is ${status} #################"
-echo "##################################################"
-
-exit $status
-
diff --git a/asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml b/asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml
deleted file mode 100644
index e53da8da8a..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/CRUDArtifacts.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="CRUDArtifacts" configfailurepolicy="continue" verbose="2" parallel="tests" thread-count="10">
-
- <test name="Test">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.devCI.CRUDExternalAPI">
- <methods>
- <include name="uploadArtifactOnVFViaExternalAPI" />
- <include name="uploadArtifactOnServiceViaExternalAPI" />
- <include name="uploadArtifactOnRIViaExternalAPI" />
- <include name="uploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI" />
- <include name="uploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset" />
- <include name="uploadArtifactOnAssetWhichNotExist" />
- <include name="uploadArtifactOnAssetWhichInInvalidStateForUploading" />
-
-
- <include name="updateArtifactForServiceViaExternalAPI" />
- <include name="updateArtifactForVFViaExternalAPI" />
- <include name="updateArtifactOnRIViaExternalAPI" />
- <include name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset" />
- <include name="updateArtifactOnAssetWhichNotExist" />
- <include name="updateArtifactOnAssetWhichInInvalidStateForUploading" />
- <include name="updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI" />
-
-
- <include name="deleteArtifactForServiceViaExternalAPI" />
- <include name="deleteArtifactForVFViaExternalAPI" />
- <include name="deleteArtifactOnRIViaExternalAPI" />
- <include name="deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset" />
- <include name="deleteArtifactOnAssetWhichNotExist" />
- <include name="deleteArtifactOnAssetWhichInInvalidStateForUploading" />
- </methods>
-
- </class>
-
- </classes>
- </test> <!-- Test -->
-</suite> <!-- Suite --> \ No newline at end of file
diff --git a/asdc-tests/src/main/resources/ci/testSuites/SearchExternalAPI.xml b/asdc-tests/src/main/resources/ci/testSuites/SearchExternalAPI.xml
deleted file mode 100644
index 40c462a4cb..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/SearchExternalAPI.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="CRUDArtifacts" configfailurepolicy="continue" verbose="2" parallel="tests" thread-count="10">
-
- <test name="Test">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.devCI.SearchFilterCategoryExternalAPI">
- <methods>
-
- <include name="searchWithInvalidFilter" />
- <include name="searchForResourceTypeNegativeTest" />
- <include name="searchingForResouceFilterIncorrectResouceTypeUsingExternalAPI" />
- <include name="searchingForSeveralResouceTypesUsingExternalAPI" />
- <include name="searchingForSeveralResourcesOfTypeVFCMTUsingExternalAPI" />
- <include name="normativeResourceCategory" />
- </methods>
-
- </class>
-
- </classes>
- </test> <!-- Test -->
-</suite> <!-- Suite --> \ No newline at end of file
diff --git a/asdc-tests/src/main/resources/ci/testSuites/artifacts.xml b/asdc-tests/src/main/resources/ci/testSuites/artifacts.xml
deleted file mode 100644
index 24229b8586..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/artifacts.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Artifacts" >
- <test name="Artifacts">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.DownloadComponentArt" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ArtifactServletTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateHeatArtFieldsTypes" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.PlaceHolderValidations" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateArtResponse" />
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.CrudArt" />
- </classes>
- </test>
-</suite> <!-- Artifacts -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/category.xml b/asdc-tests/src/main/resources/ci/testSuites/category.xml
deleted file mode 100644
index f2a0b3790c..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/category.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="category" >
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.category.CategoriesTests"/>
- <class name="org.openecomp.sdc.ci.tests.execute.category.GroupingTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.category.SubCategoriesTest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- category -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml b/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml
deleted file mode 100644
index 1d81e0f689..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/ciFull.xml
+++ /dev/null
@@ -1,174 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="ciFull" configfailurepolicy="continue" verbose="2">
- <test name="Category">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.category.ElementsApiTest" />
- <class name="org.openecomp.sdc.ci.tests.execute.category.CategoriesTests">
- <methods>
- <exclude name="importCategories" />
- <exclude name="getServiceCategoryHierarchySuccessFlow" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.category.CatalogDataApiTest" />
- <class name="org.openecomp.sdc.ci.tests.execute.category.GroupingTest" >
- <methods>
- <exclude name="createProductGroupForNonExistingCategory" />
- <exclude name="createProductGroupForNonExistingSunCategory" />
- <exclude name="getProductCategoryHierarchySuccessFlow" />
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.category.SubCategoriesTest">
- <methods>
- <exclude name="createProductSubCategoryForNonExistingCategory" />
- <exclude name="createResourceSubCategoryForNonExistingCategory" />
- <exclude name="getResourceCategoryHierarchySuccessFlow" />
- </methods>
- </class>
- </classes>
- </test> <!-- Test -->
- <test name="Distribution">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.distribution.AuthanticationTests" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.distribution.DistributionDownloadArtifactTest">
- <methods>
- <exclude name="downloadServiceArtifact_ServiceVersionNotFound" />
- </methods>
- </class>
- </classes>
- </test> <!-- Test -->
- <test name="General">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.general.ManageEcompConsumerCredentials">
- <methods>
- <exclude name="createEcompCredentialsByNoExistingIUser" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.general.FeProxyTest" />
- <class name="org.openecomp.sdc.ci.tests.execute.general.UuidTest" />
- </classes>
- </test>
- <test name="Resource">
- <classes>
- <!-- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.SimultaneousApiTest" /> -->
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.ComponentRelationshipInVfTest">
- <methods>
- <exclude name="associateOneOfTwoCPsToVl_ThenDiscocciate" />
- <exclude name="disassociateRelationInVfNotFound" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.UpdateResourceMetadataTest">
- <methods>
- <exclude name="UpdateResourceCategory_negativeFlow" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.VFResourceInstanceNameCRUD"/>
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.VfComponentInstanceCRUDTest">
- <methods>
- <exclude name="createAllAtomicInstancesTestGetReqCapAPI_suc" />
- <exclude name="createVfcInstance_UserIdIsEmpty" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceApiTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.ValidateExtendedVfData" />
- </classes>
- </test>
-
- <test name="Service">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.GetServiceLatestVersionTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.CreateServiceMetadataApiTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.ReqCapOccurrencesTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.ChangeServiceDistributionStatusApiTest">
- <methods>
- <exclude name="approveCertifiedService_byDesigner" />
- <exclude name="approveCertifiedService_byOps" />
- <exclude name="approveCertifiedService_byTester" />
- <exclude
- name="distributionStatusChange_approve_Reject_AprroveBysdncAdminDetails" />
- <exclude name="rejectCertifiedService_byDesigner" />
- <exclude name="rejectCertifiedService_byOps" />
- <exclude name="rejectCertifiedService_byTester" />
- <exclude name="rejectCertifiedService_bysdncAdminDetails" />
- <exclude name="rejectCertifiedService_bysdncGovernorDeatails" />
- <exclude name="rejectNotCertifiedService_checkedin" />
- <exclude name="rejectNotCertifiedService_checkeout" />
- <exclude name="rejectNotCertifiedService_inProgress" />
- <exclude name="rejectNotCertifiedService_readyForCer" />
- <exclude name="rejectServiceNotFound" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.ServiceComponentInstanceCRUDTest">
- <methods>
- <exclude name="associateAfterCheckoutAllInstancesTest" />
- <exclude name="associateAfterDeletingResourceTest" />
- <exclude name="associateDissociateTwoVFs" />
- <exclude name="associateInstancesInTwoServiceVersionsTest" />
- <exclude name="associateNotCompitableReqCapTest" />
- <exclude name="associateOnceAgainExistingRelationTest" />
- <exclude name="associateResourceInstanceToResourceInstanceNotFoundTest" />
- <exclude
- name="associateTwoRelations_CheckinCheckout_DissoicateOneRelationInSecondVersion" />
- <exclude name="createResourceInstanceWithEmptyUserIdTest" />
- <exclude name="deleteNotFoundResourceInstanceTest" />
- <exclude name="deleteResourceInstanceWithEmptyUserIdTest" />
- <exclude name="dissociateOnceAgainTest" />
- <exclude name="dissociateRelationNotFoundTest" />
- <exclude name="dissoicateRelationWhileInstanceNotFound" />
- <exclude name="dissoicateWithEmptyUserIdHeaderTest" />
- <exclude name="relationDeletedAfterDeletingResourceInstanceTest" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.UpdateServiceMetadataTest">
- <methods>
- <exclude name="categoryValidationTest6" />
- <exclude name="categoryValidationTest7" />
- <exclude name="descriptionValidationTest11" />
- <exclude name="descriptionValidationTest12" />
- <exclude name="descriptionValidationTest13" />
- <exclude name="descriptionValidationTest7" />
- <exclude name="serviceNameValidationTest17" />
- <exclude name="updateCertifiedService" />
- <exclude name="updateCheckoutCertifiedService" />
- <exclude name="updateServiceByMethod_delete" />
- <exclude name="updateServiceByMethod_get" />
- <exclude name="updateServiceByMethod_post" />
- <exclude name="updateServiceNotExist" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.GetAllServiceVersions" />
- </classes>
- </test>
- <test name="Artifacts">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.DownloadComponentArt" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ArtifactServletTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateHeatArtFieldsTypes" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.PlaceHolderValidations" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateArtResponse" />
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.CrudArt" />
- </classes>
- </test>
-</suite> \ No newline at end of file
diff --git a/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml b/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml
deleted file mode 100644
index 393d3b1a3e..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/externalApis.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="externalApis" configfailurepolicy="continue" verbose="2">
- <test name="ExternalApis">
- <classes>
- <class name="org.openecomp.sdc.externalApis.GetAssetServlet" />
- <class name="org.openecomp.sdc.externalApis.GetFilteredAssetServlet"/>
- <class name="org.openecomp.sdc.externalApis.GetSpecificAssetMetadataServlet"/>
- <class name="org.openecomp.sdc.ci.tests.execute.devCI.CRUDExternalAPI"/>
- <class name="org.openecomp.sdc.ci.tests.execute.devCI.SearchFilterCategoryExternalAPI"/>
- <class name="org.openecomp.sdc.ci.tests.execute.externalapi.UserAPIs"/>
- </classes>
- </test>
-</suite> \ No newline at end of file
diff --git a/asdc-tests/src/main/resources/ci/testSuites/general.xml b/asdc-tests/src/main/resources/ci/testSuites/general.xml
deleted file mode 100644
index bd7e6b6650..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/general.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="General" >
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.general.SampleTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.general.ManageEcompConsumerCredentials"/>
- <class name="org.openecomp.sdc.ci.tests.execute.general.UuidTest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- General -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/imports.xml b/asdc-tests/src/main/resources/ci/testSuites/imports.xml
deleted file mode 100644
index ae4a5bc1f8..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/imports.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Imports" >
- <test name="Imports">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportGenericResourceCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportCsarResourceTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportNewResourceCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportToscaResourceTest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- Imports -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/property.xml b/asdc-tests/src/main/resources/ci/testSuites/property.xml
deleted file mode 100644
index f94f89737a..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/property.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Property" >
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.property.PropertyApisTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.property.PropertyServletTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.property.AdditionalInformationServletTest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- Property -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/resource.xml b/asdc-tests/src/main/resources/ci/testSuites/resource.xml
deleted file mode 100644
index 64f4377420..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/resource.xml
+++ /dev/null
@@ -1,320 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Sanity" configfailurepolicy="continue" >
-
- <!--
- <listeners>
- <listener class-name="org.openecomp.sdc.ci.tests.config.InvokedMethodListener" />
- </listeners>
- -->
-
-
- <test verbose="2" name="Sanity">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.ArtifactServletTest">
- <methods>
- <include name="upadteArtifactWithPayLoadToResourcseTest"/>
- <include name="createAndUpdateArtifactToInterface"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.CrudArt">
- <methods>
- <include name="addHeatArtifactToResourceAndCertify"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.LCS_Artifacts">
- <methods>
- <include name="LCS_inherit_artifact"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.InformationalArt">
- <methods>
- <include name="UpdateAllResourceMandatoryArtifacts"/>
- <include name="updateInformationalArtifactMetadataOfResource"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.InformationalArtCloudQuestionnaire">
- <methods>
- <include name="updateMandatoryInformationalArtifact_CloudQuestionnaire"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.ServiceApiArtifactTest">
- <methods>
- <include name="uploadServiceApiArtifactSuccessfullyTest"/>
- <include name="updateApiArtifactSuccessfullyTest"/>
- <include name="deleteApiArtifactSuccessfully"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.ServiceInformationalArtifact">
- <methods>
- <include name="updateMandatoryInformationalArtifact_ServiceQuestionnaire"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateArtResponse"/>
-
- <class name="org.openecomp.sdc.ci.tests.execute.category.CatalogDataApiTest"/>
-
- <class name="org.openecomp.sdc.ci.tests.execute.category.ElementsApiTest">
- <methods>
- <include name="getAllArtifactTypes"/>
- <include name="getConfiguration"/>
- <include name="getAllPropertyScopesSuccess"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.distribution.AuthanticationTests">
- <methods>
- <include name="downloadServiceArtifactSuccessWithAutantication"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.distribution.DistributionDownloadArtifactTest">
- <methods>
- <include name="downloadResourceArtifactSuccess"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.general.BasicHttpAuthenticationTest">
- <methods>
- <include name="sendAuthenticatedRequestTest_success"/>
- </methods>
- </class>
-
-
-
- <class name="org.openecomp.sdc.ci.tests.execute.general.FeProxyTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.general.ManageEcompConsumerCredentials">
- <methods>
- <include name="deleteEcompCredentialsMethodDelete"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.general.UuidTest">
- <methods>
- <include name="testE2EUuidHeaderReturnedAndPreserved"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportGenericResourceCITest">
- <methods>
- <include name="importAllTestResources"/>
- <include name="testImportCheckoutAndUpdateUserResource"/>
- <include name="testImportWithUpdateNormativeType"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportNewResourceCITest">
- <methods>
- <include name="importAllTestResources_toValidateNewAPI"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.imports.ImportToscaResourceTest">
- <methods>
- <include name="importToscaResource"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CleanupIntermediateReources">
- <methods>
- <include name="test28"/>
- <include name="test29"/>
- <include name="test30"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CleanupIntermediateServicesTest">
- <methods>
- <include name="testCleanupIntermediateServices"/>
- </methods>
- </class>
-
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ResourceLCS_cerificationCITest">
- <methods>
- <include name="verifyAllPrevVerDeleted"/>
- <include name="verifyStartWithDesignerCertByAdmin"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ResourceLCS_CheckInCITest">
- <methods>
- <include name="checkInTest_suc"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ResourceLCS_CheckOutCITest">
- <methods>
- <include name="checkOutTest_currState_READY_FOR_CERTIFICATION_ownerDSIGNER_performByADMIN_suc"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ResourceLCS_request4CerCITest">
- <methods>
- <include name="req4cer_fromCheckOut_designer_admin"/>
- </methods>
- </class>
-
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ResourceLCS_StartCertificationCITest">
- <methods>
- <include name="startCer_suc"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ResourceLCS_UndoCheckOutCITest">
- <methods>
- <include name="undoCheckOutTest_import_outAdmin_undoOut_designer"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceCertWithMandatoryArt">
- <methods>
- <include name="CertServiceWithHeatDeployArtOnResource"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceCertWithResourceInstances">
- <methods>
- <include name="certServiceWithCertResource"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.property.AdditionalInformationServletTest">
- <methods>
- <include name="createResourceAdditionalInformationTestDuringLifecycle"/>
- <include name="updateResourceAdditionalInformationTest"/>
- <include name="deleteResourceAdditionalInformationTest"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.property.PropertyApisTest">
- <methods>
- <include name="testPropertyApis"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.property.PropertyServletTest">
- <methods>
- <include name="createCascadeVfResource"/>
- <include name="createPropertyTestSetClearDefaultValueInetegr"/>
- </methods>
- </class>
-
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetAllLatestVersionNonAbstarctResources">
- <methods>
- <include name="resourceCertifiedTwiceCoutCinCout"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetAllResourceVersions">
- <methods>
- <include name="getResourceAllVersions_version15"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetFollwedElementsTest">
- <methods>
- <include name="getResourcesListBolongsToSpecificDesigner"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetResourceAbstractApiTest">
- <methods>
- <include name="getAbstractResourceList"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetResourceNotAbstractApiTest">
- <methods>
- <include name="getNotAbstractResourceList"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetResourceTagsApiTest">
- <methods>
- <include name="getModifiedResourceTagsList"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceApiTest">
- <methods>
- <include name="updateResourceMetadataSuccess"/>
- </methods>
- </class>
- <!--
- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceInstanceNameCRUD">
- <methods>
- <include name="updateResourceInstanceNameAfterServiceCertification"/>
- </methods>
- </class>
- -->
-<!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceInstanceServletTest">
- <methods>
- <include name="updateRI_suc"/>
- </methods>
- </class> -->
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.UpdateResourceMetadataTest">
- <methods>
- <include name="UpdateDerivedFromSuccess"/>
- </methods>
- </class>
-
-
- <class name="org.openecomp.sdc.ci.tests.execute.service.GetComponentAuditApiTest">
- <methods>
- <include name="testServiceAuditCertifiedVersion"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.service.ServiceApiTest">
- <methods>
- <include name="createServiceTest"/>
- <include name="getFollowedServicesTester"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.service.ServiceInformationalArtifactApiTest">
- <methods>
- <include name="addArtifactSuccessfuly"/>
- <include name="deleteArtifact"/>
- <include name="updateArtifactMetadataSuccessfully"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.service.UpdateServiceMetadataTest">
- <methods>
- <include name="updateServiceSuccessfully"/>
- </methods>
- </class>
-
-
- <class name="org.openecomp.sdc.ci.tests.execute.user.ActivateDeActivateDeleteUser">
- <methods>
- <include name="authorizeDeActivatedUser"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.user.CreateUserApiTest">
- <methods>
- <include name="createUser"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.user.GovernorWorkspaceApiTest">
- <methods>
- <include name="governorList_AllCertifiedVersionsOfService"/>
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.user.OpsWorkspaceApiTest">
- <methods>
- <include name="opsList_AllCertifiedVersionsOfServiceApproved"/>
- </methods>
- </class>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- Sanity -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/sanity.xml b/asdc-tests/src/main/resources/ci/testSuites/sanity.xml
deleted file mode 100644
index 21b7043ad3..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/sanity.xml
+++ /dev/null
@@ -1,330 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Sanity" configfailurepolicy="continue" verbose="2">
-
- <test name="sanityE2Eflows">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.sanity.CrudE2E" />
- </classes>
- </test>
-
- <test name="General">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.general.BasicHttpAuthenticationTest">
- <methods>
- <include name="sendAuthenticatedRequestTest_success" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.general.FeProxyTest" />
- <class
- name="org.openecomp.sdc.ci.tests.execute.general.ManageEcompConsumerCredentials">
- <methods>
- <include name="deleteEcompCredentialsMethodDelete" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.general.UuidTest">
- <methods>
- <include name="testE2EUuidHeaderReturnedAndPreserved" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="ArtifactOnInstance">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.CrudArt">
- <methods>
- <include name="addDcaeInventoryToscaArtifactToResourceInstanceAndCertify" />
- <include name="addDcaeInventoryJsonArtifactToResourceInstanceAndCertify" />
- <include name="addDcaeInventoryPolicyArtifactToResourceInstanceAndCertify" />
- <include name="addDcaeInventoryDocArtifactToResourceInstanceAndCertify" />
- <include name="addDcaeInventoryBluePrintArtifactToResourceInstanceAndCertify" />
- <include name="addDcaeInventoryEventArtifactToResourceInstanceAndCertify" />
- <include name="updateArtifactDescriptionToResourceInstance" />
- <include name="deleteArtifactToResourceInstance" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="Artifact">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.ArtifactServletTest">
- <methods>
- <include name="upadteArtifactWithPayLoadToResourcseTest" />
- <include name="createAndUpdateArtifactToInterface" />
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.CrudArt">
- <methods>
- <include name="addHeatArtifactToResourceAndCertify" />
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.artifacts.ValidateArtResponse" />
-
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.artifacts.DownloadComponentArt">
- <methods>
- <include name="downloadArtifactFromResourceTest" />
- <include name="downloadArtifactFromServiceTest" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="Service">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.GetComponentAuditApiTest">
- <methods>
- <include name="testServiceAuditCertifiedVersion" />
- </methods>
- </class>
-
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.service.ServiceApiTest">
- <methods> <include name="createServiceTest" /> <include name="getFollowedServicesTester"
- /> </methods> </class> -->
-
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.service.ServiceInformationalArtifactApiTest">
- <methods> <include name="addArtifactSuccessfuly" /> <include name="deleteArtifact"
- /> <include name="updateArtifactMetadataSuccessfully" /> </methods> </class> -->
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.service.UpdateServiceMetadataTest">
- <methods>
- <include name="updateServiceSuccessfully" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="Resource">
- <classes>
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetAllLatestVersionNonAbstarctResources">
- <methods> <include name="resourceCertifiedTwiceCoutCinCout" /> </methods>
- </class> -->
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.GetAllResourceVersions">
- <methods>
- <include name="getResourceAllVersions_version15" />
- </methods>
- </class>
-
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetFollwedElementsTest">
- <methods> <include name="getResourcesListBolongsToSpecificDesigner" /> </methods>
- </class> -->
-
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetResourceAbstractApiTest">
- <methods> <include name="getAbstractResourceList" /> </methods> </class> -->
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.GetResourceNotAbstractApiTest">
- <methods>
- <include name="getNotAbstractResourceList" />
- </methods>
- </class>
-
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.GetResourceTagsApiTest">
- <methods> <include name="getModifiedResourceTagsList" /> </methods> </class> -->
-
- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceApiTest">
- <methods>
- <include name="updateResourceMetadataSuccess" />
- </methods>
- </class>
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceInstanceNameCRUD">
- <methods> <include name="updateResourceInstanceNameAfterServiceCertification"/>
- </methods> </class> -->
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.resource.ResourceInstanceServletTest">
- <methods> <include name="updateRI_suc"/> </methods> </class> -->
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.resource.UpdateResourceMetadataTest">
- <methods>
- <include name="UpdateDerivedFromSuccess" />
- </methods>
- </class>
- </classes>
- <test name="Catalog">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.category.CatalogDataApiTest" />
- </classes>
- </test>
-
- <test name="distribution">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.distribution.AuthanticationTests">
- <methods>
- <include name="downloadServiceArtifactSuccessWithAutantication" />
- </methods>
- </class>
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.distribution.DistributionDownloadArtifactTest">
- <methods>
- <include name="downloadResourceArtifactSuccess" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="Category">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.category.ElementsApiTest">
- <methods>
- <include name="getAllArtifactTypes" />
- <include name="getConfiguration" />
- <include name="getAllPropertyScopesSuccess" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="Imports">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.imports.ImportGenericResourceCITest">
- <methods>
- <include name="importAllTestResources" />
- <include name="testImportCheckoutAndUpdateUserResource" />
- <include name="testImportWithUpdateNormativeType" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.imports.ImportNewResourceCITest">
- <methods>
- <include name="importAllTestResources_toValidateNewAPI" />
- </methods>
- </class>
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.imports.ImportToscaResourceTest">
- <methods>
- <include name="importToscaResource" />
- </methods>
- </class>
- <class
- name="org.openecomp.sdc.ci.tests.execute.imports.ImportToscaCapabilitiesWithProperties">
- <methods>
- <include name="importNodeTypeWithCapabilityWithPropertiesFromYmlSucceed" />
- <include name="importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesSucceed" />
- </methods>
- </class>
- </classes>
- </test> <!-- Test -->
-
- <test name="attribute">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.attribute.ComponentInstanceAttributeTest">
- <methods>
- <include name="testUpdateAttributeOnResourceInstance" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="inputs">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.inputs.InputsApiTests">
- <methods>
- <include name="testInputsMainFunctionality" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="property">
- <classes>
- <class
- name="org.openecomp.sdc.ci.tests.execute.property.AdditionalInformationServletTest">
- <methods>
- <include name="createResourceAdditionalInformationTestDuringLifecycle" />
- <include name="updateResourceAdditionalInformationTest" />
- <include name="deleteResourceAdditionalInformationTest" />
- </methods>
- </class>
-
- <class name="org.openecomp.sdc.ci.tests.execute.property.PropertyApisTest">
- <methods>
- <include name="testPropertyApis" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.property.ComponentInstancePropertyTest">
- <methods>
- <include name="nestedVfResourceProperty3Levels" />
- </methods>
- </class>
-
-
-
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.property.PropertyServletTest">
- <methods> <include name="createCascadeVfResource" /> <include name="createPropertyTestSetClearDefaultValueInetegr"
- /> </methods> </class> -->
- </classes>
- </test>
-
- <test name="User">
- <classes>
-
- <!-- class
- name="org.openecomp.sdc.ci.tests.execute.user.ActivateDeActivateDeleteUser">
- <methods>
- <include name="authorizeDeActivatedUser" />
- </methods>
- </class-->
-
- <class name="org.openecomp.sdc.ci.tests.execute.user.CreateUserApiTest">
- <methods>
- <include name="createUser" />
- </methods>
- </class>
-
- <class
- name="org.openecomp.sdc.ci.tests.execute.user.GovernorWorkspaceApiTest">
- <methods>
- <include name="governorList_AllCertifiedVersionsOfService" />
- </methods>
- </class>
-
- </classes>
- </test>
-
- <test name="ExternalApis">
- <classes>
- <class name="org.openecomp.sdc.externalApis.GetAssetServlet" >
- <methods>
- <include name="getResourceAssetSuccess" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.externalApis.GetFilteredAssetServlet">
- <methods>
- <include name="getResourceAssetBySpecifiedCategoryAndSubCategory" />
- <include name="getServiceAssetBySpecifiedCategoryAndDistributionStatus" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.externalApis.GetSpecificAssetMetadataServlet">
- <methods>
- <include name="getResourceAssetMetadataWithResourceInstancesSuccess" />
- <include name="getServiceAssetMetadataWithCertifiedResourceInstancesAndArtifactsOnRIsAndServiceSuccess" />
- </methods>
- </class>
- </classes>
- </test>
-
-
-
-
-
-
-
-</suite> \ No newline at end of file
diff --git a/asdc-tests/src/main/resources/ci/testSuites/service.xml b/asdc-tests/src/main/resources/ci/testSuites/service.xml
deleted file mode 100644
index 18d5630c4e..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/service.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Service" >
- <test name="Service">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.service.GetServiceLatestVersionTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.service.CreateServiceMetadataApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.service.ReqCapOccurrencesTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.service.ChangeServiceDistributionStatusApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.service.ServiceComponentInstanceCRUDTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.service.UpdateServiceMetadataTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.service.GetAllServiceVersions"/>
- </classes>
- </test>
-</suite> <!-- Service -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/testngLifeCycle.xml b/asdc-tests/src/main/resources/ci/testSuites/testngLifeCycle.xml
deleted file mode 100644
index 54f1868470..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/testngLifeCycle.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="lifeCycle" >
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_cerificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceResourceLCSTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_UndoCheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_UndoCheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_StartCertificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_CheckinCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_CheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceCertWithResourceInstances"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CrossCheckOutTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CertifyVFWithNotCertRIs"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_request4CerCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CleanupIntermediateReources"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_CheckOutCIT"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_cerificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CertifyServiceWithNotCertRI"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_CheckInCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_request4CerCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_StartCertificationCITest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- lifeCycle -->
diff --git a/asdc-tests/src/main/resources/ci/testSuites/user.xml b/asdc-tests/src/main/resources/ci/testSuites/user.xml
deleted file mode 100644
index 948993c144..0000000000
--- a/asdc-tests/src/main/resources/ci/testSuites/user.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="User" >
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.user.AuthorizedUserApiTest_extend"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.AuthorizedUserApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.OpsWorkspaceApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.UserApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.GetAllAdminUsersApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.CRUDUserTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.CreateUserApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.GovernorWorkspaceApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.GetListsOfTesterUserApiTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.user.ActivateDeActivateDeleteUser"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- User -->
diff --git a/asdc-tests/src/test/resources/CI/components/apache/apache-type.yml b/asdc-tests/src/test/resources/CI/components/apache/apache-type.yml
deleted file mode 100644
index 360b1a2d60..0000000000
--- a/asdc-tests/src/test/resources/CI/components/apache/apache-type.yml
+++ /dev/null
@@ -1,50 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-description: TOSCA simple profile with Apache.
-template_name: apache-type
-template_version: 2.0.0-SNAPSHOT
-template_author: FastConnect
-
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
- - "tosca-normative-types-webServer:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- alien.nodes.Apache:
- derived_from: tosca.nodes.WebServer
- description: >
- The TOSCA Apache Node Type represents an apache component
- that can be managed and run by a TOSCA Compute Node Type.
- capabilities:
- host:
- type: alien.capabilities.ApacheContainer
- properties:
- valid_node_types: [ tosca.nodes.WebApplication ]
- tags:
- icon: /images/apache.png
- properties:
- version:
- type: version
- default: 2.4
- constraints:
- - equal: 2.4
- port:
- type: integer
- description: Port for the Apache server
- default: 80
- constraints:
- - greater_or_equal: 1
- document_root:
- type: string
- default: "/var/www"
- interfaces:
- Standard:
- create:
- inputs:
- PORT: { get_property: [SELF, port] }
- DOC_ROOT: { get_property: [SELF, document_root] }
- implementation: scripts/install_apache.sh
- start: scripts/start_apache.sh
-
-capability_types:
- alien.capabilities.ApacheContainer:
- derived_from: tosca.capabilities.Container
diff --git a/asdc-tests/src/test/resources/CI/components/apache/images/apache.png b/asdc-tests/src/test/resources/CI/components/apache/images/apache.png
deleted file mode 100644
index 8e9f402d90..0000000000
--- a/asdc-tests/src/test/resources/CI/components/apache/images/apache.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/apache/scripts/install_apache.sh b/asdc-tests/src/test/resources/CI/components/apache/scripts/install_apache.sh
deleted file mode 100644
index a77f9a13f8..0000000000
--- a/asdc-tests/src/test/resources/CI/components/apache/scripts/install_apache.sh
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/bin/bash
-
-echo "Using apt-get. Installing apache2 on one of the following : Debian, Ubuntu, Mint"
-LOCK="/tmp/lockaptget"
-DEFAULT_PORT=80
-
-while true; do
- if mkdir "${LOCK}" &>/dev/null; then
- echo "Apache 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 apt-get install -y -q apache2 || exit ${1}
-rm -rf "${LOCK}"
-
-sudo /etc/init.d/apache2 stop
-if [ ! -d $DOC_ROOT ]; then
- eval "sudo mkdir -p $DOC_ROOT"
-fi
-eval "sudo chown -R www-data:www-data $DOC_ROOT"
-
-if [[ ("$PORT" == "$DEFAULT_PORT") ]]; then
- echo "Use default port for Apache : $DEFAULT_PORT"
-else
- echo "Replacing port $DEFAULT_PORT with $PORT..."
- sudo sed -i -e "s/$DEFAULT_PORT/$PORT/g" /etc/apache2/ports.conf || exit ${1}
-fi
-
-echo "Change config of apache2"
-if sudo test -f "/etc/apache2/sites-available/default"; then
- echo "Change the DocumentRoot of apache2 on Ubuntu < 14.04"
- sudo sed -i -e "s#DocumentRoot /var/www#DocumentRoot $DOC_ROOT#g" /etc/apache2/sites-available/default
-fi
-if sudo test -f "/etc/apache2/sites-available/000-default.conf"; then
- echo "Change the DocumentRoot of Apache2 on Ubuntu >= 14.04"
- sudo sed -i -e "s#DocumentRoot /var/www/html#DocumentRoot $DOC_ROOT#g" /etc/apache2/sites-available/000-default.conf
-fi
-
-sudo bash -c "echo ServerName localhost >> /etc/apache2/apache2.conf"
-
-echo "Start apache2 whith new conf"
-sudo /etc/init.d/apache2 start
-echo "End of $0"
diff --git a/asdc-tests/src/test/resources/CI/components/apache/scripts/start_apache.sh b/asdc-tests/src/test/resources/CI/components/apache/scripts/start_apache.sh
deleted file mode 100644
index 478c56edf5..0000000000
--- a/asdc-tests/src/test/resources/CI/components/apache/scripts/start_apache.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-
-service="apache2"
-
-if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
-then
- sudo /etc/init.d/$service restart
-else
- sudo /etc/init.d/$service start
-fi
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/images/relational_db.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/images/relational_db.png
deleted file mode 100644
index a7a632effd..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/images/relational_db.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/normative-types-DBMS.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/normative-types-DBMS.yml
deleted file mode 100644
index 4a924672fc..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/DBMS/normative-types-DBMS.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-DBMS
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
- - "tosca-normative-types-softwareComponent:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.DBMS:
- abstract: true
- derived_from: tosca.nodes.SoftwareComponent
- description: >
- The TOSCA DBMS node represents a typical relational, SQL Database Management System software component or service.
- tags:
- icon: /images/relational_db.png
- properties:
- dbms_root_password:
- type: string
- required: false
- description: the root password for the DBMS service.
- dbms_port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
- capabilities:
- host:
- type: tosca.capabilities.Container
- properties:
- valid_node_types: [tosca.nodes.Database]
- endpoint:
- type: tosca.capabilities.DatabaseEndpoint
-
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/images/volume.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/images/volume.png
deleted file mode 100644
index 16fa17bd70..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/images/volume.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/normative-types-blockStorage.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/normative-types-blockStorage.yml
deleted file mode 100644
index df942b9f4f..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/blockStorage/normative-types-blockStorage.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-blockStorage
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.BlockStorage:
- derived_from: tosca.nodes.Root
- description: >
- The TOSCA BlockStorage node currently represents a server-local block storage device (i.e., not shared)
- offering evenly sized blocks of data from which raw storage volumes can be created.
- tags:
- icon: /images/volume.png
- properties:
- size:
- type: integer
- required: false
- constraints:
- - greater_than: 0
- description: The requested storage size in MegaBytes (MB).
- volume_id:
- type: string
- required: false
- description: ID of an existing volume (that is in the accessible scope of the requesting application).
- snapshot_id:
- type: string
- required: false
- description: Some identifier that represents an existing snapshot that should be used when creating the block storage (volume).
- attributes:
- volume_id:
- type: string
- description: ID provided by the orchestrator for newly created volumes.
- requirements:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/compute/images/compute.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/compute/images/compute.png
deleted file mode 100644
index 7d5297eed3..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/compute/images/compute.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/compute/normative-types-compute.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/compute/normative-types-compute.yml
deleted file mode 100644
index 3a972a81e0..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/compute/normative-types-compute.yml
+++ /dev/null
@@ -1,77 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-compute
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- # Infrastructure components
- tosca.nodes.Compute:
- derived_from: tosca.nodes.Root
- description: >
- Represents a real or virtual machine or ‘server’. Informations specified on the Compute
- node will be used to find the machine that fits the given requirements in the cloud
- available machines. If no sizing informations are specified the cloud’s provider default
- machine will be used. It is strongly recommended to specify the required cpus and memory
- at least.
- tags:
- icon: /images/compute.png
- properties:
- num_cpus:
- type: integer
- required: false
- constraints:
- - greater_than: 0
- description: Number of (actual or virtual) CPUs associated with the Compute node.
- mem_size:
- type: integer
- required: false
- constraints:
- - greater_than: 0
- description: Size of memory, in Megabytes (MB), available to applications running on the Compute node.
- disk_size:
- type: integer
- required: false
- constraints:
- - greater_than: 0
- description: Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.
- os_arch:
- type: string
- constraints:
- - valid_values: ["x86_32", "x86_64"]
- description: The host Operating System (OS) architecture.
- os_type:
- type: string
- constraints:
- - valid_values: ["linux", "aix", "mac os", "windows"]
- description: The host Operating System (OS) type.
- os_distribution:
- type: string
- required: false
- description: The host Operating System (OS) distribution.
- os_version:
- type: string
- required: false
- description: The host Operating System version.
- attributes:
- ip_address:
- type: string
- description: >
- The primary IP address assigned by the cloud provider that applications may use to access the Compute node.
- Note: This is used by the platform provider to convey the primary address used to access the compute node. Future working drafts will address implementations that support floating or multiple IP addresses.
- requirements:
- network:
- type: tosca.capabilities.Connectivity
- lower_bound: 0
- upper_bound: unbounded
- capabilities:
- host:
- type: tosca.capabilities.Container
- properties:
- valid_node_types: [tosca.nodes.SoftwareComponent]
- attach: tosca.capabilities.Attachment
- scalable: tosca.capabilities.Scalable
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/database/images/relational_db.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/database/images/relational_db.png
deleted file mode 100644
index a7a632effd..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/database/images/relational_db.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/database/normative-types-database.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/database/normative-types-database.yml
deleted file mode 100644
index 38bf5d11db..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/database/normative-types-database.yml
+++ /dev/null
@@ -1,41 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-database
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
- - "tosca-normative-types-DBMS:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.Database:
- derived_from: tosca.nodes.Root
- description: >
- Base type for the schema and content associated with a DBMS.
- The TOSCA Database node represents a logical database that can be managed and hosted by a TOSCA DBMS node.
- tags:
- icon: /images/relational_db.png
- properties:
- db_user:
- type: string
- required: false
- description: The special user account used for database administration.
- db_password:
- type: string
- required: false
- description: The password associated with the user account provided in the ‘db_user’ property.
- db_port:
- type: integer
- required: false
- description: The port on which the underlying database service will listen to data.
- db_name:
- type: string
- required: false
- description: The logical name of the database.
- requirements:
- - host: tosca.nodes.DBMS
- relationship_type: tosca.relationships.HostedOn
- capabilities:
- database_endpoint: tosca.capabilities.DatabaseEndpoint
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
deleted file mode 100644
index c8bf18f31a..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/network/images/network.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/network/normative-types-network.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/network/normative-types-network.yml
deleted file mode 100644
index bb860f82be..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/network/normative-types-network.yml
+++ /dev/null
@@ -1,39 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-network
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.Network:
- derived_from: tosca.nodes.Root
- description: >
- The TOSCA Network node represents a simple, logical network service.
- properties:
- ip_version:
- type: integer
- required: false
- default: 4
- constraints:
- - valid_values: [ 4, 6 ]
- cidr:
- type: string
- required: false
- gateway_ip:
- type: string
- required: false
- network_name:
- type: string
- required: false
- network_id:
- type: string
- required: false
- capabilities:
- connection:
- type: tosca.capabilities.Connectivity
- tags:
- icon: /images/network.png
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/images/objectstore.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/images/objectstore.png
deleted file mode 100644
index 2b2063c4f7..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/images/objectstore.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/normative-types-objectStorage.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/normative-types-objectStorage.yml
deleted file mode 100644
index a56fad5363..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/objectStorage/normative-types-objectStorage.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-objectStorage
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.ObjectStorage:
- abstract: true
- derived_from: tosca.nodes.Root
- description: >
- The TOSCA ObjectStorage node represents storage that provides the ability to store data as objects (or BLOBs of data)
- without consideration for the underlying filesystem or devices.
- tags:
- icon: /images/objectstore.png
- properties:
- store_name:
- type: string
- description: The logical name of the object store (or container).
- store_size:
- type: integer
- required: false
- constraints:
- - greater_or_equal: 0
- description: The requested initial storage size in Gigabytes.
- store_maxsize:
- type: integer
- required: false
- constraints:
- - greater_than: 0
- description: The requested maximum storage size in Gigabytes.
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/root/images/root.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/root/images/root.png
deleted file mode 100644
index 170f1c3c27..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/root/images/root.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/root/normative-types-root.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/root/normative-types-root.yml
deleted file mode 100644
index 7f4c16c260..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/root/normative-types-root.yml
+++ /dev/null
@@ -1,168 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-root
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-
-node_types:
- tosca.nodes.Root:
- abstract: true
- description: >
- This is the default (root) TOSCA Node Type that all other TOSCA nodes should extends.
- This allows all TOSCA nodes to have a consistent set of features for modeling and management
- (e.g, consistent definitions for requirements, capabilities, and lifecycle interfaces).
- tags:
- icon: /images/root.png
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- requirements:
- dependency:
- type: tosca.capabilities.Root
- lower_bound: 0
- upper_bound: unbounded
- capabilities:
- root:
- type: tosca.capabilities.Root
- interfaces:
- tosca.interfaces.node.lifecycle.Standard:
- description: >
- This lifecycle interface defines the essential, normative operations that TOSCA nodes may support.
- create:
- description: Standard lifecycle create operation.
- configure:
- description: Standard lifecycle configure operation (pre-start).
- start:
- description: Standard lifecycle start operation.
- post_start:
- description: Standard lifecycle post-configure operation (post-start)
- stop:
- description: Standard lifecycle stop operation.
- delete:
- description: Standard lifecycle delete operation.
-
-
-capability_types:
- tosca.capabilities.Root:
- description: This is the default (root) TOSCA Capability Type definition that all other TOSCA Capability Types derive from.
- tosca.capabilities.Container:
- derived_from: tosca.capabilities.Root
- properties:
- valid_node_types:
- type: string
- required: true
- description: >
- A list of one or more names of Node Types that are supported as containees that declare the Container type as a Capability.
- tosca.capabilities.Endpoint:
- derived_from: tosca.capabilities.Root
- properties:
- protocol:
- type: string
- default: tcp
- port:
- type: integer
- required: false
- constraints:
- - greater_or_equal: 1
- - less_or_equal: 65535
- secure:
- type: boolean
- default: false
- url_path:
- type: string
- required: false
- tosca.capabilities.DatabaseEndpoint:
- derived_from: tosca.capabilities.Endpoint
- description: This is the default TOSCA type that should be used or extended to define a specialized database endpoint capability.
- tosca.capabilities.Attachment:
- derived_from: tosca.capabilities.Root
- description: This is the default TOSCA type that should be used or extended to define a network endpoint capability.
- tosca.capabilities.Scalable:
- derived_from: tosca.capabilities.Root
- properties:
- min_intances:
- type: integer
- default: 1
- max_intances:
- type: integer
- default: 1
- default_instances:
- type: integer
- default: 1
- tosca.capabilities.Connectivity:
- derived_from: tosca.capabilities.Root
-
-relationship_types:
- tosca.relationships.Root:
- abstract: true
- description: This is the default (root) TOSCA Relationship Type definition that all other TOSCA Relationship Types derive from.
- valid_targets: [ tosca.capabilities.Root ]
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- interfaces:
- tosca.interfaces.relationship.Configure:
- description: >
- The lifecycle interfaces define the essential, normative operations that each TOSCA Relationship Types may support.
- pre_configure_source:
- description: Operation to pre-configure the source endpoint.
- pre_configure_target:
- description: Operation to pre-configure the target endpoint.
- post_configure_source:
- description: Operation to post-configure the source endpoint.
- post_configure_target:
- description: Operation to post-configure the target endpoint.
- add_target:
- description: Operation to notify the source node of a target node being added via a relationship.
- add_source:
- description: Operation to notify the target node of a source node which is now available via a relationship.
- remove_target:
- description: Operation to notify the source node of a target node being removed from a relationship.
- remove_source:
- description: Operation to notify the target node of a source node being removed from a relationship.
- target_changed:
- description: Operation to notify source some property or attribute of the target.
- source_changed:
- description: Operation to notify target some property or attribute of the source.
- tosca.relationships.DependsOn:
- derived_from: tosca.relationships.Root
- description: >
- A generic depends on relationship.
- tosca.relationships.HostedOn:
- derived_from: tosca.relationships.DependsOn
- description: Relationship to use to describe that the source is hosted (installed/ deployed) on the target node.
- valid_targets: [ tosca.capabilities.Container ]
- tosca.relationships.ConnectsTo:
- derived_from: tosca.relationships.DependsOn
- valid_targets: [ tosca.capabilities.Endpoint ]
- tosca.relationships.AttachTo:
- derived_from: tosca.relationships.Root
- valid_targets: [ tosca.capabilities.Attachment ]
- properties:
- location:
- type: string
- constraints:
- - min_length: 1
- device:
- type: string
- required: false
- tosca.relationships.Network:
- derived_from: tosca.relationships.Root
- valid_sources: [ tosca.capabilities.Connectivity ]
- valid_targets: [ tosca.capabilities.Connectivity ]
-
-artifact_types:
- tosca.artifacts.Root:
- description: The TOSCA Artifact Type all other TOSCA Artifact Types derive from.
- tosca.artifacts.File:
- derived_from: tosca.artifacts.Root
- description: This artifact type is used when an artifact definition needs to have its associated file simply treated as a file and no special handling/handlers are invoked.
- tosca.artifacts.ShellScript:
- description: A shell script (.sh file)
- file_ext: [ sh ]
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/images/software.png b/asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/images/software.png
deleted file mode 100644
index dc9c53245d..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/images/software.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/normative-types-softwareComponent.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/normative-types-softwareComponent.yml
deleted file mode 100644
index 04e04af640..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/softwareComponent/normative-types-softwareComponent.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-softwareComponent
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
- - "tosca-normative-types-compute:1.0.0.wd03-SNAPSHOT"
-
-node_types:
-
- tosca.nodes.SoftwareComponent:
- abstract: true
- derived_from: tosca.nodes.Root
- description: >
- The TOSCA SoftwareComponent Node Type represents a generic software component
- that can be managed and run by a TOSCA Compute Node Type.
- requirements:
- - host: tosca.nodes.Compute
- type: tosca.relationships.HostedOn
- tags:
- icon: /images/software.png
-
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
deleted file mode 100644
index c8bf18f31a..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/images/network.png
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/normative-types-webApplication.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/normative-types-webApplication.yml
deleted file mode 100644
index ded008ebdf..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/webApplication/normative-types-webApplication.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-webApplication
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
- - "tosca-normative-types-webServer:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.WebApplication:
- derived_from: tosca.nodes.Root
- description: >
- The TOSCA WebApplication node represents a software application that can be managed and run by a TOSCA WebServer node. Specific types of web applications such as Java, etc. could be derived from this type.
- tags:
- icon: /images/network.png
- requirements:
- - host: tosca.nodes.WebServer
- type: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/components/normativeTypes/webServer/normative-types-webServer.yml b/asdc-tests/src/test/resources/CI/components/normativeTypes/webServer/normative-types-webServer.yml
deleted file mode 100644
index 1c2e4b2ea5..0000000000
--- a/asdc-tests/src/test/resources/CI/components/normativeTypes/webServer/normative-types-webServer.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0_wd03
-
-template_name: tosca-normative-types-webServer
-template_author: TOSCA TC
-template_version: 1.0.0.wd03-SNAPSHOT
-
-description: Contains the normative types definition.
-imports:
- - "tosca-normative-types-root:1.0.0.wd03-SNAPSHOT"
- - "tosca-normative-types-softwareComponent:1.0.0.wd03-SNAPSHOT"
-
-node_types:
- tosca.nodes.WebServer:
- abstract: true
- derived_from: tosca.nodes.SoftwareComponent
- description: >
- The TOSCA WebServer Node Type represents an abstract software component or service that is capable of hosting and providing management operations for one or more WebApplication nodes
- capabilities:
- app_endpoint: tosca.capabilities.Endpoint
- secure_endpoint: tosca.capabilities.Endpoint
- host:
- type: tosca.capabilities.Container
- properties:
- valid_node_types: [ tosca.nodes.WebApplication ]
diff --git a/asdc-tests/src/test/resources/CI/configuration.yaml b/asdc-tests/src/test/resources/CI/configuration.yaml
deleted file mode 100644
index 87fada1b4b..0000000000
--- a/asdc-tests/src/test/resources/CI/configuration.yaml
+++ /dev/null
@@ -1,386 +0,0 @@
-identificationHeaderFields:
- - HTTP_IV_USER
- - HTTP_CSP_FIRSTNAME
- - HTTP_CSP_LASTNAME
- - HTTP_IV_REMOTE_ADDRESS
- - HTTP_CSP_WSTYPE
-
-
-
-# catalog backend hostname
-beFqdn: sdccatalog.att.com
-
-# catalog backend http port
-beHttpPort: 8080
-
-# catalog backend http context
-beContext: /sdc/rest/config/get
-
-# catalog backend protocol
-beProtocol: http
-
-# catalog backend ssl port
-beSslPort: 8443
-
-version: 1.0
-released: 2012-11-30
-
-titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
-titanInMemoryGraph: false
-titanLockTimeout: 30
-titanReconnectIntervalInSeconds: 3
-titanHealthCheckReadTimeout: 1
-esReconnectIntervalInSeconds: 3
-uebHealthCheckReconnectIntervalInSeconds: 15
-uebHealthCheckReadTimeout: 4
-
-# Protocols
-protocols:
- - http
- - https
-
-# Users
-users:
- tom: passwd
- bob: passwd
-
-neo4j:
- host: neo4jhost
- port: 7474
- user: neo4j
- password: "12345"
-
-
-#Application-specific settings of ES
-elasticSearch:
- # Mapping of index prefix to time-based frame. For example, if below is configured:
- #
- # - indexPrefix: auditingevents
- # creationPeriod: minute
- #
- # then ES object of type which is mapped to "auditingevents-*" template, and created on 2015-12-23 13:24:54, will enter "auditingevents-2015-12-23-13-24" index.
- # Another object created on 2015-12-23 13:25:54, will enter "auditingevents-2015-12-23-13-25" index.
- # If creationPeriod: month, both of the above will enter "auditingevents-2015-12" index.
- #
- # PLEASE NOTE: the timestamps are created in UTC/GMT timezone! This is needed so that timestamps will be correctly presented in Kibana.
- #
- # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour).
- #
- # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month.
-
- indicesTimeFrequency:
- - indexPrefix: auditingevents
- creationPeriod: month
- - indexPrefix: monitoring_events
- creationPeriod: month
-
-artifactTypes:
- - CHEF
- - PUPPET
- - SHELL
- - YANG
- - YANG_XML
- - HEAT
- - BPEL
- - DG_XML
- - MURANO_PKG
- - WORKFLOW
- - NETWORK_CALL_FLOW
- - OTHER
-
-licenseTypes:
- - User
- - Installation
- - CPU
-
-#Deployment artifacts placeHolder
-resourceTypes: &allResourceTypes
- - VFC
- - CP
- - VL
- - VF
-
-# validForResourceTypes usage
-# validForResourceTypes:
-# - VF
-# - VL
-deploymentResourceArtifacts:
- heat:
- displayName: "Base HEAT Template"
- type: HEAT
- validForResourceTypes: *allResourceTypes
- heatVol:
- displayName: "Volume HEAT Template"
- type: HEAT_VOL
- validForResourceTypes: *allResourceTypes
- heatNet:
- displayName: "Network HEAT Template"
- type: HEAT_NET
- validForResourceTypes: *allResourceTypes
-
-deploymentResourceInstanceArtifacts:
- heatEnv:
- displayName: "HEAT ENV"
- type: HEAT_ENV
- description: "Auto-generated HEAT Environment deployment artifact"
- fileExtension: "env"
-
-#Informational artifacts placeHolder
-excludeResourceCategory:
- - Generic
-informationalResourceArtifacts:
- features:
- displayName: Features
- type: OTHER
- capacity:
- displayName: Capacity
- type: OTHER
- vendorTestResult:
- displayName: Vendor Test Result
- type: OTHER
- testScripts:
- displayName: Test Scripts
- type: OTHER
- CloudQuestionnaire:
- displayName: Cloud Questionnaire (completed)
- type: OTHER
- HEATTemplateFromVendor:
- displayName: HEAT Template from Vendor
- type: HEAT
- resourceSecurityTemplate:
- displayName: Resource Security Template
- type: OTHER
-
-excludeServiceCategory:
-
-informationalServiceArtifacts:
- serviceArtifactPlan:
- displayName: Service Artifact Plan
- type: OTHER
- summaryOfImpactsToECOMPElements:
- displayName: Summary of impacts to ECOMP elements,OSSs, BSSs
- type: OTHER
- controlLoopFunctions:
- displayName: Control Loop Functions
- type: OTHER
- dimensioningInfo:
- displayName: Dimensioning Info
- type: OTHER
- affinityRules:
- displayName: Affinity Rules
- type: OTHER
- operationalPolicies:
- displayName: Operational Policies
- type: OTHER
- serviceSpecificPolicies:
- displayName: Service-specific Policies
- type: OTHER
- engineeringRules:
- displayName: Engineering Rules (ERD)
- type: OTHER
- distributionInstructions:
- displayName: Distribution Instructions
- type: OTHER
- certificationTestResults:
- displayName: TD Certification Test Results
- type: OTHER
- deploymentVotingRecord:
- displayName: Deployment Voting Record
- type: OTHER
- serviceQuestionnaire:
- displayName: Service Questionnaire
- type: OTHER
- serviceSecurityTemplate:
- displayName: Service Security Template
- type: OTHER
-
-serviceApiArtifacts:
- configuration:
- displayName: Configuration
- type: OTHER
- instantiation:
- displayName: Instantiation
- type: OTHER
- monitoring:
- displayName: Monitoring
- type: OTHER
- reporting:
- displayName: Reporting
- type: OTHER
- logging:
- displayName: Logging
- type: OTHER
- testing:
- displayName: Testing
- type: OTHER
-
-
-additionalInformationMaxNumberOfKeys: 50
-
-systemMonitoring:
- enabled: false
- isProxy: false
- probeIntervalInSeconds: 15
-
-defaultHeatArtifactTimeoutMinutes: 60
-
-serviceDeploymentArtifacts:
- YANG_XML:
- acceptedTypes:
- - xml
- VNF_CATALOG:
- acceptedTypes:
- - xml
- MODEL_INVENTORY_PROFILE:
- acceptedTypes:
- - xml
- MODEL_QUERY_SPEC:
- acceptedTypes:
- - xml
- OTHER:
- acceptedTypes:
-
-resourceDeploymentArtifacts:
- HEAT:
- acceptedTypes:
- - yaml
- - yml
- validForResourceTypes: *allResourceTypes
- HEAT_VOL:
- acceptedTypes:
- - yaml
- - yml
- validForResourceTypes: *allResourceTypes
- HEAT_NET:
- acceptedTypes:
- - yaml
- - yml
- validForResourceTypes: *allResourceTypes
- YANG_XML:
- acceptedTypes:
- - xml
- validForResourceTypes: *allResourceTypes
- VNF_CATALOG:
- acceptedTypes:
- - xml
- validForResourceTypes: *allResourceTypes
- VF_LICENSE:
- acceptedTypes:
- - xml
- validForResourceTypes: *allResourceTypes
- VENDOR_LICENSE:
- acceptedTypes:
- - xml
- validForResourceTypes: *allResourceTypes
- MODEL_INVENTORY_PROFILE:
- acceptedTypes:
- - xml
- validForResourceTypes: *allResourceTypes
- MODEL_QUERY_SPEC:
- acceptedTypes:
- - xml
- validForResourceTypes: *allResourceTypes
- APPC_CONFIG:
- acceptedTypes:
- - xml
- - json
- validForResourceTypes:
- - VF
- OTHER:
- acceptedTypes:
- validForResourceTypes: *allResourceTypes
-
-resourceInstanceDeploymentArtifacts:
- HEAT_ENV:
- acceptedTypes:
- - env
-
-resourceInformationalDeployedArtifacts:
-
-
-requirementsToFulfillBeforeCert:
- CP:
- - tosca.capabilities.network.Bindable
-
-capabilitiesToConsumeBeforeCert:
-
-unLoggedUrls:
- - /sdc2/rest/healthCheck
-
-cleanComponentsConfiguration:
- cleanIntervalInMinutes: 1440
- componentsToClean:
- - Resource
- - Service
-
-artifactsIndex: resources
-
-cassandraConfig:
- cassandraHosts: ['localhost']
- localDataCenter:
- reconnectTimeout : 30000
- authenticate: false
- username: koko
- password: bobo
- ssl: false
- truststorePath : /path/path
- truststorePassword : 123123
- keySpaces:
- - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
-
-heatEnvArtifactHeader: ""
-heatEnvArtifactFooter: ""
-
-onboarding:
- protocol: http
- host: localhost
- port: 8181
- downloadCsarUri: "/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages"
-
-switchoverDetector:
- gBeFqdn: AIO-BE.ecomp.idns.cip.com
- gFeFqdn: AIO-FE.ecomp.idns.cip.com
- beVip: 0.0.0.0
- feVip: 0.0.0.0
- beResolveAttempts: 3
- feResolveAttempts: 3
- enabled: false
- interval: 60
- changePriorityUser: ecompasdc
- changePriorityPassword: ecompasdc123
- publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
- publishNetworkBody: '{"note":"publish network"}'
- groups:
- beSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip.com?user=root",
- changePriorityBody: '{"name":"AIO-BE.ecomp.idns.cip.com","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.cip.com","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'}
- feSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip.att.com?user=root",
- changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.cip.com","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.cip.com"}'}
-
-
-applicationL1Cache:
- datatypes:
- enabled: true
- firstRunDelay: 10
- pollIntervalInSec: 60
-
-applicationL2Cache:
- enabled: false
- catalogL1Cache:
- enabled: true
- resourcesSizeInCache: 300
- servicesSizeInCache: 200
- productsSizeInCache: 100
- queue:
- syncIntervalInSecondes: 60
- waitOnShutDownInMinutes: 30
- numberOfCacheWorkers: 4
-
-toscaValidators:
- stringMaxLength: 1024
-
-
-genericAssetNodeTypes:
- VFC: org.openecomp.resource.abstract.nodes.VFC
- VF : org.openecomp.resource.abstract.nodes.VF
- Service: org.openecomp.resource.abstract.nodes.service \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csar b/asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csar
deleted file mode 100644
index 9c1629eae7..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/FCGI_with_inputs.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC.csar b/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC.csar
deleted file mode 100644
index 7fc5306bcc..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csar b/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csar
deleted file mode 100644
index 7a77e2011d..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/ImportArtifactsToVFC_empty.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csar b/asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csar
deleted file mode 100644
index 821b62d48a..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/LDSA1_with_inputs.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/ToscaTemplateCsar.csar b/asdc-tests/src/test/resources/CI/csars/ToscaTemplateCsar.csar
deleted file mode 100644
index e12f45e1b1..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/ToscaTemplateCsar.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csar
deleted file mode 100644
index 98e20258b2..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_a.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_a.csar
deleted file mode 100644
index 98e20258b2..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_a.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_b.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_b.csar
deleted file mode 100644
index 4668bbefb8..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_b.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming.csar
deleted file mode 100644
index 04464af741..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_a.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_a.csar
deleted file mode 100644
index 4903bff3b6..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_a.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_add_update.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_add_update.csar
deleted file mode 100644
index 8398e710b4..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_add_update.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_delete_update.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_delete_update.csar
deleted file mode 100644
index 61a494c092..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_group_naming_delete_update.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_update.csar b/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_update.csar
deleted file mode 100644
index 035497a52e..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_update.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csar b/asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csar
deleted file mode 100644
index 07118fc014..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/jsonPropertyTypeTest.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/mycompute.yml b/asdc-tests/src/test/resources/CI/csars/mycompute.yml
deleted file mode 100644
index c8a0c03384..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/mycompute.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vfc.mycompute:
- derived_from: tosca.nodes.Compute
- capabilities:
- scalable:
- type: tosca.capabilities.Scalable
- properties:
- propertyForTest:
- type: string
- description: test
- required: true
- default: success
- # min_instances property should override property from tosca.capabilities.Scalable
- min_instances:
- type: integer
- default: 3
-
diff --git a/asdc-tests/src/test/resources/CI/csars/mycompute2.yml b/asdc-tests/src/test/resources/CI/csars/mycompute2.yml
deleted file mode 100644
index 9d479a1a55..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/mycompute2.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vfc.mycompute2:
- derived_from: tosca.nodes.Compute
- capabilities:
- scalable:
- type: tosca.capabilities.Scalable
- properties:
- propertyForTest:
- type: string
- description: test
- required: true
- default: success
- # min_instances property should override property from tosca.capabilities.Scalable
- min_instances:
- type: integer
- default: 3
-
diff --git a/asdc-tests/src/test/resources/CI/csars/mycompute_failed.yml b/asdc-tests/src/test/resources/CI/csars/mycompute_failed.yml
deleted file mode 100644
index a4d8e448f1..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/mycompute_failed.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vfc.mycompute:
- derived_from: tosca.nodes.Compute
- capabilities:
- scalable:
- type: tosca.capabilities.Scalable
- properties:
- propertyForTest:
- type: string
- description: test
- required: true
- default: success
- # min_instances property should override property from tosca.capabilities.Scalable
- min_instances:
- type: string
- default: 3
-
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2G.csar b/asdc-tests/src/test/resources/CI/csars/orig2G.csar
deleted file mode 100644
index 2e8670f1eb..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2G.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2GV001.csar b/asdc-tests/src/test/resources/CI/csars/orig2GV001.csar
deleted file mode 100644
index e6e545ea2f..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2GV001.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csar b/asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csar
deleted file mode 100644
index d5a7b47b70..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2GV001_a.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2GV006-remove-all-nested-artifacts.csar b/asdc-tests/src/test/resources/CI/csars/orig2GV006-remove-all-nested-artifacts.csar
deleted file mode 100644
index 88cebe44f2..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2GV006-remove-all-nested-artifacts.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2GV008-change-nested-oam-fileContent.csar b/asdc-tests/src/test/resources/CI/csars/orig2GV008-change-nested-oam-fileContent.csar
deleted file mode 100644
index 7c24de025d..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2GV008-change-nested-oam-fileContent.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2G_a.csar b/asdc-tests/src/test/resources/CI/csars/orig2G_a.csar
deleted file mode 100644
index 9af7501b76..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2G_a.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/orig2G_updated.csar b/asdc-tests/src/test/resources/CI/csars/orig2G_updated.csar
deleted file mode 100644
index 1a4107811d..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/orig2G_updated.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/valid_vf.csar b/asdc-tests/src/test/resources/CI/csars/valid_vf.csar
deleted file mode 100644
index 01bf159071..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/valid_vf.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/valid_vf_a.csar b/asdc-tests/src/test/resources/CI/csars/valid_vf_a.csar
deleted file mode 100644
index 01bf159071..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/valid_vf_a.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/valid_vf_b.csar b/asdc-tests/src/test/resources/CI/csars/valid_vf_b.csar
deleted file mode 100644
index 3c0b683321..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/valid_vf_b.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/valid_vf_c.csar b/asdc-tests/src/test/resources/CI/csars/valid_vf_c.csar
deleted file mode 100644
index 57e3551682..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/valid_vf_c.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/valid_vf_d.csar b/asdc-tests/src/test/resources/CI/csars/valid_vf_d.csar
deleted file mode 100644
index d66dfb60d9..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/valid_vf_d.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/valid_vf_f.csar b/asdc-tests/src/test/resources/CI/csars/valid_vf_f.csar
deleted file mode 100644
index a9a4bc75ab..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/valid_vf_f.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vf_relate_by_cap_name.csar b/asdc-tests/src/test/resources/CI/csars/vf_relate_by_cap_name.csar
deleted file mode 100644
index eec433e8ff..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vf_relate_by_cap_name.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop.csar b/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop.csar
deleted file mode 100644
index df98e259d6..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csar b/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csar
deleted file mode 100644
index ce1541f32c..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csar b/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csar
deleted file mode 100644
index a2a9ad77c9..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop_failed.csar b/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop_failed.csar
deleted file mode 100644
index 6e23829e8a..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop_failed.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vfc_artifacts.csar b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts.csar
deleted file mode 100644
index 8b5f58b7ef..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vfc_artifacts.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csar b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csar
deleted file mode 100644
index a15e7b46c1..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_delete_all.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_update.csar b/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_update.csar
deleted file mode 100644
index af712f1a59..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vfc_artifacts_update.csar
+++ /dev/null
Binary files 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
deleted file mode 100644
index b11bd9386a..0000000000
--- a/asdc-tests/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.json
deleted file mode 100644
index 1bf593852b..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "LAN_Connector.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.Connector.LAN_Connector",
- "description": "Represents a LAN_Connector Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "org.openecomp.asdc.nodes.Connector.LAN_Connector"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.yml
deleted file mode 100644
index 4fff368cdc..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-org.openecomp.asdc.nodes.Connector.LAN_Connector:
- #The LAN_Connector node connects Router and VNF_Container
- derived_from: org.openecomp.asdc.nodes.Connector
- properties:
- network_id:
- #or called: vlan_id
- type: string
- required: true
- network_type:
- #The technology types used by LAN connector
- type: string
- attributes:
- network_ip_address:
- #ip address is generated only after the node is instantiated at run-time
- type: string
- requirements:
- - connectToRouter :
- capability: tosca.capabilities.Root
- node: org.openecomp.asdc.nodes.Router
- - connectToVNF :
- capability: tosca.capabilities.Root
- node: org.openecomp.asdc.nodes.VNF_Container
- #These two explicit requirements specify the LAN_Connector has two "connectTo" to connect to the node of Router type and VNF_Container type respectively
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.zip
deleted file mode 100644
index 09c3709ace..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/LAN_Connector/LAN_Connector.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.json
deleted file mode 100644
index 35b426c831..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "VNF.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.VNF",
- "description": "Represents a VNF Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "org.openecomp.asdc.nodes.VNF"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.yml
deleted file mode 100644
index 22be623303..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-org.openecomp.asdc.nodes.VNF:
- #The VNF node is required to be hosted by a VNF_Container
- derived_from: org.openecomp.asdc.nodes.Root
- properties:
- service_name:
- type: string
- attributes:
- #attribute means the value is fulfilled at run-time.
- service_id:
- #In this case, we consider the VNF node only has the service_id value when the node is instantiated
- type: string
- requirements:
- #the "host" requirement can establish the relationship with a VNF_Container node
- - host :
- capability: org.openecomp.asdc.capabilities.Container
- node: org.openecomp.asdc.nodes.VNF_Container \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip
deleted file mode 100644
index 95183b48d3..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF/VNF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.json
deleted file mode 100644
index c1347780e3..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "VNF_Container.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.VNF_Container",
- "description": "Represents a VNF_Container Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "org.openecomp.asdc.nodes.VNF_Container"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.yml
deleted file mode 100644
index b8dd8355fa..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-org.openecomp.asdc.nodes.VNF_Container:
- #The VNF_Container node provides the capability to host VNFs.
- derived_from: org.openecomp.asdc.nodes.Root
- capabilities:
- host:
- #The "host" capability allows other TOSCA nodes (VNF) that requires such a capability to connect to this node
- type: org.openecomp.asdc.capabilities.Container
- connectTo:
- #The "connectTo" capability allows other TOSCA nodes (connectors) that requires such a capability to connect to this node.
- type: org.openecomp.asdc.capabilities.Endpoint \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.zip
deleted file mode 100644
index fc1a5e54e8..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/VNF_Container/VNF_Container.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.json
deleted file mode 100644
index 4cb0880297..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "WAN_Connector.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.Connector.WAN_Connector",
- "description": "Represents a WAN_Connector Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "org.openecomp.asdc.nodes.Connector.WAN_Connector"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.yml
deleted file mode 100644
index 741d585488..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-org.openecomp.asdc.nodes.Connector.WAN_Connector:
- #The WAN_Connector node only connects to Router
- derived_from: org.openecomp.asdc.nodes.Connector
- properties:
- customer_id:
- type: string
- required: true
- vpn_id:
- type: string
- required: true
- vpn_name:
- type: string
- required: true
- network_type:
- #The technology types used by WAN connector
- type: string
- attributes:
- network_ip_address:
- #ip address is generated only after the node is instantiated at run-time
- type: string
- requirements:
- - connectTo :
- capability: org.openecomp.asdc.capabilities.Endpoint
- node: org.openecomp.asdc.nodes.Router
- #This explicit requirement specifies WAN_Connector has only one "connectTo" to connect to the node of Router type \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.zip
deleted file mode 100644
index 3c558f0603..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/WAN_Connector/WAN_Connector.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.yml
deleted file mode 100644
index 32989237d2..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-org.openecomp.asdc.capabilities.Endpoint:
- derived_from: tosca.capabilities.Endpoint
-org.openecomp.asdc.capabilities.Container:
- derived_from: tosca.capabilities.Container \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip
deleted file mode 100644
index 9424556f08..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/capabilityTypesWanLan.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.json
deleted file mode 100644
index 99be86c707..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "connector.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.Connector",
- "description": "Represents a connector Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Abstract",
- "tags": [
- "org.openecomp.asdc.nodes.Connector"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.yml
deleted file mode 100644
index d9c9361daa..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-org.openecomp.asdc.nodes.Connector:
- #Connector is the parent node of both WAN and LAN connectors.
- derived_from: org.openecomp.asdc.nodes.Root
- requirements:
- - connectTo:
- capability: org.openecomp.asdc.capabilities.Endpoint
- #the requirement can establish the relationship with a node providing such capability
- relationship: org.openecomp.asdc.relationships.ConnectsTo
- #occurrences means how many times this requirement can appear in one node.
- occurrences: [1, UNBOUNDED] \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip
deleted file mode 100644
index 203db0e34e..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/connector/connector.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/deleteResourcesLanWanDemo.sh b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/deleteResourcesLanWanDemo.sh
deleted file mode 100644
index 9f992d56dd..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/deleteResourcesLanWanDemo.sh
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort>"
-}
-
-function deleteResource() {
-
- ELEMENT_NAME=$1
- echo "###################### Removing Element ${ELEMENT_NAME} Start ######################"
- curl -X "DELETE" -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/resources/res_${ELEMENT_NAME}".1.0"
- echo ""
- echo "###################### Removing Element ${ELEMENT_NAME} End ########################"
- echo ""
- echo ""
- echo ""
-}
-if [ $# -lt 2 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-
-
-deleteResource "org.openecomp.asdc.nodes.Connector.LAN_Connector"
-deleteResource "org.openecomp.asdc.nodes.Connector.WAN_Connector"
-deleteResource "org.openecomp.asdc.nodes.Connector"
-deleteResource "org.openecomp.asdc.nodes.VNF"
-deleteResource "org.openecomp.asdc.nodes.VNF_Container"
-deleteResource "org.openecomp.asdc.nodes.Router"
-deleteResource "org.openecomp.asdc.nodes.Root"
-
-
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/importResourcesLanWanDemo.sh b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/importResourcesLanWanDemo.sh
deleted file mode 100644
index 90a06d53b5..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/importResourcesLanWanDemo.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort>"
-}
-
-function addResource() {
-
- ELEMENT_NAME=$1
- echo -e "###################### Adding Element ${ELEMENT_NAME} Start ######################"
- CURRENT_ZIP_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.zip
- CURRENT_JSON_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.json
- JSON_CONTENT=`paste -s ${CURRENT_JSON_FILE}`
- curl -v -F resourceMetadata="${JSON_CONTENT}" -F resourceZip=@${CURRENT_ZIP_FILE} -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/upload/multipart
- echo ""
- echo -e "###################### Adding Element ${ELEMENT_NAME} End ########################"
-
-}
-if [ $# -lt 2 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-
-#Add The CapabilityTypes
-http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F capabilityTypeZip=@capabilityTypesWanLan.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/capability)
-if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding The CapabilityTypes status code:${http_code} End ########################\n\n\n"
-elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-else
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-fi
-
-addResource "root"
-addResource "router"
-addResource "VNF_Container"
-addResource "VNF"
-addResource "connector"
-addResource "WAN_Connector"
-addResource "LAN_Connector"
-
-
-
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.json
deleted file mode 100644
index 54cbb798a2..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "root.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.Root",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Abstract",
- "tags": [
- "org.openecomp.asdc.nodes.Root"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.yml
deleted file mode 100644
index 34e7d0fb62..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-org.openecomp.asdc.nodes.Root:
- #Define the root node for ASDC modeling
- derived_from: tosca.nodes.Root \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip
deleted file mode 100644
index af28d79174..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/root/root.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.json b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.json
deleted file mode 100644
index 19e4669a38..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "router.yml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.asdc.nodes.Router",
- "description": "Represents a Router Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "org.openecomp.asdc.nodes.Router"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.yml b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.yml
deleted file mode 100644
index 0598663c64..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-org.openecomp.asdc.nodes.Router:
- #The Router node has a property "routing_table" which is a list. The entry of the routing_table is the customized data type "RoutingTableEntry"
- derived_from: org.openecomp.asdc.nodes.Root
- properties:
- routing_table:
- type: list
- entry_schema:
- #"entry_schema" is the TOSCA spec to describe the type of the list item
- type: RoutingTableEntry
- capabilities:
- connectTo:
- #The "connectTo" capability allows other TOSCA nodes (connectors) that requires such a capability to connect to this node.
- type: org.openecomp.asdc.capabilities.Endpoint \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip b/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip
deleted file mode 100644
index f6e2fff528..0000000000
--- a/asdc-tests/src/test/resources/CI/demoResourcesWanLan/router/router.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.json b/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.json
deleted file mode 100644
index 2560a8acfa..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "HSS.yml",
- "contactId": "jh0003",
- "resourceName": "att.nodes.ims.HSS",
- "description": "The home subscriber server (HSS), or user profile server function (UPSF), is a master user database that supports the IMS network entities that actually handle calls. It contains the subscription-related information (subscriber profiles), performs authentication and authorization of the user, and can provide information about the subscriber's location and IP information.",
- "resourceIconPath": "defaulticon",
- "category": "IMS",
- "tags": [
- "att.nodes.ims.HSS", "IMS_TAG"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml b/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml
deleted file mode 100644
index 060059508a..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-att.nodes.ims.HSS:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- icscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more I-CSCF functions
- scscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more S-CSCF functions
- requirements:
- database_endpoint:
- capability: tosca.capabilities.Endpoint.Database
- node: tosca.nodes.Database
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml.old b/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml.old
deleted file mode 100644
index c58191e85b..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.yml.old
+++ /dev/null
@@ -1,28 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-description: >
- The home subscriber server (HSS), or user profile server function (UPSF),
- is a master user database that supports the IMS network entities that actually handle calls.
- It contains the subscription-related information (subscriber profiles),
- performs authentication and authorization of the user, and can provide information about the
- subscriber's location and IP information.
-
-node_types:
- att.nodes.ims.HSS:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- icscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more I-CSCF functions
- scscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more S-CSCF functions
- requirements:
- database_endpoint:
- capability: tosca.capabilities.Endpoint.Database
- node: tosca.nodes.Database
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.zip b/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.zip
deleted file mode 100644
index ed8949f445..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/HSS/HSS.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.json b/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.json
deleted file mode 100644
index 89bf58a2fb..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "ICSCF.yml",
- "contactId": "jh0003",
- "resourceName": "att.nodes.ims.ICSCF",
- "description": "Interrogating-CSCF (I-CSCF) is a SIP function located at the edge of an administrative domain. Its IP address is published in the Domain Name System (DNS) of the domain(using NAPTR and SRV type of DNS records), so that remote servers can find it, and use it as a forwarding point (e.g., registering) for SIP packets to this domain.It queries the HSS to retrieve the address of the S-CSCF and assign it to a user performing SIP registration. It also forwards SIP request or response to the S-CSCF.",
- "resourceIconPath": "defaulticon",
- "category": "IMS",
- "tags": [
- "att.nodes.ims.ICSCF", "IMS_TAG"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml b/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml
deleted file mode 100644
index a00685bc03..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-att.nodes.ims.ICSCF:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- pcscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more P-CSCF functions
- requirements:
- hss_endpoint:
- capability: tosca.capabilities.Endpoint
- node: att.nodes.ims.HSS
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml.old b/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml.old
deleted file mode 100644
index 183f8db3f4..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.yml.old
+++ /dev/null
@@ -1,24 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-description: >
- Interrogating-CSCF (I-CSCF) is a SIP function located at the edge of an administrative domain.
- Its IP address is published in the Domain Name System (DNS) of the domain
- (using NAPTR and SRV type of DNS records), so that remote servers can find it,
- and use it as a forwarding point (e.g., registering) for SIP packets to this domain.
- It queries the HSS to retrieve the address of the S-CSCF and assign it to a user performing SIP
- registration. It also forwards SIP request or response to the S-CSCF.
-
-node_types:
- att.nodes.ims.ICSCF:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- pcscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more P-CSCF functions
- requirements:
- hss_endpoint:
- capability: tosca.capabilities.Endpoint
- node: att.nodes.ims.HSS
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.zip b/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.zip
deleted file mode 100644
index 228372e2f3..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/ICSCF/ICSCF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF .yml.old b/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF .yml.old
deleted file mode 100644
index cd215933ab..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF .yml.old
+++ /dev/null
@@ -1,29 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-description: >
- A Proxy-CSCF (P-CSCF) is a SIP proxy that is the first point of contact for the IMS terminal.
- It can be located either in the visited network (in full IMS networks) or in the home network
- (when the visited network is not IMS compliant yet).
- Some networks may use a Session Border Controller (SBC) for this function.
- The P-CSCF is at its core a specialized SBC for the User network interface which not only
- protects the network, but also the IMS terminal.
- The use of an additional SBC between the IMS terminal and the P-CSCF is unnecessary and
- infeasible due to the signaling being encrypted on this leg.
- The terminal discovers its P-CSCF with either DHCP, or it may be configured
- (e.g. during initial provisioning or via a 3GPP IMS Management Object (MO))
- or in the ISIM or assigned in the PDP Context (in General Packet Radio Service (GPRS)).
-
-node_types:
- att.nodes.ims.PCSCF:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- pcscf_endpoint:
- type: tosca.capabilities.Endpoint.Public
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more UAs
- requirements:
- icscf_endpoint:
- capability: tosca.capabilities.Endpoint
- node: att.nodes.ims.ICSCF
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.json b/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.json
deleted file mode 100644
index 8c4e5745ab..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "PCSCF.yml",
- "contactId": "jh0003",
- "resourceName": "att.nodes.ims.PCSCF",
- "description": "A Proxy-CSCF (P-CSCF) is a SIP proxy that is the first point of contact for the IMS terminal. It can be located either in the visited network (in full IMS networks) or in the home network (when the visited network is not IMS compliant yet). Some networks may use a Session Border Controller (SBC) for this function. The P-CSCF is at its core a specialized SBC for the User network interface which not onlyprotects the network, but also the IMS terminal. The use of an additional SBC between the IMS terminal and the P-CSCF is unnecessary and infeasible due to the signaling being encrypted on this leg. The terminal discovers its P-CSCF with either DHCP, or it may be configured (e.g. during initial provisioning or via a 3GPP IMS Management Object (MO)) or in the ISIM or assigned in the PDP Context (in General Packet Radio Service (GPRS)).",
- "resourceIconPath": "defaulticon",
- "category": "IMS",
- "tags": [
- "att.nodes.ims.PCSCF", "IMS_TAG"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.yml b/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.yml
deleted file mode 100644
index 3d0e38eefc..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-att.nodes.ims.PCSCF:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- pcscf_endpoint:
- type: tosca.capabilities.Endpoint.Public
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more UAs
- requirements:
- icscf_endpoint:
- capability: tosca.capabilities.Endpoint
- node: att.nodes.ims.ICSCF
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.zip b/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.zip
deleted file mode 100644
index 37a6bac251..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/PCSCF/PCSCF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.json b/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.json
deleted file mode 100644
index 0f893ddb9b..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "SCSCF.yml",
- "resourceName": "att.nodes.ims.SCSCF",
- "description": "A Serving-CSCF (S-CSCF) is the central node of the signaling plane. It is a SIP server, but performs session control too. It is always located in the home network. It uses Diameter Cx and Dx interfaces to the HSS to download user profiles and upload user-to-S-CSCF associations (the user profile is only cached locally for processing reasons only and is not changed). All necessary subscriber profile information is loaded from the HSS.",
- "resourceIconPath": "defaulticon",
- "category": "IMS",
- "contactId": jh0003,
- "tags": [
- "att.nodes.ims.SCSCF", "IMS_TAG"
- ]
-}
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml b/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml
deleted file mode 100644
index a2672ddb13..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-att.nodes.ims.SCSCF:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- icscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more I-CSCF functions
- requirements:
- hss_endpoint:
- capability: tosca.capabilities.Endpoint
- node: att.nodes.ims.HSS
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml.old b/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml.old
deleted file mode 100644
index d8fb1b0d33..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.yml.old
+++ /dev/null
@@ -1,23 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-
-description: >
- A Serving-CSCF (S-CSCF) is the central node of the signalling plane.
- It is a SIP server, but performs session control too. It is always located in the home network.
- It uses Diameter Cx and Dx interfaces to the HSS to download user profiles and upload
- user-to-S-CSCF associations (the user profile is only cached locally for processing reasons only
- and is not changed). All necessary subscriber profile information is loaded from the HSS.
-
-node_types:
- att.nodes.ims.SCSCF:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- icscf_endpoint:
- type: tosca.capabilities.Endpoint
- relationship: tosca.relationships.ConnectTo
- occurrences: [0, UNBOUNDED]
- description: Connection with one ore more I-CSCF functions
- requirements:
- hss_endpoint:
- capability: tosca.capabilities.Endpoint
- node: att.nodes.ims.HSS
- relationship: tosca.relationships.ConnectsTo \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.zip b/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.zip
deleted file mode 100644
index 7a579dc5c1..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/SCSCF/SCSCF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.json b/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.json
deleted file mode 100644
index 7425778dd1..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "payloadName": "compute.yml",
- "contactId": "jh0003",
- "resourceName": "tosca.nodes.Compute",
- "description": "Represents a real or virtual machine or server. Information specified on the Compute
- node will be used to find the machine that fits the given requirements in the cloud
- available machines. If no sizing information are specified the cloud provider default
- machine will be used. It is strongly recommended to specify the required CPUs and memory
- at least.",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "tosca.nodes.Compute"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.yml b/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.yml
deleted file mode 100644
index b110157df3..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.Compute:
- 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/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.zip b/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.zip
deleted file mode 100644
index 95a1325d92..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/compute/compute.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/deleteResourcesDemo.sh b/asdc-tests/src/test/resources/CI/importAttResources/deleteResourcesDemo.sh
deleted file mode 100644
index 549a4ca78d..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/deleteResourcesDemo.sh
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort>"
-}
-
-function deleteResource() {
-
- ELEMENT_NAME=$1
- echo "###################### Removing Element ${ELEMENT_NAME} Start ######################"
- curl -X "DELETE" -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/resources/res_${ELEMENT_NAME}".1.0"
- echo ""
- echo "###################### Removing Element ${ELEMENT_NAME} End ########################"
- echo ""
- echo ""
- echo ""
-}
-if [ $# -lt 2 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-
-deleteResource "tosca.nodes.root"
-deleteResource "tosca.nodes.compute"
-deleteResource "tosca.nodes.softwarecomponent"
-deleteResource "tosca.nodes.loadbalancer"
-deleteResource "att.nodes.ims.hss"
-deleteResource "att.nodes.ims.icscf"
-deleteResource "att.nodes.ims.pcscf"
-deleteResource "att.nodes.ims.scscf"
-
-
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/importResourcesDemo.sh b/asdc-tests/src/test/resources/CI/importAttResources/importResourcesDemo.sh
deleted file mode 100644
index 92beb9625a..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/importResourcesDemo.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort>"
-}
-
-function addResource() {
-
- ELEMENT_NAME=$1
- echo "###################### Adding Element ${ELEMENT_NAME} Start ######################"
- CURRENT_ZIP_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.zip
- CURRENT_JSON_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.json
- JSON_CONTENT=`paste -s ${CURRENT_JSON_FILE}`
- curl -v -F resourceMetadata="${JSON_CONTENT}" -F resourceZip=@${CURRENT_ZIP_FILE} -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/upload/multipart
- echo ""
- echo "###################### Adding Element ${ELEMENT_NAME} End ########################"
- echo ""
- echo ""
- echo ""
-}
-if [ $# -lt 2 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-
-addResource "root"
-addResource "compute"
-addResource "softwareComponent"
-addResource "loadBalancer"
-addResource "HSS"
-addResource "ICSCF"
-addResource "PCSCF"
-addResource "SCSCF"
-
-
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.json b/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.json
deleted file mode 100644
index d74dc3a3d5..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "loadBalancer.yml",
- "contactId": "jh0003",
- "resourceName": "tosca.nodes.LoadBalancer",
- "description": "Represents logical function that be used in conjunction with a Floating Address to distribute an application’s traffic (load) across a number of instances of the application (e.g., for a clustered or scaled application).",
- "resourceIconPath": "defaulticon",
- "category": "Infrastructure",
- "tags": [
- "tosca.nodes.LoadBalancer"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.yml b/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.yml
deleted file mode 100644
index 53c053f0a6..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tosca.nodes.LoadBalancer:
- derived_from: tosca.nodes.Root
- properties:
- # TBD
- algorithm :
- type: string
- required: false
- status: experimental
- capabilities :
- client:
- type: tosca.capabilities.Endpoint.Public
- description: the Floating (IP) client’s on the public network can connect to
- requirements:
- - application:
- capability: tosca.capabilities.Endpoint
- relationship: tosca.relationships.RoutesTo
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.zip b/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.zip
deleted file mode 100644
index 45edc204b5..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/loadBalancer/loadBalancer.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/root/root.json b/asdc-tests/src/test/resources/CI/importAttResources/root/root.json
deleted file mode 100644
index 6f96cf8b02..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/root/root.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "root.yml",
- "contactId": "jh0003",
- "resourceName": "tosca.nodes.Root",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Abstract",
- "tags": [
- "tosca.nodes.Root"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/root/root.yml b/asdc-tests/src/test/resources/CI/importAttResources/root/root.yml
deleted file mode 100644
index 81aacd56ab..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/root/root.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca.nodes.Root:
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature:
- type: tosca.capabilities.Node
- requirements:
- - dependency :
- capability: tosca.capabilities.Node
- node: tosca.nodes.Root
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- interfaces:
- Standard:
- type: tosca.interfaces.node.lifecycle.Standard
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/root/root.zip b/asdc-tests/src/test/resources/CI/importAttResources/root/root.zip
deleted file mode 100644
index bdafdfbeb6..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/root/root.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.json b/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.json
deleted file mode 100644
index 22379bf695..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "softwareComponent.yml",
- "contactId": "jh0003",
- "resourceName": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "category": "Abstract",
- "tags": [
- "tosca.nodes.SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.yml b/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.yml
deleted file mode 100644
index 287a376fc3..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-tosca.nodes.SoftwareComponent:
- 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
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.zip b/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.zip
deleted file mode 100644
index 8e39b87808..0000000000
--- a/asdc-tests/src/test/resources/CI/importAttResources/softwareComponent/softwareComponent.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.capabilities.yaml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.capabilities.yaml
deleted file mode 100644
index 073eba5ee7..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.capabilities.yaml
+++ /dev/null
@@ -1,13 +0,0 @@
-asdc.capabilities.NetworkInterface:
- derived_from: tosca.capabilities.Root
-
-asdc.capabilities.Container:
- derived_from: tosca.capabilities.Container
-
-# binding a VDU to a CP
-asdc.capabilities.nfv.VirtualBindable:
- derived_from: tosca.capabilities.Root
-
-# linking a VL to a CP
-asdc.capabilities.nfv.VirtualLinkable:
- derived_from: tosca.capabilities.Root
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.json
deleted file mode 100644
index e1727aca5c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "asdc.nodes.Module.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.Module",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "asdc.nodes.Module", "module"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.yml
deleted file mode 100644
index b95156b5e1..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-asdc.nodes.Module:
- derived_from: tosca.nodes.Root
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.zip
deleted file mode 100644
index 08003f1af8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Module/asdc.nodes.Module.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.json
deleted file mode 100644
index c52bbeebc2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "asdc.nodes.Network.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.Network",
- "description": "This is the default AT&T TOSCA Network Node Type that all other AT&T Network TOSCA nodes should extends.",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "asdc.nodes.Network", "Network"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.yml
deleted file mode 100644
index 0e56ef7bf2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-asdc.nodes.Network:
- derived_from: tosca.nodes.Root
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.zip
deleted file mode 100644
index 9b7fa35c2e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Network/asdc.nodes.Network.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.json
deleted file mode 100644
index 5e1dda7106..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "payloadName": "asdc.nodes.Root.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.Root",
- "description": "This is the default (root) AT&T TOSCA Node Type that all other AT&T TOSCA nodes should extends.
- This allows all AT&T TOSCA nodes to have a consistent set of features for modeling and management (e.g, consistent definitions for requirements, capabilities, and lifecycle interfaces).",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "asdc.nodes.Root"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.yml
deleted file mode 100644
index ed8e1e46aa..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-asdc.nodes.Root:
- derived_from: tosca.nodes.Root
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.zip
deleted file mode 100644
index 8453bf3843..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.Root/asdc.nodes.Root.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.json
deleted file mode 100644
index 7a122a57cd..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.module.ECA_OAM.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.module.ECA_OAM",
- "description": "Operation, Administration & Management of vMMSC ECA TRX",
- "resourceIconPath": "applicationServer",
- "category": "Application Layer 4+/Application Servers",
- "tags": [
- "asdc.nodes.module.ECA_OAM", "MMSC OAM", "ECA", "MMSC", "vMMSC", "Mobility"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.yml
deleted file mode 100644
index 054c98439c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-asdc.nodes.module.ECA_OAM:
- derived_from: asdc.nodes.Module
- requirements:
- - oam_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.OAM
- - internal_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Internal
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.zip
deleted file mode 100644
index 389ef18bae..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_OAM/asdc.nodes.module.ECA_OAM.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.json
deleted file mode 100644
index 338099286f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.module.ECA_TRX.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.module.ECA_TRX",
- "description": "External Content Adaption Transcoder. Transcodes and adapts MMS content according to the capabilities of receiving MS or UE.",
- "resourceIconPath": "applicationServer",
- "category": "Application Layer 4+/Application Servers",
- "tags": [
- "asdc.nodes.module.ECA_TRX", "Content Adaptation Transcoder", "MMSC", "vMMSC", "Mobility"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.yml
deleted file mode 100644
index e2a520dc1d..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-asdc.nodes.module.ECA_TRX:
- derived_from: asdc.nodes.Module
- requirements:
- - oam_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.OAM
- - traffic_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Traffic
- - internal_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Internal
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.zip
deleted file mode 100644
index f7911beb8f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.ECA_TRX/asdc.nodes.module.ECA_TRX.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.json
deleted file mode 100644
index 8ce0b8a961..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.module.F5_LTM.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.module.F5_LTM",
- "description": "vMMSC Local Traffic Manager serves as the load balancer for traffic coming into the vMMSC. Traffic from MMSC designated to external network passes via F5. Also, internal communication between ECA and MMSC is via F5",
- "resourceIconPath": "loadBalancer",
- "category": "Application Layer 4+/Load Balancer",
- "tags": [
- "asdc.nodes.module.F5_LTM", "F5", "Load Balancer", "vMMSC", "Mobility"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.yml
deleted file mode 100644
index c50cd0a481..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-asdc.nodes.module.F5_LTM:
- derived_from: asdc.nodes.Module
- requirements:
- - core_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Core
- - dmz_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.DMZ
- - traffic_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Traffic
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.zip
deleted file mode 100644
index 2bb9bbaa03..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.F5_LTM/asdc.nodes.module.F5_LTM.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.json
deleted file mode 100644
index 4103880abf..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.module.MMSC.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.module.MMSC",
- "description": "Accepts MMS messages via F5 and distributes among MMSCs. Messages are from user mobile device or from another Message Service",
- "resourceIconPath": "applicationServer",
- "category": "Application Layer 4+/Application Servers",
- "tags": [
- "asdc.nodes.module.MMSC", "MMSC", "vMMSC", "Mobility"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.yml
deleted file mode 100644
index b65b20f5b2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-asdc.nodes.module.MMSC:
- derived_from: asdc.nodes.Module
- requirements:
- - oam_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.OAM
- - cinder_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Cinder
- - traffic_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Traffic
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.zip
deleted file mode 100644
index abf8dd8ced..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.MMSC/asdc.nodes.module.MMSC.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.json
deleted file mode 100644
index a289e4dd1b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.module.NEMS_BE.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.module.NEMS_BE",
- "description": "The Back End of a Network Message Storage allows external multimedia content to use SMTP e-mail mechanism to submit MMS messages",
- "resourceIconPath": "applicationServer",
- "category": "Application Layer 4+/Application Servers",
- "tags": [
- "asdc.nodes.module.NEMS_BE", "MMSC", "vMMSC", "Network Message Storage", "Back End", "Mobility"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.yml
deleted file mode 100644
index b460bf57a5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-asdc.nodes.module.NEMS_BE:
- derived_from: asdc.nodes.Module
- requirements:
- - oam_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.OAM
- - internal_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Internal
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.zip
deleted file mode 100644
index 2ee35f5cde..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_BE/asdc.nodes.module.NEMS_BE.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.json
deleted file mode 100644
index 4d80b25712..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "asdc.nodes.module.NEMS_FE.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.module.NEMS_FE",
- "description": "The Front End of a Network Message Storage allows external multimedia content to use SMTP e-mail mechanism to submit MMS messages",
- "resourceIconPath": "objectStorage",
- "category": "Application Layer 4+/Application Servers",
- "tags": [
- "asdc.nodes.module.NEMS_FE", "MMSC", "vMMSC", "Network Message Storage", "Front End", "Mobility"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.yml
deleted file mode 100644
index 256aa7e4a3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-asdc.nodes.module.NEMS_FE:
- derived_from: asdc.nodes.Module
- requirements:
- - oam_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.OAM
- - cinder_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Cinder
- - traffic_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Traffic
- - internal_connection:
- capability: asdc.capabilities.NetworkInterface
- node: asdc.nodes.network.Internal
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.zip
deleted file mode 100644
index 28eb1ccb60..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.module.NEMS_FE/asdc.nodes.module.NEMS_FE.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.json
deleted file mode 100644
index 1538d93b2a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.network.Cinder.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.network.Cinder",
- "description": "Represents access to Cloud shared storae.",
- "resourceIconPath": "network",
- "category": "Generic/Network Elements",
- "tags": [
- "asdc.nodes.network.Cinder", "Network", "Cinder", "Cloud"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.yml
deleted file mode 100644
index 54b34d23fe..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-asdc.nodes.network.Cinder:
- derived_from: asdc.nodes.Network
- capabilities:
- cinder_connection:
- type: asdc.capabilities.NetworkInterface
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.zip
deleted file mode 100644
index 5210a39f29..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Cinder/asdc.nodes.network.Cinder.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.json
deleted file mode 100644
index 343a785b6f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.network.Core.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.network.Core",
- "description": "Represents Cloud Core network which provide interface to other services.",
- "resourceIconPath": "network",
- "category": "Generic/Network Elements",
- "tags": [
- "asdc.nodes.network.Core", "Network", "Core", "Cloud"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.yml
deleted file mode 100644
index ac4ceed23e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-asdc.nodes.network.Core:
- derived_from: asdc.nodes.Network
- capabilities:
- core_connection:
- type: asdc.capabilities.NetworkInterface
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.zip
deleted file mode 100644
index 7482fee585..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Core/asdc.nodes.network.Core.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.json
deleted file mode 100644
index 50041339b6..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.network.DMZ.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.network.DMZ",
- "description": "Represents DMZ network.",
- "resourceIconPath": "network",
- "category": "Generic/Network Elements",
- "tags": [
- "asdc.nodes.network.DMZ", "Network", "DMZ", "Cloud"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.yml
deleted file mode 100644
index df41ae4072..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-asdc.nodes.network.DMZ:
- derived_from: asdc.nodes.Network
- capabilities:
- dmz_connection:
- type: asdc.capabilities.NetworkInterface
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.zip
deleted file mode 100644
index fab96c9a64..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.DMZ/asdc.nodes.network.DMZ.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.json
deleted file mode 100644
index a2cf1c8026..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "asdc.nodes.network.Internal.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.network.Internal",
- "description": "Represents Internal Network",
- "resourceIconPath": "network",
- "category": "Generic/Network Elements",
- "tags": [
- "asdc.nodes.network.Internal", "Network", "Cloud"
- ]
-}
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.yml
deleted file mode 100644
index 01b6dece24..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.yml
+++ /dev/null
@@ -1,5 +0,0 @@
- asdc.nodes.network.Internal:
- derived_from: asdc.nodes.Network
- capabilities:
- dmz_connection:
- type: asdc.capabilities.NetworkInterface
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.zip
deleted file mode 100644
index 2317ce5ad0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Internal/asdc.nodes.network.Internal.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.json
deleted file mode 100644
index bb9560be88..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "asdc.nodes.network.OAM.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.network.OAM",
- "description": "Represents Operation, Administration and Management (OA&M) network.",
- "resourceIconPath": "network",
- "category": "Generic/Network Elements",
- "tags": [
- "asdc.nodes.network.OAM", "Network", "OAM", "Cloud"
- ]
-}
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.yml
deleted file mode 100644
index 0a0875ad07..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-asdc.nodes.network.OAM:
- derived_from: asdc.nodes.Network
- capabilities:
- oam_connection:
- type: asdc.capabilities.NetworkInterface
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.zip
deleted file mode 100644
index b2fbb78a7c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.OAM/asdc.nodes.network.OAM.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.json b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.json
deleted file mode 100644
index fb8269039c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "asdc.nodes.network.Traffic.yml",
- "contactId": "jh0003",
- "name": "asdc.nodes.network.Traffic",
- "description": "Represents Network Traffic",
- "resourceIconPath": "network",
- "category": "Generic/Network Elements",
- "tags": [
- "asdc.nodes.network.Traffic", "Network", "Cloud"
- ]
-}
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.yml b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.yml
deleted file mode 100644
index b50bc8e612..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-asdc.nodes.network.Traffic:
- derived_from: asdc.nodes.Network
- capabilities:
- dmz_connection:
- type: asdc.capabilities.NetworkInterface
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.zip
deleted file mode 100644
index 3add4e6ade..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/asdc.nodes.network.Traffic/asdc.nodes.network.Traffic.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/capabilityTypes.zip b/asdc-tests/src/test/resources/CI/importResource-MMSC/capabilityTypes.zip
deleted file mode 100644
index a1f0cdeee5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/capabilityTypes.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/deleteNormative.sh b/asdc-tests/src/test/resources/CI/importResource-MMSC/deleteNormative.sh
deleted file mode 100644
index fb46daa544..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/deleteNormative.sh
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort> <resourceName>"
-}
-
-function deleteResource() {
-
- ELEMENT_NAME=$1
- echo -e "############### Removing Element ${ELEMENT_NAME} Start ######################"
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -X "DELETE" -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/resources/res_${ELEMENT_NAME}".1.0")
- if [ ${http_code} -eq 204 ]; then
- echo -e "\n############### Removing Element ${ELEMENT_NAME} status code:${http_code} End #######\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n############### Failed to remove Element ${ELEMENT_NAME} status code:${http_code} End #######\n\n\n"
- exit 1
- elif [ ${http_code} -eq 404 ]; then
- echo -e "\n############### Element ${ELEMENT_NAME} not found status code:${http_code} End #######\n\n\n"
- else
- echo -e "\n############### Failed to remove Element ${ELEMENT_NAME} status code:${http_code} End #######\n\n\n"
- exit 1
- fi
-}
-if [ $# -lt 3 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-
-deleteResource $3
-
-exit 0
diff --git a/asdc-tests/src/test/resources/CI/importResource-MMSC/importNormative.sh b/asdc-tests/src/test/resources/CI/importResource-MMSC/importNormative.sh
deleted file mode 100644
index 9e568dddc3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-MMSC/importNormative.sh
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort> <userId>"
-}
-
-function addResource() {
-
- ELEMENT_NAME=$1
- echo -e "###################### Adding Element ${ELEMENT_NAME} Start ######################"
- CURRENT_ZIP_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.zip
- CURRENT_JSON_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.json
- sed -i 's/"userId": ".*",/"userId": "'${ATT_UID}'",/' ${CURRENT_JSON_FILE}
- JSON_CONTENT=`paste -s ${CURRENT_JSON_FILE}`
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F resourceMetadata="${JSON_CONTENT}" -F resourceZip=@${CURRENT_ZIP_FILE} -H USER_ID:${ATT_UID} ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/upload/multipart)
- if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding Element ${ELEMENT_NAME} End ########################\n\n\n"
- elif [ ${http_code} -eq 409 ]; then
- echo -e "\n###################### Already exists Element ${ELEMENT_NAME} status code:${http_code} End ########################\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add Element ${ELEMENT_NAME} status code:${http_code} End ########################\n\n\n"
- exit 1
- fi
-}
-if [ $# -lt 3 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-ATT_UID=$3
-NO_CAPS=$4
-
-if [ "$NO_CAPS" = "nocaps" ]; then
- echo "Skipping Caps import..."
-else
- #Add The CapabilityTypes
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F capabilityTypeZip=@capabilityTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/capability)
- if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding The CapabilityTypes status code:${http_code} End ########################\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
- else
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
- fi
- #Add The InterfaceLifecycleTypes
- #http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F interfaceLifecycleTypeZip=@interfaceLifecycleTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle)
- #if [ ${http_code} -eq 201 ]; then
- # echo -e "\n###################### Adding The InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- #elif [ ${http_code} -eq 409 ]; then
- # echo -e "\n###################### Already exists InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- #elif [ ${http_code} -eq 500 ]; then
- # echo -e "\n###################### Failed to add InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- # exit 1
- #else
- # echo -e "\n###################### Failed to add InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- # exit 1
- #fi
-fi
-
-addResource "asdc.nodes.Root"
-addResource "asdc.nodes.Network"
-addResource "asdc.nodes.network.Cinder"
-addResource "asdc.nodes.network.Core"
-addResource "asdc.nodes.network.DMZ"
-addResource "asdc.nodes.network.OAM"
-addResource "asdc.nodes.network.Traffic"
-addResource "asdc.nodes.network.Internal"
-addResource "asdc.nodes.Module"
-addResource "asdc.nodes.module.ECA_OAM"
-addResource "asdc.nodes.module.ECA_TRX"
-addResource "asdc.nodes.module.F5_LTM"
-addResource "asdc.nodes.module.MMSC"
-addResource "asdc.nodes.module.NEMS_BE"
-addResource "asdc.nodes.module.NEMS_FE"
-
-
-
-
-
-exit 0
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/VCE_Brocade_Tosca.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/VCE_Brocade_Tosca.yaml
deleted file mode 100644
index aecef6260d..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/VCE_Brocade_Tosca.yaml
+++ /dev/null
@@ -1,834 +0,0 @@
-tosca_definitions_version: tosca_simple_profile_for_nfv_1_0_0
-tosca_default_namespace: Need to figure out the namespace
-description: vCEBrocade and Base Types for VNF, Connection Point, Virtual Link, etc based on VNF Modeling Guidelines
-
-metadata:
- template_name: VCE_Brocade.yaml
- template_author: Kazi Farooqui (KF6593)
- template_version: "0.1"
-
-#####################################################################
-############################ Data Types ###########################
-#####################################################################
-#data_types:
-
-###########################################################################################
-###################### NODE TYPE DEFINITIONS ############################################
-###########################################################################################
-
-node_types:
- ##################################################################
- ################### TOSCA VNF Node ##########################
- ##################################################################
- tosca.nodes.nfv.VNF:
- derived_from: tosca.nodes.Root
- properties:
- vnf_category:
- type: string
- description: Router, FW, LB, DNS are example categories
- id:
- type: string
- description: ID of this VNF
- vendor:
- type: string
- description: name of the vendor who provides this VNF
- version:
- type: version
- description: version of the software for this VNF
- #device_config:
- # type: map
- #entry_schema:
- # type: string
- #default:
- # p1: 1
- # p2: 2
- #p3: 3
- #requirements:
- # - virtualLink:
- #capability: tosca.capabilities.nfv.VirtualLinkable
- #occurrences: [1, UNBOUNDED]
-
- ##################################################################
- ################### ASDC VNF Node ##########################
- ##################################################################
- org.openecomp.resource.nfv.VNF:
- derived_from: tosca.nodes.nfv.VNF
-
-
- ##################################################################
- ###################### TOSCA VDU Node ##########################
- ##################################################################
-
- tosca.nodes.nfv.VDU:
- derived_from: tosca.nodes.SoftwareComponent
- #properties:
-
- capabilities:
- high_availability:
- type: tosca.capabilities.nfv.HA
- occurrences: [1, UNBOUNDED] # this is default
-
- virtual_binding:
- type: tosca.capabilities.nfv.VDU.VirtualBindable
- occurrences: [1, UNBOUNDED] # this is default
-
- requirements:
- - high_availability:
- capability: tosca.capabilities.nfv.HA
- occurrences: [0,1]
-
- - host: ##Is hosted in a VM
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
- occurrences: [1, 1] #this is default
-
- ##################################################################
- ###################### ASDC VDU Node###### ######################
- ##################################################################
- org.openecomp.resource.nfv.VDU:
- derived_from: tosca.nodes.nfv.VDU
- description: A VDU is a compute component of VNF
-
- ##################################################################
- ####################### TOSCA CP Node ##########################
- ##################################################################
- tosca.nodes.nfv.CP:
- derived_from: tosca.nodes.Root
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualbinding:
- capability: tosca.capabilities.nfv.VDU.VirtualBindable
- occurrences: [1, 1] #this is default
-
- - virtuallink:
- capability: tosca.capabilities.nfv.VirtualLinkable
- occurrences: [1, 1] #this is default
-
- attributes:
- ip_address:
- type: string
- # required: false
-
- ##################################################################
- ############################ ASDC CP Node #####################
- ##################################################################
- org.openecomp.resource.nfv.CP:
- derived_from: tosca.nodes.nfv.CP
-
- ##################################################################
- ############### IPAG VLAN Connector CP Node #####################
- ##################################################################
- org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector:
- derived_from: org.openecomp.resource.nfv.CP
- properties:
- ipag_network_name:
- type: string
-
- ipag_network_type:
- type: string
-
- ipag_network_uuid:
- type: string
-
- vlan_segment_ids:
- type: list
- entry_schema:
- type: string
- description: list of segmentation Ids.
-
-
- #attributes:
- capabilities:
- dummy_capability:
- type: org.openecomp.capabilities.nfv.IPAG_VLAN_Connector
- description: This capability has been introduced to model this Connector as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- requirements:
- - virtualBindingRequirement:
- capability: org.openecomp.capabilities.nfv.VDU.VirtualBindable
- #node: org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU
- relationship: org.openecomp.relationships.nfv.VirtualBindsTo
- occurrences: [1, 1] #default
-
- - virtualLinkingrequirement:
- capability: org.openecomp.capabilities.nfv.VirtualLinkable
- #node: org.openecomp.resource.nfv.VL
- relationship: org.openecomp.relationships.nfv.VirtualLinksTo
- occurrences: [1, 1] #default
-
- #interfaces:
- #standard:
- #configure:
- #implementation: configure.sh
-
- ##################################################################
- ############### VPE VLAN Connector CP Node #####################
- ##################################################################
- org.openecomp.resource.nfv.CP.VPE_VLAN_Connector:
- derived_from: org.openecomp.resource.nfv.CP
- properties:
- vpe_network_name:
- type: string
-
- vpe_network_type:
- type: string
-
- vpe_network_uuid:
- type: string
-
- vlan_segment_ids:
- type: list
- entry_schema:
- type: string
- description: list of segmentation Ids.
-
-
- #attributes:
- capabilities:
- dummy_capability:
- type: org.openecomp.capabilities.nfv.VPE_VLAN_Connector
- description: This capability has been introduced to model this Connector as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- requirements:
- - virtualBindingRequirement:
- capability: org.openecomp.capabilities.nfv.VDU.VirtualBindable
- #node: org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU
- relationship: org.openecomp.relationships.nfv.VirtualBindsTo
- occurrences: [1, 1] #default
-
- - virtualLinkingrequirement:
- capability: org.openecomp.capabilities.nfv.VirtualLinkable
- #node: org.openecomp.resource.nfv.VL
- relationship: org.openecomp.relationships.nfv.VirtualLinksTo
- occurrences: [1, 1] #default
-
- #interfaces:
- #standard:
- #configure:
- #implementation: configure.sh
- ##################################################################
- ############### OAM VLAN Connector CP Node #####################
- ##################################################################
- org.openecomp.resource.nfv.CP.OAM_VLAN_Connector:
- derived_from: org.openecomp.resource.nfv.CP
- properties:
- oam_network_name:
- type: string
-
- oam_network_type:
- type: string
-
- oam_network_uuid:
- type: string
-
- vlan_segment_ids:
- type: list
- entry_schema:
- type: string
- description: list of segmentation Ids.
-
-
- #attributes:
- capabilities:
- dummy_capability:
- type: org.openecomp.capabilities.nfv.OAM_VLAN_Connector
- description: This capability has been introduced to model this Connector as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- requirements:
- - virtualBindingRequirement:
- capability: org.openecomp.capabilities.nfv.VDU.VirtualBindable
- #node: org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU
- relationship: org.openecomp.relationships.nfv.VirtualBindsTo
- occurrences: [1, 1] #default
-
- - virtualLinkingrequirement:
- capability: org.openecomp.capabilities.nfv.VirtualLinkable
- #node: org.openecomp.resource.nfv.VL
- relationship: org.openecomp.relationships.nfv.VirtualLinksTo
- occurrences: [1, 1] #default
-
- #interfaces:
- #standard:
- #configure:
- #implementation: configure.sh
-
- ##################################################################
- ############## TOSCA VL Node Type #######################
- ##################################################################
- tosca.nodes.nfv.VL:
- derived_from: tosca.nodes.Root
- properties:
- vendor:
- type: string
- required: false
- description: name of the vendor who provides this VL
-
- capabilities:
- virtuallinkable:
- type: tosca.capabilities.nfv.VirtualLinkable
- occurrences: [1, UNBOUNDED] # this is default
-
-##################################################################
-###################### ASDC VL Node TYPE ######################
-##################################################################
- org.openecomp.resource.nfv.VL:
- derived_from: tosca.nodes.nfv.VL
-
-
-##################################################################
-###################### ASDC VNF Node TYPE ######################
-##################################################################
- org.openecomp.resource.nfv.VNF:
- derived_from: tosca.nodes.nfv.VNF
-
-##################################################################
-###################### ASDC Routing Category VDU #################
-##################################################################
-
- org.openecomp.resource.nfv.VDU.RoutingCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
-
-##################################################################
-###################### vCE_Brocade_VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU:#paharoni - renamed from org.openecomp.resource.v/VCE_Brocade_VDU to keep convention
- derived_from: org.openecomp.resource.nfv.VDU.RoutingCategoryVDU
- description: Definition of VCE Brocade VDU
- properties:
- vnf_category:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- vce_type:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- vendor:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- version:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- image_id:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer -vCE image used to boot VM
- flavor_id:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer - VM Size, SMALL, MEDIUM, LARGE
- username:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer -login user Id of Router
- password:
- type: string
- description: I Input provided at DESIGN TIME by Service Composer or Designer - password for login
- domain_name:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer or (perhaps pre-defined for each cloud Region) - login domain
- time_zone:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer or (perhaps pre-defined for each cloud Region) - time zone to set for vCE
- login_session_timeout:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer or (perhaps pre-defined for each cloud Region) - user login session timeout
- ipag_vlan_bandwidth:
- type: integer
- description: Input provided at DESIGN TIME by Service Composer or Designer - bandwidth allocation of customer VLAN requested by customer
- vpe_vlan_interface_qos_name:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer - QoS Policy name to be applied to this interface
- ipag_vlan_interface_qos_name:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer - QoS Policy name to be applied to this interface
- hostname:
- type: string
- description: Input provided at RUN TIME by cloud-PO - Host VM is created first and this value is input when the vCE image is later on installed by cloud-PO
- host_ip:
- type: string
- description: Input provided at RUN TIME by cloud-PO - Host VM IP
- availability_zone:
- type: string
- description: Input provided at RUN TIME by cloud-PO - cloud availability zone where VM is created
- oam_loopback_vlan_ip_address:
- type: string
- description: Input provided at RUN TIME by cloud-PO - OAM Network is pre-created - already exists in Data Center
- ipag_vlan_ip_address:
- type: string
- description: Input provided at RUN TIME by cloud-PO - IPAG VLAN Network is created by cloud-PO before the vCE is created or installed
- vpe_vlan_ip_address:
- type: string
- description: Input provided at RUN TIME by cloud-PO - VPE VLAN Network is created by cloud-PO before the vCE is created / installed
- vpe_vlan_id:
- type: string
- description: Input provided at RUN TIME by cloud-PO - VLAN Id is created first by cloud-PO. It is required to apply VPE QoS Policy
- ipag_vlan_id:
- type: string
- description: Input provided at RUN TIME by cloud-PO - VLAN Id is created first by cloud-PO. It is required to apply IPAG QoS Policy
- oam_vlan_interface_name:
- type: string
- description: Input provided at RUN TIME by cloud-PO - This interfce is created first by cloud-PO. This is the interface to which QoS policy is applied
- vpe_vlan_interface_name:
- type: string
- description: Input provided at RUN TIME by cloud-PO - This interfce is created first by cloud-PO. This is the interface to which QoS policy is applied
- ipag_vlan_interface_name:
- type: string
- description: Input provided at RUN TIME by cloud-PO - This interfce is created first by cloud-PO. This is the interface to which QoS policy is applied
- #############ATTRIBUTES of vCE - These values are outputted by cloud-PO when vCE is created / installed ##############
- attributes:
- vce_name:
- type: string
- description: Name assigned to vCE by cloud-PO
- oam_loopback_vlan_ipaddres:
- type: string
- description: IP Address assigned by cloud-PO to OAM VLAN
- ipag_vlan_ipaddres:
- type: string
- description: IP Address assigned by cloud-PO to IPAG VLAN
- vpe_vlan_ipaddres:
- type: string
- description: IP Address assigned by cloud-PO to VPE VLAN
- vnf_id:
- type: string
- description: unique id assigned to VNF by cloud-PO - used for AAI metadata
-
- #############CAPABILITIES of vCE - #########################
- capabilities:
- ce_routing_capability:
- type: org.openecomp.capabilities.nfv.CERouting
- description: This is the base capability of vCE
- occurrences: [1, UNBOUNDED] # default
-
- static_routing:
- type: org.openecomp.capabilities.nfv.StaticRouting
- description: This is the optional capability of the vCE
- occurrences: [0, UNBOUNDED]
-
- bgp_routing:
- type: org.openecomp.capabilities.nfv.BGPRouting
- description: This is the optional capability of the vCE
- occurrences: [0, UNBOUNDED]
-
- virtual_bindable:
- type: org.openecomp.capabilities.nfv.VDU.VirtualBindable# paharoni - changed to org.openecomp.capabilities.nfv.vdu.VirtualBindable from tosca.capabilities.nfv.VDU.VirtualBindable - was it intentional??
- description: This is the internal capability of the VDU to support Binding to Connection Points
- occurrences: [1, UNBOUNDED]
-
- dummy_capability:
- type: org.openecomp.capabilities.nfv.VCE_Brocade_Routing
- description: This capability has been introduced to model VCE VDU as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- #############REQUIREMENTS of vCE - ###########################
- requirements:
- - nat: # A vCE may have a requirement to connect to a VNF offering this capability, during service composition
- capability: org.openecomp.capabilities.nfv.VNF.NetworkAddressTranslationCapability
- node: org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU
- relationship: org.openecomp.relationships.nfv.CnnectsToNAT
- occurrences: [0, 1]
-
- - pat: # A vCE may have a requirement to connect to a VNF offering this capability, during service composition
- capability: org.openecomp.capabilities.nfv.VNF.PortAddressTranslationCapability
- node: org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU #paharoni - renamed from org.openecomp.resource.nfv.VDU.PortAddressTranslationCategoryVDU. Resource name can be up to 50 chars
- relationship: org.openecomp.relationships.nfv.CnnectsToPAT
- occurrences: [0, 1]
-
-
- - firewall: # A vCE may have a requirement to connect to a VNF offering this capability, during service composition
- capability: org.openecomp.capabilities.nfv.VNF.FirewallCapability
- node: org.openecomp.resource.nfv.VDU.FirewallCategoryVDU
- relationship: org.openecomp.relationships.nfv.CnnectsToFirewall
- occurrences: [0, 1]
-
- - dhcp: # A vCE may have a requirement to connect to a VNF offering this capability, during service composition
- capability: org.openecomp.capabilities.nfv.VNF.DHCPCapability
- node: org.openecomp.resource.nfv.VDU.DHCPCategoryVDU
- relationship: org.openecomp.relationships.nfv.CnnectsToDHCP
- occurrences: [0, 1]
-
- - dns: # A vCE may have a requirement to connect to a VNF offering this capability, during service composition
- capability: org.openecomp.capabilities.nfv.VNF.DNSCapability
- node: org.openecomp.resource.nfv.VDU.DNSCategoryVDU
- relationship: org.openecomp.relationships.nfv.CnnectsToDNS
- occurrences: [0, 1]
-
- - hosted_on: # A vCE needs to be hosted in a VM
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
- occurrences: [1, 1] #default
-
-
-
-
-########################################################################################################
-###################### vCE_Brocade_VNF Node TYPE #####################################################
-########### IN THE ABSENCE OF NODE TEMPLATE, the vCE_Brocade_VNF Node Type is modeled as REQUIRING: #####
-########### 1. vce_Brocade_VDU Node
-########### 2. oam_vlan_connector Node
-########### 3. ipag_vlan_connector Node
-########### 4. vpe_vlan_connector Node
-########################################################################################################
-
- org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF:
- derived_from: org.openecomp.resource.nfv.VNF
- requirements:
- - vce_brocade_vdu:
- capability: org.openecomp.capabilities.nfv.VCE_Brocade_Routing
- node: org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU
- occurrences: [1, 1]
-
- - oam_vlan_connector:
- capability: org.openecomp.capabilities.nfv.OAM_VLAN_Connector
- node: org.openecomp.resource.nfv.CP.OAM_VLAN_Connector
- occurrences: [1, 1]
-
- - vpe_vlan_connector:
- capability: org.openecomp.capabilities.nfv.VPE_VLAN_Connector
- node: org.openecomp.resource.nfv.CP.VPE_VLAN_Connector
- occurrences: [1, 1]
-
- - ipag_vlan_connector:
- capability: org.openecomp.capabilities.nfv.IPAG_VLAN_Connector
- node: org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector
- occurrences: [1, 1]
-
-##################################################################
-###################### ASDC NAT VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU: #paharoni - renamed from org.openecomp.resource.nfv.VDU.NetworkAddressTranslationCategoryVDU. Resource name can be up to 50 chars in ASDC
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- nat:
- type: org.openecomp.capabilities.nfv.VNF.NetworkAddressTranslationCapability
- description: This capability has been introduced
- ###############Further details described in NAT VNF TOSCA Model
-
-##################################################################
-###################### PAT VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU: #paharoni - renamed from org.openecomp.resource.nfv.VDU.PortAddressTranslationCategoryVDU. Resource name can be up to 50 chars in ASDC
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- pat:
- type: org.openecomp.capabilities.nfv.VNF.PortAddressTranslationCapability
- description: This capability has been introduced
- ###############Further details described in PAT VNF TOSCA Model
-
-##################################################################
-###################### Firewall VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.FirewallCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- firewall:
- type: org.openecomp.capabilities.nfv.VNF.FirewallCapability
- description: This capability has been introduced
- ###############Further details described in Firewall VNF TOSCA Model
-
-##################################################################
-###################### DHCP VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.DHCPCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- dhcp:
- type: org.openecomp.capabilities.nfv.VNF.DHCPCapability
- description: This capability has been introduced
- ###############Further details described in DHCP VNF TOSCA Model
-
-##################################################################
-###################### DNS VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.DNSCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- dns:
- type: org.openecomp.capabilities.nfv.VNF.DNSCapability
- description: This capability has been introduced
- ###############Further details described in DNS VNF TOSCA Model
-
-
-###########################################################################################
-###################### CAPABILITY TYPE DEFINITIONS ######################################
-###########################################################################################
-
-capability_types:
- #####################################################################################
- ###################### TOSCA Capability: VirtualBindable ##########################
- #####################################################################################
- tosca.capabilities.nfv.VDU.VirtualBindable:
- derived_from: tosca.capabilities.Root
- valid_source_types: [tosca.nodes.nfv.VDU]
-
- #####################################################################################
- ############################ ASDC Capability: VirtualBindable #####################
- #####################################################################################
- org.openecomp.capabilities.nfv.VDU.VirtualBindable:
- derived_from: tosca.capabilities.nfv.VDU.VirtualBindable
- valid_source_types: [org.openecomp.resource.nfv.VDU]
-
- #####################################################################################
- ##################### TOSCA Capability: VirtualLinkable ##########################
- #####################################################################################
- tosca.capabilities.nfv.VirtualLinkable:
- derived_from: tosca.capabilities.Root ##paharoni - changed from tosca.capabilities.nfv.VirtualLinkable - cannot derive from itself
- valid_source_types: [org.openecomp.resource.nfv.VL]
-
- #####################################################################################
- ############################ ASDC Capability: VirtualLinkable #####################
- #####################################################################################
- org.openecomp.capabilities.nfv.VirtualLinkable:
- derived_from: tosca.capabilities.Root
- valid_source_types: [tosca.nodes.nfv.VL]
-
- #####################################################################################
- ############################ Capability: HighAvailability ##########################
- #####################################################################################
- tosca.capabilities.nfv.HA:
- derived_from: tosca.capabilities.Root
- valid_source_types: [tosca.nodes.nfv.VDU]
-
- #####################################################################################
- ######################Capability: Generic asdc capability ##########################
- #####################################################################################
- org.openecomp.capabilities.Root:
- derived_from: tosca.capabilities.Root
-
- #####################################################################################
- ############################ Capability: GENERIC ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.RoutingCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- routing_type:
- type: string
- description: some basic routing descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.VDU.RoutingCategoryVDU]
-
- #####################################################################################
- ############################ Capability: CE ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.CERouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: PE ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.PERouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: P ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.PRouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: BGP ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.BGPRouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: STATIC ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.StaticRouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: Network Address Translation ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.VNF.NetworkAddressTranslationCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- nat_type:
- type: string
- description: some basic NAT descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU]
-
- #####################################################################################
- ############################ Capability: Port Address Translation ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.VNF.PortAddressTranslationCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- pat_type:
- type: string
- description: some basic PAT descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU]
-
- #####################################################################################
- ############################ Capability: FIREWALL ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.VNF.FirewallCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- firewall_type:
- type: string
- description: some basic Firewall Capability descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.VDU.FirewallCategoryVDU]
-
- #####################################################################################
- ############################ Capability: DHCP ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.VNF.DHCPCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- dhcp_type:
- type: string
- description: some basic DHCP Capability descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.VDU.DHCPCategoryVDU]
-
- #####################################################################################
- ############################ Capability: DNS ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.VNF.DNSCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- dns_type:
- type: string
- description: some basic DNS Capability descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.VDU.DNSCategoryVDU]
-
- #####################################################################################
- ############################ Capability: vCE Brocade ROUTING ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC BROCADE VDU ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.vCE_Brocade_Routing:
- derived_from: org.openecomp.capabilities.nfv.CERouting
- valid_source_types: [org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU]
-
- #####################################################################################
- ############################ Capability: OAM VLAn Connector ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC Connector ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.OAM_VLAN_Connector:
- derived_from: org.openecomp.capabilities.Root
- valid_source_types: [org.openecomp.resource.nfv.CP.OAM_VLAN_Connector]
-
- #####################################################################################
- ############################ Capability: IPAG VLAn Connector ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC Connector ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.IPAG_VLAN_Connector:
- derived_from: org.openecomp.capabilities.Root
- valid_source_types: [org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector]
-
- #####################################################################################
- ############################ Capability: VPE VLAn Connector ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC Connector ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.VPE_VLAN_Connector:
- derived_from: org.openecomp.capabilities.Root
- valid_source_types: [org.openecomp.resource.nfv.CP.VPE_VLAN_Connector]
-
-###########################################################################################
-###################### RELATIONSHIP TYPE DEFINITIONS ###################################
-###########################################################################################
-
-relationship_types:
-#####################################################################################
-######################TOSCA Relationship: VirtualBindsTo ##########################
-#####################################################################################
- tosca.relationships.nfv.VirtualBindsTo:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between VDU and CP Node Types
- valid_target_types: [tosca.capabilities.nfv.VDU.VirtualBindable]
-
-#####################################################################################
-######################ASDC Relationship: VirtualBindsTo ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.VirtualBindsTo:
- derived_from: tosca.relationships.nfv.VirtualBindsTo
- description: Represents the relationsHIP between VDU and CP Node Types
- valid_target_types: [org.openecomp.capabilities.nfv.VDU.VirtualBindable]
-
-#####################################################################################
-##################### TOSCA Relationship: VirtualLinksTo ##########################
-#####################################################################################
- tosca.relationships.nfv.VirtualLinksTo:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between CP and VL Node Types
- valid_target_types: [tosca.capabilities.nfv.VirtualLinkable]
-
-#####################################################################################
-##################### ASDC Relationship: VirtualLinksTo ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.VirtualLinksTo:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between CP and VL Node Types
- valid_target_types: [org.openecomp.capabilities.nfv.VirtualLinkable]
-
-#####################################################################################
-###################### ASDC Relationship: ConnectsToNAT ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.CnnectsToNAT:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between a VNF and NAT capable Node
- #properties:
- #attributes:
- #interfaces:
- valid_target_types: [org.openecomp.capabilities.nfv.VNF.NetworkAddressTranslationCapability]
-
-#####################################################################################
-###################### ASDC Relationship: ConnectsToPAT ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.CnnectsToPAT:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between a VNF and PAT capable Node
- #properties:
- #attributes:
- #interfaces:
- valid_target_types: [org.openecomp.capabilities.nfv.VNF.PortAddressTranslationCapability]
-
-#####################################################################################
-###################### ASDC Relationship: ConnectsToFirewall ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.CnnectsToFirewall:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between a VNF and Firewall capable Node
- #properties:
- #attributes:
- #interfaces:
- valid_target_types: [org.openecomp.capabilities.nfv.VNF.FirewallCapability]
-
-#####################################################################################
-###################### ASDC Relationship: ConnectsToDNS ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.CnnectsToDNS:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between a VNF and DNS capable Node
- #properties:
- #attributes:
- #interfaces:
- valid_target_types: [org.openecomp.capabilities.nfv.VNF.DNSCapability]
-
-#####################################################################################
-###################### ASDC Relationship: ConnectsToDHCP ##########################
-#####################################################################################
- org.openecomp.relationships.nfv.CnnectsToDHCP:
- derived_from: tosca.relationships.ConnectsTo
- description: Represents the relationsHIP between a VNF and DHCP capable Node
- #properties:
- #attributes:
- #interfaces:
- valid_target_types: [org.openecomp.capabilities.nfv.VNF.DHCPCapability]
- \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zip
deleted file mode 100644
index 7f1a513fc1..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/capabilityTypes.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/importVceBrocade.sh b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/importVceBrocade.sh
deleted file mode 100644
index 76f567bfe2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/importVceBrocade.sh
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort> <userId>"
-}
-
-function addResource() {
-
- ELEMENT_NAME=$1
- echo -e "###################### Adding Element ${ELEMENT_NAME} Start ######################"
- CURRENT_ZIP_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.zip
- CURRENT_JSON_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.json
- sed -i 's/"userId": ".*",/"userId": "'${ATT_UID}'",/' ${CURRENT_JSON_FILE}
- JSON_CONTENT=`paste -s ${CURRENT_JSON_FILE}`
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F resourceMetadata="${JSON_CONTENT}" -F resourceZip=@${CURRENT_ZIP_FILE} -H USER_ID:${ATT_UID} ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/upload/multipart)
- if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding Element ${ELEMENT_NAME} End ########################\n\n\n"
- elif [ ${http_code} -eq 409 ]; then
- echo -e "\n###################### Already exists Element ${ELEMENT_NAME} status code:${http_code} End ########################\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add Element ${ELEMENT_NAME} status code:${http_code} End ########################\n\n\n"
- exit 1
- fi
-}
-if [ $# -lt 3 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-ATT_UID=$3
-NO_CAPS=$4
-
-if [ "$NO_CAPS" = "nocaps" ]; then
- echo "Skipping Caps import..."
-else
- #Add The CapabilityTypes
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F capabilityTypeZip=@capabilityTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/capability)
- if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding The CapabilityTypes status code:${http_code} End ########################\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
- else
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
- fi
- #Add The InterfaceLifecycleTypes
- #http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F interfaceLifecycleTypeZip=@interfaceLifecycleTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle)
- #if [ ${http_code} -eq 201 ]; then
- # echo -e "\n###################### Adding The InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- #elif [ ${http_code} -eq 409 ]; then
- # echo -e "\n###################### Already exists InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- #elif [ ${http_code} -eq 500 ]; then
- # echo -e "\n###################### Failed to add InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- # exit 1
- #else
- # echo -e "\n###################### Failed to add InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- # exit 1
- #fi
-fi
-
-addResource "tosca.nodes.nfv.CP"
-addResource "tosca.nodes.nfv.VDU"
-
-addResource "org.openecomp.resource.nfv.CP"
-addResource "org.openecomp.resource.nfv.VDU"
-
-addResource "org.openecomp.resource.nfv.vdu.RoutingCategoryVDU"
-addResource "org.openecomp.resource.nfv.vdu.VCE_Brocade_VDU"
-addResource "org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector"
-addResource "org.openecomp.resource.nfv.cp.OAM_VLAN_Connector"
-addResource "org.openecomp.resource.nfv.cp.VPE_VLAN_Connector"
-
-#addResource "tosca.nodes.nfv.VL"
-#addResource "tosca.nodes.nfv.VNF"
-#addResource "org.openecomp.resource.nfv.VL"
-#addResource "org.openecomp.resource.nfv.VNF"
-#addResource "org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU"
-#addResource "org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF"
-#addResource "org.openecomp.resource.nfv.VDU.DHCPCategoryVDU"
-#addResource "org.openecomp.resource.nfv.VDU.DNSCategoryVDU"
-#addResource "org.openecomp.resource.nfv.VDU.FirewallCategoryVDU"
-#addResource "org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU"
-
-
-exit 0
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.json
deleted file mode 100644
index 390fda0257..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector.yaml",
- "contactId": "jh0003",
- "name": "org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector",
- "description": "Represents a virtual or physical interface between the NFV and the LAN.",
- "resourceIconPath": "port",
- "category": "Network Layer 2-3/LAN Connectors",
- "tags": [
- "org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector", "LAN Connector"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.yaml
deleted file mode 100644
index 03ecc8ea3e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
-##################################################################
- ############### IPAG VLAN Connector CP Node #####################
- ##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector:
- derived_from: org.openecomp.resource.nfv.CP
- properties:
- ipag_network_name:
- type: string
-
- ipag_network_type:
- type: string
-
- ipag_network_uuid:
- type: string
-
- vlan_segment_ids:
- type: list
- entry_schema:
- type: string
- description: list of segmentation Ids.
-
-
- #attributes:
- capabilities:
- dummy_capability:
- type: org.openecomp.capabilities.nfv.IPAG_VLAN_Connector
- description: This capability has been introduced to model this Connector as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- requirements:
- - virtualBindingRequirement:
- capability: org.openecomp.capabilities.nfv.vdu.VirtualBindable
- #node: org.openecomp.asdc.nodes.vCE_Brocade_VDU
- relationship: org.openecomp.relationships.nfv.VirtualBindsTo
- occurrences: [1, 1] #default
-
- - virtualLinkingrequirement:
- capability: org.openecomp.capabilities.nfv.VirtualLinkable
- #node: org.openecomp.asdc.nodes.nfv.VL
- relationship: org.openecomp.relationships.nfv.VirtualLinksTo
- occurrences: [1, 1] #default
-
- #interfaces:
- #standard:
- #configure:
- #implementation: configure.sh
- \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.zip
deleted file mode 100644
index a7ba8119d9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector/org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.json
deleted file mode 100644
index b4f9a8f03e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.cp.OAM_VLAN_Connector.yaml",
- "contactId": "jh0003",
- "name": "org.openecomp.resource.nfv.cp.OAM_VLAN_Connector",
- "description": "Represents a virtual or physical interface between the NFV and the OAM.",
- "resourceIconPath": "port",
- "category": "Network Layer 2-3/LAN Connectors",
- "tags": [
- "org.openecomp.resource.nfv.cp.OAM_VLAN_Connector", "OAM Connector", "OAM"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.yaml
deleted file mode 100644
index 6f7c86f676..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
-##################################################################
- ############### OAM VLAN Connector CP Node #####################
- ##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.cp.OAM_VLAN_Connector:
- derived_from: org.openecomp.resource.nfv.CP
- properties:
- oam_network_name:
- type: string
-
- oam_network_type:
- type: string
-
- oam_network_uuid:
- type: string
-
- vlan_segment_ids:
- type: list
- entry_schema:
- type: string
- description: list of segmentation Ids.
-
-
- #attributes:
- capabilities:
- dummy_capability:
- type: org.openecomp.capabilities.nfv.OAM_VLAN_Connector
- description: This capability has been introduced to model this Connector as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- requirements:
- - virtualBindingRequirement:
- capability: org.openecomp.capabilities.nfv.vdu.VirtualBindable
- #node: org.openecomp.asdc.nodes.vCE_Brocade_VDU
- relationship: org.openecomp.relationships.nfv.VirtualBindsTo
- occurrences: [1, 1] #default
-
- - virtualLinkingrequirement:
- capability: org.openecomp.capabilities.nfv.VirtualLinkable
- #node: org.openecomp.asdc.nodes.nfv.VL
- relationship: org.openecomp.relationships.nfv.VirtualLinksTo
- occurrences: [1, 1] #default
-
- #interfaces:
- #standard:
- #configure:
- #implementation: configure.sh
- \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.zip
deleted file mode 100644
index f7ebded1d9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector/org.openecomp.resource.nfv.CP.OAM_VLAN_Connector.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.json
deleted file mode 100644
index 819335d0f3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.cp.VPE_VLAN_Connector.yaml",
- "contactId": "jh0003",
- "name": "org.openecomp.resource.nfv.cp.VPE_VLAN_Connector",
- "description": "Represents a virtual or physical interface between the NFV and the WAN.",
- "resourceIconPath": "port",
- "category": "Network Layer 2-3/WAN Connectors",
- "tags": [
- "org.openecomp.resource.nfv.cp.VPE_VLAN_Connector", "WAN Connector"
- ]
-}
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.yaml
deleted file mode 100644
index f5f7380374..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
-##################################################################
- ############### VPE VLAN Connector CP Node #####################
- ##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.cp.VPE_VLAN_Connector:
- derived_from: org.openecomp.resource.nfv.CP
- properties:
- vpe_network_name:
- type: string
-
- vpe_network_type:
- type: string
-
- vpe_network_uuid:
- type: string
-
- vlan_segment_ids:
- type: list
- entry_schema:
- type: string
- description: list of segmentation Ids.
-
-
- #attributes:
- capabilities:
- dummy_capability:
- type: org.openecomp.capabilities.nfv.VPE_VLAN_Connector
- description: This capability has been introduced to model this Connector as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- requirements:
- - virtualBindingRequirement:
- capability: org.openecomp.capabilities.nfv.vdu.VirtualBindable
- #node: org.openecomp.asdc.nodes.vCE_Brocade_VDU
- relationship: org.openecomp.relationships.nfv.VirtualBindsTo
- occurrences: [1, 1] #default
-
- - virtualLinkingrequirement:
- capability: org.openecomp.capabilities.nfv.VirtualLinkable
- #node: org.openecomp.asdc.nodes.nfv.VL
- relationship: org.openecomp.relationships.nfv.VirtualLinksTo
- occurrences: [1, 1] #default
-
- #interfaces:
- #standard:
- #configure:
- #implementation: configure.sh
- \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.zip
deleted file mode 100644
index cabbde3ac8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector/org.openecomp.resource.nfv.CP.VPE_VLAN_Connector.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.json
deleted file mode 100644
index 76c3eabc26..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.CP.yaml",
- "contactId": "jh0003",
- "name": "org.openecomp.resource.nfv.CP",
- "description": "ATT CP element",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "org.openecomp.resource.nfv.CP"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.yaml
deleted file mode 100644
index ba6bda0c8b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-##################################################################
-############################ ASDC CP Node #####################
-##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.CP:
- derived_from: tosca.nodes.nfv.CP \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.zip
deleted file mode 100644
index 708d20f99f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.CP/org.openecomp.resource.nfv.CP.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.json
deleted file mode 100644
index 4fa3fe9bf4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.vdu.RoutingCategoryVDU.yaml",
- "attContact": "jh0003",
- "name": "org.openecomp.resource.nfv.vdu.RoutingCategoryVDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Infrastructure",
- "tags": [
- "org.openecomp.resource.nfv.vdu.RoutingCategoryVDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.yaml
deleted file mode 100644
index 5bbc64cb2c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-##################################################################
-###################### ASDC Routing Category VDU #################
-##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.vdu.RoutingCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.zip
deleted file mode 100644
index 68f16aaa96..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU/org.openecomp.resource.nfv.VDU.RoutingCategoryVDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.json
deleted file mode 100644
index 91b692357b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.vdu.VCE_Brocade_VDU.yaml",
- "contactId": "jh0003",
- "name": "org.openecomp.resource.nfv.vdu.VCE_Brocade_VDU",
- "description": "Brocade Vyatta 5600 vRouter used as Virtual Customer Edge (vCE) delivers high throughput on general-purpose x86 server. it is based on open standards, open protocols and is fully compatible with legacy networks. It has advanced functionality to be able to deploy in a variety of network environments.",
- "resourceIconPath": "brocade",
- "category": "Network Layer 2-3/Router",
- "tags": [
- "org.openecomp.resource.nfv.vdu.VCE_Brocade_VDU", "vCE", "Brocade", "Gamma"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.yaml
deleted file mode 100644
index 2ba732ab3b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.yaml
+++ /dev/null
@@ -1,156 +0,0 @@
-##################################################################
-###################### vCE_Brocade_VDU Node TYPE ###############
-##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.vdu.VCE_Brocade_VDU:
- derived_from: org.openecomp.resource.nfv.vdu.RoutingCategoryVDU
- description: Definition of VCE Brocade VDU
- properties:
- vnf_category:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- vce_type:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- vendor:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- version:
- type: string
- description: input provided at RESOURCE INJECTION TIME in ASDC TOOL
- image_id:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer -vCE image used to boot VM
- flavor_id:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer - VM Size, SMALL, MEDIUM, LARGE
- username:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer -login user Id of Router
- password:
- type: string
- description: I Input provided at DESIGN TIME by Service Composer or Designer - password for login
- domain_name:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer or (perhaps pre-defined for each Cloud Region) - login domain
- time_zone:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer or (perhaps pre-defined for each Cloud Region) - time zone to set for vCE
- login_session_timeout:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer or (perhaps pre-defined for each Cloud Region) - user login session timeout
- ipag_vlan_bandwidth:
- type: integer
- description: Input provided at DESIGN TIME by Service Composer or Designer - bandwidth allocation of customer VLAN requested by customer
- vpe_vlan_interface_qos_name:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer - QoS Policy name to be applied to this interface
- ipag_vlan_interface_qos_name:
- type: string
- description: Input provided at DESIGN TIME by Service Composer or Designer - QoS Policy name to be applied to this interface
- hostname:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - Host VM is created first and this value is input when the vCE image is later on installed by Cloud-PO
- host_ip:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - Host VM IP
- availability_zone:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - Cloud availability zone where VM is created
- oam_loopback_vlan_ip_address:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - OAM Network is pre-created - already exists in Data Center
- ipag_vlan_ip_address:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - IPAG VLAN Network is created by Cloud-PO before the vCE is created or installed
- vpe_vlan_ip_address:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - VPE VLAN Network is created by Cloud-PO before the vCE is created / installed
- vpe_vlan_id:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - VLAN Id is created first by Cloud-PO. It is required to apply VPE QoS Policy
- ipag_vlan_id:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - VLAN Id is created first by Cloud-PO. It is required to apply IPAG QoS Policy
- oam_vlan_interface_name:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - This interfce is created first by Cloud-PO. This is the interface to which QoS policy is applied
- vpe_vlan_interface_name:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - This interfce is created first by Cloud-PO. This is the interface to which QoS policy is applied
- ipag_vlan_interface_name:
- type: string
- description: Input provided at RUN TIME by Cloud-PO - This interfce is created first by Cloud-PO. This is the interface to which QoS policy is applied
- #############ATTRIBUTES of vCE - These values are outputted by Cloud-PO when vCE is created / installed ##############
- attributes:
- vce_name:
- type: string
- description: Name assigned to vCE by Cloud-PO
- oam_loopback_vlan_ipaddres:
- type: string
- description: IP Address assigned by Cloud-PO to OAM VLAN
- ipag_vlan_ipaddres:
- type: string
- description: IP Address assigned by Cloud-PO to IPAG VLAN
- vpe_vlan_ipaddres:
- type: string
- description: IP Address assigned by Cloud-PO to VPE VLAN
- vnf_id:
- type: string
- description: unique id assigned to VNF by Cloud-PO - used for AAI metadata
-
- #############CAPABILITIES of vCE - #########################
- capabilities:
- ce_routing_capability:
- type: org.openecomp.capabilities.nfv.CERouting
- description: This is the base capability of vCE
- occurrences: [1, UNBOUNDED] # default
-
- static_routing:
- type: org.openecomp.capabilities.nfv.StaticRouting
- description: This is the optional capability of the vCE
- occurrences: [0, UNBOUNDED]
-
- bgp_routing:
- type: org.openecomp.capabilities.nfv.BGPRouting
- description: This is the optional capability of the vCE
- occurrences: [0, UNBOUNDED]
-
- virtual_bindable:
- type: org.openecomp.capabilities.nfv.vdu.VirtualBindable
- description: This is the internal capability of the VDU to support Binding to Connection Points
- occurrences: [1, UNBOUNDED]
-
- dummy_capability:
- type: org.openecomp.capabilities.nfv.VCE_Brocade_Routing
- description: This capability has been introduced to model VCE VDU as a component of VCE VNF, because Node Template is not supported by ASDC Team
-
- #############REQUIREMENTS of vdu - ###########################
- requirements:
- - oam_vlan_connector:
- capability: org.openecomp.capabilities.nfv.OAM_VLAN_Connector
- node: org.openecomp.resource.nfv.cp.OAM_VLAN_Connector
- relationship: tosca.relationships.ConnectsTo
- occurrences: [1, 1]
-
- - vpe_vlan_connector:
- capability: org.openecomp.capabilities.nfv.VPE_VLAN_Connector
- node: org.openecomp.resource.nfv.cp.VPE_VLAN_Connector
- relationship: tosca.relationships.ConnectsTo
- occurrences: [1, 1]
-
- - ipag_vlan_connector:
- capability: org.openecomp.capabilities.nfv.IPAG_VLAN_Connector
- node: org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector
- relationship: tosca.relationships.ConnectsTo
- occurrences: [1, 1]
-
- - hosted_on: # A vCE needs to be hosted in a VM
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
- occurrences: [1, 1] #default
-
-
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.zip
deleted file mode 100644
index 47e3cbff2a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU/org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.json
deleted file mode 100644
index 9623090743..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VDU.yaml",
- "contactId": "jh0003",
- "name": "org.openecomp.resource.nfv.VDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "org.openecomp.resource.nfv.VDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.yaml
deleted file mode 100644
index f5e5aa9195..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.nfv.VDU:
- derived_from: tosca.nodes.nfv.VDU
- description: A VDU is a compute component of VNF \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.zip
deleted file mode 100644
index 9e5c12189a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/org.openecomp.resource.nfv.VDU/org.openecomp.resource.nfv.VDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.json
deleted file mode 100644
index d0f60bb7e3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.yaml",
- "attContact": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VDU.DHCPCategoryVDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Network Elements",
- "tags": [
- "org.openecomp.resource.nfv.VDU.DHCPCategoryVDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.yaml
deleted file mode 100644
index 04aac7300e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-##################################################################
-###################### DHCP VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.DHCPCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paronin - added to connect to VCE_Brocade_VDU
- dhcp:
- type: org.openecomp.capabilities.nfv.VNF.DHCPCapability
- description: This capability has been introduced
- ###############Further details described in DHCP VNF TOSCA Model \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.zip
deleted file mode 100644
index d55698f3e6..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU/org.openecomp.resource.nfv.VDU.DHCPCategoryVDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.json
deleted file mode 100644
index ca0f2c9ea8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VDU.DNSCategoryVDU.yaml",
- "attContact": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VDU.DNSCategoryVDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Network Elements",
- "tags": [
- "org.openecomp.resource.nfv.VDU.DNSCategoryVDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.yaml
deleted file mode 100644
index 58aa9f3e81..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-##################################################################
-###################### DNS VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.DNSCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- dns:
- type: org.openecomp.capabilities.nfv.VNF.DNSCapability
- description: This capability has been introduced
- ###############Further details described in DNS VNF TOSCA Model \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.zip
deleted file mode 100644
index f036a2fdd9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.DNSCategoryVDU/org.openecomp.resource.nfv.VDU.DNSCategoryVDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.json
deleted file mode 100644
index 6c0b033552..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.yaml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VDU.FirewallCategoryVDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Network Elements",
- "tags": [
- "org.openecomp.resource.nfv.VDU.FirewallCategoryVDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.yaml
deleted file mode 100644
index f22dfcb35e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-##################################################################
-###################### Firewall VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.FirewallCategoryVDU:
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- firewall:
- type: org.openecomp.capabilities.nfv.VNF.FirewallCapability
- description: This capability has been introduced
- ###############Further details described in Firewall VNF TOSCA Model \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.zip
deleted file mode 100644
index aa453f0912..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU/org.openecomp.resource.nfv.VDU.FirewallCategoryVDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.json
deleted file mode 100644
index 67762f8c60..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.yaml",
- "attContact": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Network Elements",
- "tags": [
- "org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.yaml
deleted file mode 100644
index 133ccc33b5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-##################################################################
-###################### ASDC NAT VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU: #paharoni - renamed from org.openecomp.resource.nfv.VDU.NetworkAddressTranslationCategoryVDU. Resource name can be up to 50 chars in ASDC
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- nat:
- type: org.openecomp.capabilities.nfv.VNF.NetworkAddressTranslationCapability
- description: This capability has been introduced
- ###############Further details described in NAT VNF TOSCA Model \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.zip
deleted file mode 100644
index 708d8a8521..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU/org.openecomp.resource.nfv.VDU.NetworkAddrCategoryVDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.json
deleted file mode 100644
index 26a2dd9a08..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.yaml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Network Elements",
- "tags": [
- "org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.yaml
deleted file mode 100644
index 04aad2f848..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.yaml
+++ /dev/null
@@ -1,10 +0,0 @@
-##################################################################
-###################### PAT VDU Node TYPE ###############
-##################################################################
- org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU: #paharoni - renamed from org.openecomp.resource.nfv.VDU.PortAddressTranslationCategoryVDU. Resource name can be up to 50 chars in ASDC
- derived_from: org.openecomp.resource.nfv.VDU
- capabilities: #paharoni - added to connect to VCE_Brocade_VDU
- pat:
- type: org.openecomp.capabilities.nfv.VNF.PortAddressTranslationCapability
- description: This capability has been introduced
- ###############Further details described in PAT VNF TOSCA Model \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.zip
deleted file mode 100644
index ce987de81f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU/org.openecomp.resource.nfv.VDU.PortAddrCategoryVDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.json
deleted file mode 100644
index 7ea24e09f5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VL.yaml",
- "contactId": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VL",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "org.openecomp.resource.nfv.VL"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.yaml
deleted file mode 100644
index 0709072040..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-##################################################################
-###################### ASDC VL Node TYPE ######################
-##################################################################
- org.openecomp.resource.nfv.VL:
- derived_from: tosca.nodes.nfv.VL
-
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.zip
deleted file mode 100644
index a5029cd710..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VL/org.openecomp.resource.nfv.VL.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.json
deleted file mode 100644
index d191fe14cc..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.yaml",
- "attContact": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Network Elements",
- "tags": [
- "org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.yaml
deleted file mode 100644
index bbd0fe0945..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.yaml
+++ /dev/null
@@ -1,32 +0,0 @@
-########################################################################################################
-###################### vCE_Brocade_VNF Node TYPE #####################################################
-########### IN THE ABSENCE OF NODE TEMPLATE, the vCE_Brocade_VNF Node Type is modeled as REQUIRING: #####
-########### 1. vce_Brocade_VDU Node
-########### 2. oam_vlan_connector Node
-########### 3. ipag_vlan_connector Node
-########### 4. vpe_vlan_connector Node
-########################################################################################################
-
- org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF:
- derived_from: org.openecomp.resource.nfv.VNF
- requirements:
- - vce_brocade_vdu:
- capability: org.openecomp.capabilities.nfv.VCE_Brocade_Routing
- node: org.openecomp.resource.nfv.VDU.VCE_Brocade_VDU
- occurrences: [1, 1]
-
- - oam_vlan_connector:
- capability: org.openecomp.capabilities.nfv.OAM_VLAN_Connector
- node: org.openecomp.resource.nfv.CP.OAM_VLAN_Connector
- occurrences: [1, 1]
-
- - vpe_vlan_connector:
- capability: org.openecomp.capabilities.nfv.VPE_VLAN_Connector
- node: org.openecomp.resource.nfv.CP.VPE_VLAN_Connector
- occurrences: [1, 1]
-
- - ipag_vlan_connector:
- capability: org.openecomp.capabilities.nfv.IPAG_VLAN_Connector
- node: org.openecomp.resource.nfv.CP.IPAG_VLAN_Connector
- occurrences: [1, 1]
-
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.zip
deleted file mode 100644
index 403a7b8281..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF/org.openecomp.resource.nfv.VNF.VCE_Brocade_VNF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.json
deleted file mode 100644
index 2106ae9ff7..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "org.openecomp.resource.nfv.VNF.yaml",
- "attContact": "jh0003",
- "resourceName": "org.openecomp.resource.nfv.VNF",
- "description": "Node Type that represents a Module",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "org.openecomp.resource.nfv.VNF"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.yaml
deleted file mode 100644
index 6872cfc7fb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-##################################################################
-###################### ASDC VNF Node TYPE ######################
-##################################################################
- org.openecomp.resource.nfv.VNF:
- derived_from: tosca.nodes.nfv.VNF
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.zip
deleted file mode 100644
index 1e14315fa7..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/org.openecomp.resource.nfv.VNF/org.openecomp.resource.nfv.VNF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.json
deleted file mode 100644
index e5bcfb204e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "tosca.nodes.nfv.VL.yaml",
- "contactId": "jh0003",
- "resourceName": "tosca.nodes.nfv.VL",
- "description": "TOSCA VL base element",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "tosca.nodes.nfv.VL"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.yaml
deleted file mode 100644
index 2fbcc9c46d..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-##################################################################
- ############## TOSCA VL Node Type #######################
- ##################################################################
- tosca.nodes.nfv.VL:
- derived_from: tosca.nodes.Root
- properties:
- vendor:
- type: string
- required: false
- description: name of the vendor who provides this VL
-
- capabilities:
- virtuallinkable:
- type: tosca.capabilities.nfv.VirtualLinkable
- occurrences: [1, UNBOUNDED] # this is default
- \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.zip
deleted file mode 100644
index fc7ba8d27b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VL/tosca.nodes.nfv.VL.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.json
deleted file mode 100644
index bd6047734c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "tosca.nodes.nfv.VNF.yaml",
- "contactId": "jh0003",
- "resourceName": "tosca.nodes.nfv.VNF",
- "description": "TOSCA VNF base element",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "tosca.nodes.nfv.VNF"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.yaml
deleted file mode 100644
index 5cf9453884..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-##################################################################
-################### TOSCA VNF Node ##########################
-##################################################################
-tosca.nodes.nfv.VNF:
- derived_from: tosca.nodes.Root
- properties:
- vnf_category:
- type: string
- description: Router, FW, LB, DNS are example categories
- id:
- type: string
- description: ID of this VNF
- vendor:
- type: string
- description: name of the vendor who provides this VNF
- version:
- type: version
- description: version of the software for this VNF
- #device_config:
- # type: map
- #entry_schema:
- # type: string
- #default:
- # p1: 1
- # p2: 2
- #p3: 3
- #requirements:
- # - virtualLink:
- #capability: tosca.capabilities.nfv.VirtualLinkable
- #occurrences: [1, UNBOUNDED] \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.zip
deleted file mode 100644
index 3c10c5f388..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/resourcesToFix/tosca.nodes.nfv.VNF/tosca.nodes.nfv.VNF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.json
deleted file mode 100644
index bf82a9a390..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "tosca.nodes.nfv.CP.yaml",
- "contactId": "jh0003",
- "name": "tosca.nodes.nfv.CP",
- "description": "TOSCA CP base element",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "tosca.nodes.nfv.CP"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.yaml
deleted file mode 100644
index 271a4bf026..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.yaml
+++ /dev/null
@@ -1,24 +0,0 @@
- ##################################################################
- ####################### TOSCA CP Node ##########################
- ##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.nfv.CP:
- derived_from: tosca.nodes.Root
- properties:
- type:
- type: string
- required: false
- requirements:
- - virtualbinding:
- capability: tosca.capabilities.nfv.vdu.VirtualBindable
- occurrences: [1, 1] #this is default
-
- - virtuallink:
- capability: tosca.capabilities.nfv.VirtualLinkable
- occurrences: [1, 1] #this is default
-
- attributes:
- ip_address:
- type: string
- # required: false \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.zip
deleted file mode 100644
index 2d7281a915..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.CP/tosca.nodes.nfv.CP.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.json b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.json
deleted file mode 100644
index 2ab0340e59..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "payloadName": "tosca.nodes.nfv.VDU.yaml",
- "contactId": "jh0003",
- "name": "tosca.nodes.nfv.VDU",
- "description": "TOSCA VDU base element",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Abstract",
- "tags": [
- "tosca.nodes.nfv.VDU"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.yaml
deleted file mode 100644
index d1cba804e6..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.yaml
+++ /dev/null
@@ -1,28 +0,0 @@
- ##################################################################
- ###################### TOSCA VDU Node ##########################
- ##################################################################
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.nfv.VDU:
- derived_from: tosca.nodes.SoftwareComponent
- #properties:
-
- capabilities:
- high_availability:
- type: tosca.capabilities.nfv.HA
- occurrences: [1, UNBOUNDED] # this is default
-
- virtual_binding:
- type: tosca.capabilities.nfv.vdu.VirtualBindable
- occurrences: [1, UNBOUNDED] # this is default
-
- requirements:
- - high_availability:
- capability: tosca.capabilities.nfv.HA
- occurrences: [0,1]
-
- - host: ##Is hosted in a VM
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
- occurrences: [1, 1] #this is default \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.zip b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.zip
deleted file mode 100644
index 3ba4eb7d80..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/tosca.nodes.nfv.VDU/tosca.nodes.nfv.VDU.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/vce.brocade.capabilities.yaml b/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/vce.brocade.capabilities.yaml
deleted file mode 100644
index af55754cf3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource-VCE-Brocade/vce.brocade.capabilities.yaml
+++ /dev/null
@@ -1,191 +0,0 @@
-#####################################################################################
- ###################### TOSCA Capability: VirtualBindable ##########################
- #####################################################################################
- tosca.capabilities.nfv.vdu.VirtualBindable:
- derived_from: tosca.capabilities.Root
- valid_source_types: [tosca.nodes.nfv.VDU]
-
- #####################################################################################
- ##################### TOSCA Capability: VirtualLinkable ##########################
- #####################################################################################
- tosca.capabilities.nfv.VirtualLinkable:
- derived_from: tosca.capabilities.Root ##paharoni - changed from tosca.capabilities.nfv.VirtualLinkable - cannot derive from itself
- valid_source_types: [org.openecomp.resource.nfv.VL]
-
- #####################################################################################
- ############################ Capability: HighAvailability ##########################
- #####################################################################################
- tosca.capabilities.nfv.HA:
- derived_from: tosca.capabilities.Root
- valid_source_types: [tosca.nodes.nfv.VDU]
-
- #####################################################################################
- ############################ ASDC Capability: VirtualBindable #####################
- #####################################################################################
- org.openecomp.capabilities.nfv.vdu.VirtualBindable:
- derived_from: tosca.capabilities.nfv.vdu.VirtualBindable
- valid_source_types: [org.openecomp.resource.nfv.VDU]
-
-
-
- #####################################################################################
- ############################ ASDC Capability: VirtualLinkable #####################
- #####################################################################################
- org.openecomp.capabilities.nfv.VirtualLinkable:
- derived_from: tosca.capabilities.Root
- valid_source_types: [tosca.nodes.nfv.VL]
-
-
-
- #####################################################################################
- ######################Capability: Generic asdc capability ##########################
- #####################################################################################
- org.openecomp.capabilities.Root:
- derived_from: tosca.capabilities.Root
-
- #####################################################################################
- ############################ Capability: GENERIC ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.RoutingCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- routing_type:
- type: string
- description: some basic routing descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.vdu.RoutingCategoryVDU]
-
- #####################################################################################
- ############################ Capability: CE ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.CERouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: PE ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.PERouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: P ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.PRouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: BGP ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.BGPRouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: STATIC ROUTING ##########################
- #####################################################################################
- org.openecomp.capabilities.nfv.StaticRouting:
- derived_from: org.openecomp.capabilities.nfv.RoutingCapability
-
- #####################################################################################
- ############################ Capability: Network Address Translation ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.vnf.NetworkAddressTranslationCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- nat_type:
- type: string
- description: some basic NAT descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.vdu.NetworkAddressTranslationCategoryVDU]
-
- #####################################################################################
- ############################ Capability: Port Address Translation ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.vnf.PortAddressTranslationCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- pat_type:
- type: string
- description: some basic PAT descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.vdu.PortAddressTranslationCategoryVDU]
-
- #####################################################################################
- ############################ Capability: FIREWALL ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.vnf.FirewallCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- firewall_type:
- type: string
- description: some basic Firewall Capability descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.vdu.FirewallCategoryVDU]
-
- #####################################################################################
- ############################ Capability: DHCP ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.vnf.DHCPCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- dhcp_type:
- type: string
- description: some basic DHCP Capability descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.vdu.DHCPCategoryVDU]
-
- #####################################################################################
- ############################ Capability: DNS ###############
- #####################################################################################
- org.openecomp.capabilities.nfv.vnf.DNSCapability:
- derived_from: org.openecomp.capabilities.Root
- properties:
- dns_type:
- type: string
- description: some basic DNS Capability descriptor, if any???
- constraints:
- - valid_values: [TBD1, TBDn]
- #attributes: ???
- valid_source_types: [org.openecomp.resource.nfv.vdu.DNSCategoryVDU]
-
- #####################################################################################
- ############################ Capability: vCE Brocade ROUTING ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC BROCADE VDU ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.VCE_Brocade_Routing:
- derived_from: org.openecomp.capabilities.nfv.CERouting
- valid_source_types: [org.openecomp.resource.nfv.vdu.VCE_Brocade_VDU]
-
- #####################################################################################
- ############################ Capability: OAM VLAn Connector ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC Connector ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.OAM_VLAN_Connector:
- derived_from: org.openecomp.capabilities.Root
- valid_source_types: [org.openecomp.resource.nfv.cp.OAM_VLAN_Connector]
-
- #####################################################################################
- ############################ Capability: IPAG VLAn Connector ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC Connector ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.IPAG_VLAN_Connector:
- derived_from: org.openecomp.capabilities.Root
- valid_source_types: [org.openecomp.resource.nfv.cp.IPAG_VLAN_Connector]
-
- #####################################################################################
- ############################ Capability: VPE VLAn Connector ################# DUMMY
- ############## THIS IS CAPABILITY IS ONLY OFFERED BY SPECIFIC Connector ###########
- #####################################################################################
- org.openecomp.capabilities.nfv.VPE_VLAN_Connector:
- derived_from: org.openecomp.capabilities.Root
- valid_source_types: [org.openecomp.resource.nfv.cp.VPE_VLAN_Connector]
- \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/DBMS/DBMS.json b/asdc-tests/src/test/resources/CI/importResource/DBMS/DBMS.json
deleted file mode 100644
index 790a30ab42..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/DBMS/DBMS.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-DBMS.yml",
- "contactId": "jh0003",
- "name": "DBMS",
- "description": "Represents a typical relational, SQL Database Management System software component or service.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Abstract"
- }
- ]
- }
-],
- "tags": [
- "DBMS"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.yml b/asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.yml
deleted file mode 100644
index 28919d38e4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.DBMS:
- derived_from: tosca.nodes.SoftwareComponent
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
- capabilities:
- host:
- type: tosca.capabilities.Container
- valid_source_types: [ tosca.nodes.Database ]
diff --git a/asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.zip b/asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.zip
deleted file mode 100644
index 84bddbce47..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/DBMS/normative-types-new-DBMS.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/blockStorage/blockStorage.json b/asdc-tests/src/test/resources/CI/importResource/blockStorage/blockStorage.json
deleted file mode 100644
index 72ef5c009b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/blockStorage/blockStorage.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-blockStorage.yml",
- "contactId": "jh0003",
- "name": "BlockStorage",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "objectStorage",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "BlockStorage"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.yml b/asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.yml
deleted file mode 100644
index a82965215f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.BlockStorage:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.zip b/asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.zip
deleted file mode 100644
index f690e9d8ea..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/blockStorage/normative-types-new-blockStorage.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/capabilityTypes.yml b/asdc-tests/src/test/resources/CI/importResource/capabilityTypes.yml
deleted file mode 100644
index 58d661b17e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/capabilityTypes.yml
+++ /dev/null
@@ -1,148 +0,0 @@
-tosca.capabilities.Root:
- description: The TOSCA root Capability Type all other TOSCA base Capability Types derive from
-tosca.capabilities.Attachment:
- derived_from: tosca.capabilities.Root
-tosca.capabilities.Node:
- derived_from: tosca.capabilities.Root
-tosca.capabilities.Container:
- derived_from: tosca.capabilities.Root
- properties:
- num_cpus:
- type: integer
- required: false
- constraints:
- - greater_or_equal: 1
- cpu_frequency:
- type: scalar-unit.frequency
- required: false
- constraints:
- - greater_or_equal: 0.1 GHz
- disk_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
- mem_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
-tosca.capabilities.Endpoint:
- derived_from: tosca.capabilities.Root
- properties:
- protocol:
- type: string
- default: tcp
- port:
- type: PortDef
- required: false
- secure:
- type: boolean
- default: false
- url_path:
- type: string
- required: false
- port_name:
- type: string
- required: false
- network_name:
- type: string
- required: false
- default: PRIVATE
- initiator:
- type: string
- default: source
- constraints:
- - valid_values: [ source, target, peer ]
- ports:
- type: map
- required: false
- constraints:
- - min_length: 1
- entry_schema:
- type: PortSpec
- attributes:
- ip_address:
- type: string
-tosca.capabilities.DatabaseEndpoint:
- derived_from: tosca.capabilities.Endpoint
-tosca.capabilities.Endpoint.Public:
- derived_from: tosca.capabilities.Endpoint
- properties:
- # Change the default network_name to use the first public network found
- network_name: PUBLIC
- floating:
- description: >
- indicates that the public address should be allocated from a pool of floating IPs that are associated with the network.
- type: boolean
- default: false
- status: experimental
- dns_name:
- description: The optional name to register with DNS
- type: string
- required: false
- status: experimental
-tosca.capabilities.Endpoint.Admin:
- derived_from: tosca.capabilities.Endpoint
- # Change Endpoint secure indicator to true from its default of false
- properties:
- secure: true
-tosca.capabilities.Endpoint.Database:
- derived_from: tosca.capabilities.Endpoint
-tosca.capabilities.OperatingSystem:
- derived_from: tosca.capabilities.Root
- properties:
- architecture:
- type: string
- required: false
- type:
- type: string
- required: false
- distribution:
- type: string
- required: false
- version:
- type: version
- required: false
-tosca.capabilities.Scalable:
- derived_from: tosca.capabilities.Root
- properties:
- min_instances:
- type: integer
- default: 1
- max_instances:
- type: integer
- default: 1
- default_instances:
- type: integer
-tosca.capabilities.network.Bindable:
- derived_from: tosca.capabilities.Node
-
-
-tosca.capabilities.Container.Docker:
- derived_from: tosca.capabilities.Container
- properties:
- version:
- type: list
- required: false
- entry_schema: version
- publish_all:
- type: boolean
- default: false
- required: false
- publish_ports:
- type: list
- entry_schema: PortSpec
- required: false
- expose_ports:
- type: list
- entry_schema: PortSpec
- required: false
- volumes:
- type: list
- entry_schema: string
- required: false
-tosca.capabilities.network.Linkable:
- derived_from: tosca.capabilities.Root
-
-
diff --git a/asdc-tests/src/test/resources/CI/importResource/capabilityTypes.zip b/asdc-tests/src/test/resources/CI/importResource/capabilityTypes.zip
deleted file mode 100644
index 50b66e61be..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/capabilityTypes.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/capabilityTypesCi.zip b/asdc-tests/src/test/resources/CI/importResource/capabilityTypesCi.zip
deleted file mode 100644
index 550cd756f4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/capabilityTypesCi.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/categoryTypes.yml b/asdc-tests/src/test/resources/CI/importResource/categoryTypes.yml
deleted file mode 100644
index d88a326859..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/categoryTypes.yml
+++ /dev/null
@@ -1,89 +0,0 @@
-services:
- Mobility:
- name: "Mobility"
- icons: ['mobility']
- Network_L1_3:
- name: "Network L1-3"
- icons: ['network_l_1-3']
- Network_L4:
- name: "Network L4+"
- icons: ['network_l_4']
- VoIP_Call_Control:
- name: "VoIP Call Control"
- icons: ['call_controll']
-resources:
- NetworkLayer23:
- name: "Network L2-3"
- subcategories:
- Router:
- name: "Router"
- icons: ['router','vRouter']
- Gateway:
- name: "Gateway"
- icons: ['gateway']
- WAN_Connectors:
- name: "WAN Connectors"
- icons: ['network','connector','port']
- LAN_Connectors:
- name: "LAN Connectors"
- icons: ['network','connector','port']
- Infrastructure:
- name: "Infrastructure"
- icons: ['ucpe']
- NetworkLayer4:
- name: "Network L4+"
- subcategories:
- Common_Network_Resources:
- name: "Common Network Resources"
- icons: ['network']
- ApplicationLayer4:
- name: "Application L4+"
- subcategories:
- Border_Element:
- name: "Border Element"
- icons: ['borderElement']
- Application_Server:
- name: "Application Server"
- icons: ['applicationServer']
- Web_Server:
- name: "Web Server"
- icons: ['applicationServer']
- Call_Control:
- name: "Call Control"
- icons: ['call_controll']
- Media_Servers:
- name: "Media Servers"
- icons: ['applicationServer']
- Load_Balancer:
- name: "Load Balancer"
- icons: ['loadBalancer']
- Database:
- name: "Database"
- icons: ['database']
- Firewall:
- name: "Firewall"
- icons: ['firewall']
- Generic:
- name: "Generic"
- subcategories:
- Infrastructure:
- name: "Infrastructure"
- icons: ['connector']
- Abstract:
- name: "Abstract"
- icons: ['objectStorage', 'compute']
- Network_Elements:
- name: "Network Elements"
- icons: ['network', 'connector']
- Database:
- name: "Database"
- icons: ['database']
- NetworkConnectivity:
- name: "Network Connectivity"
- subcategories:
- ConnectionPoints:
- name: "Connection Points"
- icons: ['cp']
- VirtualLinks:
- name: "Virtual Links"
- icons: ['vl'] \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/categoryTypes.zip b/asdc-tests/src/test/resources/CI/importResource/categoryTypes.zip
deleted file mode 100644
index 29984b8a06..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/categoryTypes.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/compute/compute.json b/asdc-tests/src/test/resources/CI/importResource/compute/compute.json
deleted file mode 100644
index 48775d0f14..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/compute/compute.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "payloadName": "normative-types-new-compute.yml",
- "contactId": "jh0003",
- "name": "Compute",
- "description": "Represents a real or virtual machine or server. Information specified on the Compute
- node will be used to find the machine that fits the given requirements in the cloud
- available machines. If no sizing information are specified the cloud provider default
- machine will be used. It is strongly recommended to specify the required CPUs and memory
- at least.",
- "resourceIconPath": "compute",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "Compute"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.yml b/asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.yml
deleted file mode 100644
index 00b07fb908..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.Compute:
- 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/asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.zip b/asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.zip
deleted file mode 100644
index f7a7c31bf0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/compute/normative-types-new-compute.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/containerApplication/containerApplication.json b/asdc-tests/src/test/resources/CI/importResource/containerApplication/containerApplication.json
deleted file mode 100644
index 1713e56cb4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/containerApplication/containerApplication.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-containerApplication.yml",
- "contactId": "jh0003",
- "name": "Application",
- "description": "Represents an application that requires Container-level virtualization technology.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Abstract"
- }
- ]
- }
-],
- "tags": [
- "Application"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.yml b/asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.yml
deleted file mode 100644
index 8813f26e04..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.Container.Application:
- derived_from: tosca.nodes.Root
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Container
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.zip b/asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.zip
deleted file mode 100644
index 1da3bc1707..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/containerApplication/normative-types-new-containerApplication.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/containerRuntime/containerRuntime.json b/asdc-tests/src/test/resources/CI/importResource/containerRuntime/containerRuntime.json
deleted file mode 100644
index 233bf39bce..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/containerRuntime/containerRuntime.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-containerRuntime.yml",
- "contactId": "jh0003",
- "name": "Runtime",
- "description": "Represents operating system-level virtualization technology used to run multiple application services on a single Compute host.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Abstract"
- }
- ]
- }
-],
- "tags": [
- "Runtime"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.yml b/asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.yml
deleted file mode 100644
index 86a10a0185..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.Container.Runtime:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- host:
- type: tosca.capabilities.Container
- scalable:
- type: tosca.capabilities.Scalable
diff --git a/asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.zip b/asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.zip
deleted file mode 100644
index 5140472147..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/containerRuntime/normative-types-new-containerRuntime.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/database/database.json b/asdc-tests/src/test/resources/CI/importResource/database/database.json
deleted file mode 100644
index 0f09e278c0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/database/database.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-database.yml",
- "contactId": "jh0003",
- "name": "Database",
- "description": "Represents a logical database that can be managed and hosted by a DBMS node.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Database"
- }
- ]
- }
-],
- "tags": [
- "Database"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.yml b/asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.yml
deleted file mode 100644
index 5166150c73..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.Database:
- derived_from: tosca.nodes.Root
- properties:
- name:
- type: string
- description: the logical name of the database
- port:
- type: integer
- description: the port the underlying database service will listen to for data
- user:
- type: string
- description: the optional user account name for DB administration
- required: false
- password:
- type: string
- description: the optional password for the DB user account
- required: false
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.DBMS
- relationship: tosca.relationships.HostedOn
- capabilities:
- database_endpoint:
- type: tosca.capabilities.Endpoint.Database
diff --git a/asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.zip b/asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.zip
deleted file mode 100644
index 9e8b178554..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/database/normative-types-new-database.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/deleteNormative.sh b/asdc-tests/src/test/resources/CI/importResource/deleteNormative.sh
deleted file mode 100644
index fb70f71418..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/deleteNormative.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort>"
-}
-
-function deleteResource() {
-
- ELEMENT_NAME=$1
- echo -e "############### Removing Element ${ELEMENT_NAME} Start ######################"
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -X "DELETE" -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/resources/res_${ELEMENT_NAME}".1.0")
- if [ ${http_code} -eq 204 ]; then
- echo -e "\n############### Removing Element ${ELEMENT_NAME} status code:${http_code} End #######\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n############### Failed to remove Element ${ELEMENT_NAME} status code:${http_code} End #######\n\n\n"
- exit 1
- elif [ ${http_code} -eq 404 ]; then
- echo -e "\n############### Element ${ELEMENT_NAME} not found status code:${http_code} End #######\n\n\n"
- else
- echo -e "\n############### Failed to remove Element ${ELEMENT_NAME} status code:${http_code} End #######\n\n\n"
- exit 1
- fi
-}
-if [ $# -lt 2 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-
-deleteResource "tosca.nodes.Root"
-deleteResource "tosca.nodes.Compute"
-deleteResource "tosca.nodes.SoftwareComponent"
-deleteResource "tosca.nodes.WebServer"
-deleteResource "tosca.nodes.WebApplication"
-deleteResource "tosca.nodes.DBMS"
-deleteResource "tosca.nodes.Database"
-deleteResource "tosca.nodes.ObjectStorage"
-deleteResource "tosca.nodes.BlockStorage"
-deleteResource "tosca.nodes.Container.Runtime"
-deleteResource "tosca.nodes.Container.Application"
-deleteResource "tosca.nodes.LoadBalancer"
-deleteResource "tosca.nodes.network.Port"
-deleteResource "tosca.nodes.network.Network"
-
-exit 0
-
diff --git a/asdc-tests/src/test/resources/CI/importResource/importNormative.sh b/asdc-tests/src/test/resources/CI/importResource/importNormative.sh
deleted file mode 100644
index 7c420ceb43..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/importNormative.sh
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/bin/bash
-
-function usage {
- echo "Usage: $0 <hostIp> <hostPort> <userId>"
-}
-
-function addResource() {
-
- ELEMENT_NAME=$1
- echo -e "###################### Adding Element ${ELEMENT_NAME} Start ######################"
- CURRENT_ZIP_FILE=./${ELEMENT_NAME}/normative-types-new-${ELEMENT_NAME}.zip
- CURRENT_JSON_FILE=./${ELEMENT_NAME}/${ELEMENT_NAME}.json
- sed -i 's/"userId": ".*",/"userId": "'${ATT_UID}'",/' ${CURRENT_JSON_FILE}
- JSON_CONTENT=`paste -s ${CURRENT_JSON_FILE}`
- http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F resourceMetadata="${JSON_CONTENT}" -F resourceZip=@${CURRENT_ZIP_FILE} -H USER_ID:${ATT_UID} ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/upload/multipart)
- if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding Element ${ELEMENT_NAME} End ########################\n\n\n"
- elif [ ${http_code} -eq 409 ]; then
- echo -e "\n###################### Already exists Element ${ELEMENT_NAME} status code:${http_code} End ########################\n\n\n"
- elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add Element ${ELEMENT_NAME} status code:${http_code} End ########################\n\n\n"
- exit 1
- fi
-}
-if [ $# -lt 3 ]
-then
- usage
- exit 2
-fi
-
-HOST_IP=$1
-HOST_PORT=$2
-ATT_UID=$3
-
-#Add The CapabilityTypes
-http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F capabilityTypeZip=@capabilityTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/capability)
-if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding The CapabilityTypes status code:${http_code} End ########################\n\n\n"
-elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-else
- echo -e "\n###################### Failed to add CapabilityTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-fi
-#Add The InterfaceLifecycleTypes
-http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F interfaceLifecycleTypeZip=@interfaceLifecycleTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle)
-if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding The InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
-elif [ ${http_code} -eq 409 ]; then
- echo -e "\n###################### Already exists InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
-elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-else
- echo -e "\n###################### Failed to add InterfaceLifecycleTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-fi
-#Add The CategoryTypes
-http_code=$(curl -s -o /dev/null -w "%{http_code}" -v -F categoriesZip=@categoryTypes.zip -H "USER_ID: jh0003" ${HOST_IP}:${HOST_PORT}/sdc2/rest/v1/catalog/uploadType/categories)
-if [ ${http_code} -eq 201 ]; then
- echo -e "\n###################### Adding The CategoryTypes status code:${http_code} End ########################\n\n\n"
-elif [ ${http_code} -eq 409 ]; then
- echo -e "\n###################### Already exists CategoryTypes status code:${http_code} End ########################\n\n\n"
-elif [ ${http_code} -eq 500 ]; then
- echo -e "\n###################### Failed to add CategoryTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-else
- echo -e "\n###################### Failed to add CategoryTypes status code:${http_code} End ########################\n\n\n"
- exit 1
-fi
-
-addResource "root"
-addResource "compute"
-addResource "softwareComponent"
-addResource "webServer"
-addResource "webApplication"
-addResource "DBMS"
-addResource "database"
-addResource "objectStorage"
-addResource "blockStorage"
-addResource "containerRuntime"
-addResource "containerApplication"
-addResource "loadBalancer"
-addResource "port"
-addResource "network"
-
-exit 0
-
diff --git a/asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.yml b/asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.yml
deleted file mode 100644
index 1b67118934..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-tosca.interfaces.node.lifecycle.Standard:
- create:
- description: Standard lifecycle create operation.
- configure:
- description: Standard lifecycle configure operation.
- start:
- description: Standard lifecycle start operation.
- stop:
- description: Standard lifecycle stop operation.
- delete:
- description: Standard lifecycle delete operation. \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.zip b/asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.zip
deleted file mode 100644
index 9bcf93ab7d..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/interfaceLifecycleTypes.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/loadBalancer/loadBalancer.json b/asdc-tests/src/test/resources/CI/importResource/loadBalancer/loadBalancer.json
deleted file mode 100644
index fbddc18c07..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/loadBalancer/loadBalancer.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-loadBalancer.yml",
- "contactId": "jh0003",
- "name": "LoadBalancer",
- "description": "Represents logical function that be used in conjunction with a Floating Address to distribute an application’s traffic (load) across a number of instances of the application (e.g., for a clustered or scaled application).",
- "resourceIconPath": "loadBalancer",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "LoadBalancer"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.yml b/asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.yml
deleted file mode 100644
index 86857656ad..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.LoadBalancer:
- derived_from: tosca.nodes.Root
- properties:
- # TBD
- algorithm :
- type: string
- required: false
- status: experimental
- capabilities :
- client:
- type: tosca.capabilities.Endpoint.Public
- description: the Floating (IP) client’s on the public network can connect to
- requirements:
- - application:
- capability: tosca.capabilities.Endpoint
- relationship: tosca.relationships.RoutesTo
diff --git a/asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.zip b/asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.zip
deleted file mode 100644
index fefed6f0f4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/loadBalancer/normative-types-new-loadBalancer.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/network/network.json b/asdc-tests/src/test/resources/CI/importResource/network/network.json
deleted file mode 100644
index cf1eb03ff0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/network/network.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "payloadName": "normative-types-new-network.yml",
- "contactId": "jh0003",
- "name": "Network",
- "description": "Represents a simple , logical network service.",
- "resourceIconPath": "network",
- "resourceType": "VL",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "Network"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.yml b/asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.yml
deleted file mode 100644
index e1f9d3db70..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.yml
+++ /dev/null
@@ -1,41 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vl.Network:
- derived_from: tosca.nodes.Root
- properties:
- ip_version:
- type: integer
- required: false
- default: 4
- constraints:
- - valid_values: [ 4, 6 ]
- cidr:
- type: string
- required: false
- start_ip:
- type: string
- required: false
- end_ip:
- type: string
- required: false
- gateway_ip:
- type: string
- required: false
- network_name:
- type: string
- required: false
- network_id:
- type: string
- required: false
- segmentation_id:
- type: string
- required: false
- network_type:
- type: string
- required: false
- physical_network:
- type: string
- required: false
- capabilities:
- link:
- type: tosca.capabilities.network.Linkable
diff --git a/asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.zip b/asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.zip
deleted file mode 100644
index b10daebb2b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/network/normative-types-new-network.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.yml b/asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.yml
deleted file mode 100644
index 2d1540b27b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.network.Port:
- derived_from: tosca.nodes.Root
- properties:
- ip_address:
- type: string
- required: false
- order:
- type: integer
- required: true
- default: 0
- constraints:
- - greater_or_equal: 0
- is_default:
- type: boolean
- required: false
- default: false
- ip_range_start:
- type: string
- required: false
- ip_range_end:
- type: string
- required: false
- requirements:
- - link:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - binding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo
diff --git a/asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.zip b/asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.zip
deleted file mode 100644
index f6903ea8ee..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/normative-port/normative-types-new-port.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/normative-port/port.json b/asdc-tests/src/test/resources/CI/importResource/normative-port/port.json
deleted file mode 100644
index 7b62d7ff0a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/normative-port/port.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-port.yml",
- "contactId": "jh0003",
- "name": "Port",
- "description": "Represents a logical entity that associates between Compute and Network normative types.",
- "resourceIconPath": "port",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Network Elements"
- }
- ]
- }
-],
- "tags": [
- "Port"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/notmative-network/network.json b/asdc-tests/src/test/resources/CI/importResource/notmative-network/network.json
deleted file mode 100644
index 636499fba4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/notmative-network/network.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-network.yml",
- "contactId": "jh0003",
- "name": "Network",
- "description": "Represents a simple , logical network service.",
- "resourceIconPath": "network",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "Network"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.yml b/asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.yml
deleted file mode 100644
index e92e87716f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.yml
+++ /dev/null
@@ -1,41 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.network.Network:
- derived_from: tosca.nodes.Root
- properties:
- ip_version:
- type: integer
- required: false
- default: 4
- constraints:
- - valid_values: [ 4, 6 ]
- cidr:
- type: string
- required: false
- start_ip:
- type: string
- required: false
- end_ip:
- type: string
- required: false
- gateway_ip:
- type: string
- required: false
- network_name:
- type: string
- required: false
- network_id:
- type: string
- required: false
- segmentation_id:
- type: string
- required: false
- network_type:
- type: string
- required: false
- physical_network:
- type: string
- required: false
- capabilities:
- link:
- type: tosca.capabilities.network.Linkable
diff --git a/asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.zip b/asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.zip
deleted file mode 100644
index 79c5fb2573..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/notmative-network/normative-types-new-network.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.yml b/asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.yml
deleted file mode 100644
index 9c338c3400..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.ObjectStorage:
- derived_from: tosca.nodes.Root
- properties:
- name:
- type: string
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 0 GB
- maxsize:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 0 GB
- capabilities:
- storage_endpoint:
- type: tosca.capabilities.Endpoint
diff --git a/asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.zip b/asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.zip
deleted file mode 100644
index b9046c1a66..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/objectStorage/normative-types-new-objectStorage.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/objectStorage/objectStorage.json b/asdc-tests/src/test/resources/CI/importResource/objectStorage/objectStorage.json
deleted file mode 100644
index 247b468952..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/objectStorage/objectStorage.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-objectStorage.yml",
- "contactId": "jh0003",
- "name": "ObjectStorage",
- "description": "Represents storage that provides the ability to store data as objects (or BLOBs of data) without consideration for the underlying filesystem or devices.",
- "resourceIconPath": "objectStorage",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "ObjectStorage"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.yml b/asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.yml
deleted file mode 100644
index 7cd71360f2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.cp.Port:
- derived_from: tosca.nodes.Root
- properties:
- ip_address:
- type: string
- required: false
- order:
- type: integer
- required: true
- default: 0
- constraints:
- - greater_or_equal: 0
- is_default:
- type: boolean
- required: false
- default: false
- ip_range_start:
- type: string
- required: false
- ip_range_end:
- type: string
- required: false
- requirements:
- - link:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - binding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo
diff --git a/asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.zip b/asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.zip
deleted file mode 100644
index e1688a7304..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/port/normative-types-new-port.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/port/port.json b/asdc-tests/src/test/resources/CI/importResource/port/port.json
deleted file mode 100644
index 38106903e3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/port/port.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "payloadName": "normative-types-new-port.yml",
- "contactId": "jh0003",
- "name": "Port",
- "description": "Represents a logical entity that associates between Compute and Network normative types.",
- "resourceIconPath": "port",
- "resourceType": "CP",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Network Elements"
- }
- ]
- }
-],
- "tags": [
- "Port"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.yml b/asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.yml
deleted file mode 100644
index e9b1de9518..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.Root:
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature:
- type: tosca.capabilities.Node
- requirements:
- - dependency :
- capability: tosca.capabilities.Node
- node: tosca.nodes.Root
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- interfaces:
- Standard:
- type: tosca.interfaces.node.lifecycle.Standard
diff --git a/asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.zip b/asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.zip
deleted file mode 100644
index 07583e89f5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/root/normative-types-new-root.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.yml b/asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.yml
deleted file mode 100644
index a154632c74..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.SoftwareComponent:
- 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
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.zip b/asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.zip
deleted file mode 100644
index ea61eec01f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/softwareComponent/normative-types-new-softwareComponent.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/softwareComponent/softwareComponent.json b/asdc-tests/src/test/resources/CI/importResource/softwareComponent/softwareComponent.json
deleted file mode 100644
index 43012d7adc..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/softwareComponent/softwareComponent.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-softwareComponent.yml",
- "contactId": "jh0003",
- "name": "SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Abstract"
- }
- ]
- }
-],
- "tags": [
- "SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.yml b/asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.yml
deleted file mode 100644
index 5f9a775fe0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.WebApplication:
- derived_from: tosca.nodes.Root
- 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
diff --git a/asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.zip b/asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.zip
deleted file mode 100644
index 516d9d9feb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/webApplication/normative-types-new-webApplication.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/webApplication/webApplication.json b/asdc-tests/src/test/resources/CI/importResource/webApplication/webApplication.json
deleted file mode 100644
index fc25c6966b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/webApplication/webApplication.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-webApplication.yml",
- "contactId": "jh0003",
- "name": "WebApplication",
- "description": "Represents a software application that can be managed and run by a Web Server node. Specific types of web applications such as Java, etc. could be derived from this type.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Abstract"
- }
- ]
- }
-],
- "tags": [
- "WebApplication"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.yml b/asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.yml
deleted file mode 100644
index 7c957b5247..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.WebServer:
- derived_from: tosca.nodes.SoftwareComponent
- capabilities:
- # Private, layer 4 endpoints
- data_endpoint: tosca.capabilities.Endpoint
- admin_endpoint: tosca.capabilities.Endpoint.Admin
- host:
- type: tosca.capabilities.Container
- valid_source_types: [ tosca.nodes.WebApplication ] \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.zip b/asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.zip
deleted file mode 100644
index a88761fa5f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/webServer/normative-types-new-webServer.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/webServer/webServer.json b/asdc-tests/src/test/resources/CI/importResource/webServer/webServer.json
deleted file mode 100644
index bd74fb18f8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResource/webServer/webServer.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "payloadName": "normative-types-new-webServer.yml",
- "contactId": "jh0003",
- "name": "WebServer",
- "description": "Represents an abstract software component or service that is capable of hosting and providing management operations for one or more Web Application nodes.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Abstract"
- }
- ]
- }
-],
- "tags": [
- "WebServer"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/Derived_VFC.json b/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/Derived_VFC.json
deleted file mode 100644
index a26149e8e5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/Derived_VFC.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "payloadName": "normative-types-new-Derived_VFC.yml",
- "contactId": "jh0003",
- "name": "ciDerivedVFC",
- "description": "Represents a real or virtual machine or server. Information specified on the Compute
- node will be used to find the machine that fits the given requirements in the cloud
- available machines. If no sizing information are specified the cloud provider default
- machine will be used. It is strongly recommended to specify the required CPUs and memory
- at least.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "ciDerivedVFC"
- ],
- "vendorName": "UserVendor",
- "vendorRelease": "1.1.1"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.yml b/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.yml
deleted file mode 100644
index 949fa6e633..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vfc.nodes.VFCderive:
- derived_from: org.openecomp.resource.abstract.nodes.VFC
-
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.zip b/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.zip
deleted file mode 100644
index dcc9eb37db..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/Derived_VFC/normative-types-new-Derived_VFC.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/VSPPackage.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/VSPPackage.csar
deleted file mode 100644
index b4aa77511b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/VSPPackage.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_1.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_1.csar
deleted file mode 100644
index 4b167cfa69..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_1.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_2.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_2.csar
deleted file mode 100644
index 1f7bc5ac8d..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/caseSensitiveTest_2.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/csars.zip b/asdc-tests/src/test/resources/CI/importResourceTests/csars/csars.zip
deleted file mode 100644
index 8a7f5de6e3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/csars.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/fiveLinesAsBlock0.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/fiveLinesAsBlock0.csar
deleted file mode 100644
index 870a777c66..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/fiveLinesAsBlock0.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion.csar
deleted file mode 100644
index 273fab3a0b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion2.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion2.csar
deleted file mode 100644
index aa0027f48e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion2.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion3.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion3.csar
deleted file mode 100644
index ce9a80b240..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion3.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion4.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion4.csar
deleted file mode 100644
index 88ccb448e7..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion4.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion5.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion5.csar
deleted file mode 100644
index a429110ea1..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/invalidCsarVersion5.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile1.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile1.csar
deleted file mode 100644
index 3361bfd867..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile1.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile2.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile2.csar
deleted file mode 100644
index 200fbd95af..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile2.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile3.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile3.csar
deleted file mode 100644
index 5ffdf6c4c4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile3.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile4.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile4.csar
deleted file mode 100644
index 30da05f951..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile4.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile5.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile5.csar
deleted file mode 100644
index e5a3fb862b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/longNamesInToscaMetaFile5.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/missingEntryDefintionPair.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/missingEntryDefintionPair.csar
deleted file mode 100644
index 63a58bcd27..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/missingEntryDefintionPair.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/missingOneLineInToscaMeta.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/missingOneLineInToscaMeta.csar
deleted file mode 100644
index ac949ce734..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/missingOneLineInToscaMeta.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf.csar
deleted file mode 100644
index 4b37f44c73..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf2.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf2.csar
deleted file mode 100644
index ec1a65ebb9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/mock_vf2.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThanOneMetaFile.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThanOneMetaFile.csar
deleted file mode 100644
index 084ada11cb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThanOneMetaFile.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThenOneYamlFile.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThenOneYamlFile.csar
deleted file mode 100644
index 9615c62e73..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/moreThenOneYamlFile.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noCSARVersion.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/noCSARVersion.csar
deleted file mode 100644
index 65a21c12b8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noCSARVersion.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noCreatedByValue.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/noCreatedByValue.csar
deleted file mode 100644
index cb08b19463..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noCreatedByValue.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noEntryDefinitionsValue.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/noEntryDefinitionsValue.csar
deleted file mode 100644
index a3a0e8fd1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noEntryDefinitionsValue.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noNewLineAfterBLock0.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/noNewLineAfterBLock0.csar
deleted file mode 100644
index 4b37f44c73..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noNewLineAfterBLock0.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noTOSCAMetaFileVersionValue.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/noTOSCAMetaFileVersionValue.csar
deleted file mode 100644
index c2f4d0442a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/noTOSCAMetaFileVersionValue.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlAndMetaFiles.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlAndMetaFiles.csar
deleted file mode 100644
index 74058d5f82..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlAndMetaFiles.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlFile.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlFile.csar
deleted file mode 100644
index 31cc2942d5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/notContainYamlFile.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/someValueAfterBlock0.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/someValueAfterBlock0.csar
deleted file mode 100644
index e600a39693..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/someValueAfterBlock0.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaFolderNotExists.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaFolderNotExists.csar
deleted file mode 100644
index 17a7e5e39f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaFolderNotExists.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaFileNotExists.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaFileNotExists.csar
deleted file mode 100644
index 55e7179505..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaFileNotExists.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaOutsideTheFolder.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaOutsideTheFolder.csar
deleted file mode 100644
index 53d6987ac7..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/toscaMetaOutsideTheFolder.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/underscoreInsteadOfDash.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/underscoreInsteadOfDash.csar
deleted file mode 100644
index c217dd5006..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/underscoreInsteadOfDash.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/validCsarVersion.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/validCsarVersion.csar
deleted file mode 100644
index 60ac6e3dd2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/validCsarVersion.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf.csar b/asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf.csar
deleted file mode 100644
index 01bf159071..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf.csar
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf_zip.zip b/asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf_zip.zip
deleted file mode 100644
index 66922ae15e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/csars/valid_vf_zip.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/empty_category.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/empty_category.json
deleted file mode 100644
index 7ce1fd5e5f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/empty_category.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "payloadName": "normative-types-new-empty_category.yml",
- "contactId": "adminid",
- "name": "tosca.nodes.empty_category",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.empty_category"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.yml
deleted file mode 100644
index 0ab5ac9322..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tosca.nodes.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.zip
deleted file mode 100644
index 537787f955..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_category/normative-types-new-empty_category.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/empty_contact.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/empty_contact.json
deleted file mode 100644
index 6e043f5606..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/empty_contact.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "payloadName": "normative-types-new-empty_contact.yml",
- "contactId": "",
- "name": "tosca.nodes.empty_contact",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
-"categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.empty_contact"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.yml
deleted file mode 100644
index 3d9c111871..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_contact:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.zip
deleted file mode 100644
index a91defb4f6..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_contact/normative-types-new-empty_contact.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/empty_desc.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/empty_desc.json
deleted file mode 100644
index 7aa4c167b4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/empty_desc.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "payloadName": "normative-types-new-empty_desc.yml",
- "contactId": "adminid",
- "name": "tosca.nodes.empty_desc",
- "description": "",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.empty_desc"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.yml
deleted file mode 100644
index 0ab5ac9322..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tosca.nodes.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.zip
deleted file mode 100644
index c105c0989f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_desc/normative-types-new-empty_desc.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/empty_icon.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/empty_icon.json
deleted file mode 100644
index e1980cee79..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/empty_icon.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "payloadName": "normative-types-new-empty_icon.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.empty_icon",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.empty_icon"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.yml
deleted file mode 100644
index 0ab5ac9322..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tosca.nodes.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.zip
deleted file mode 100644
index a500656ff7..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_icon/normative-types-new-empty_icon.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/empty_payloadName.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/empty_payloadName.json
deleted file mode 100644
index 2e46c69243..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/empty_payloadName.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "payloadName": "",
- "contactId": "adminid",
- "name": "tosca.nodes.empty_payloadName",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.empty_payloadName"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.yml
deleted file mode 100644
index 0ab5ac9322..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tosca.nodes.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.zip
deleted file mode 100644
index 901d2de441..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_payloadName/normative-types-new-empty_payloadName.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/empty_resource_name.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/empty_resource_name.json
deleted file mode 100644
index dff8e13ad5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/empty_resource_name.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-empty_resource_name.yml",
- "contactId": "adminid",
- "name": "",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["empty_resource_name"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.zip
deleted file mode 100644
index 6146cb8524..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_resource_name/normative-types-new-empty_resource_name.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/empty_tag.json b/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/empty_tag.json
deleted file mode 100644
index 5028baa786..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/empty_tag.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-empty_tag.yml",
- "contactId": "adminid",
- "name": "tosca.nodes.empty_tag",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": [""],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.yml b/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.zip b/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.zip
deleted file mode 100644
index 069b3d1979..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/empty_tag/normative-types-new-empty_tag.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/import _multiple_tags.json b/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/import _multiple_tags.json
deleted file mode 100644
index ec361827b0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/import _multiple_tags.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "payloadName": "normative-types-new-import _multiple_tags.yml",
- "contactId": "adminid",
- "name": "tosca.nodes.import _multiple_tags",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["tosca.nodes.import _multiple_tags",
- "import _multiple_tags",
- "import _multiple_tags2"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.yml b/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.yml
deleted file mode 100644
index 0ab5ac9322..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tosca.nodes.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.zip b/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.zip
deleted file mode 100644
index 1de1fac68c..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import _multiple_tags/normative-types-new-import _multiple_tags.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/importResource4test.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/importResource4test.json
deleted file mode 100644
index c6a4b47903..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/importResource4test.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4test.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.yml
deleted file mode 100644
index bce6af3db4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.zip
deleted file mode 100644
index facd591e1d..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4test/normative-types-new-importResource4test.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/importResource4testCP.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/importResource4testCP.json
deleted file mode 100644
index 417d8a2854..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/importResource4testCP.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testCP.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "resourceType" : "VFC",
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.yml
deleted file mode 100644
index fb0cef1068..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.CP.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.zip
deleted file mode 100644
index 9efacc69eb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testCP/normative-types-new-importResource4testCP.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/importResource4testMissingNameSpace.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/importResource4testMissingNameSpace.json
deleted file mode 100644
index 3a14cfc1c8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/importResource4testMissingNameSpace.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testMissingNameSpace.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "resourceType" : "VFC",
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.yml
deleted file mode 100644
index 693ec75b51..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.vfc.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.zip
deleted file mode 100644
index 688fe84b5f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testMissingNameSpace/normative-types-new-importResource4testMissingNameSpace.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/importResource4testUnknown.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/importResource4testUnknown.json
deleted file mode 100644
index 3059d99eec..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/importResource4testUnknown.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testUnknown.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "resourceType" : "VFC",
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.yml
deleted file mode 100644
index 115a61a12b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.Unknown.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.zip
deleted file mode 100644
index 5e2b0ac582..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUnknown/normative-types-new-importResource4testUnknown.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/importResource4testUpdateVendorNameAndCategory.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/importResource4testUpdateVendorNameAndCategory.json
deleted file mode 100644
index 4e9affe462..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/importResource4testUpdateVendorNameAndCategory.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testUpdateVendorNameAndCategory.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Network L2-3",
- "subcategories": [{
- "name": "Router"
- }]
- }],
- "tags": ["importResource4test"],
- "vendorName": "ATT (Tosaaaaaaaaaaaaa)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.yml
deleted file mode 100644
index 69d88984ac..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.importResource4test:
- derived_from: tosca.nodes.Root
- description: update update
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.zip
deleted file mode 100644
index bf42a80ed9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateVendorNameAndCategory/normative-types-new-importResource4testUpdateVendorNameAndCategory.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/importResource4testUpdateWithoutReqCap.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/importResource4testUpdateWithoutReqCap.json
deleted file mode 100644
index f6ab834378..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/importResource4testUpdateWithoutReqCap.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testUpdateWithoutReqCap.yml",
- "contactId": "cs0004",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.Update",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test",
- "updatedTag"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.3.33"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.yml
deleted file mode 100644
index a580e8b7c6..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.zip
deleted file mode 100644
index 75622b7c25..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testUpdateWithoutReqCap/normative-types-new-importResource4testUpdateWithoutReqCap.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/importResource4testVF.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/importResource4testVF.json
deleted file mode 100644
index 6ebba43604..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/importResource4testVF.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testVF.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "resourceType" : "VFC",
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.yml
deleted file mode 100644
index 2879ab8cc8..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.vF.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.zip
deleted file mode 100644
index b6ccc062eb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVF/normative-types-new-importResource4testVF.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/importResource4testVFC.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/importResource4testVFC.json
deleted file mode 100644
index b5e2e329bd..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/importResource4testVFC.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testVFC.yml",
- "contactId": "jh0003",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "vendorName": "ATT (Tosca)",
- "resourceType" : "VFC",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.yml
deleted file mode 100644
index cdf347e872..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.VFC.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.zip
deleted file mode 100644
index 97daa8e401..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVFC/normative-types-new-importResource4testVFC.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/importResource4testVL.json b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/importResource4testVL.json
deleted file mode 100644
index 158530a3e5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/importResource4testVL.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "payloadName": "normative-types-new-importResource4testVL.yml",
- "contactId": "jh0003",
- "resourceType" : "VFC",
- "name": "importResource4test",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["importResource4test"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.yml b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.yml
deleted file mode 100644
index 55888da2bc..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.Vl.importResource4test:
- derived_from: tosca.nodes.Root
- description: The TOSCA Node Type all other TOSCA base Node Types derive from
- attributes:
- tosca_id:
- type: string
- tosca_name:
- type: string
- state:
- type: string
- capabilities:
- feature2:
- type: tosca.capabilities.Node
- requirements:
- - dependency2 :
- capability: tosca.capabilities.Node
- node: tosca.nodes.importResource4test
- relationship: tosca.relationships.DependsOn
- occurrences: [ 0, UNBOUNDED ]
- properties:
- root_password:
- type: string
- required: false
- description: the optional root password for the DBMS service
- port:
- type: integer
- required: false
- description: the port the DBMS service will listen to for data and requests
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.zip b/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.zip
deleted file mode 100644
index 5d3a7e6b50..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/importResource4testVL/normative-types-new-importResource4testVL.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.yml b/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.yml
deleted file mode 100644
index 72fe26e0d1..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.yml
+++ /dev/null
@@ -1,141 +0,0 @@
-tosca.capabilities.Root:
- description: The TOSCA root Capability Type all other TOSCA base Capability Types derive from
-tosca.capabilities.Node:
- derived_from: tosca.capabilities.Root
-tosca.capabilities.Container:
- derived_from: tosca.capabilities.Root
- properties:
- num_cpus:
- type: integer
- required: false
- constraints:
- - greater_or_equal: 1
- cpu_frequency:
- type: scalar-unit.frequency
- required: false
- constraints:
- - greater_or_equal: 0.1 GHz
- disk_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
- mem_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
-tosca.capabilities.Endpoint:
- derived_from: tosca.capabilities.Root
- properties:
- protocol:
- type: string
- default: tcp
- port:
- type: PortDef
- required: false
- secure:
- type: boolean
- default: false
- url_path:
- type: string
- required: false
- port_name:
- type: string
- required: false
- network_name:
- type: string
- required: false
- default: PRIVATE
- initiator:
- type: string
- default: source
- constraints:
- - valid_values: [ source, target, peer ]
- ports:
- type: map
- required: false
- constraints:
- - min_length: 1
- entry_schema:
- type: PortSpec
- attributes:
- ip_address:
- type: string
-tosca.capabilities.Endpoint.Public:
- derived_from: tosca.capabilities.Endpoint
- properties:
- # Change the default network_name to use the first public network found
- network_name: PUBLIC
- floating:
- description: >
- indicates that the public address should be allocated from a pool of floating IPs that are associated with the network.
- type: boolean
- default: false
- status: experimental
- dns_name:
- description: The optional name to register with DNS
- type: string
- required: false
- status: experimental
-tosca.capabilities.Endpoint.Admin:
- derived_from: tosca.capabilities.Endpoint
- # Change Endpoint secure indicator to true from its default of false
- properties:
- secure: true
-tosca.capabilities.Endpoint.Database:
- derived_from: tosca.capabilities.Endpoint
-tosca.capabilities.OperatingSystem:
- derived_from: tosca.capabilities.Root
- properties:
- architecture:
- type: string
- required: false
- type:
- type: string
- required: false
- distribution:
- type: string
- required: false
- version:
- type: version
- required: false
-tosca.capabilities.Scalable:
- derived_from: tosca.capabilities.Root
- properties:
- min_instances:
- type: integer
- default: 1
- max_instances:
- type: integer
- default: 1
- default_instances:
- type: integer
-tosca.capabilities.network.Bindable:
- derived_from: tosca.capabilities.Node
-
-
-tosca.capabilities.Container.Docker:
- derived_from: tosca.capabilities.Container
- properties:
- version:
- type: list
- required: false
- entry_schema: version
- publish_all:
- type: boolean
- default: false
- required: false
- publish_ports:
- type: list
- entry_schema: PortSpec
- required: false
- expose_ports:
- type: list
- entry_schema: PortSpec
- required: false
- volumes:
- type: list
- entry_schema: string
- required: false
-
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.zip b/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.zip
deleted file mode 100644
index 4f945a7d1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypes.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi.zip b/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi.zip
deleted file mode 100644
index 550cd756f4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_MissingDerivedFrom.yml b/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_MissingDerivedFrom.yml
deleted file mode 100644
index 31fac955e3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_MissingDerivedFrom.yml
+++ /dev/null
@@ -1,132 +0,0 @@
-tosca.capabilities.Root:
- description: The TOSCA root Capability Type all other TOSCA base Capability Types derive from
-tosca.capabilities.Node:
-tosca.capabilities.Container:
- properties:
- num_cpus:
- type: integer
- required: false
- constraints:
- - greater_or_equal: 1
- cpu_frequency:
- type: scalar-unit.frequency
- required: false
- constraints:
- - greater_or_equal: 0.1 GHz
- disk_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
- mem_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
-tosca.capabilities.Test.Ci:
-tosca.capabilities.Endpoint:
- properties:
- protocol:
- type: string
- default: tcp
- port:
- type: PortDef
- required: false
- secure:
- type: boolean
- default: false
- url_path:
- type: string
- required: false
- port_name:
- type: string
- required: false
- network_name:
- type: string
- required: false
- default: PRIVATE
- initiator:
- type: string
- default: source
- constraints:
- - valid_values: [ source, target, peer ]
- ports:
- type: map
- required: false
- constraints:
- - min_length: 1
- entry_schema:
- type: PortSpec
- attributes:
- ip_address:
- type: string
-tosca.capabilities.Endpoint.Public:
- properties:
- # Change the default network_name to use the first public network found
- network_name: PUBLIC
- floating:
- description: >
- indicates that the public address should be allocated from a pool of floating IPs that are associated with the network.
- type: boolean
- default: false
- status: experimental
- dns_name:
- description: The optional name to register with DNS
- type: string
- required: false
- status: experimental
-tosca.capabilities.Endpoint.Admin:
- # Change Endpoint secure indicator to true from its default of false
- properties:
- secure: true
-tosca.capabilities.Endpoint.Database:
-tosca.capabilities.OperatingSystem:
- properties:
- architecture:
- type: string
- required: false
- type:
- type: string
- required: false
- distribution:
- type: string
- required: false
- version:
- type: version
- required: false
-tosca.capabilities.Scalable:
- properties:
- min_instances:
- type: integer
- default: 1
- max_instances:
- type: integer
- default: 1
- default_instances:
- type: integer
-tosca.capabilities.network.Bindable:
-
-
-tosca.capabilities.Container.Docker:
- properties:
- version:
- type: list
- required: false
- entry_schema: version
- publish_all:
- type: boolean
- default: false
- required: false
- publish_ports:
- type: list
- entry_schema: PortSpec
- required: false
- expose_ports:
- type: list
- entry_schema: PortSpec
- required: false
- volumes:
- type: list
- entry_schema: string
- required: false
-
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_WithoutRoot.yml b/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_WithoutRoot.yml
deleted file mode 100644
index 12c7d5a977..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/import_capabilitiesTypes/capabilityTypesCi_WithoutRoot.yml
+++ /dev/null
@@ -1,141 +0,0 @@
-tosca.capabilities.Node:
- derived_from: tosca.capabilities.Root
-tosca.capabilities.Container:
- derived_from: tosca.capabilities.Root
- properties:
- num_cpus:
- type: integer
- required: false
- constraints:
- - greater_or_equal: 1
- cpu_frequency:
- type: scalar-unit.frequency
- required: false
- constraints:
- - greater_or_equal: 0.1 GHz
- disk_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
- mem_size:
- type: scalar-unit.size
- required: false
- constraints:
- - greater_or_equal: 0 MB
-tosca.capabilities.Test.Ci:
- derived_from: tosca.capabilities.Root
-tosca.capabilities.Endpoint:
- derived_from: tosca.capabilities.Root
- properties:
- protocol:
- type: string
- default: tcp
- port:
- type: PortDef
- required: false
- secure:
- type: boolean
- default: false
- url_path:
- type: string
- required: false
- port_name:
- type: string
- required: false
- network_name:
- type: string
- required: false
- default: PRIVATE
- initiator:
- type: string
- default: source
- constraints:
- - valid_values: [ source, target, peer ]
- ports:
- type: map
- required: false
- constraints:
- - min_length: 1
- entry_schema:
- type: PortSpec
- attributes:
- ip_address:
- type: string
-tosca.capabilities.Endpoint.Public:
- derived_from: tosca.capabilities.Endpoint
- properties:
- # Change the default network_name to use the first public network found
- network_name: PUBLIC
- floating:
- description: >
- indicates that the public address should be allocated from a pool of floating IPs that are associated with the network.
- type: boolean
- default: false
- status: experimental
- dns_name:
- description: The optional name to register with DNS
- type: string
- required: false
- status: experimental
-tosca.capabilities.Endpoint.Admin:
- derived_from: tosca.capabilities.Endpoint
- # Change Endpoint secure indicator to true from its default of false
- properties:
- secure: true
-tosca.capabilities.Endpoint.Database:
- derived_from: tosca.capabilities.Endpoint
-tosca.capabilities.OperatingSystem:
- derived_from: tosca.capabilities.Root
- properties:
- architecture:
- type: string
- required: false
- type:
- type: string
- required: false
- distribution:
- type: string
- required: false
- version:
- type: version
- required: false
-tosca.capabilities.Scalable:
- derived_from: tosca.capabilities.Root
- properties:
- min_instances:
- type: integer
- default: 1
- max_instances:
- type: integer
- default: 1
- default_instances:
- type: integer
-tosca.capabilities.network.Bindable:
- derived_from: tosca.capabilities.Node
-
-
-tosca.capabilities.Container.Docker:
- derived_from: tosca.capabilities.Container
- properties:
- version:
- type: list
- required: false
- entry_schema: version
- publish_all:
- type: boolean
- default: false
- required: false
- publish_ports:
- type: list
- entry_schema: PortSpec
- required: false
- expose_ports:
- type: list
- entry_schema: PortSpec
- required: false
- volumes:
- type: list
- entry_schema: string
- required: false
-
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/missing_category.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/missing_category.json
deleted file mode 100644
index 23a7d76103..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/missing_category.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_category.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.missing_category",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "tags": [
- "tosca.nodes.missing_category"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.zip
deleted file mode 100644
index 7a458426b4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_category/normative-types-new-missing_category.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/missing_contact.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/missing_contact.json
deleted file mode 100644
index 8f3e5ae2e2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/missing_contact.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_contact.yml",
- "name": "tosca.nodes.missing_contact",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.missing_contact"
- ],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.yml
deleted file mode 100644
index 3d9c111871..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_contact:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.zip
deleted file mode 100644
index d89b711cdb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_contact/normative-types-new-missing_contact.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/missing_derived_from.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/missing_derived_from.json
deleted file mode 100644
index 37a55bf17a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/missing_derived_from.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_derived_from.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.missing_derived_from",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["tosca.nodes.missing_derived_from"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.yml
deleted file mode 100644
index 82069ecb7b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-tosca.nodes.missing_userId:
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.zip
deleted file mode 100644
index 22e3d4da29..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_derived_from/normative-types-new-missing_derived_from.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/missing_desc.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/missing_desc.json
deleted file mode 100644
index bec3896cfd..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/missing_desc.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_desc.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.missing_desc",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["tosca.nodes.missing_desc"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.zip
deleted file mode 100644
index 6cdde04c67..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_desc/normative-types-new-missing_desc.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/missing_icon.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/missing_icon.json
deleted file mode 100644
index 9e9b7572bc..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/missing_icon.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_icon.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.missing_icon",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["tosca.nodes.missing_icon"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.zip
deleted file mode 100644
index 5a53c7b5bf..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_icon/normative-types-new-missing_icon.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/missing_payloadName.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/missing_payloadName.json
deleted file mode 100644
index 58df0f7400..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/missing_payloadName.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "contactId": "jh0003",
- "name": "tosca.nodes.missing_payloadName",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["tosca.nodes.missing_payloadName"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.zip
deleted file mode 100644
index 2de80ad97a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_payloadName/normative-types-new-missing_payloadName.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/missing_resource_name.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/missing_resource_name.json
deleted file mode 100644
index dbf7ef82f1..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/missing_resource_name.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_resource_name.yml",
- "contactId": "jh0003",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "category": "Generic/Infrastructure",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["missing_resource_name"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.zip
deleted file mode 100644
index b6ae3ba9ad..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_resource_name/normative-types-new-missing_resource_name.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/missing_tags.json b/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/missing_tags.json
deleted file mode 100644
index 36c845f001..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/missing_tags.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "payloadName": "normative-types-new-missing_tags.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.missing_tags",
- "description": "Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.yml b/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.yml
deleted file mode 100644
index bad0c73a1f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.missing_userId:
- derived_from: tosca.nodes.Root
- properties:
- size:
- type: scalar-unit.size
- constraints:
- - greater_or_equal: 1 MB
- volume_id:
- type: string
- required: false
- snapshot_id:
- type: string
- required: false
- capabilities:
- attachment:
- type: tosca.capabilities.Attachment
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.zip b/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.zip
deleted file mode 100644
index 0ad7b6ee05..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/missing_tags/normative-types-new-missing_tags.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/myCompute.json b/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/myCompute.json
deleted file mode 100644
index af216b7c21..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/myCompute.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "payloadName": "normative-types-new-myCompute.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.MyCompute",
- "description": "Represents a real or virtual machine or server. Information specified on the Compute
- node will be used to find the machine that fits the given requirements in the cloud
- available machines. If no sizing information are specified the cloud provider default
- machine will be used. It is strongly recommended to specify the required CPUs and memory
- at least.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.MyCompute"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.yml b/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.yml
deleted file mode 100644
index dff93f621a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- tosca.nodes.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/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.zip b/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.zip
deleted file mode 100644
index a4fb8979fc..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/myCompute/normative-types-new-myCompute.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.yml b/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.yml
deleted file mode 100644
index eccfd4ddc5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-tosca.nodes.network.PortInvalidDefaultValue:
- derived_from: tosca.nodes.Root
- properties:
- ip_address:
- type: string
- required: false
- order:
- type: integer
- required: true
- default: 1.5
- constraints:
- - greater_or_equal: 0
- is_default:
- type: boolean
- required: false
- default: false
- ip_range_start:
- type: string
- required: false
- ip_range_end:
- type: string
- required: false
- requirements:
- - link:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- - binding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.zip b/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.zip
deleted file mode 100644
index fed020cdd3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/normative-types-new-portInvalidDefaultValue.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/portInvalidDefaultValue.json b/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/portInvalidDefaultValue.json
deleted file mode 100644
index 6b6e064a30..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/portInvalidDefaultValue/portInvalidDefaultValue.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-portInvalidDefaultValue.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.network.PortInvalidDefaultValue",
- "description": "Represents a logical entity that associates between Compute and Network normative types.",
- "resourceIconPath": "port",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Network Elements"
- }]
- }],
- "tags": ["tosca.nodes.network.PortInvalidDefaultValue"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.yml b/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.yml
deleted file mode 100644
index de109820a9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.Compute:
- 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/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.zip b/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.zip
deleted file mode 100644
index 895d397728..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/normative-types-new-userCompute.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/userCompute.json b/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/userCompute.json
deleted file mode 100644
index ab10c0b523..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/userCompute/userCompute.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "payloadName": "normative-types-new-userCompute.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.userCompute",
- "description": "Represents a real or virtual machine or server. Information specified on the Compute
- node will be used to find the machine that fits the given requirements in the cloud
- available machines. If no sizing information are specified the cloud provider default
- machine will be used. It is strongly recommended to specify the required CPUs and memory
- at least.",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "tags": [
- "tosca.nodes.userCompute"
- ],
- "vendorName": "UserVendor",
- "vendorRelease": "1.1.1"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.yml b/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.yml
deleted file mode 100644
index 5c73365640..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.Compute:
- 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 \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.zip b/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.zip
deleted file mode 100644
index 25a0312031..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/normative-types-new-userUpdateCompute.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/userUpdateCompute.json b/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/userUpdateCompute.json
deleted file mode 100644
index 6e63c434fb..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/userUpdateCompute/userUpdateCompute.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "payloadName": "normative-types-new-userUpdateCompute.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.userCompute",
- "description": "Short description",
- "resourceIconPath": "defaulticon",
- "categories": [
- {
- "name": "Generic",
- "subcategories": [
- {
- "name": "Infrastructure"
- }
- ]
- }
-],
- "vendorName": "UpdatedVendor",
- "vendorRelease": "1.1.2",
- "tags": [
- "tosca.nodes.userCompute"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.yml
deleted file mode 100644
index af70663fbe..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.yml
+++ /dev/null
@@ -1,39 +0,0 @@
-validateProporties_happyScenarios:
- 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
- validation_test1:
- type: boolean
- required: false
- default: true
- validation_test2:
- type: boolean
- required: false
- default: false
- validation_test3:
- type: integer
- required: false
- default: 1234
- validation_test4:
- type: float
- required: false
- default: 123.123
- validation_test5:
- type: string
- required: false
- default: cooolString
- validation_test6:
- type: scalar-unit.size
- required: false
- default: cooolString
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.zip
deleted file mode 100644
index 4104dc3618..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/normative-types-new-validateProporties_happyScenarios.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/validateProporties_happyScenarios.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/validateProporties_happyScenarios.json
deleted file mode 100644
index 1235ba57e6..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_happyScenarios/validateProporties_happyScenarios.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_happyScenarios.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Infrastructure"
- }]
- }],
- "tags": ["tosca.nodes.SoftwareComponent"]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.yml
deleted file mode 100644
index 14778745ef..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeBoolean_valueInit:
- 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
- validation_test:
- type: boolean
- required: false
- default: 123456
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.zip
deleted file mode 100644
index 46dc70477b..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/normative-types-new-validateProporties_typeBoolean_valueInit.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/validateProporties_typeBoolean_valueInit.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/validateProporties_typeBoolean_valueInit.json
deleted file mode 100644
index c4f4b37911..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueInit/validateProporties_typeBoolean_valueInit.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeBoolean_valueInit.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["tosca.nodes.SoftwareComponent"]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.yml
deleted file mode 100644
index 4d529ad285..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeBoolean_valueString:
- 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
- validation_test:
- type: boolean
- required: false
- default: abcd
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.zip
deleted file mode 100644
index 5cc2e4f916..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/normative-types-new-validateProporties_typeBoolean_valueString.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/validateProporties_typeBoolean_valueString.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/validateProporties_typeBoolean_valueString.json
deleted file mode 100644
index f1ff279a84..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeBoolean_valueString/validateProporties_typeBoolean_valueString.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeBoolean_valueString.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["tosca.nodes.SoftwareComponent"]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.yml
deleted file mode 100644
index fee8c9b68e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeFloat_valueBoolean:
- 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
- validation_test:
- type: float
- required: false
- default: true
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.zip
deleted file mode 100644
index 9ac3bb72e4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/normative-types-new-validateProporties_typeFloat_valueBoolean.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/validateProporties_typeFloat_valueBoolean.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/validateProporties_typeFloat_valueBoolean.json
deleted file mode 100644
index f1769769d4..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueBoolean/validateProporties_typeFloat_valueBoolean.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeFloat_valueBoolean.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["tosca.nodes.SoftwareComponent"]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.yml
deleted file mode 100644
index 88e5bb85c3..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeFloat_valueString:
- 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
- validation_test:
- type: float
- required: false
- default: abcd
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.zip
deleted file mode 100644
index 88d67edc48..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/normative-types-new-validateProporties_typeFloat_valueString.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/validateProporties_typeFloat_valueString.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/validateProporties_typeFloat_valueString.json
deleted file mode 100644
index 3eab4bb311..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeFloat_valueString/validateProporties_typeFloat_valueString.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeFloat_valueString.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["tosca.nodes.SoftwareComponent"]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.yml
deleted file mode 100644
index 69bd3ba41e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeInit_valueBoolean:
- 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
- validation_test:
- type: integer
- required: false
- default: true
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.zip
deleted file mode 100644
index 04b32e1dee..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/normative-types-new-validateProporties_typeInit_valueBoolean.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/validateProporties_typeInit_valueBoolean.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/validateProporties_typeInit_valueBoolean.json
deleted file mode 100644
index bb145d2f28..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueBoolean/validateProporties_typeInit_valueBoolean.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeInit_valueBoolean.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": [
- "tosca.nodes.SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.yml
deleted file mode 100644
index 60ae3b6333..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeInit_valueFloat:
- 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
- validation_test:
- type: integer
- required: false
- default: 0.123
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.zip
deleted file mode 100644
index b224b70d40..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/normative-types-new-validateProporties_typeInit_valueFloat.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/validateProporties_typeInit_valueFloat.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/validateProporties_typeInit_valueFloat.json
deleted file mode 100644
index 2e7f5f232a..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueFloat/validateProporties_typeInit_valueFloat.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeInit_valueFloat.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": [
- "tosca.nodes.SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.yml
deleted file mode 100644
index 7bd723e915..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeInit_valueString:
- 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
- validation_test:
- type: integer
- required: false
- default: abcd
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.zip
deleted file mode 100644
index d7eb9f59b1..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/normative-types-new-validateProporties_typeInit_valueString.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/validateProporties_typeInit_valueString.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/validateProporties_typeInit_valueString.json
deleted file mode 100644
index 29e4b29be0..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeInit_valueString/validateProporties_typeInit_valueString.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeInit_valueString.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": [
- "tosca.nodes.SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.yml
deleted file mode 100644
index 217f3405e2..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.yml
+++ /dev/null
@@ -1,50 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeList_valueUrlCredential:
- 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
- validation_test:
- type: list
- required: false
- default:
- - protocol: protocol1~!#@~$%^*()[];:'"|\/
- token: token1
- - protocol: protocol2~!#@~$%^*()[];:'"|\/
- token: token2
- entry_schema:
- type: tosca.datatypes.Credential
- attributes:
- validation_test_list:
- type: list
- required: false
- default:
- - protocol: protocol1~!#@~$%^*()[];:'"|\/
- token: token1
- - protocol: protocol2~!#@~$%^*()[];:'"|\/
- token: token2
- entry_schema:
- type: tosca.datatypes.Credential
- validation_test_map:
- type: map
- required: false
- default:
- key1:
- protocol: protocol1~!#@~$%^*()[];:'"|\/
- token: token1
- key2:
- protocol: protocol2~!#@~$%^*()[];:'"|\/
- token: token2
- entry_schema:
- type: tosca.datatypes.Credential
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.zip
deleted file mode 100644
index 7fee84c8a5..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/normative-types-new-validateProporties_typeList_valueUrlCredential.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/validateProporties_typeList_valueUrlCredential.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/validateProporties_typeList_valueUrlCredential.json
deleted file mode 100644
index 59d6bbff21..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeList_valueUrlCredential/validateProporties_typeList_valueUrlCredential.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeList_valueUrlCredential.yml",
- "contactId": "jh0003",
- "name": "resourceListValueCredential",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["resourceListValueCredential"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.yml
deleted file mode 100644
index 2ce14b21a9..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_typeMap_valueUrlCredential:
- 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
- validation_test:
- type: map
- required: false
- default:
- key1:
- protocol: protocol1
- token: token1
- key2:
- protocol: protocol2
- token: token2
- entry_schema:
- type: tosca.datatypes.Credential
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.zip
deleted file mode 100644
index c7e65e7068..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/normative-types-new-validateProporties_typeMap_valueUrlCredential.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/validateProporties_typeMap_valueUrlCredential.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/validateProporties_typeMap_valueUrlCredential.json
deleted file mode 100644
index 3fb0bec243..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeMap_valueUrlCredential/validateProporties_typeMap_valueUrlCredential.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeMap_valueUrlCredential.yml",
- "contactId": "jh0003",
- "name": "resourceMapValueCredential",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["resourceMapValueCredential"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/normative-types-new-validateProporties_typeString_valueString_special_chars.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/normative-types-new-validateProporties_typeString_valueString_special_chars.yml
deleted file mode 100644
index cc109d1528..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/normative-types-new-validateProporties_typeString_valueString_special_chars.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-validateProporties_typeString_valueString_special_chars:
- 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
- validation_test:
- type: string
- required: false
- default: ~!#@~
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/validateProporties_typeString_valueString_special_chars.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/validateProporties_typeString_valueString_special_chars.json
deleted file mode 100644
index 90f66e800e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_special_chars/validateProporties_typeString_valueString_special_chars.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeString_valueString_special_chars.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": [
- "tosca.nodes.SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/normative-types-new-validateProporties_typeString_valueString_trimming.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/normative-types-new-validateProporties_typeString_valueString_trimming.yml
deleted file mode 100644
index 4ecd161682..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/normative-types-new-validateProporties_typeString_valueString_trimming.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-validateProporties_typeBoolean_valueInit:
- 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
- validation_test:
- type: boolean
- required: false
- default: true
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/validateProporties_typeString_valueString_trimming.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/validateProporties_typeString_valueString_trimming.json
deleted file mode 100644
index 34d9321b7e..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeString_valueString_trimming/validateProporties_typeString_valueString_trimming.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeBoolean_valueInit.yml",
- "contactId": "jh0003",
- "name": "tosca.nodes.SoftwareComponent",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": [
- "tosca.nodes.SoftwareComponent"
- ]
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.yml b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.yml
deleted file mode 100644
index feb13b367f..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeMap.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_0_0
-node_types:
- org.openecomp.resource.validateProporties_type:
- 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
- myprop:
- type: tosca.datatypes.network.PortInfoComplex
- default:
- addressesMap:
- key1:
- protocol: protocol1
- token: token1
- key2:
- protocol: protocol2
- token: token2
- addressesList:
- - protocol: protocol1~!#@~$%^*()[];:'"|\/
- token: token1
- - protocol: protocol2~!#@~$%^*()[];:'"|\/
- token: token2
- requirements:
- - host:
- capability: tosca.capabilities.Container
- node: tosca.nodes.Compute
- relationship: tosca.relationships.HostedOn
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeTestDataType.zip b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeTestDataType.zip
deleted file mode 100644
index 27ce7bc887..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/normative-types-new-validateProporties_typeTestDataType.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/validateProporties_typeTestDataType.json b/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/validateProporties_typeTestDataType.json
deleted file mode 100644
index b751545f11..0000000000
--- a/asdc-tests/src/test/resources/CI/importResourceTests/validateProporties_typeTestDataType/validateProporties_typeTestDataType.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "payloadName": "normative-types-new-validateProporties_typeMap.yml",
- "contactId": "jh0003",
- "name": "resourceMapValueTest",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
- "resourceIconPath": "defaulticon",
- "categories": [{
- "name": "Generic",
- "subcategories": [{
- "name": "Abstract"
- }]
- }],
- "tags": ["resourceMapValueTest"],
- "vendorName": "ATT (Tosca)",
- "vendorRelease": "1.0.0.wd03"
-} \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.yml b/asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.yml
deleted file mode 100644
index 120f33d5f1..0000000000
--- a/asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-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/asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.zip b/asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.zip
deleted file mode 100644
index 68b7aa9114..0000000000
--- a/asdc-tests/src/test/resources/CI/importTypesTest/categoryTypesTest.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml
deleted file mode 100644
index 484ed4dff6..0000000000
--- a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-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/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip
deleted file mode 100644
index 2619853f4b..0000000000
--- a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack1/myHeatStack1.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml
deleted file mode 100644
index 94fbb0451e..0000000000
--- a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-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/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip b/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip
deleted file mode 100644
index 7f43af70eb..0000000000
--- a/asdc-tests/src/test/resources/CI/importTypesTest/myHeatStack2/myHeatStack2.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/other/mapping.json b/asdc-tests/src/test/resources/CI/other/mapping.json
deleted file mode 100644
index 3310d776b9..0000000000
--- a/asdc-tests/src/test/resources/CI/other/mapping.json
+++ /dev/null
@@ -1,182 +0,0 @@
-{ "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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml
deleted file mode 100644
index 0415385bd0..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/addYangXmlArtifactToResource.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0"?>
-<data>
- <sports>
- <person>
- <name>Lionel Andres Messi</name>
- <birthday>1987-06-24T00:00:00-00:00</birthday>
- </person>
- <person>
- <name>Cristiano Ronaldo</name>
- <birthday>1985-02-05T00:00:00-00:00</birthday>
- </person>
- <team>
- <name>FC Barcelona</name>
- <player>
- <name>Lionel Andres Messi</name>
- <season>Champions League 2014-2015</season>
- <number>10</number>
- <scores>43</scores>
- </player>
- </team>
- <team>
- <name>Real Madrid</name>
- <player>
- <name>Cristiano Ronaldo</name>
- <season>Champions League 2014-2015</season>
- <number>7</number>
- <scores>48</scores>
- </player>
- </team>
- </sports>
-
-</data> \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.yaml
+++ /dev/null
@@ -1,787 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip
deleted file mode 100644
index c8a2726421..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat 0 2.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/asc_heat_net 0 2.yaml
+++ /dev/null
@@ -1,787 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env
deleted file mode 100644
index 6835485ca1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatEnvfile.env
+++ /dev/null
@@ -1,787 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml
deleted file mode 100644
index b70d5a4b0a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heatInvalidFormat.yaml
+++ /dev/null
@@ -1,9 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml
deleted file mode 100644
index a545569129..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/heat_mini.yaml
+++ /dev/null
@@ -1,13 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json
deleted file mode 100644
index 48a3e89deb..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidJson.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "glossary": {
- "title": "example glossary",
- "GlossDiv": {
- "title": "S",
- "GlossList": {
- "GlossEntry": {
- "ID": "SGML",
- "SortAs": "SGML",
- "GlossTerm": "Standard Generalized Markup Language",
- "Acronym": "SGML",
diff --git a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml
deleted file mode 100644
index 5c51039931..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYamlFormat.yaml
+++ /dev/null
@@ -1,787 +0,0 @@
- 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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml
deleted file mode 100644
index 8978e0d5ed..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/invalidYangXml.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
-
- <sports xmlns="http://example.com/example-sports">
- <person>
- <name>Lionel Andr�s Messi</name>
- <birthday>1987-06-24T00:00:00-00:00</birthday>
- </person>
- <person>
- <name>Cristiano Ronaldo</name>
- <birthday>1985-02-05T00:00:00-00:00</birthday>
- </person>
- <team>
- <name>FC Barcelona</name>
- <player>
- <name>Lionel Andr�s Messi</name>
- <season>Champions League 2014/2015</season>
- <number>10</number>
- <scores>43</scores>
- </player>
- </team>
- <team>
- <name>Real Madrid</name>
- <player>
- <name>Cristiano Ronaldo</name>
- <season>Champions League 2014/2015</season>
- <number>7</number>
- <scores>48</scores>
- </player>
- </team>
- </sports>
-
-
-
-</data>
-</data> \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json
deleted file mode 100644
index d5ca56d195..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/jsonArtifact.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "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/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt b/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt
deleted file mode 100644
index 5f8f77ca2c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/HeatDeploymentArtifacts/other.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-cmd1
-cmd2
-cmd3 \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml
deleted file mode 100644
index 10c46b7269..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/bluePrintSampleArtifact.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<test>
- dfsfsdfsdf
-</test> \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx
deleted file mode 100644
index c281f532f8..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/docSampleArtifact.docx
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf
deleted file mode 100644
index 9c478f6ce1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.emf
+++ /dev/null
@@ -1,2 +0,0 @@
-This is sample EMF file
-We currently not checking the file content. \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml
deleted file mode 100644
index 10c46b7269..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/emfSampleArtifact.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<test>
- dfsfsdfsdf
-</test> \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml
deleted file mode 100644
index 10c46b7269..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/eventSampleArtifact.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<test>
- dfsfsdfsdf
-</test> \ No newline at end of file
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json
deleted file mode 100644
index b749a9e89c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/jsonSampleArtifact.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "test": "This is test"
-}
diff --git a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml b/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml
deleted file mode 100644
index 10ccf71d51..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/ResourceInstanceArtifacts/toscaSampleArtifact.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml b/asdc-tests/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/addHeatArtifactToServiceAndSertify/asc_heat 0 2.yaml
+++ /dev/null
@@ -1,787 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip b/asdc-tests/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip
deleted file mode 100644
index 0951d5cef8..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/downloadResourceArtifactSuccess/org.openstack.Rally.zip
+++ /dev/null
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml b/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml
deleted file mode 100644
index 6aad589bdb..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDefault.yaml
+++ /dev/null
@@ -1,603 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml b/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml
deleted file mode 100644
index d51a20d77f..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingDesc.yaml
+++ /dev/null
@@ -1,603 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml b/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml
deleted file mode 100644
index 29527495f7..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithParamsMissingType.yaml
+++ /dev/null
@@ -1,603 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml b/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml
deleted file mode 100644
index 6835485ca1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatArtifactParameters/heatWithValidParams.yaml
+++ /dev/null
@@ -1,787 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_1.yaml b/asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_1.yaml
deleted file mode 100644
index 7d4a85c2b6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_1.yaml
+++ /dev/null
@@ -1,144 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_2.yaml b/asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_2.yaml
deleted file mode 100644
index 2c404f0721..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatEnv/artifact_2.yaml
+++ /dev/null
@@ -1,469 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/heatEnv/yuli.yaml b/asdc-tests/src/test/resources/CI/tests/heatEnv/yuli.yaml
deleted file mode 100644
index 7d4a85c2b6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/heatEnv/yuli.yaml
+++ /dev/null
@@ -1,144 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml
deleted file mode 100644
index 5117247373..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/BindingAsset.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml
deleted file mode 100644
index 8309df24b5..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml
deleted file mode 100644
index 478e742bc5..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPHasNoReqCap_DerivedFromMyCompute1.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml
deleted file mode 100644
index 807f7fe630..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CPWithAttributes.yml
+++ /dev/null
@@ -1,56 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml
deleted file mode 100644
index b9e6c4f9b5..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_1.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml
deleted file mode 100644
index 230e4fa924..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveCapTest_2.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml
deleted file mode 100644
index 0d097a8f20..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_1.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml
deleted file mode 100644
index 9cc1f2737b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/CaseInsensitiveReqTest_2.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml
deleted file mode 100644
index 3514acfe9f..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromCPWithOwnReq.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml
deleted file mode 100644
index 7fbf4ec132..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DerivedFromWebApplication_HasNoReqType.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml
deleted file mode 100644
index fe79bb3af9..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentCapFromRoot.yml
+++ /dev/null
@@ -1,26 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml
deleted file mode 100644
index 798cd5b9cd..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqAndCap.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml
deleted file mode 100644
index c72d0ee62a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute1.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml
deleted file mode 100644
index 7132ca493a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqCapFromCompute2.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml
deleted file mode 100644
index e9438bae3c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/DifferentReqFromCompute.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml
deleted file mode 100644
index 039ab61939..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/FatherHasNoReqCap.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml
deleted file mode 100644
index f20a9eb48f..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure01.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml
deleted file mode 100644
index f1af89ca6a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure02.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml
deleted file mode 100644
index 974d96ba5b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure03.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml
deleted file mode 100644
index 52377e4b02..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure04.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml
deleted file mode 100644
index c66b4347f6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure05.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml
deleted file mode 100644
index 79b3c03cdf..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure06.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml
deleted file mode 100644
index 5556e9ddfb..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure07.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml
deleted file mode 100644
index a3b21a64a3..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure08.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml
deleted file mode 100644
index dc28591499..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure09.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml
deleted file mode 100644
index e465448064..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure10.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml
deleted file mode 100644
index a428b51974..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure11.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml
deleted file mode 100644
index d840253120..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure12.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml
deleted file mode 100644
index 4eb59886e4..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure13.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml
deleted file mode 100644
index ad263f3d00..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure14.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml
deleted file mode 100644
index 93e8caa0a3..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure15.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml
deleted file mode 100644
index ed8ea4d70c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/ListPropertyFalure16.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml
deleted file mode 100644
index c7ff0743f2..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure01.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml
deleted file mode 100644
index d9abb87db8..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure02.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml
deleted file mode 100644
index e8f9b6eaa9..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure03.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml
deleted file mode 100644
index d9dc4f955b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure04.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml
deleted file mode 100644
index aba6ff1992..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure05.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml
deleted file mode 100644
index f27904d6e6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure06.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml
deleted file mode 100644
index ea123f3b1b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure07.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml
deleted file mode 100644
index 87b51fb2de..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure08.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml
deleted file mode 100644
index 2fc8ded544..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure09.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml
deleted file mode 100644
index 3ab449d72e..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure10.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml
deleted file mode 100644
index e437de822e..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure11.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml
deleted file mode 100644
index f2fbc7c435..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure12.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml
deleted file mode 100644
index e375aae197..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure13.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml
deleted file mode 100644
index e087212f1b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure14.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml
deleted file mode 100644
index 3923ee18d7..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure15.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml
deleted file mode 100644
index ed8ea4d70c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MapPropertyFalure16.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml
deleted file mode 100644
index dfc564b458..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/MyFatherCompute_NoReqCap.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml
deleted file mode 100644
index 533333ee09..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameCapAsCompute.yml
+++ /dev/null
@@ -1,26 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml
deleted file mode 100644
index 9d8b2d8375..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml
deleted file mode 100644
index a5413e516f..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/SameReqAsCompute_DerivedFromMyCompute1.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml
deleted file mode 100644
index 9cea0b9dc8..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap11.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml
deleted file mode 100644
index 24efc27711..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/computeCap1UNBOUNDED.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml
deleted file mode 100644
index 237bec1f0c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromMyCompute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml
deleted file mode 100644
index 0679bff4b1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/derivedFromWebAppDerivedReqCap.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml
deleted file mode 100644
index 0fa9a302f2..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importAttributeSuccessFlow.yml
+++ /dev/null
@@ -1,53 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml
deleted file mode 100644
index 4d6db6c8c0..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importCapabilityNameExistsOnParent.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml
deleted file mode 100644
index fcc3952f94..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateCapability.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml
deleted file mode 100644
index 7cab3ac590..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importDuplicateRequirements.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml
deleted file mode 100644
index a3ff088a35..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyBadDefault.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml
deleted file mode 100644
index 2f864a727e..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertyGoodDefault.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml
deleted file mode 100644
index fd52df5f9b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importListPropertySuccessFlow.yml
+++ /dev/null
@@ -1,198 +0,0 @@
-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:
- - <b>asdc<b>
- - $?^@ecomp$!#%()_-~@+*^...;;/w#
- - uc
- entry_schema:
- description: This is my property
- type: string
- my_string_array:
- type: list
- description : another description
- default: [ <b>AAA</b>, ~$~#bbb%^*_-, qwe , 1.3 , <b>500</b> , true ]
- entry_schema:
- description: This is my property
- type: string
- string_null_value:
- type: list
- description : another description
- default:
- - <b>asdc<b>
- -
- - uc
- entry_schema:
- description: This is my property
- type: string
- string_space_value:
- type: list
- description : another description
- default:
- - <b> asdc<b>
- -
- - 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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml
deleted file mode 100644
index f856603397..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importMapPropertySuccessFlow.yml
+++ /dev/null
@@ -1,452 +0,0 @@
-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 : <b>true</b> }
- 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 : <b>AbcD</b>
- entry_schema:
- description: This is my property
- type: string
- string_prop19:
- type: map
- description : another description
- default:
- keyA : <b>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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml
deleted file mode 100644
index e4d626fca6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml
deleted file mode 100644
index 7ae9552d6a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/loadBalancerTestVersion.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/loadBalancerTestVersion.yml
deleted file mode 100644
index 6b68dd00d4..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/loadBalancerTestVersion.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-tosca_definitions_version: tosca_simple_yaml_1_1_0
-node_types:
- org.openecomp.resource.vfc.nodes.LoadBalancerTest1:
- derived_from: tosca.nodes.Root
- properties:
-
diff --git a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml
deleted file mode 100644
index 301116c985..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInCapDefinition.yml
+++ /dev/null
@@ -1,37 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml
deleted file mode 100644
index d100dafdf9..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/missingCapInReqDefinition.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml
deleted file mode 100644
index cc5b202bc7..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildCompute_NoReqCap.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml
deleted file mode 100644
index b7859d4c14..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myChildWebApp_DerivedFromContainer.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml
deleted file mode 100644
index 98bf9b7902..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myCompute.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml
deleted file mode 100644
index 2b2807395a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeDerivedFromNotExists.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml
deleted file mode 100644
index 2fa3ad0c08..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectDefenitionVersionValue.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml
deleted file mode 100644
index d1a613fff2..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeIncorrectNameSpaceFormat.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml
deleted file mode 100644
index 8084d049db..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeNoDefenitionVersion.yml
+++ /dev/null
@@ -1,34 +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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml
deleted file mode 100644
index 40ae610c06..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeOccurencySuccess.yml
+++ /dev/null
@@ -1,77 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml
deleted file mode 100644
index b243add14a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeParssingFalure.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml
deleted file mode 100644
index 43d92d1681..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeReqNameExistsOnDerived.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml
deleted file mode 100644
index 90e771dab1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeVF.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml
deleted file mode 100644
index 73b201eab4..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithNodeTypesTwice.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml
deleted file mode 100644
index c451eb2514..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myComputeWithTopologyTemplate.yml
+++ /dev/null
@@ -1,44 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml
deleted file mode 100644
index 43a9a174f8..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myFatherWebApp_derviedFromDocker.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml
deleted file mode 100644
index 7c796d2801..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myLinkVL.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml
deleted file mode 100644
index ff255f2394..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/myPortCP.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml
deleted file mode 100644
index f007a0fed2..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure01.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml
deleted file mode 100644
index 0487b63cb3..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure02.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml
deleted file mode 100644
index 7afdffa59d..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure03.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml
deleted file mode 100644
index f8a582f401..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure04.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml
deleted file mode 100644
index f1c6a93e1f..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure05.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml
deleted file mode 100644
index b0ef54b0eb..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure06.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml
deleted file mode 100644
index afd999f575..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure07.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml
deleted file mode 100644
index 60efc99273..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure08.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml
deleted file mode 100644
index d6ec7eabe6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure09.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml
deleted file mode 100644
index 27de429186..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure10.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml
deleted file mode 100644
index 5bdae3a5f5..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure11.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml
deleted file mode 100644
index 8c3034afce..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure31.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml
deleted file mode 100644
index 4b5eba9110..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure32.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml
deleted file mode 100644
index 9c42e22aa1..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure33.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml
deleted file mode 100644
index 49953b5834..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure34.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml
deleted file mode 100644
index 8d8985d7f7..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure35.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml
deleted file mode 100644
index 12944507f6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure36.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml
deleted file mode 100644
index 618c980e16..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure37.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml
deleted file mode 100644
index d0c4575c83..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure38.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml
deleted file mode 100644
index 024338d380..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure39.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml
deleted file mode 100644
index a4a32ba772..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure40.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml
deleted file mode 100644
index c3024a3ee4..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/occurencyFalure41.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml
deleted file mode 100644
index b9bda183e6..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq11.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml b/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml
deleted file mode 100644
index 9676bcdb6c..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/softwareComponentReq12.yml
+++ /dev/null
@@ -1,17 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/testCsarAPI/topology.txt b/asdc-tests/src/test/resources/CI/tests/testCsarAPI/topology.txt
deleted file mode 100644
index f46af26605..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/testCsarAPI/topology.txt
+++ /dev/null
@@ -1 +0,0 @@
-{"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/asdc-tests/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt b/asdc-tests/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt
deleted file mode 100644
index f3fdf0297b..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/testCsarAPI/topologyTemplate.txt
+++ /dev/null
@@ -1 +0,0 @@
-{"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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml
deleted file mode 100644
index b6faadd4f9..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool10_false.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml
deleted file mode 100644
index 7fb2923b04..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool11_false.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml
deleted file mode 100644
index fd451aa3af..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool12_false.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml
deleted file mode 100644
index a253e4c8d7..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool1_true.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml
deleted file mode 100644
index ce273b3522..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool2_true.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml
deleted file mode 100644
index 4680eb6996..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool3_true.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml
deleted file mode 100644
index 1ed7781831..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool4_true.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml
deleted file mode 100644
index c0b42e6288..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool5_true.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml
deleted file mode 100644
index 24b862b751..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool6_true.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml
deleted file mode 100644
index 7bad8efd6f..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool7_false.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml
deleted file mode 100644
index 8b35e2adf7..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool8_false.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml
deleted file mode 100644
index 2768e0d480..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_bool9_false.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml
deleted file mode 100644
index fc7f84ca81..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number1.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml b/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml
deleted file mode 100644
index 28ec3358be..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/tmp/positive_artifact_number2.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml b/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml
deleted file mode 100644
index 764b8d4c58..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/artifact_unsupported.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml b/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml
deleted file mode 100644
index 19119f3d9a..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool1.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml b/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml
deleted file mode 100644
index f9c09a4fed..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_bool2.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml b/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml
deleted file mode 100644
index 9a489879cc..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number1.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml b/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml
deleted file mode 100644
index 4c0e07affc..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_number2.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml b/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml
deleted file mode 100644
index f52ef04712..0000000000
--- a/asdc-tests/src/test/resources/CI/tests/yamlFieldsValidation/negative_artifact_string1.yaml
+++ /dev/null
@@ -1,140 +0,0 @@
-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/asdc-tests/src/test/resources/config.json b/asdc-tests/src/test/resources/config.json
deleted file mode 100644
index 71c9d35e59..0000000000
--- a/asdc-tests/src/test/resources/config.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
-
-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/asdc-tests/testng.xml b/asdc-tests/testng.xml
deleted file mode 100644
index 8a47ef6d62..0000000000
--- a/asdc-tests/testng.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Suite" >
- <listeners>
- <listener class-name="org.openecomp.sdc.ci.tests.run.ExtentReporterNG" />
- </listeners>
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.category.CategoriesTests"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- Suite -->
-
-
-
diff --git a/asdc-tests/testngLifeCycle.xml b/asdc-tests/testngLifeCycle.xml
deleted file mode 100644
index aa390dc213..0000000000
--- a/asdc-tests/testngLifeCycle.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="lifeCycle" parallel="none">
- <test name="Test">
- <classes>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_cerificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceResourceLCSTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_UndoCheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_UndoCheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_StartCertificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_CheckinCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_CheckOutCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceCertWithResourceInstances"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CrossCheckOutTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CertifyVFWithNotCertRIs"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_request4CerCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CleanupIntermediateReources"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_CheckOutCIT"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_cerificationCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.CertifyServiceWithNotCertRI"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCS_CheckInCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_request4CerCITest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.lifecycle.ServiceLCS_StartCertificationCITest"/>
- </classes>
- </test> <!-- Test -->
-</suite> <!-- lifeCycle -->
diff --git a/asdctool/pom.xml b/asdctool/pom.xml
index 1950a3b048..740f8f44b4 100644
--- a/asdctool/pom.xml
+++ b/asdctool/pom.xml
@@ -77,6 +77,20 @@
<groupId>org.openecomp.sdc.common</groupId>
<artifactId>openecomp-common-lib</artifactId>
</exclusion>
+
+ <exclusion>
+ <groupId>com.att.nsa</groupId>
+ <artifactId>cambriaClient</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.att.nsa</groupId>
+ <artifactId>dmaapClient</artifactId>
+ </exclusion>
+ <exclusion>
+ <artifactId>slf4j-log4j12</artifactId>
+ <groupId>org.slf4j</groupId>
+ </exclusion>
+
</exclusions>
<scope>compile</scope>
@@ -92,7 +106,10 @@
<groupId>com.att.nsa</groupId>
<artifactId>cambriaClient</artifactId>
</exclusion>
-
+ <exclusion>
+ <groupId>com.att.nsa</groupId>
+ <artifactId>dmaapClient</artifactId>
+ </exclusion>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
@@ -476,6 +493,15 @@
</dependency>
<!-- CASSANDRA END -->
+
+ <!-- OPEN CSV -->
+ <dependency>
+ <groupId>com.opencsv</groupId>
+ <artifactId>opencsv</artifactId>
+ <version>4.0</version>
+ <scope>compile</scope>
+ </dependency>
+
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>com.springsource.org.apache.poi</artifactId>
@@ -517,7 +543,6 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<!-- testing end -->
@@ -556,12 +581,11 @@
</executions>
</plugin>
-
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
- <executions>
+ <executions>
<execution>
<phase>package</phase>
<goals>
@@ -753,7 +777,7 @@
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
- <version>0.23.0</version>
+ <version>${fabric8.version}</version>
<configuration>
<verbose>true</verbose>
diff --git a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
index e16cb1a8e8..75a5d756c3 100644
--- a/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
+++ b/asdctool/sdc-cassandra-init/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
@@ -107,6 +107,7 @@ elasticSearch:
creationPeriod: month
- indexPrefix: monitoring_events
creationPeriod: month
+
artifactTypes:
- CHEF
- PUPPET
@@ -143,13 +144,25 @@ resourceTypes: &allResourceTypes
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
# - VF
# - VL
deploymentResourceArtifacts:
-
+# heat:
+# displayName: "Base HEAT Template"
+# type: HEAT
+# validForResourceTypes: *allResourceTypes
+# heatVol:
+# displayName: "Volume HEAT Template"
+# type: HEAT_VOL
+# validForResourceTypes: *allResourceTypes
+# heatNet:
+# displayName: "Network HEAT Template"
+# type: HEAT_NET
+# validForResourceTypes: *allResourceTypes
deploymentResourceInstanceArtifacts:
heatEnv:
@@ -179,6 +192,8 @@ toscaArtifacts:
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
@@ -265,13 +280,13 @@ serviceApiArtifacts:
displayName: Testing
type: OTHER
-
additionalInformationMaxNumberOfKeys: 50
systemMonitoring:
enabled: true
isProxy: false
probeIntervalInSeconds: 15
+
defaultHeatArtifactTimeoutMinutes: 60
serviceDeploymentArtifacts:
@@ -287,6 +302,11 @@ serviceDeploymentArtifacts:
MODEL_QUERY_SPEC:
acceptedTypes:
- xml
+ UCPE_LAYER_2_CONFIGURATION:
+ acceptedTypes:
+ - xml
+
+#AAI Artifacts
AAI_SERVICE_MODEL:
acceptedTypes:
- xml
@@ -299,7 +319,6 @@ serviceDeploymentArtifacts:
OTHER:
acceptedTypes:
-
resourceDeploymentArtifacts:
HEAT:
acceptedTypes:
@@ -484,7 +503,15 @@ resourceInformationalArtifacts:
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
@@ -496,10 +523,10 @@ resourceInformationalArtifacts:
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
-
requirementsToFulfillBeforeCert:
capabilitiesToConsumeBeforeCert:
@@ -587,7 +614,9 @@ vfModuleProperties:
genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
+ CVFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
+ PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
workloadContext: Production
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLITool.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLITool.java
new file mode 100644
index 0000000000..053596d229
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLITool.java
@@ -0,0 +1,56 @@
+package org.openecomp.sdc.asdctool.cli;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * abstract base class to extend when implementing a cli tool
+ */
+public abstract class CLITool {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(CLITool.class);
+
+ public CLIToolData init(String[] args) {
+ CommandLine commandLine = initCmdLineOptions(args);
+ return new CLIToolData(commandLine);
+ }
+
+ private CommandLine initCmdLineOptions(String[] args) {
+ Options options = buildCmdLineOptions();
+ CommandLineParser parser = new DefaultParser();
+ try {
+ return parser.parse( options, args );
+ }
+ catch( ParseException exp ) {
+ LOGGER.error("Parsing failed. Reason: " + exp.getMessage() );
+ usageAndExit(options);
+ return null;
+ }
+ }
+
+ private void usageAndExit(Options options) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp(commandName(), options );
+ System.exit(1);
+ }
+
+ /**
+ *
+ * @return all command line options required by this command line tool
+ */
+ protected abstract Options buildCmdLineOptions();
+
+ /**
+ *
+ * @return the command name
+ */
+ protected abstract String commandName();
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIToolData.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIToolData.java
new file mode 100644
index 0000000000..2811905029
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIToolData.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.asdctool.cli;
+
+import org.apache.commons.cli.CommandLine;
+import org.springframework.context.support.AbstractApplicationContext;
+
+public class CLIToolData {
+
+ private CommandLine commandLine;
+ private AbstractApplicationContext springApplicationContext;
+
+ public CLIToolData(CommandLine commandLine) {
+ this.commandLine = commandLine;
+ }
+
+ public CLIToolData(CommandLine commandLine, AbstractApplicationContext springApplicationContext) {
+ this.commandLine = commandLine;
+ this.springApplicationContext = springApplicationContext;
+ }
+
+ public CommandLine getCommandLine() {
+ return commandLine;
+ }
+
+ public AbstractApplicationContext getSpringApplicationContext() {
+ return springApplicationContext;
+ }
+
+ public void setSpringApplicationContext(AbstractApplicationContext springApplicationContext) {
+ this.springApplicationContext = springApplicationContext;
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIUtils.java
new file mode 100644
index 0000000000..b5f7ae0900
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/CLIUtils.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.asdctool.cli;
+
+import org.apache.commons.cli.Option;
+
+public class CLIUtils {
+
+ static final String CONFIG_PATH_SHORT_OPT = "c";
+ private static final String CONFIG_PATH_LONG_OPT = "configFolderPath";
+
+ private CLIUtils(){}
+
+ public static Option getConfigurationPathOption() {
+ return Option.builder(CONFIG_PATH_SHORT_OPT)
+ .longOpt(CONFIG_PATH_LONG_OPT)
+ .required()
+ .hasArg()
+ .desc("path to sdc configuration folder - required")
+ .build();
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/SpringCLITool.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/SpringCLITool.java
new file mode 100644
index 0000000000..a672c2af67
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/cli/SpringCLITool.java
@@ -0,0 +1,32 @@
+package org.openecomp.sdc.asdctool.cli;
+
+import org.apache.commons.cli.Options;
+import org.openecomp.sdc.asdctool.configuration.ConfigurationUploader;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+/**
+ * abstract class to extend when implementing a spring and sdc configuration based command line tool
+ */
+public abstract class SpringCLITool extends CLITool {
+
+ @Override
+ public CLIToolData init(String[] args) {
+ CLIToolData cliToolData = super.init(args);
+ String appConfigDir = cliToolData.getCommandLine().getOptionValue(CLIUtils.CONFIG_PATH_SHORT_OPT);
+ ConfigurationUploader.uploadConfigurationFiles(appConfigDir);
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(getSpringConfigurationClass());
+ cliToolData.setSpringApplicationContext(context);
+ return cliToolData;
+ }
+
+ @Override
+ protected Options buildCmdLineOptions() {
+ return new Options().addOption(CLIUtils.getConfigurationPathOption());
+ }
+
+ /**
+ *
+ * @return the {@code Class} which holds all the spring bean declaration needed by this cli tool
+ */
+ protected abstract Class<?> getSpringConfigurationClass();
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ArtifactUUIDFixConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ArtifactUUIDFixConfiguration.java
index f14196681e..a7620b1272 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ArtifactUUIDFixConfiguration.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ArtifactUUIDFixConfiguration.java
@@ -1,54 +1,11 @@
package org.openecomp.sdc.asdctool.configuration;
+
import org.openecomp.sdc.asdctool.impl.ArtifactUuidFix;
-import org.openecomp.sdc.be.auditing.impl.AuditingManager;
-import org.openecomp.sdc.be.components.ArtifactsResolver;
-import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
-import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactResolverImpl;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.CompositionBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
-import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic;
-import org.openecomp.sdc.be.components.merge.input.InputsValuesMergingBusinessLogic;
-import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
-import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
-import org.openecomp.sdc.be.dao.DAOTitanStrategy;
-import org.openecomp.sdc.be.dao.TitanClientStrategy;
-import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
-import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.config.CatalogModelSpringConfig;
import org.openecomp.sdc.be.dao.config.DAOSpringConfig;
-import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
-import org.openecomp.sdc.be.dao.impl.AuditingDao;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.cache.ComponentCache;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-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.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.PropertyOperation;
-import org.openecomp.sdc.be.tosca.CsarUtils;
-import org.openecomp.sdc.be.tosca.ToscaExportHandler;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.springframework.beans.factory.annotation.Qualifier;
+import org.openecomp.sdc.config.CatalogBESpringConfig;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@@ -57,17 +14,10 @@ import org.springframework.context.annotation.Import;
import org.springframework.core.io.FileSystemResource;
@Configuration
-@Import(DAOSpringConfig.class)
-@ComponentScan({
- "org.openecomp.sdc.be.model.operations.impl",
- "org.openecomp.sdc.be.model.cache",
- "org.openecomp.sdc.be.dao.titan",
- "org.openecomp.sdc.be.dao.cassandra",
- "org.openecomp.sdc.be.model.jsontitan.operations",
- "org.openecomp.sdc.be.dao.jsongraph",
- "org.openecomp.sdc.be.tosca",
- "org.openecomp.sdc.be.components.merge",
- })
+@Import({DAOSpringConfig.class, CatalogBESpringConfig.class, CatalogModelSpringConfig.class})
+@ComponentScan({"org.openecomp.sdc.asdctool.migration.tasks",//migration tasks
+ "org.openecomp.sdc.asdctool.migration.config.mocks"
+ })
public class ArtifactUUIDFixConfiguration {
@Bean
@@ -75,246 +25,11 @@ public class ArtifactUUIDFixConfiguration {
return new ArtifactUuidFix();
}
- @Bean(name = "cassandra-client")
- public CassandraClient cassandraClient() {
- return new CassandraClient();
- }
-
-
- @Bean(name = "dao-titan-strategy")
- public TitanClientStrategy daoStrategy() {
- return new DAOTitanStrategy();
- }
-
- @Bean(name = "titan-dao")
- public TitanDao titanDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) {
- return new TitanDao(titanGraphClient);
- }
-
- @Bean(name = "titan-client", initMethod = "createGraph")
- public TitanGraphClient titanClient(@Qualifier("dao-titan-strategy") TitanClientStrategy titanClientStrategy) {
- return new TitanGraphClient(titanClientStrategy);
- }
-
- @Bean(name = "resource-business-logic")
- public ResourceBusinessLogic resourceBusinessLogic() {
- return new ResourceBusinessLogic();
- }
-
-// @Bean(name = "healthCheckBusinessLogic")
-// public HealthCheckBusinessLogic healthCheckBusinessLogic() {
-// return new HealthCheckBusinessLogic();
-// }
-//
-// @Bean(name = "distribution-engine-cluster-health")
-// public DistributionEngineClusterHealth distributionEngineClusterHealth() {
-// return new DistributionEngineClusterHealth();
-// }
-//
-// @Bean(name = "cassandra-health-check")
-// public CassandraHealthCheck cassandraHealthCheck() {
-// return new CassandraHealthCheck();
-// }
-
-// @Bean(name = "switchover-detector")
-// public SwitchoverDetector switchoverDetector() {
-// return new SwitchoverDetector();
-// }
-
- @Bean(name = "service-business-logic")
- public ServiceBusinessLogic serviceBusinessLogic() {
- return new ServiceBusinessLogic();
- }
-
- @Bean(name = "capability-type-operation")
- public CapabilityTypeOperation CapabilityTypeOperation() {
- return new CapabilityTypeOperation();
- }
-
- @Bean(name = "lifecycle-business-logic")
- public LifecycleBusinessLogic lifecycleBusinessLogic() {
- return new LifecycleBusinessLogic();
- }
-
- @Bean(name = "property-operation")
- public PropertyOperation propertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new PropertyOperation(titanGenericDao);
- }
-
- @Bean(name = "csar-operation")
- public CsarOperation csarOperation() {
- return new CsarOperation();
- }
-
- @Bean(name = "vf-component-instance-business-logic")
- public VFComponentInstanceBusinessLogic vFComponentInstanceBusinessLogic() {
- return new VFComponentInstanceBusinessLogic();
- }
-
- @Bean(name = "resource-import-manager")
- public ResourceImportManager resourceImportManager() {
- return new ResourceImportManager();
- }
-
- @Bean(name = "group-business-logic")
- public GroupBusinessLogic groupBusinessLogic() {
- return new GroupBusinessLogic();
- }
-
- @Bean(name = "inputs-business-logic")
- public InputsBusinessLogic inputsBusinessLogic() {
- return new InputsBusinessLogic();
- }
-
- @Bean(name = "composition-business-logic")
- public CompositionBusinessLogic compositionBusinessLogic() {
- return new CompositionBusinessLogic();
- }
-
- @Bean(name = "artifacts-business-logic")
- public ArtifactsBusinessLogic artifactsBusinessLogic() {
- return new ArtifactsBusinessLogic();
- }
-
- @Bean(name = "component-cache")
- public ComponentCache componentCache() {
- return new ComponentCache();
- }
-
- @Bean(name = "componentUtils")
- public ComponentsUtils componentsUtils() {
- return new ComponentsUtils();
- }
-
- @Bean(name = "user-business-logic")
- public UserBusinessLogic userBusinessLogic() {
- return new UserBusinessLogic();
- }
-
- @Bean(name = "graph-lock-operation")
- public GraphLockOperation graphLockOperation() {
- return new GraphLockOperation();
- }
-
- @Bean(name = "titan-generic-dao")
- public TitanGenericDao titanGenericDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) {
- return new TitanGenericDao(titanGraphClient);
- }
-
- @Bean(name = "element-operation")
- public ElementOperation elementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new ElementOperation(titanGenericDao);
- }
-
- @Bean(name = "group-operation")
- public GroupOperation groupOperation() {
- return new GroupOperation();
- }
-
- @Bean(name = "group-instance-operation")
- public GroupInstanceOperation groupInstanceOperation() {
- return new GroupInstanceOperation();
- }
-
- @Bean(name = "group-type-operation")
- public GroupTypeOperation groupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation") PropertyOperation propertyOperation) {
- return new GroupTypeOperation(titanGenericDao, propertyOperation);
- }
-
- @Bean(name = "tosca-operation-facade")
- public ToscaOperationFacade toscaOperationFacade() {
- return new ToscaOperationFacade();
- }
-
- @Bean(name = "distribution-engine")
- public DistributionEngine distributionEngine() {
- return null;
- }
-
- @Bean(name = "audit-cassandra-dao")
- public AuditCassandraDao auditCassandraDao() {
- return new AuditCassandraDao();
- }
- @Bean(name = "service-component-instance-business-logic")
- public ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic() {
- return new ServiceComponentInstanceBusinessLogic();
- }
-
- @Bean("tosca-export-handler")
- public ToscaExportHandler toscaExportHandler() {
- return new ToscaExportHandler();
- }
-
- @Bean(name = "component-instance-operation")
- public ComponentInstanceOperation componentInstanceOperation() {
- return new ComponentInstanceOperation();
- }
-
- @Bean(name = "additional-information-business-logic")
- public AdditionalInformationBusinessLogic additionalInformationBusinessLogic() {
- return new AdditionalInformationBusinessLogic();
- }
-
- @Bean(name = "auditing-manager")
- public AuditingManager auditingManager() {
- return new AuditingManager();
- }
-
- @Bean(name = "auditing-dao")
- public AuditingDao auditingDao() {
- return new AuditingDao();
- }
-
- @Bean(name = "elasticsearch-client", initMethod = "initialize")
- public ElasticSearchClient elasticSearchClient() {
- return new ElasticSearchClient();
- }
-
- @Bean(name = "csar-utils")
- public CsarUtils csarUtils() {
- return new CsarUtils();
- }
-
- @Bean(name = "service-distribution-artifacts-builder")
+ @Bean(name = "serviceDistributionArtifactsBuilder")
public ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder() {
return new ServiceDistributionArtifactsBuilder();
}
-
- @Bean(name = "product-business-logic")
- public ProductBusinessLogic productBusinessLogic() {
- return null;
- }
-
- @Bean(name = "dataDefinitionsValuesMergingBusinessLogic")
- public DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic() {
- return new DataDefinitionsValuesMergingBusinessLogic();
- }
-
- @Bean(name = "artifacts-resolver")
- public ArtifactsResolver artifactsResolver() {
- return new ArtifactResolverImpl();
- }
-
- @Bean(name = "InputsValuesMergingBusinessLogic")
- public InputsValuesMergingBusinessLogic InputsValuesMergingBusinessLogic(){
- return new InputsValuesMergingBusinessLogic();
- }
-
- @Bean(name = "GenericTypeBusinessLogic")
- public GenericTypeBusinessLogic genericTypeBusinessLogic(){
- return new GenericTypeBusinessLogic();
- }
-
- @Bean(name ="componentInstanceMergeDataBusinessLogic")
- public ComponentInstanceMergeDataBusinessLogic componentInstanceMergeDataBusinessLogic(){
- return new ComponentInstanceMergeDataBusinessLogic();
- }
-
- @Bean(name ="heatEnvArtifactsMergeBusinessLogic")
- public HeatEnvArtifactsMergeBusinessLogic heatEnvArtifactsMergeBusinessLogic(){
- return new HeatEnvArtifactsMergeBusinessLogic();
- }
@Bean(name = "elasticsearchConfig")
public PropertiesFactoryBean mapper() {
@@ -324,4 +39,5 @@ public class ArtifactUUIDFixConfiguration {
return bean;
}
+
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ConfigurationUploader.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ConfigurationUploader.java
index 267f20904c..ac75dc8310 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ConfigurationUploader.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/ConfigurationUploader.java
@@ -1,12 +1,12 @@
package org.openecomp.sdc.asdctool.configuration;
-import java.io.File;
-
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import java.io.File;
+
public class ConfigurationUploader {
public static void uploadConfigurationFiles(String appConfigDir) {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java
new file mode 100644
index 0000000000..e411b53c08
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/GetConsumersConfiguration.java
@@ -0,0 +1,20 @@
+package org.openecomp.sdc.asdctool.configuration;
+
+import org.openecomp.sdc.be.dao.config.TitanSpringConfig;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+
+@Configuration
+@Import({TitanSpringConfig.class})
+public class GetConsumersConfiguration {
+
+
+ @Bean("consumer-operation")
+ public ConsumerOperation consumerOperation(TitanGenericDao titanGenericDao) {
+ return new ConsumerOperation(titanGenericDao);
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ESCatalogDAOMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ESCatalogDAOMock.java
new file mode 100644
index 0000000000..302d20fea7
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ESCatalogDAOMock.java
@@ -0,0 +1,41 @@
+package org.openecomp.sdc.asdctool.configuration.mocks.es;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.api.ICatalogDAO;
+import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+
+import java.util.List;
+
+public class ESCatalogDAOMock implements ICatalogDAO {
+
+ @Override
+ public void addToIndicesMap(String typeName, String indexName) {
+
+ }
+
+ @Override
+ public void writeArtifact(ESArtifactData artifactData) {
+
+ }
+
+ @Override
+ public Either<ESArtifactData, ResourceUploadStatus> getArtifact(String id) {
+ return null;
+ }
+
+ @Override
+ public Either<List<ESArtifactData>, ResourceUploadStatus> getArtifacts(String[] ids) {
+ return null;
+ }
+
+ @Override
+ public void deleteArtifact(String id) {
+
+ }
+
+ @Override
+ public void deleteAllArtifacts() {
+
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchClientMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchClientMock.java
new file mode 100644
index 0000000000..0038a9595d
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchClientMock.java
@@ -0,0 +1,26 @@
+package org.openecomp.sdc.asdctool.configuration.mocks.es;
+
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+
+import java.net.URISyntaxException;
+
+public class ElasticSearchClientMock extends ElasticSearchClient {
+
+ @Override
+ public void initialize() {
+
+ }
+
+ @Override
+ public void setClusterName(final String clusterName) {
+
+ }
+
+ @Override
+ public void setLocal(final String strIsLocal) {
+ }
+
+ @Override
+ public void setTransportClient(final String strIsTransportclient) {
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchMocksConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchMocksConfiguration.java
new file mode 100644
index 0000000000..ad78a8c0c7
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/ElasticSearchMocksConfiguration.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.asdctool.configuration.mocks.es;
+
+import org.openecomp.sdc.be.dao.api.ICatalogDAO;
+import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
+import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ElasticSearchMocksConfiguration {
+
+ @Bean("elasticsearch-client")
+ public ElasticSearchClient elasticSearchClientMock() {
+ return new ElasticSearchClientMock();
+ }
+
+ @Bean("resource-dao")
+ public ICatalogDAO esCatalogDAOMock() {
+ return new ESCatalogDAOMock();
+ }
+
+ @Bean("esHealthCheckDao")
+ public IEsHealthCheckDao esHealthCheckDaoMock() {
+ return new EsHealthCheckDaoMock();
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/EsHealthCheckDaoMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/EsHealthCheckDaoMock.java
new file mode 100644
index 0000000000..2aabc86519
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/configuration/mocks/es/EsHealthCheckDaoMock.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.asdctool.configuration.mocks.es;
+
+import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+
+public class EsHealthCheckDaoMock implements IEsHealthCheckDao {
+ @Override
+ public HealthCheckInfo.HealthCheckStatus getClusterHealthStatus() {
+ return HealthCheckInfo.HealthCheckStatus.UP;
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java
index b8d9ae6b5f..5d4610c91f 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ArtifactUuidFix.java
@@ -1,14 +1,13 @@
package org.openecomp.sdc.asdctool.impl;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import fj.data.Either;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -16,8 +15,12 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
+
+import org.openecomp.sdc.asdctool.impl.validator.utils.VfModuleArtifactPayloadEx;
import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
@@ -30,1081 +33,1413 @@ import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.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.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.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.ESArtifactData;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.tosca.ToscaRepresentation;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
+
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.StringUtils;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+
+import fj.data.Either;
@org.springframework.stereotype.Component("artifactUuidFix")
public class ArtifactUuidFix {
- @Autowired
- private TitanDao titanDao;
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
- @Autowired
- private ToscaExportHandler toscaExportUtils;
- @Autowired
- private ArtifactCassandraDao artifactCassandraDao;
-
- @Autowired
- private CsarUtils csarUtils;
-
- private static Logger log = LoggerFactory.getLogger(ArtifactUuidFix.class.getName());
-
- public boolean doFix(String fixComponent, String runMode) {
- List<Resource> vfLst = new ArrayList<>();
- List<Service> serviceList = new ArrayList<>();
- Map<String, List<Component>> nodeToFixTosca = new HashMap<>();
- Map<String, List<Component>> vfToFixTosca = new HashMap<>();
- Map<String, List<Component>> serviceToFixTosca = new HashMap<>();
-
- long time = System.currentTimeMillis();
-
- doFixTosca(nodeToFixTosca, vfToFixTosca, serviceToFixTosca);
-
- if (fixComponent.equals("vf_only")) {
- if (!fetchFaultVf(vfLst, time)) {
- return false;
- }
- } else {
- if (!fetchServices(fixComponent, serviceList, time)) {
- return false;
- }
- }
- if (runMode.equals("service_vf") || runMode.equals("fix")) {
- log.info("Mode {}. Find problem VFs", runMode);
- if (!fetchVf(serviceList, vfLst, time)) {
- log.info("Mode {}. Find problem VFs finished with failure", runMode);
- return false;
- }
- log.info("Mode {}. Find problem VFs finished with success", runMode);
- }
- if (runMode.equals("fix") || runMode.equals("fix_only_services")) {
- log.info("Mode {}. Start fix", runMode);
- if (!fix(vfLst, serviceList, nodeToFixTosca, vfToFixTosca, serviceToFixTosca)) {
- log.info("Mode {}. Fix finished with failure", runMode);
- return false;
- }
- log.info("Mode {}. Fix finished with success", runMode);
- }
- return true;
- }
-
- private boolean fetchFaultVf(List<Resource> vfLst, long time) {
- log.info("Find fault VF ");
- String fileName = "fault_" + time + ".csv";
-
- try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
- writer.write("vf name, vf id, state, version\n");
-
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
-
- Map<GraphPropertyEnum, Object> hasNotProps = new HashMap<>();
- hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
- log.info("Try to fetch resources with properties {} and not {}", hasProps, hasNotProps);
-
- Either<List<GraphVertex>, TitanOperationStatus> servicesByCriteria = titanDao
- .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll);
- if (servicesByCriteria.isRight()) {
- log.info("Failed to fetch resources {}", servicesByCriteria.right().value());
- return false;
- }
- List<GraphVertex> resources = servicesByCriteria.left().value();
- for (GraphVertex gv : resources) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreArtifacts(false);
- filter.setIgnoreGroups(false);
-
- Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade
- .getToscaElement(gv.getUniqueId());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch resources {} {}", gv.getUniqueId(), toscaElement.right().value());
- return false;
- }
-
- Resource resource = toscaElement.left().value();
- String resourceName = resource.getName();
- Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
- List<GroupDefinition> groups = resource.getGroups();
- if (groups == null || groups.isEmpty()) {
- log.info("No groups for resource {} id {} ", resourceName, gv.getUniqueId());
- continue;
- }
- boolean isProblematic = false;
- for (GroupDefinition gr : groups) {
- if ((gr.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE))
- && (isProblematicGroup(gr, resourceName, deploymentArtifacts))) {
- isProblematic = true;
- break;
- }
- }
- if (isProblematic) {
- vfLst.add(resource);
- writeModuleResultToFile(writer, resource, null);
- writer.flush();
- }
- titanDao.commit();
- }
-
- } catch (Exception e) {
- log.info("Failed to fetch vf resources ", e);
- return false;
- } finally {
- titanDao.commit();
- }
- return true;
- }
-
- private boolean fetchVf(List<Service> serviceList, List<Resource> vfLst, long time) {
- log.info("Find problem VF ");
- if (serviceList.isEmpty()) {
- log.info("No services as input");
- return true;
- }
- String fileName = "problemVf_" + time + ".csv";
-
- try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
- writer.write("vf name, vf id, state, version, example service name\n");
- Set<String> vfIds = new HashSet<>();
- for (Service service : serviceList) {
- List<ComponentInstance> componentInstances = service.getComponentInstances().stream()
- .filter(ci -> ci.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
- for (ComponentInstance ci : componentInstances) {
- if (!vfIds.contains(ci.getComponentUid())) {
- vfIds.add(ci.getComponentUid());
- Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade
- .getToscaElement(ci.getComponentUid());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch resource {} {}", ci.getComponentUid(),
- toscaElement.right().value());
- return false;
- }
- Resource resource = toscaElement.left().value();
- if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
- vfLst.add(resource);
- writeModuleResultToFile(writer, resource, service);
- writer.flush();
- titanDao.commit();
- }
- }
- }
- }
- log.info("output file with list of Vf : {}", fileName);
- } catch (Exception e) {
- log.info("Failed to fetch services ", e);
- return false;
- } finally {
- titanDao.commit();
- }
- return true;
- }
-
- private boolean fetchServices(String fixServices, List<Service> serviceList, long time) {
- log.info("Find problem Services {}", fixServices);
- String fileName = "problemService_" + time + ".csv";
-
- try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
- writer.write("service name, service id, state, version\n");
-
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- if (fixServices.equals("distributed_only")) {
- hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- hasProps.put(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTED.name());
- }
-
- Map<GraphPropertyEnum, Object> hasNotProps = new HashMap<>();
- hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
- log.info("Try to fetch services with properties {} and not {}", hasProps, hasNotProps);
-
- Either<List<GraphVertex>, TitanOperationStatus> servicesByCriteria = titanDao
- .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll);
- if (servicesByCriteria.isRight()) {
- log.info("Failed to fetch services {}", servicesByCriteria.right().value());
- return false;
- }
-
- List<GraphVertex> services = servicesByCriteria.left().value();
- for (GraphVertex gv : services) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreArtifacts(false);
- filter.setIgnoreGroups(false);
-
- Either<Service, StorageOperationStatus> toscaElement = toscaOperationFacade
- .getToscaElement(gv.getUniqueId());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch service {} {}", gv.getUniqueId(), toscaElement.right().value());
- continue;
- }
-
- Service service = toscaElement.left().value();
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- boolean isProblematic = false;
- if (componentInstances == null) {
- log.info("No instances for service {} ", gv.getUniqueId());
- continue;
- }
- String serviceName = (String) gv.getMetadataProperty(GraphPropertyEnum.NAME);
-
- for (ComponentInstance ci : componentInstances) {
- Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
- List<GroupInstance> groupInstances = ci.getGroupInstances();
- if (groupInstances == null || groupInstances.isEmpty()) {
- log.info("No instance groups for instance {} in service {} id {} ", ci.getName(), serviceName,
- gv.getUniqueId());
- continue;
- }
-
- for (GroupInstance gi : groupInstances) {
- if (gi.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)
- && isProblematicGroupInstance(gi, ci.getName(), serviceName, deploymentArtifacts)) {
- isProblematic = true;
- break;
- }
- }
- if (isProblematic) {
- serviceList.add(service);
- writeModuleResultToFile(writer, service, null);
- writer.flush();
- break;
- }
- }
- titanDao.commit();
- }
- log.info("output file with list of services : {}", fileName);
- } catch (Exception e) {
- log.info("Failed to fetch services ", e);
- return false;
- } finally {
- titanDao.commit();
- }
- return true;
- }
-
- private boolean isProblematicGroup(GroupDefinition gr, String resourceName,
- Map<String, ArtifactDefinition> deploymentArtifacts) {
- List<String> artifacts = gr.getArtifacts();
- List<String> artifactsUuid = gr.getArtifactsUuid();
-
- if (artifactsUuid == null || artifactsUuid.isEmpty() || artifacts == null || artifacts.isEmpty()) {
- log.info("No groups in resource {} ", resourceName);
- return true;
- }
- Set<String> artifactsSet = new HashSet<>(artifacts);
- if (artifactsSet.size() < artifacts.size()) {
- log.info(" artifactsSet.size() < artifacts.size() group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
- if (artifacts.size() < artifactsUuid.size()) {
- log.info(" artifacts.size() < artifactsUuid.size() group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
- if (artifactsUuid.contains(null)) {
- log.info(" artifactsUuid.contains(null) group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
-
- for (String artifactId : artifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
- if (artifactDefinition == null) {
- log.info(" artifactDefinition == null label {} group {} in resource {} ", artifactlabel, gr.getName(),
- resourceName);
- return true;
- }
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- if (!artifactId.equals(artifactDefinition.getUniqueId())) {
- log.info(
- " !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} group {} in resource {} ",
- artifactlabel, artifactId, gr.getName(), resourceName);
- return true;
- }
- if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- log.info(
- " artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} group {} in resource {} ",
- artifactlabel, gr.getName(), resourceName);
- return true;
- }
- }
- }
-
- for (String artifactUuid : artifactsUuid) {
- String label = findArtifactLabelFromArtifactId(artifactUuid);
- if (label != null && !label.isEmpty()) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isProblematicGroupInstance(GroupInstance gi, String instName, String servicename,
- Map<String, ArtifactDefinition> deploymentArtifacts) {
- List<String> artifacts = gi.getArtifacts();
- List<String> artifactsUuid = gi.getArtifactsUuid();
- List<String> instArtifactsUuid = gi.getGroupInstanceArtifactsUuid();
- List<String> instArtifactsId = gi.getGroupInstanceArtifacts();
- Set<String> instArtifatIdSet = new HashSet<>();
-
- if (artifactsUuid == null || artifactsUuid.isEmpty() || artifacts == null || artifacts.isEmpty()) {
- log.info("No instance groups for instance {} in service {} ", instName, servicename);
- return true;
- }
- Set<String> artifactsSet = new HashSet<>(artifacts);
- if (artifactsSet.size() < artifacts.size()) {
- log.info(" artifactsSet.size() < artifacts.size() group {} in resource {} ", instName, servicename);
- return true;
- }
- if (instArtifactsId != null && !instArtifactsId.isEmpty()) {
- instArtifatIdSet.addAll(instArtifactsId);
- }
- if (artifacts.size() < artifactsUuid.size()) {
- log.info(" artifacts.size() < artifactsUuid.size() inst {} in service {} ", instName, servicename);
- return true;
- }
- if (artifactsUuid.contains(null)) {
- log.info(" artifactsUuid.contains(null) inst {} in service {} ", instName, servicename);
- return true;
- }
- if (instArtifactsId != null && instArtifatIdSet.size() < instArtifactsId.size()) {
- log.info(" instArtifatIdSet.size() < instArtifactsId.size() inst {} in service {} ", instName, servicename);
- return true;
- }
- if ((instArtifactsId != null && instArtifactsUuid != null)
- && instArtifactsId.size() != instArtifactsUuid.size()) {
- log.info(" instArtifactsId.size() != instArtifactsUuid.size() inst {} in service {} ", instName,
- servicename);
- return true;
- }
-
- for (String artifactId : artifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
- if (artifactDefinition == null) {
- log.info(" artifactDefinition == null label {} inst {} in service {} ", artifactlabel, instName,
- servicename);
- return true;
- }
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- if (!artifactId.equals(artifactDefinition.getUniqueId())) {
- log.info(
- " !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} inst {} in service {} ",
- artifactlabel, artifactId, instName, servicename);
- return true;
- }
- if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- log.info(
- " artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ",
- artifactlabel, instName, servicename);
- return true;
- }
- } else {
- if (instArtifactsUuid == null || instArtifactsUuid.isEmpty()) {
- log.info(" instArtifactsUuid empty. label {} inst {} in service {} ", artifactlabel, instName,
- servicename);
- return true;
- }
- if (!instArtifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- log.info(
- " instArtifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ",
- artifactlabel, instName, servicename);
- return true;
- }
- }
- }
- for (String artifactUuid : artifactsUuid) {
- String label = findArtifactLabelFromArtifactId(artifactUuid);
- if (label != null && !label.isEmpty()) {
- return true;
- }
- }
- return false;
- }
-
- private boolean fix(List<Resource> vfLst, List<Service> serviceList, Map<String, List<Component>> nodesToFixTosca,
- Map<String, List<Component>> vfToFixTosca, Map<String, List<Component>> servicesToFixTosca) {
- boolean res = true;
- log.info(" Fix started ***** ");
- if (vfLst != null && !vfLst.isEmpty()) {
- res = fixVf(vfLst);
- }
- if (res && serviceList != null && !serviceList.isEmpty()) {
- res = fixServices(serviceList);
- }
-
- Set<String> fixedIds = new HashSet<>();
- if (res && nodesToFixTosca != null && !nodesToFixTosca.isEmpty()) {
- generateAndSaveToscaArtifacts(nodesToFixTosca, fixedIds, null);
-
- for (Map.Entry<String, List<Component>> entry : nodesToFixTosca.entrySet()) {
- List<Component> components = entry.getValue();
- for (Component c : components) {
-
- ToscaElement topologyTemplate = ModelConverter.convertToToscaElement(c);
- Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
- res = fixDataOnGraph(c.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS,
- arifacts);
- titanDao.commit();
- }
- }
- }
- if (res && vfToFixTosca != null && !vfToFixTosca.isEmpty()) {
- generateAndSaveToscaArtifacts(vfToFixTosca, fixedIds, vfLst);
-
- for (Map.Entry<String, List<Component>> entry : vfToFixTosca.entrySet()) {
- List<Component> components = entry.getValue();
- for (Component c : components) {
- TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(c);
- Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
- res = fixDataOnGraph(c.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS,
- arifacts);
- titanDao.commit();
- }
- }
- }
-
- if (res && servicesToFixTosca != null && !servicesToFixTosca.isEmpty()) {
- generateAndSaveToscaArtifacts(servicesToFixTosca, fixedIds, serviceList);
-
- for (Map.Entry<String, List<Component>> entry : servicesToFixTosca.entrySet()) {
- List<Component> components = entry.getValue();
- for (Component c : components) {
- TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(c);
- Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
- res = fixDataOnGraph(c.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS,
- arifacts);
- titanDao.commit();
- }
- }
- }
-
- if (res) {
- for (Component component : vfLst) {
- generateToscaPerComponent(fixedIds, component);
-
- TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(component);
- Map<String, GroupDataDefinition> groups = topologyTemplate.getGroups();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
- if (res) {
- Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getDeploymentArtifacts();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.DEPLOYMENT_ARTIFACTS,
- EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, arifacts);
- }
- if (res) {
- Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS,
- EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts);
- }
- titanDao.commit();
- }
- }
-
- if (res) {
- for (Component component : serviceList) {
- generateToscaPerComponent(fixedIds, component);
-
- TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(component);
- Map<String, MapGroupsDataDefinition> groups = topologyTemplate.getInstGroups();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS,
- groups);
-
- if (res) {
- Map<String, MapArtifactDataDefinition> artifacts = topologyTemplate.getInstDeploymentArtifacts();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS,
- EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, artifacts);
- }
- if (res) {
- Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS,
- EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts);
- }
- titanDao.commit();
- }
- }
- log.info(" Fix finished with res {} ***** ", res);
- return res;
- }
-
- private boolean generateAndSaveToscaArtifacts(Map<String, List<Component>> nodesToFixTosca, Set<String> fixedIds,
- List<? extends Component> componentsWithFailedGroups) {
- boolean res = true;
- log.debug("Migration1707ArtifactUuidFix generateAndSaveToscaArtifacts started ");
- for (Map.Entry<String, List<Component>> entry : nodesToFixTosca.entrySet()) {
-
- List<Component> component = entry.getValue();
- for (Component c : component) {
- log.debug("Migration1707ArtifactUuidFix fix tosca on component : id {}, name {} ", c.getUniqueId(),
- c.getName());
- if (componentsWithFailedGroups != null) {
- Optional<Component> op = (Optional<Component>) componentsWithFailedGroups.stream()
- .filter(cg -> cg.getUniqueId().equals(c.getUniqueId())).findAny();
- if (!op.isPresent()) {
- res = generateToscaPerComponent(fixedIds, c);
- }
- } else {
- res = generateToscaPerComponent(fixedIds, c);
- }
- }
- }
- log.debug("Migration1707ArtifactUuidFix generateAndSaveToscaArtifacts finished with res {} ", res);
- return res;
- }
-
- private boolean generateToscaPerComponent(Set<String> fixedIds, Component c) {
- boolean res = true;
- log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent started component name {} id {}",
- c.getName(), c.getUniqueId());
- try {
- Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
- .getToscaFullElement(c.getUniqueId());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch resources {} {}", c.getUniqueId(), toscaElement.right().value());
- return false;
- }
- Component toscaElementFull = toscaElement.left().value();
- toscaElementFull.setGroups(c.getGroups());
- List<ComponentInstance> ciListFull = toscaElementFull.getComponentInstances();
- List<ComponentInstance> ciList = c.getComponentInstances();
- if (ciListFull != null && !ciListFull.isEmpty()) {
- ciListFull.forEach(ciFull -> ciList.stream()
- .filter(ci -> ci.getUniqueId().equals(ciFull.getUniqueId()))
- .findAny()
- .ifPresent(compInst -> ciFull.setGroupInstances(compInst.getGroupInstances())));
- }
-
- Map<String, ArtifactDefinition> toscaArtifacts = c.getToscaArtifacts();
- log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent tocsa artifacts size {}",
- toscaArtifacts.size());
-
- Either<ArtifactDefinition, ToscaError> either = Either.right(ToscaError.GENERAL_ERROR);
- ArtifactDefinition toscaArtifact = null;
- Optional<ArtifactDefinition> op = toscaArtifacts.values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
-
- if (op.isPresent()) {
- toscaArtifact = op.get();
- }
-
- if (toscaArtifact != null) {
- log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent artifact name {} id {} esId {}",
- toscaArtifact.getArtifactName(), toscaArtifact.getUniqueId(), toscaArtifact.getEsId());
- either = generateToscaArtifact(toscaElementFull, toscaArtifact);
- if (either.isRight()) {
- log.error("Couldn't generate and save tosca template component unique id {}, name {} error: {}",
- toscaElementFull.getUniqueId(), toscaElementFull.getName(), either.right().value());
- res = false;
-
- }
- }
- if (res) {
- ArtifactDefinition csarArtifact = null;
- op = toscaArtifacts.values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
-
- if (op.isPresent()) {
- csarArtifact = op.get();
- }
-
- if (csarArtifact != null) {
- log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent artifact name {} id {} esId {}",
- csarArtifact.getArtifactName(), csarArtifact.getUniqueId(), csarArtifact.getEsId());
- either = generateToscaArtifact(toscaElementFull, csarArtifact);
- if (either.isRight()) {
- log.error("Couldn't generate and save tosca csar for component uuid {}, id {}, name {}. error: {}",
- toscaElementFull.getUUID(), toscaElementFull.getUniqueId(), toscaElementFull.getName(), either.right().value());
- res = false;
-
- }
- }
- }
- c.setToscaArtifacts(toscaArtifacts);
-
- if (res) {
- fixedIds.add(toscaElementFull.getUniqueId());
- }
- } finally {
- titanDao.commit();
- }
- log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent finished component name {} id {} res {}",
- c.getName(), c.getUniqueId(), res);
- return res;
- }
-
- private <T extends ToscaDataDefinition> boolean fixDataOnGraph(String componentId, VertexTypeEnum vertexTypeEnum,
- EdgeLabelEnum edgeLabelEnum, Map<String, T> groups) {
- log.debug("amount groups to update: VertexTypeEnum {} EdgeLabelEnum {} data size {}", vertexTypeEnum.getName(),
- edgeLabelEnum, groups.size());
- boolean res = true;
- Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentId,
- JsonParseFlagEnum.NoParse);
- if (getResponse.isRight()) {
- log.debug("Couldn't fetch component unique id {}, error: {}", componentId, getResponse.right().value());
- res = false;
- }
- if (res) {
- GraphVertex componentVertex = getResponse.left().value();
- GraphVertex toscaDataVertex;
- Either<GraphVertex, TitanOperationStatus> groupVertexEither = titanDao.getChildVertex(componentVertex,
- edgeLabelEnum, JsonParseFlagEnum.ParseJson);
- if (groupVertexEither.isRight() && groupVertexEither.right().value() == TitanOperationStatus.NOT_FOUND) {
- log.debug("no child {} vertex for component unique id {}, error: {}", edgeLabelEnum, componentId,
- groupVertexEither.right().value());
- return true;
- }
- if (groupVertexEither.isRight()) {
- res = false;
- log.debug("failed to get child {} vertex for component unique id {}, error: {}", edgeLabelEnum,
- componentId, groupVertexEither.right().value());
- }
- if (res) {
- toscaDataVertex = groupVertexEither.left().value();
- toscaDataVertex.setJson(groups);
- Either<GraphVertex, TitanOperationStatus> updatevertexEither = titanDao.updateVertex(toscaDataVertex);
- if (updatevertexEither.isRight()) {
- log.debug("failed to update vertex for component unique id {}, error: {}", componentId,
- updatevertexEither.right().value());
- titanDao.rollback();
- return false;
- }
- }
- }
- log.debug("Fix data on graph finished: VertexTypeEnum {} EdgeLabelEnum {} res {}", vertexTypeEnum.getName(),
- res);
- return res;
- }
-
- private boolean fixServices(List<Service> serviceList) {
- for (Service service : serviceList) {
- log.debug("Migration1707ArtifactUuidFix fix service: id {}, name {} ", service.getUniqueId(),
- service.getName());
- List<ComponentInstance> instances = service.getComponentInstances();
- for (ComponentInstance instance : instances) {
- fixComponentInstances(service, instance);
- }
- }
- return true;
- }
-
- private void fixComponentInstances(Service service, ComponentInstance instance) {
- Map<String, ArtifactDefinition> artifactsMap = instance.getDeploymentArtifacts();
- List<GroupInstance> groupsList = instance.getGroupInstances();
- if (groupsList != null && artifactsMap != null) {
- List<GroupInstance> groupsToDelete = new ArrayList<>();
- for (GroupInstance group : groupsList) {
- fixGroupInstances(service, artifactsMap, groupsToDelete, group);
- }
-
- if (!groupsToDelete.isEmpty()) {
- log.debug("Migration1707ArtifactUuidFix delete group: resource id {}, group instance to delete {} ",
- service.getUniqueId(), groupsToDelete);
- groupsList.removeAll(groupsToDelete);
- }
-
- Optional<ArtifactDefinition> optionalVfModuleArtifact = artifactsMap.values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
- if (optionalVfModuleArtifact.isPresent()) {
- ArtifactDefinition vfModuleAertifact = optionalVfModuleArtifact.get();
- fillVfModuleInstHeatEnvPayload(groupsList, vfModuleAertifact);
- }
- }
- }
-
- private void fixGroupInstances(Service service, Map<String, ArtifactDefinition> artifactsMap,
- List<GroupInstance> groupsToDelete, GroupInstance group) {
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- log.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", service.getUniqueId(),
- group.getName());
- List<String> groupArtifacts = new ArrayList<>(group.getArtifacts());
-
- group.getArtifacts().clear();
- group.getArtifactsUuid().clear();
- group.getGroupInstanceArtifacts().clear();
- group.getGroupInstanceArtifactsUuid().clear();
-
- for (String artifactId : groupArtifacts) {
- fixArtifactUndergroupInstances(artifactsMap, group, groupArtifacts, artifactId);
- }
- if (group.getArtifacts() == null || group.getArtifacts().isEmpty()) {
- log.debug(
- "Migration1707ArtifactUuidFix fix groupInstance add to delete list: resource id {} name {} , group name {} ",
- service.getUniqueId(), service.getName(), group.getName());
- groupsToDelete.add(group);
- }
- }
- }
-
- private void fixArtifactUndergroupInstances(Map<String, ArtifactDefinition> artifactsMap, GroupInstance group,
- List<String> groupArtifacts, String artifactId) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ",
- group.getName(), artifactId, artifactlabel);
- if (!artifactlabel.isEmpty() && artifactsMap.containsKey(artifactlabel)) {
- ArtifactDefinition artifact = artifactsMap.get(artifactlabel);
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
- String correctArtifactId = artifact.getUniqueId();
- String correctArtifactUUID = artifact.getArtifactUUID();
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- boolean isAddToGroup = true;
- if (groupArtifacts.size() == 1 && artifactType == ArtifactTypeEnum.HEAT_ARTIFACT) {
- isAddToGroup = false;
- artifact.setArtifactType(ArtifactTypeEnum.OTHER.getType());
- }
- if (isAddToGroup) {
- log.debug(
- "Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ",
- group.getName(), correctArtifactId, correctArtifactUUID);
- group.getArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getArtifactsUuid().add(correctArtifactUUID);
- }
- }
- } else {
- log.debug(
- "Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ",
- group.getName(), correctArtifactId, correctArtifactUUID);
- group.getGroupInstanceArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getGroupInstanceArtifactsUuid().add(correctArtifactUUID);
- }
- }
- }
- }
-
- private boolean fixVf(List<Resource> vfLst) {
- for (Resource resource : vfLst) {
- log.debug("Migration1707ArtifactUuidFix fix resource: id {}, name {} ", resource.getUniqueId(),
- resource.getName());
- Map<String, ArtifactDefinition> artifactsMap = resource.getDeploymentArtifacts();
- List<GroupDefinition> groupsList = resource.getGroups();
- List<GroupDefinition> groupsToDelete = new ArrayList<>();
- if (groupsList != null && artifactsMap != null) {
- for (GroupDefinition group : groupsList) {
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && group.getArtifacts() != null) {
- fixVfGroup(resource, artifactsMap, group);
- }
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)
- && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
- log.debug(
- "Migration1707ArtifactUuidFix add group to delete list fix resource: id {}, name {} ",
- resource.getUniqueId(), resource.getName(), group.getName());
- groupsToDelete.add(group);
- }
- }
- if (!groupsToDelete.isEmpty()) {
- groupsList.removeAll(groupsToDelete);
- }
- }
- }
- return true;
- }
-
- private void fixVfGroup(Resource resource, Map<String, ArtifactDefinition> artifactsMap, GroupDefinition group) {
- log.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", resource.getUniqueId(),
- group.getName());
- List<String> groupArtifacts = new ArrayList<>(group.getArtifacts());
-
- for (String artifactId : groupArtifacts) {
- fixArtifactUnderGroup(artifactsMap, group, groupArtifacts, artifactId);
- }
- }
-
- private void fixArtifactUnderGroup(Map<String, ArtifactDefinition> artifactsMap, GroupDefinition group,
- List<String> groupArtifacts, String artifactId) {
- group.getArtifacts().clear();
- group.getArtifactsUuid().clear();
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ",
- group.getName(), artifactId, artifactlabel);
- if (!artifactlabel.isEmpty() && artifactsMap.containsKey(artifactlabel)) {
- ArtifactDefinition artifact = artifactsMap.get(artifactlabel);
- String correctArtifactId = artifact.getUniqueId();
- String correctArtifactUUID = artifact.getArtifactUUID();
- boolean isAddToGroup = true;
- if (groupArtifacts.size() == 1) {
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
- if (artifactType == ArtifactTypeEnum.HEAT_ARTIFACT) {
- isAddToGroup = false;
- artifact.setArtifactType(ArtifactTypeEnum.OTHER.getType());
- }
- }
- if (isAddToGroup) {
- log.debug(
- "Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ",
- group.getName(), correctArtifactId, correctArtifactUUID);
- group.getArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getArtifactsUuid().add(correctArtifactUUID);
- }
- }
- }
- }
-
- private String findArtifactLabelFromArtifactId(String artifactId) {
- String artifactLabel = "";
- int index = artifactId.lastIndexOf('.');
- if (index > 0 && index + 1 < artifactId.length()) {
- artifactLabel = artifactId.substring(index + 1);
- }
- return artifactLabel;
- }
-
- private void writeModuleResultToFile(Writer writer, org.openecomp.sdc.be.model.Component component,
- Service service) {
- try {
- // "service name, service id, state, version
- StringBuilder sb = new StringBuilder(component.getName());
- sb.append(",").append(component.getUniqueId()).append(",").append(component.getLifecycleState()).append(",")
- .append(component.getVersion());
- if (service != null) {
- sb.append(",").append(service.getName());
- }
- sb.append("\n");
- writer.write(sb.toString());
- } catch (IOException e) {
- log.error(e.getMessage(), e);
- }
- }
-
- private void writeModuleResultToFile(Writer writer, List<Component> components) {
- try {
- // "service name, service id, state, version
- for (Component component : components) {
- StringBuilder sb = new StringBuilder(component.getName());
- sb.append(",").append(component.getUniqueId())
- .append(",").append(component.getInvariantUUID())
- .append(",").append(component.getLifecycleState())
- .append(",").append(component.getVersion())
- .append("\n");
- writer.write(sb.toString());
- }
- } catch (IOException e) {
- log.error(e.getMessage(), e);
- }
- }
-
- public boolean doFixTosca(Map<String, List<Component>> nodeToFix, Map<String, List<Component>> vfToFix,
- Map<String, List<Component>> serviceToFix) {
-
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- Map<String, List<Component>> vertices = getVerticesToValidate(VertexTypeEnum.NODE_TYPE, hasProps);
- boolean result = validateTosca(vertices, nodeToFix, "RESOURCE_TOSCA_ARTIFACTS");
-
- hasProps.clear();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF);
- hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- vertices = getVerticesToValidate(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps);
- result = validateTosca(vertices, vfToFix, "VF_TOSCA_ARTIFACTS");
-
- hasProps.clear();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- vertices = getVerticesToValidate(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps);
- result = validateTosca(vertices, serviceToFix, "SERVICE_TOSCA_ARTIFACTS");
-
- return result;
- }
-
- public Map<String, List<Component>> getVerticesToValidate(VertexTypeEnum type,
- Map<GraphPropertyEnum, Object> hasProps) {
-
- Map<String, List<Component>> result = new HashMap<>();
- try {
- Either<List<GraphVertex>, TitanOperationStatus> resultsEither = titanDao.getByCriteria(type, hasProps);
- if (resultsEither.isRight()) {
- log.info("getVerticesToValidate failed " + resultsEither.right().value());
- return result;
- }
- log.info("getVerticesToValidate: " + resultsEither.left().value().size() + " vertices to scan");
- List<GraphVertex> componentsList = resultsEither.left().value();
- componentsList.forEach(vertex -> {
- String ivariantUuid = (String) vertex.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID);
- if (!result.containsKey(ivariantUuid)) {
- result.put(ivariantUuid, new ArrayList<>());
- }
- List<Component> compList = result.get(ivariantUuid);
-
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreArtifacts(false);
-
- Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
- .getToscaElement(vertex.getUniqueId(), filter);
- if (toscaElement.isRight()) {
- log.info("getVerticesToValidate: failed to find element" + vertex.getUniqueId()
- + " staus is" + toscaElement.right().value());
- } else {
- compList.add(toscaElement.left().value());
- }
- titanDao.commit();
- });
- } catch (Exception e) {
- log.info("Failed to fetch vf resources ", e);
- } finally {
- titanDao.commit();
- }
- return result;
- }
-
- public boolean validateTosca(Map<String, List<Component>> vertices, Map<String, List<Component>> compToFix,
- String name) {
- boolean result = true;
- long time = System.currentTimeMillis();
- String fileName = name + "_" + time + ".csv";
- try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
- writer.write("name, UUID, invariantUUID, state, version\n");
- for (Map.Entry<String, List<Component>> entry : vertices.entrySet()) {
- List<Component> compList = entry.getValue();
- Set<String> artifactEsId = new HashSet<>();
- for (Component component : compList) {
- Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- Optional<ArtifactDefinition> op = toscaArtifacts.values().stream()
- .filter(a -> artifactEsId.contains(a.getEsId()) && a.getEsId() != null).findAny();
- if (op.isPresent()) {
- result = false;
- writeModuleResultToFile(writer, compList);
- writer.flush();
- break;
- } else {
- artifactEsId.addAll(toscaArtifacts.values().stream().map(ArtifactDefinition::getEsId)
- .collect(Collectors.toList()));
- }
- }
- if (!result) {
- List<Component> compListfull = new ArrayList<>();
- for (Component c : compList) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreArtifacts(false);
- filter.setIgnoreGroups(false);
-
- Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
- .getToscaElement(c.getUniqueId(), filter);
- if (toscaElement.isRight()) {
- log.info("getVerticesToValidate: failed to find element" + c.getUniqueId()
- + " staus is" + toscaElement.right().value());
- } else {
- compListfull.add(toscaElement.left().value());
- }
- this.titanDao.commit();
- }
- compToFix.put(entry.getKey(), compListfull);
- result = true;
- }
- }
- } catch (Exception e) {
- log.info("Failed to fetch vf resources ", e);
- return false;
- } finally {
- titanDao.commit();
- }
- return result;
- }
-
- private Either<ArtifactDefinition, ToscaError> generateToscaArtifact(Component parent,
- ArtifactDefinition artifactInfo) {
- log.debug("tosca artifact generation");
- try {
- if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
- Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, true, true);
-
- if (generated.isRight()) {
- log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(),
- generated.right().value());
-
- return Either.right(ToscaError.GENERAL_ERROR);
- }
- byte[] value = generated.left().value();
- artifactInfo.setPayload(value);
- } else {
- Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
- if (exportComponent.isRight()) {
- log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(),
- exportComponent.right().value());
-
- return Either.right(exportComponent.right().value());
- }
- log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
- String payload = exportComponent.left().value().getMainYaml();
-
- artifactInfo.setPayloadData(payload);
- }
-
- byte[] decodedPayload = artifactInfo.getPayloadData();
- artifactInfo.setEsId(artifactInfo.getUniqueId());
- artifactInfo.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
- ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), decodedPayload);
- artifactCassandraDao.saveArtifact(artifactData);
- log.debug("Tosca yaml artifact esId ", artifactInfo.getEsId());
- } catch (Exception ex) {
- log.error("Failed to generate tosca atifact id {} component id {} component name {} error {}",
- artifactInfo.getUniqueId(), parent.getUniqueId(), parent.getName(), ex.getMessage(), ex);
- return Either.right(ToscaError.GENERAL_ERROR);
- }
- return Either.left(artifactInfo);
- }
-
- private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF,
- ArtifactDefinition vfModuleArtifact) {
-
- List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<>();
- if (groupsForCurrVF != null) {
- for (GroupInstance groupInstance : groupsForCurrVF) {
- VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
- vfModulePayloadForCurrVF.add(modulePayload);
- }
- vfModulePayloadForCurrVF.sort(VfModuleArtifactPayload::compareByGroupName);
-
- final Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
- if (vfModulePayloadString != null) {
- String newCheckSum = GeneralUtility
- .calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes());
- vfModuleArtifact.setArtifactChecksum(newCheckSum);
-
- ESArtifactData artifactData = new ESArtifactData(vfModuleArtifact.getEsId(),
- vfModulePayloadString.getBytes());
- artifactCassandraDao.saveArtifact(artifactData);
- }
- }
- }
+ @Autowired
+ private TitanDao titanDao;
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+ @Autowired
+ private ToscaExportHandler toscaExportUtils;
+ @Autowired
+ private ArtifactCassandraDao artifactCassandraDao;
+
+
+ @Autowired
+ private CsarUtils csarUtils;
+
+ private static Logger log = LoggerFactory.getLogger(ArtifactUuidFix.class.getName());
+
+ public boolean doFix(String fixComponent, String runMode) {
+ List<Resource> vfLst = new ArrayList<>();
+ List<Service> serviceList = new ArrayList<>();
+ Map<String, List<Component>> nodeToFixTosca = new HashMap<>();
+ Map<String, List<Component>> vfToFixTosca = new HashMap<>();
+ Map<String, List<Component>> serviceToFixTosca = new HashMap<>();
+
+ long time = System.currentTimeMillis();
+
+ doFixTosca(nodeToFixTosca, vfToFixTosca, serviceToFixTosca);
+
+ if (fixComponent.equals("vf_only")) {
+ if (fetchFaultVf(fixComponent, vfLst, time) == false) {
+ return false;
+ }
+ } else {
+ if (fetchServices(fixComponent, serviceList, time) == false) {
+ return false;
+ }
+ }
+ if (runMode.equals("service_vf") || runMode.equals("fix")) {
+ log.info("Mode {}. Find problem VFs", runMode);
+ if (fetchVf(serviceList, vfLst, time) == false) {
+ log.info("Mode {}. Find problem VFs finished with failure", runMode);
+ return false;
+ }
+ log.info("Mode {}. Find problem VFs finished with success", runMode);
+ }
+ if (runMode.equals("fix") || runMode.equals("fix_only_services")) {
+ log.info("Mode {}. Start fix", runMode);
+ if (fix(vfLst, serviceList, nodeToFixTosca, vfToFixTosca, serviceToFixTosca) == false) {
+ log.info("Mode {}. Fix finished with failure", runMode);
+ return false;
+ }
+ log.info("Mode {}. Fix finished with success", runMode);
+ }
+
+ return true;
+ }
+
+ private boolean fetchFaultVf(String fixComponent, List<Resource> vfLst, long time) {
+ log.info("Find fault VF ");
+ Writer writer = null;
+ try {
+ String fileName = "fault_" + time + ".csv";
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
+ writer.write("vf name, vf id, state, version\n");
+
+ Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
+
+ Map<GraphPropertyEnum, Object> hasNotProps = new HashMap<>();
+ hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
+ log.info("Try to fetch resources with properties {} and not {}", hasProps, hasNotProps);
+
+ Either<List<GraphVertex>, TitanOperationStatus> servicesByCriteria = titanDao
+ .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll);
+ if (servicesByCriteria.isRight()) {
+ log.info("Failed to fetch resources {}", servicesByCriteria.right().value());
+ return false;
+ }
+ List<GraphVertex> resources = servicesByCriteria.left().value();
+ for (GraphVertex gv : resources) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreArtifacts(false);
+ filter.setIgnoreGroups(false);
+
+ Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaElement(gv.getUniqueId());
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch resources {} {}", gv.getUniqueId(), toscaElement.right().value());
+ continue;
+ }
+
+ Resource resource = toscaElement.left().value();
+ String resourceName = resource.getName();
+ Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
+ List<GroupDefinition> groups = resource.getGroups();
+ if (groups == null || groups.isEmpty()) {
+ log.info("No groups for resource {} id {} ", resourceName, gv.getUniqueId());
+ continue;
+ }
+ boolean isProblematic = false;
+ for (GroupDefinition gr : groups) {
+ if (gr.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ if (isProblematicGroup(gr, resourceName, deploymentArtifacts)) {
+ isProblematic = true;
+ break;
+ }
+ }
+ }
+ if (isProblematic) {
+ vfLst.add(resource);
+ writeModuleResultToFile(writer, resource, null);
+ writer.flush();
+ }
+ titanDao.commit();
+ }
+
+ } catch (Exception e) {
+ log.info("Failed to fetch vf resources ", e);
+ return false;
+ } finally {
+ titanDao.commit();
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */
+ }
+ }
+ return true;
+ }
+
+ private boolean fetchVf(List<Service> serviceList, List<Resource> vfLst, long time) {
+ log.info("Find problem VF ");
+ if (serviceList.isEmpty()) {
+ log.info("No services as input");
+ return true;
+ }
+ Writer writer = null;
+ try {
+ String fileName = "problemVf_" + time + ".csv";
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
+ writer.write("vf name, vf id, state, version, example service name\n");
+ Set<String> vfIds = new HashSet<>();
+ for (Service service : serviceList) {
+ List<ComponentInstance> componentInstances = service.getComponentInstances().stream()
+ .filter(ci -> ci.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
+ for (ComponentInstance ci : componentInstances) {
+ if (!vfIds.contains(ci.getComponentUid())) {
+ vfIds.add(ci.getComponentUid());
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreArtifacts(false);
+ filter.setIgnoreGroups(false);
+ Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaElement(ci.getComponentUid(), filter);
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch resource {} {}", ci.getComponentUid(),
+ toscaElement.right().value());
+ continue;
+ }
+ Resource resource = toscaElement.left().value();
+ if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ vfLst.add(resource);
+ writeModuleResultToFile(writer, resource, service);
+ writer.flush();
+
+ }
+ titanDao.commit();
+ }
+ }
+ }
+ log.info("output file with list of Vf : {}", fileName);
+ } catch (Exception e) {
+ log.info("Failed to fetch services ", e);
+ return false;
+ } finally {
+ titanDao.commit();
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */
+ }
+ }
+ return true;
+ }
+
+ private boolean fetchServices(String fixServices, List<Service> serviceList, long time) {
+ log.info("Find problem Services {}", fixServices);
+ Writer writer = null;
+
+ try {
+ String fileName = "problemService_" + time + ".csv";
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
+ writer.write("service name, service id, state, version\n");
+
+ Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ if (fixServices.equals("distributed_only")) {
+ hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ hasProps.put(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTED.name());
+ }
+
+ Map<GraphPropertyEnum, Object> hasNotProps = new HashMap<>();
+ hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
+ log.info("Try to fetch services with properties {} and not {}", hasProps, hasNotProps);
+
+ Either<List<GraphVertex>, TitanOperationStatus> servicesByCriteria = titanDao
+ .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll);
+ if (servicesByCriteria.isRight()) {
+ log.info("Failed to fetch services {}", servicesByCriteria.right().value());
+ return false;
+ }
+ List<GraphVertex> services = servicesByCriteria.left().value();
+ for (GraphVertex gv : services) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreArtifacts(false);
+ filter.setIgnoreGroups(false);
+
+ Either<Service, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaElement(gv.getUniqueId(), filter);
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch service {} {}", gv.getUniqueId(), toscaElement.right().value());
+ continue;
+ }
+ Service service = toscaElement.left().value();
+
+ String serviceName = (String) gv.getMetadataProperty(GraphPropertyEnum.NAME);
+
+ boolean isProblematic = isProblematicService(service, serviceName);
+ if (isProblematic) {
+ serviceList.add(service);
+ writeModuleResultToFile(writer, service, null);
+ writer.flush();
+
+ }
+
+ titanDao.commit();
+ }
+ log.info("output file with list of services : {}", fileName);
+ } catch (Exception e) {
+ log.info("Failed to fetch services ", e);
+ return false;
+ } finally {
+ titanDao.commit();
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */
+ }
+ }
+ return true;
+ }
+
+ private boolean isProblematicService( Service service, String serviceName) throws IOException {
+
+ List<ComponentInstance> componentInstances = service.getComponentInstances();
+
+ if (componentInstances == null) {
+ log.info("No instances for service {} ", service.getUniqueId());
+ return false;
+ }
+ boolean isCheckVFModules = true;
+ if(service.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN ||
+ service.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
+ isCheckVFModules = false;
+ }
+ for (ComponentInstance ci : componentInstances) {
+ Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
+ List<GroupInstance> groupInstances = ci.getGroupInstances();
+ if (groupInstances == null || groupInstances.isEmpty()) {
+ log.info("No instance groups for instance {} in service {} id {} ", ci.getName(), serviceName,
+ service.getUniqueId());
+ continue;
+ }
+ List<VfModuleArtifactPayloadEx> vfModules = null;
+ if(isCheckVFModules){
+ Optional<ArtifactDefinition> optionalVfModuleArtifact = deploymentArtifacts.values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
+
+ if(!optionalVfModuleArtifact.isPresent())
+ return true;
+
+ ArtifactDefinition vfModuleArtifact = optionalVfModuleArtifact.get();
+ Either<List<VfModuleArtifactPayloadEx>, StorageOperationStatus> vfModulesEither = parseVFModuleJson(vfModuleArtifact);
+ if(vfModulesEither.isRight()){
+ log.error("Failed to parse vfModule for service {} status is {}", service.getUniqueId(), vfModulesEither.right().value());
+ return true;
+ }
+ vfModules = vfModulesEither.left().value();
+ if(vfModules == null || vfModules.isEmpty() ){
+ log.info("vfModules empty for service {}", service.getUniqueId());
+ return true;
+ }
+ }
+
+ for (GroupInstance gi : groupInstances) {
+ if (gi.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ VfModuleArtifactPayloadEx vfModule= null;
+ if(isCheckVFModules && vfModules != null){
+ Optional<VfModuleArtifactPayloadEx> op = vfModules.stream().filter(vf -> vf.getVfModuleModelName().equals(gi.getGroupName())).findAny();
+ if(!op.isPresent()){
+ log.error("Failed to find vfModule for group {}", gi.getGroupName());
+ return true;
+ }
+ vfModule = op.get();
+ }
+ if (isProblematicGroupInstance(gi, ci.getName(), serviceName, deploymentArtifacts, vfModule)) {
+ return true;
+ }
+ }
+ }
+
+ }
+ return false;
+ }
+
+ private boolean isProblematicGroup(GroupDefinition gr, String resourceName,
+ Map<String, ArtifactDefinition> deploymentArtifacts) {
+ List<String> artifacts = gr.getArtifacts();
+ List<String> artifactsUuid = gr.getArtifactsUuid();
+ Set<String> artifactsSet = new HashSet<>();
+
+ if ((artifactsUuid == null || artifactsUuid.isEmpty()) && (artifacts == null || artifacts.isEmpty())) {
+ log.info("No groups in resource {} ", resourceName);
+ return true;
+ }
+ artifactsSet.addAll(artifacts);
+ if (artifactsSet.size() < artifacts.size()) {
+ log.info(" artifactsSet.size() < artifacts.size() group {} in resource {} ", gr.getName(), resourceName);
+ return true;
+ }
+
+ if (artifacts.size() < artifactsUuid.size()) {
+ log.info(" artifacts.size() < artifactsUuid.size() group {} in resource {} ", gr.getName(), resourceName);
+ return true;
+ }
+ if (artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty())) {
+ log.info(
+ " artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty() group {} in resource {} ",
+ gr.getName(), resourceName);
+ return true;
+ }
+ if (artifactsUuid.contains(null)) {
+ log.info(" artifactsUuid.contains(null) group {} in resource {} ", gr.getName(), resourceName);
+ return true;
+ }
+
+ for (String artifactId : artifacts) {
+ String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
+ if (artifactDefinition == null) {
+ log.info(" artifactDefinition == null label {} group {} in resource {} ", artifactlabel, gr.getName(),
+ resourceName);
+ return true;
+ }
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
+ if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
+ if (!artifactId.equals(artifactDefinition.getUniqueId())) {
+ log.info(
+ " !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} group {} in resource {} ",
+ artifactlabel, artifactId, gr.getName(), resourceName);
+ return true;
+ }
+ if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
+ log.info(
+ " artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} group {} in resource {} ",
+ artifactlabel, gr.getName(), resourceName);
+ return true;
+ }
+ }
+ }
+ for (String artifactUUID : artifactsUuid) {
+ String label = findArtifactLabelFromArtifactId(artifactUUID);
+ if (label != null && !label.isEmpty() && !label.equals("")) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private boolean isProblematicGroupInstance(GroupInstance gi, String instName, String servicename,
+ Map<String, ArtifactDefinition> deploymentArtifacts, VfModuleArtifactPayloadEx vfModule) {
+ List<String> artifacts = gi.getArtifacts();
+ List<String> artifactsUuid = gi.getArtifactsUuid();
+ List<String> instArtifactsUuid = gi.getGroupInstanceArtifactsUuid();
+ List<String> instArtifactsId = gi.getGroupInstanceArtifacts();
+ Set<String> instArtifatIdSet = new HashSet<>();
+ Set<String> artifactsSet = new HashSet<>();
+
+ log.info("check group {} for instance {} ", gi.getGroupName(), instName);
+ if ((artifactsUuid == null || artifactsUuid.isEmpty()) && (artifacts == null || artifacts.isEmpty())) {
+ log.info("No instance groups for instance {} in service {} ", instName, servicename);
+ return true;
+ }
+ artifactsSet.addAll(artifacts);
+ if (artifactsSet.size() < artifacts.size()) {
+ log.info(" artifactsSet.size() < artifacts.size() group {} in resource {} ", instName, servicename);
+ return true;
+ }
+
+ if (instArtifactsId != null && !instArtifactsId.isEmpty()) {
+ instArtifatIdSet.addAll(instArtifactsId);
+ }
+
+ if (artifacts.size() < artifactsUuid.size()) {
+ log.info(" artifacts.size() < artifactsUuid.size() inst {} in service {} ", instName, servicename);
+ return true;
+ }
+ if (!artifacts.isEmpty() && (artifactsUuid == null || artifactsUuid.isEmpty())) {
+ log.info(
+ " artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty() inst {} in service {} ",
+ instName, servicename);
+ return true;
+ }
+ if (artifactsUuid.contains(null)) {
+ log.info(" artifactsUuid.contains(null) inst {} in service {} ", instName, servicename);
+ return true;
+ }
+ if (instArtifactsId != null && instArtifatIdSet.size() < instArtifactsId.size()) {
+ log.info(" instArtifatIdSet.size() < instArtifactsId.size() inst {} in service {} ", instName, servicename);
+ return true;
+ }
+
+ if ((instArtifactsId != null && instArtifactsUuid != null)
+ && instArtifactsId.size() != instArtifactsUuid.size()) {
+ log.info(" instArtifactsId.size() != instArtifactsUuid.size() inst {} in service {} ", instName,
+ servicename);
+ return true;
+ }
+
+ for (String artifactId : artifacts) {
+ String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
+ if (artifactDefinition == null) {
+ log.info(" artifactDefinition == null label {} inst {} in service {} ", artifactlabel, instName,
+ servicename);
+ return true;
+ }
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
+ if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
+ if (!artifactId.equals(artifactDefinition.getUniqueId())) {
+ log.info(
+ " !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} inst {} in service {} ",
+ artifactlabel, artifactId, instName, servicename);
+ return true;
+ }
+ if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
+ log.info(
+ " artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ",
+ artifactlabel, instName, servicename);
+ return true;
+ }
+ } else {
+ if (instArtifactsUuid == null || instArtifactsUuid.isEmpty()) {
+ log.info(" instArtifactsUuid empty. label {} inst {} in service {} ", artifactlabel, instName,
+ servicename);
+ return true;
+ }
+ if (!instArtifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
+ log.info(
+ " instArtifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ",
+ artifactlabel, instName, servicename);
+ return true;
+ }
+ }
+ }
+ for (String artifactUUID : artifactsUuid) {
+ String label = findArtifactLabelFromArtifactId(artifactUUID);
+ if (label != null && !label.isEmpty() && !label.equals("")) {
+ return true;
+ }
+ }
+ if(vfModule != null ){
+ return isProblematicVFModule(vfModule, artifactsUuid, instArtifactsUuid);
+ }
+
+ return false;
+ }
+
+ private boolean isProblematicVFModule(VfModuleArtifactPayloadEx vfModule, List<String> artifactsUuid,
+ List<String> instArtifactsUuid) {
+ log.info(" isProblematicVFModule {} ", vfModule.getVfModuleModelName());
+ List<String> vfModuleArtifacts = vfModule.getArtifacts();
+ List<String> allArtifacts = new ArrayList<>();
+ allArtifacts.addAll(artifactsUuid);
+ if(instArtifactsUuid != null)
+ allArtifacts.addAll(instArtifactsUuid);
+ if((vfModuleArtifacts == null || vfModuleArtifacts.isEmpty()) && !artifactsUuid.isEmpty()){
+ log.error(" vfModuleArtifacts == null || vfModuleArtifacts.isEmpty()) && !artifactsUuid.isEmpty()");
+ return true;
+ }
+ if(vfModuleArtifacts!= null){
+ if( vfModuleArtifacts.size() != allArtifacts.size()){
+ log.error(" vfModuleArtifacts.size() != allArtifacts.size()");
+ return true;
+ }
+ for(String vfModuleArtifact: vfModuleArtifacts){
+ Optional<String> op = allArtifacts.stream().filter(a -> a.equals(vfModuleArtifact)).findAny();
+ if(!op.isPresent()){
+ log.error("failed to find artifact {} in group artifacts {}", vfModuleArtifact, allArtifacts);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+
+
+ private boolean fix(List<Resource> vfLst, List<Service> serviceList, Map<String, List<Component>> nodesToFixTosca,
+ Map<String, List<Component>> vfToFixTosca, Map<String, List<Component>> servicesToFixTosca) {
+ boolean res = true;
+ log.info(" Fix started ***** ");
+ if (vfLst != null && !vfLst.isEmpty()) {
+ res = fixVf(vfLst);
+
+ }
+
+ if (res && serviceList != null && !serviceList.isEmpty()) {
+ res = fixServices(serviceList);
+
+ }
+
+ Set<String> fixedIds = new HashSet<>();
+
+ long time = System.currentTimeMillis();
+ String fileName = "FailedGenerateTosca" + "_" + time + ".csv";
+ Writer writer = null;
+ try {
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
+ writer.write("componentType, name, version, UID, UUID, invariantUUID, state\n");
+ List<Component> failedList = new ArrayList<>();
+
+ if (res && nodesToFixTosca != null && !nodesToFixTosca.isEmpty()) {
+
+ generateAndSaveToscaArtifacts(nodesToFixTosca, fixedIds, null, failedList);
+
+ }
+ if (vfToFixTosca != null && !vfToFixTosca.isEmpty()) {
+
+ generateAndSaveToscaArtifacts(vfToFixTosca, fixedIds, vfLst, failedList);
+
+ }
+
+ for (Component component : vfLst) {
+ res = generateToscaPerComponent(fixedIds, component);
+ if (res) {
+ TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(component);
+ Map<String, GroupDataDefinition> groups = topologyTemplate.getGroups();
+ res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
+ if (res) {
+ Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getDeploymentArtifacts();
+ res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.DEPLOYMENT_ARTIFACTS,
+ EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, arifacts);
+ }
+ if (res) {
+ Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
+ res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS,
+ EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts);
+ }
+ titanDao.commit();
+ } else {
+ failedList.add(component);
+ }
+ }
+
+ if (servicesToFixTosca != null && !servicesToFixTosca.isEmpty()) {
+ generateAndSaveToscaArtifacts(servicesToFixTosca, fixedIds, serviceList, failedList);
+
+ }
+
+
+ for (Component component : serviceList) {
+ res = generateToscaPerComponent(fixedIds, component);
+ if (res) {
+ TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(component);
+ Map<String, MapGroupsDataDefinition> groups = topologyTemplate.getInstGroups();
+ res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS,
+ groups);
+
+ if (res) {
+ Map<String, MapArtifactDataDefinition> artifacts = topologyTemplate
+ .getInstDeploymentArtifacts();
+ res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS,
+ EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, artifacts);
+ }
+ if (res) {
+ Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
+ res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS,
+ EdgeLabelEnum.TOSCA_ARTIFACTS, arifacts);
+ }
+ titanDao.commit();
+ } else {
+ failedList.add(component);
+ }
+
+ }
+ if (!failedList.isEmpty()) {
+ for (Component component : failedList) {
+ StringBuilder sb = new StringBuilder(component.getComponentType().getValue());
+ sb.append(",").append(component.getName()).append(",").append(component.getVersion()).append(",")
+ .append(component.getUniqueId()).append(",").append(component.getUUID()).append(",")
+ .append(component.getInvariantUUID()).append(",").append(component.getLifecycleState());
+
+ sb.append("\n");
+ writer.write(sb.toString());
+ }
+ writer.flush();
+ }
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ } finally {
+ titanDao.commit();
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */}
+ }
+ log.info(" Fix finished with res {} ***** ", res);
+ return res;
+ }
+
+ private boolean generateAndSaveToscaArtifacts(Map<String, List<Component>> nodesToFixTosca, Set<String> fixedIds,
+ List<? extends Component> componentsWithFailedGroups, List<Component> failedList) {
+ boolean res = true;
+ log.debug("Migration1707ArtifactUuidFix generateAndSaveToscaArtifacts started ");
+ for (Map.Entry<String, List<Component>> entry : nodesToFixTosca.entrySet()) {
+
+ List<Component> component = entry.getValue();
+ for (Component c : component) {
+ log.debug("Migration1707ArtifactUuidFix fix tosca on component : id {}, name {} ", c.getUniqueId(),
+ c.getName());
+ if (componentsWithFailedGroups != null) {
+ Optional<Component> op = (Optional<Component>) componentsWithFailedGroups.stream()
+ .filter(cg -> cg.getUniqueId().equals(c.getUniqueId())).findAny();
+ if (!op.isPresent())
+ res = generateToscaPerComponent(fixedIds, c);
+ } else
+ res = generateToscaPerComponent(fixedIds, c);
+ if (res) {
+ ToscaElement topologyTemplate = ModelConverter.convertToToscaElement(c);
+ Map<String, ArtifactDataDefinition> arifacts = topologyTemplate.getToscaArtifacts();
+ res = fixDataOnGraph(c.getUniqueId(), VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS,
+ arifacts);
+ titanDao.commit();
+ } else {
+ failedList.add(c);
+ }
+
+ }
+ }
+ log.debug("Migration1707ArtifactUuidFix generateAndSaveToscaArtifacts finished with res {} ", res);
+ return res;
+ }
+
+ private boolean generateToscaPerComponent(Set<String> fixedIds, Component c) {
+ boolean res = true;
+ log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent started component name {} id {}",
+ c.getName(), c.getUniqueId());
+ try {
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaFullElement(c.getUniqueId());
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch resources {} {}", c.getUniqueId(), toscaElement.right().value());
+ return false;
+ }
+ Component toscaElementFull = toscaElement.left().value();
+ toscaElementFull.setGroups(c.getGroups());
+ List<ComponentInstance> ciListFull = toscaElementFull.getComponentInstances();
+ List<ComponentInstance> ciList = c.getComponentInstances();
+ if (ciListFull != null && !ciListFull.isEmpty()) {
+ ciListFull.forEach(ciFull -> {
+ ComponentInstance compInst = ciList.stream()
+ .filter(ci -> ci.getUniqueId().equals(ciFull.getUniqueId())).findAny().get();
+ ciFull.setGroupInstances(compInst.getGroupInstances());
+ });
+ }
+
+ Either<Component, ToscaError> either = generateToscaArtifact(toscaElementFull);
+
+ if (either.isRight()) {
+ log.error("Couldn't generate and save tosca template component unique id {}, name {} error: {}",
+ toscaElementFull.getUniqueId(), toscaElementFull.getName(), either.right().value());
+ res = false;
+
+ }
+
+ if (res) {
+ c.setToscaArtifacts(either.left().value().getToscaArtifacts());
+ fixedIds.add(toscaElementFull.getUniqueId());
+ }
+ } finally {
+ if (res)
+ titanDao.commit();
+ else
+ titanDao.rollback();
+ }
+ log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent finished component name {} id {} res {}",
+ c.getName(), c.getUniqueId(), res);
+ return res;
+ }
+
+ private <T extends ToscaDataDefinition> boolean fixDataOnGraph(String componentId, VertexTypeEnum vertexTypeEnum,
+ EdgeLabelEnum edgeLabelEnum, Map<String, T> groups) {
+ log.debug("amount groups to update: VertexTypeEnum {} EdgeLabelEnum {} data size {}", vertexTypeEnum.getName(),
+ edgeLabelEnum, groups.size());
+ boolean res = true;
+ Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentId,
+ JsonParseFlagEnum.NoParse);
+ if (getResponse.isRight()) {
+ log.debug("Couldn't fetch component unique id {}, error: {}", componentId, getResponse.right().value());
+ res = false;
+
+ }
+ if (res) {
+ GraphVertex componentVertex = getResponse.left().value();
+
+ GraphVertex toscaDataVertex = null;
+ Either<GraphVertex, TitanOperationStatus> groupVertexEither = titanDao.getChildVertex(componentVertex,
+ edgeLabelEnum, JsonParseFlagEnum.ParseJson);
+ if (groupVertexEither.isRight() && groupVertexEither.right().value() == TitanOperationStatus.NOT_FOUND) {
+ log.debug("no child {} vertex for component unique id {}, error: {}", edgeLabelEnum, componentId,
+ groupVertexEither.right().value());
+ return true;
+ }
+ if (groupVertexEither.isRight()) {
+ res = false;
+ log.debug("failed to get child {} vertex for component unique id {}, error: {}", edgeLabelEnum,
+ componentId, groupVertexEither.right().value());
+ }
+ if (res) {
+ toscaDataVertex = groupVertexEither.left().value();
+ toscaDataVertex.setJson(groups);
+ Either<GraphVertex, TitanOperationStatus> updatevertexEither = titanDao.updateVertex(toscaDataVertex);
+ if (updatevertexEither.isRight()) {
+ log.debug("failed to update vertex for component unique id {}, error: {}", componentId,
+ updatevertexEither.right().value());
+ titanDao.rollback();
+ return false;
+ }
+ }
+ }
+ log.debug("Fix data on graph finished: VertexTypeEnum {} EdgeLabelEnum {} res {}", vertexTypeEnum.getName(),
+ res);
+ return res;
+ }
+
+ private boolean fixServices(List<Service> serviceList) {
+ for (Service service : serviceList) {
+ log.debug("Migration1707ArtifactUuidFix fix service: id {}, name {} ", service.getUniqueId(),
+ service.getName());
+ List<ComponentInstance> instances = service.getComponentInstances();
+ for (ComponentInstance instance : instances) {
+ fixComponentInstances(service, instance);
+ }
+
+ }
+ return true;
+
+ }
+
+ private void fixComponentInstances(Service service, ComponentInstance instance) {
+ Map<String, ArtifactDefinition> artifactsMap = instance.getDeploymentArtifacts();
+ List<GroupInstance> groupsList = instance.getGroupInstances();
+ if (groupsList != null && artifactsMap != null) {
+ List<GroupInstance> groupsToDelete = new ArrayList<>();
+ for (GroupInstance group : groupsList) {
+ fixGroupInstances(service, artifactsMap, groupsToDelete, group);
+
+ }
+
+ if (!groupsToDelete.isEmpty()) {
+ log.debug("Migration1707ArtifactUuidFix delete group: resource id {}, group instance to delete {} ",
+ service.getUniqueId(), groupsToDelete);
+ groupsList.removeAll(groupsToDelete);
+
+ }
+
+ Optional<ArtifactDefinition> optionalVfModuleArtifact = artifactsMap.values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
+ ArtifactDefinition vfModuleAertifact = null;
+ if(!optionalVfModuleArtifact.isPresent()){
+ vfModuleAertifact = createVfModuleArtifact(instance, service);
+ artifactsMap.put(vfModuleAertifact.getArtifactLabel(), vfModuleAertifact);
+ }
+ else {
+ vfModuleAertifact = optionalVfModuleArtifact.get();
+ }
+ fillVfModuleInstHeatEnvPayload(service, instance, groupsList, vfModuleAertifact);
+ }
+ }
+
+ private void fixGroupInstances(Service service, Map<String, ArtifactDefinition> artifactsMap,
+ List<GroupInstance> groupsToDelete, GroupInstance group) {
+ if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ log.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", service.getUniqueId(),
+ group.getName());
+ if(group.getArtifacts() != null){
+ Set<String> groupArtifactsSet = new HashSet<>(group.getArtifacts());
+ if(group.getGroupInstanceArtifacts() != null){
+ List<String> groupInsArtifacts = new ArrayList<>(group.getGroupInstanceArtifacts());
+ groupArtifactsSet.addAll(groupInsArtifacts);
+ }
+ List<String> groupArtifacts = new ArrayList<>(groupArtifactsSet);
+
+ clearGroupInstanceArtifacts(group);
+
+ for (String artifactId : groupArtifacts) {
+ fixArtifactUndergroupInstances(artifactsMap, group, groupArtifacts, artifactId);
+ }
+ }
+ if (group.getArtifacts() == null || group.getArtifacts().isEmpty()) {
+ log.debug(
+ "Migration1707ArtifactUuidFix fix groupInstance add to delete list: resource id {} name {} , group name {} ",
+ service.getUniqueId(), service.getName(), group.getName());
+ groupsToDelete.add(group);
+ }
+ }
+ }
+
+ private void clearGroupInstanceArtifacts(GroupInstance group) {
+ if(group.getArtifacts() != null)
+ group.getArtifacts().clear();
+ else
+ group.setArtifacts(new ArrayList<>());
+ if(group.getArtifactsUuid() != null)
+ group.getArtifactsUuid().clear();
+ else{
+ group.setArtifactsUuid(new ArrayList<>());
+ }
+ if(group.getGroupInstanceArtifacts() != null)
+ group.getGroupInstanceArtifacts().clear();
+ else{
+ group.setGroupInstanceArtifacts(new ArrayList<>());
+ }
+ if(group.getGroupInstanceArtifactsUuid() != null )
+ group.getGroupInstanceArtifactsUuid().clear();
+ else
+ group.setGroupInstanceArtifactsUuid(new ArrayList<>());
+ }
+
+ private void fixArtifactUndergroupInstances(Map<String, ArtifactDefinition> artifactsMap, GroupInstance group,
+ List<String> groupArtifacts, String artifactId) {
+ String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
+ log.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ",
+ group.getName(), artifactId, artifactlabel);
+ if (!artifactlabel.isEmpty() && artifactsMap.containsKey(artifactlabel)) {
+ ArtifactDefinition artifact = artifactsMap.get(artifactlabel);
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ String correctArtifactId = artifact.getUniqueId();
+ String correctArtifactUUID = artifact.getArtifactUUID();
+ if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
+ boolean isAddToGroup = true;
+ if (groupArtifacts.size() == 1) {
+ if (artifactType == ArtifactTypeEnum.HEAT_ARTIFACT) {
+ isAddToGroup = false;
+ artifact.setArtifactType(ArtifactTypeEnum.OTHER.getType());
+ }
+ }
+ if (isAddToGroup) {
+ log.debug(
+ "Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ",
+ group.getName(), correctArtifactId, correctArtifactUUID);
+ group.getArtifacts().add(correctArtifactId);
+ if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
+ group.getArtifactsUuid().add(correctArtifactUUID);
+ }
+ }
+ } else {
+ log.debug(
+ "Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ",
+ group.getName(), correctArtifactId, correctArtifactUUID);
+ Set<String> tmpSet = new HashSet<>(group.getGroupInstanceArtifacts());
+ tmpSet.add(correctArtifactId);
+ group.setGroupInstanceArtifacts(new ArrayList<>(tmpSet));
+ if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
+ Set<String> tmpSetUUID = new HashSet<>(group.getGroupInstanceArtifactsUuid());
+ tmpSetUUID.add(correctArtifactUUID);
+ group.setGroupInstanceArtifactsUuid(new ArrayList<>(tmpSetUUID));
+ }
+ }
+ }
+ }
+
+ private boolean fixVf(List<Resource> vfLst) {
+ for (Resource resource : vfLst) {
+ log.debug("Migration1707ArtifactUuidFix fix resource: id {}, name {} ", resource.getUniqueId(),
+ resource.getName());
+ Map<String, ArtifactDefinition> artifactsMap = resource.getDeploymentArtifacts();
+ List<GroupDefinition> groupsList = resource.getGroups();
+ List<GroupDefinition> groupsToDelete = new ArrayList<>();
+ if (groupsList != null && artifactsMap != null) {
+ for (GroupDefinition group : groupsList) {
+ if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && group.getArtifacts() != null) {
+ fixVfGroup(resource, artifactsMap, group);
+ }
+ if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)
+ && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
+ log.debug(
+ "Migration1707ArtifactUuidFix add group to delete list fix resource: id {}, name {} ",
+ resource.getUniqueId(), resource.getName(), group.getName());
+ groupsToDelete.add(group);
+ }
+ }
+
+ if (!groupsToDelete.isEmpty()) {
+ groupsList.removeAll(groupsToDelete);
+
+ }
+ }
+
+ }
+
+ return true;
+ }
+
+ private void fixVfGroup(Resource resource, Map<String, ArtifactDefinition> artifactsMap, GroupDefinition group) {
+ log.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", resource.getUniqueId(),
+ group.getName());
+ Set<String> groupArtifactsSet = new HashSet<>(group.getArtifacts());
+ List<String> groupArtifacts = new ArrayList<>(groupArtifactsSet);
+ group.getArtifacts().clear();
+ group.getArtifactsUuid().clear();
+
+ for (String artifactId : groupArtifacts) {
+ fixArtifactUnderGroup(artifactsMap, group, groupArtifacts, artifactId);
+ }
+ }
+
+ private void fixArtifactUnderGroup(Map<String, ArtifactDefinition> artifactsMap, GroupDefinition group,
+ List<String> groupArtifacts, String artifactId) {
+
+ String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
+ log.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ",
+ group.getName(), artifactId, artifactlabel);
+ if (!artifactlabel.isEmpty() && artifactsMap.containsKey(artifactlabel)) {
+ ArtifactDefinition artifact = artifactsMap.get(artifactlabel);
+ String correctArtifactId = artifact.getUniqueId();
+ String correctArtifactUUID = artifact.getArtifactUUID();
+ boolean isAddToGroup = true;
+ if (groupArtifacts.size() == 1) {
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT_ARTIFACT) {
+ isAddToGroup = false;
+ artifact.setArtifactType(ArtifactTypeEnum.OTHER.getType());
+ }
+ }
+ if (isAddToGroup) {
+ log.debug(
+ "Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ",
+ group.getName(), correctArtifactId, correctArtifactUUID);
+ group.getArtifacts().add(correctArtifactId);
+ if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
+ group.getArtifactsUuid().add(correctArtifactUUID);
+ }
+ }
+
+ }
+ }
+
+ private String findArtifactLabelFromArtifactId(String artifactId) {
+ String artifactLabel = "";
+
+ int index = artifactId.lastIndexOf('.');
+ if (index > 0 && index + 1 < artifactId.length())
+ artifactLabel = artifactId.substring(index + 1);
+ return artifactLabel;
+ }
+
+ private void writeModuleResultToFile(Writer writer, org.openecomp.sdc.be.model.Component component,
+ Service service) {
+ try {
+ // "service name, service id, state, version
+ StringBuilder sb = new StringBuilder(component.getName());
+ sb.append(",").append(component.getUniqueId()).append(",").append(component.getLifecycleState()).append(",")
+ .append(component.getVersion());
+ if (service != null) {
+ sb.append(",").append(service.getName());
+ }
+ sb.append("\n");
+ writer.write(sb.toString());
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ }
+
+ private void writeModuleResultToFile(Writer writer, List<Component> components) {
+ try {
+ // "service name, service id, state, version
+ for (Component component : components) {
+ StringBuilder sb = new StringBuilder(component.getName());
+ sb.append(",").append(component.getUniqueId()).append(",").append(component.getInvariantUUID())
+ .append(",").append(component.getLifecycleState()).append(",").append(component.getVersion());
+
+ sb.append("\n");
+ writer.write(sb.toString());
+ }
+ } catch (IOException e) {
+
+ log.error(e.getMessage());
+ }
+ }
+
+ public boolean doFixTosca(Map<String, List<Component>> nodeToFix, Map<String, List<Component>> vfToFix,
+ Map<String, List<Component>> serviceToFix) {
+
+ Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ Map<String, List<Component>> vertices = getVerticesToValidate(VertexTypeEnum.NODE_TYPE, hasProps);
+ boolean result = validateTosca(vertices, nodeToFix, "RESOURCE_TOSCA_ARTIFACTS");//
+
+ hasProps.clear();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF);
+ hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ vertices = getVerticesToValidate(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps);
+ result = validateTosca(vertices, vfToFix, "VF_TOSCA_ARTIFACTS");
+
+ hasProps.clear();
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ vertices = getVerticesToValidate(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps);
+ result = validateTosca(vertices, serviceToFix, "SERVICE_TOSCA_ARTIFACTS");
+
+ return result;
+ }
+
+ public Map<String, List<Component>> getVerticesToValidate(VertexTypeEnum type,
+ Map<GraphPropertyEnum, Object> hasProps) {
+
+ Map<String, List<Component>> result = new HashMap<>();
+ try {
+
+ Either<List<GraphVertex>, TitanOperationStatus> resultsEither = titanDao.getByCriteria(type, hasProps);
+ if (resultsEither.isRight()) {
+ log.error("getVerticesToValidate failed {} ",resultsEither.right().value());
+ return result;
+ }
+ log.info("getVerticesToValidate: {} vertices to scan", resultsEither.left().value().size());
+ List<GraphVertex> componentsList = resultsEither.left().value();
+ componentsList.forEach(vertex -> {
+ String ivariantUuid = (String) vertex.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID);
+ if (!result.containsKey(ivariantUuid)) {
+ List<Component> compList = new ArrayList<Component>();
+ result.put(ivariantUuid, compList);
+ }
+ List<Component> compList = result.get(ivariantUuid);
+
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreArtifacts(false);
+
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaElement(vertex.getUniqueId(), filter);
+ if (toscaElement.isRight()) {
+ log.error("getVerticesToValidate: failed to find element {} staus is {}", vertex.getUniqueId()
+ ,toscaElement.right().value());
+ } else {
+ compList.add(toscaElement.left().value());
+ }
+ titanDao.commit();
+
+ });
+
+ } catch (Exception e) {
+ log.info("Failed to fetch vf resources ", e);
+
+ } finally {
+ titanDao.commit();
+
+ }
+ return result;
+ }
+
+ public boolean validateTosca(Map<String, List<Component>> vertices, Map<String, List<Component>> compToFix,
+ String name) {
+ boolean result = true;
+ long time = System.currentTimeMillis();
+ String fileName = name + "_" + time + ".csv";
+ Writer writer = null;
+ try {
+ writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
+ writer.write("name, UUID, invariantUUID, state, version\n");
+ for (Map.Entry<String, List<Component>> entry : vertices.entrySet()) {
+ List<Component> compList = entry.getValue();
+ Set<String> artifactEsId = new HashSet<>();
+ for (Component component : compList) {
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ Optional<ArtifactDefinition> op = toscaArtifacts.values().stream()
+ .filter(a -> artifactEsId.contains(a.getEsId()) && a.getEsId() != null).findAny();
+ if (op.isPresent()) {
+ result = false;
+ writeModuleResultToFile(writer, compList);
+ writer.flush();
+ break;
+ } else {
+ artifactEsId.addAll(toscaArtifacts.values().stream().map(ArtifactDefinition::getEsId)
+ .collect(Collectors.toList()));
+ }
+ }
+ if (!result) {
+ List<Component> compListfull = new ArrayList<>();
+ for (Component c : compList) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreArtifacts(false);
+ filter.setIgnoreGroups(false);
+
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
+ .getToscaElement(c.getUniqueId(), filter);
+ if (toscaElement.isRight()) {
+ System.out.println("getVerticesToValidate: failed to find element" + c.getUniqueId()
+ + " staus is" + toscaElement.right().value());
+ } else {
+ compListfull.add(toscaElement.left().value());
+ }
+ this.titanDao.commit();
+ }
+
+ compToFix.put(entry.getKey(), compListfull);
+ result = true;
+ }
+
+ }
+
+ } catch (Exception e) {
+ log.info("Failed to fetch vf resources ", e);
+ return false;
+ } finally {
+ titanDao.commit();
+ try {
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ /* ignore */}
+ }
+ return result;
+ }
+
+ private Either<Component, ToscaError> generateToscaArtifact(Component parent) {
+ log.debug("tosca artifact generation");
+ try {
+ Map<String, ArtifactDefinition> toscaArtifacts = parent.getToscaArtifacts();
+
+ ArtifactDefinition toscaArtifact = null;
+ Optional<ArtifactDefinition> op = toscaArtifacts.values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
+
+ if (op.isPresent()) {
+ toscaArtifact = op.get();
+ }
+ if (toscaArtifact != null) {
+ log.debug("Migration1707ArtifactUuidFix generateToscaPerComponent artifact name {} id {} esId {}",
+ toscaArtifact.getArtifactName(), toscaArtifact.getUniqueId(), toscaArtifact.getEsId());
+
+ Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
+ if (exportComponent.isRight()) {
+ log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(),
+ exportComponent.right().value());
+
+ return Either.right(exportComponent.right().value());
+ }
+ log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
+ String payload = exportComponent.left().value().getMainYaml();
+
+ toscaArtifact.setPayloadData(payload);
+ byte[] decodedPayload = toscaArtifact.getPayloadData();
+
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(parent.getUniqueId(),
+ toscaArtifact.getArtifactLabel());
+ toscaArtifact.setUniqueId(uniqueId);
+ toscaArtifact.setEsId(toscaArtifact.getUniqueId());
+
+ toscaArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
+ ESArtifactData artifactData = new ESArtifactData(toscaArtifact.getEsId(), decodedPayload);
+ artifactCassandraDao.saveArtifact(artifactData);
+
+ log.debug("Tosca yaml artifact esId {} ", toscaArtifact.getEsId());
+ }
+ ArtifactDefinition csarArtifact = null;
+ op = toscaArtifacts.values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
+
+ if (op.isPresent()) {
+ csarArtifact = op.get();
+ }
+
+ if (csarArtifact != null) {
+ Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, true, true);
+
+ if (generated.isRight()) {
+ log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(),
+ generated.right().value());
+
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+ byte[] value = generated.left().value();
+ csarArtifact.setPayload(value);
+ byte[] decodedPayload = csarArtifact.getPayloadData();
+
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(parent.getUniqueId(),
+ csarArtifact.getArtifactLabel());
+ csarArtifact.setUniqueId(uniqueId);
+ csarArtifact.setEsId(csarArtifact.getUniqueId());
+
+ csarArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
+ ESArtifactData artifactData = new ESArtifactData(csarArtifact.getEsId(), decodedPayload);
+ artifactCassandraDao.saveArtifact(artifactData);
+ log.debug("Tosca csar artifact esId {} ", csarArtifact.getEsId());
+
+ }
+
+ } catch (Exception ex) {
+ log.error("Failed to generate tosca atifact component id {} component name {} error {}",
+ parent.getUniqueId(), parent.getName(), ex.getMessage());
+
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+
+ return Either.left(parent);
+ }
+
+ private ArtifactDefinition createVfModuleArtifact(ComponentInstance currVF, Service service) {
+
+ ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
+ String newCheckSum = null;
+
+ vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
+ vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
+ vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
+ vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
+ vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata");
+ vfModuleArtifactDefinition.setTimeout(0);
+ vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
+
+ return vfModuleArtifactDefinition;
+ }
+
+
+ private void fillVfModuleInstHeatEnvPayload(Component parent, ComponentInstance instance, List<GroupInstance> groupsForCurrVF,
+ ArtifactDefinition vfModuleArtifact) {
+ log.debug("generate new vf module for component. name {}, id {}, Version {}", instance.getName(), instance.getUniqueId());
+
+ String uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(parent.getUniqueId(), instance.getUniqueId(), vfModuleArtifact.getArtifactLabel());
+
+ vfModuleArtifact.setUniqueId(uniqueId);
+ vfModuleArtifact.setEsId(vfModuleArtifact.getUniqueId());
+
+ List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<>();
+ if (groupsForCurrVF != null) {
+ for (GroupInstance groupInstance : groupsForCurrVF) {
+ VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
+ vfModulePayloadForCurrVF.add(modulePayload);
+ }
+ Collections.sort(vfModulePayloadForCurrVF,
+ (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
+
+ final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
+ log.debug("vfModulePayloadString {}", vfModulePayloadString);
+ if (vfModulePayloadString != null) {
+ String newCheckSum = GeneralUtility
+ .calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes());
+ vfModuleArtifact.setArtifactChecksum(newCheckSum);
+
+ ESArtifactData artifactData = new ESArtifactData(vfModuleArtifact.getEsId(),
+ vfModulePayloadString.getBytes());
+ artifactCassandraDao.saveArtifact(artifactData);
+
+ }
+
+ }
+
+ }
+
+ private Either<List<VfModuleArtifactPayloadEx>, StorageOperationStatus> parseVFModuleJson(ArtifactDefinition vfModuleArtifact) {
+ log.info("Try to get vfModule json from cassandra {}", vfModuleArtifact.getEsId());
+ Either<ESArtifactData, CassandraOperationStatus> vfModuleData = artifactCassandraDao.getArtifact(vfModuleArtifact.getEsId());
+
+ if (vfModuleData.isRight()) {
+ CassandraOperationStatus resourceUploadStatus = vfModuleData.right().value();
+ StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
+ log.error("failed to fetch vfModule json {} from cassandra. Status is {}", vfModuleArtifact.getEsId(), storageResponse);
+ return Either.right(storageResponse);
+
+ }
+
+ ESArtifactData esArtifactData = vfModuleData.left().value();
+ String gsonData = new String( esArtifactData.getDataAsArray());
+ final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ JsonArray jsonElement = new JsonArray();
+ jsonElement = gson.fromJson(gsonData, jsonElement.getClass());
+ List<VfModuleArtifactPayloadEx> vfModules = new ArrayList<>();
+ jsonElement.forEach(je ->{
+ VfModuleArtifactPayloadEx vfModule = ComponentsUtils.parseJsonToObject(je.toString(), VfModuleArtifactPayloadEx.class);
+ vfModules.add(vfModule);
+ });
+
+ log.debug ("parse vf module finish {}", gsonData);
+ return Either.left(vfModules);
+
+ }
+
+ /*public boolean manualFix() {
+
+ Set<String> fixedIds = new HashSet<>();
+ Component component;
+ String componentId = "86683566-20e8-4cc5-872d-12abca1d57f0";//"9f6a6976-18e3-488a-98a4-c1aade480739";
+ Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(componentId);
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch resources {} {}", componentId, toscaElement.right().value());
+
+ }
+ boolean res = generateToscaPerComponent(fixedIds, toscaElement.left().value());
+ log.info("Fix component return res {} ", res);
+ titanDao.commit();
+
+ return res;
+ }
+
+
+ public boolean manualCheck() {
+
+ Set<String> fixedIds = new HashSet<>();
+ Component component;
+ String componentId = "86d50186-7b00-4bfc-abcb-9e4c6892f338";//"9f6a6976-18e3-488a-98a4-c1aade480739";
+ Either<Service, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(componentId);
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch resources {} {}", componentId, toscaElement.right().value());
+
+ }
+ boolean res = true;
+ try {
+ res = isProblematicService(toscaElement.left().value(), toscaElement.left().value().getName());
+ if(res){
+ List<Service> services = new ArrayList<>();
+ services.add(toscaElement.left().value());
+ this.fix(new ArrayList<Resource>(), services, null, null, null);
+
+ Either<Service, StorageOperationStatus> toscaElementNew = toscaOperationFacade.getToscaFullElement(componentId);
+ if (toscaElement.isRight()) {
+ log.info("Failed to fetch resources {} {}", componentId, toscaElementNew.right().value());
+
+ }
+ res = isProblematicService(toscaElementNew.left().value(), toscaElementNew.left().value().getName());
+ }
+ titanDao.commit();
+
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ log.info("Fix component return res {} ", res);
+
+ return res;
+}*/
}
+
+
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java
index 7ed8b17907..502ddd1981 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/ProductLogic.java
@@ -44,23 +44,18 @@ public class ProductLogic {
public boolean deleteAllProducts(String titanFile, String beHost, String bePort, String adminUser) {
log.debug("retrieving all products from graph");
RestUtils restUtils = null;
- try {
- List<String> productList = getAllProducts(titanFile);
- restUtils = new RestUtils();
- if (productList != null) {
- for (String productUid : productList) {
- Integer status = restUtils.deleteProduct(productUid, beHost, bePort, adminUser);
- }
- return true;
- } else {
- log.error("failed to get products from graph");
- return false;
- }
- } finally {
- if (restUtils != null) {
- restUtils.closeClient();
- }
- }
+ List<String> productList = getAllProducts(titanFile);
+ restUtils = new RestUtils();
+ if (productList != null) {
+ for (String productUid : productList) {
+ restUtils.deleteProduct(productUid, beHost, bePort, adminUser);
+ }
+ return true;
+ }
+ else {
+ log.error("failed to get products from graph");
+ return false;
+ }
}
private List<String> getAllProducts(String titanFile) {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/RestUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/RestUtils.java
index 355780cfc6..50781f25c2 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/RestUtils.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/RestUtils.java
@@ -20,13 +20,11 @@
package org.openecomp.sdc.asdctool.impl;
-import java.io.IOException;
+import java.util.Properties;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpDelete;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
+import org.apache.http.HttpStatus;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,48 +33,33 @@ import org.slf4j.LoggerFactory;
*/
public class RestUtils {
- final String DELETE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s";
- final Integer DELETE_SUCCSES_RESPONSE = 200;
+ final static String DELETE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s";
private static Logger log = LoggerFactory.getLogger(RestUtils.class.getName());
- CloseableHttpClient httpClient;
public RestUtils() {
- this.httpClient = HttpClients.createDefault();
- }
-
- private CloseableHttpResponse exacuteRequest(HttpUriRequest httpRequest) throws IOException {
- log.debug("received http request: {}", httpRequest.toString());
- return httpClient.execute(httpRequest);
- }
-
- public void closeClient() {
- log.debug("closing http client");
- try {
- this.httpClient.close();
- log.debug("closed http client");
- } catch (IOException e) {
- log.debug("close http client failed", e);
-
- }
}
public Integer deleteProduct(String productUid, String beHost, String bePort, String adminUser) {
String url = String.format(DELETE_PRODUCT, beHost, bePort, productUid);
- HttpDelete deleteRequest = new HttpDelete(url);
- deleteRequest.setHeader("USER_ID", adminUser);
- try (CloseableHttpResponse response = this.httpClient.execute(deleteRequest)) {
- int status = response.getStatusLine().getStatusCode();
- if (DELETE_SUCCSES_RESPONSE.equals(status)) {
- log.debug("Product uid:{} succsesfully deleted", productUid);
- } else {
- log.error("Product uid:{} delete failed status {}", productUid, status);
- }
- return status;
- } catch (IOException e) {
- log.error("Product uid:{} delete failed with exception",productUid, e);
+
+ Properties headers = new Properties();
+ headers.put("USER_ID", adminUser);
+ try {
+ HttpResponse<String> httpResponse = HttpRequest.delete(url, headers);
+ int status = httpResponse.getStatusCode();
+ if (status == HttpStatus.SC_OK) {
+ log.debug("Product uid:{} succsesfully deleted", productUid);
+ }
+ else {
+ log.error("Product uid:{} delete failed status {}", productUid, status);
+ }
+ return status;
+ }
+ catch(Exception e) {
+ log.error("Product uid:{} delete failed with exception",productUid, e);
}
- return null;
+ return null;
}
}
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 11d52023f8..ae226f1a82 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
@@ -28,9 +28,12 @@ import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.resources.data.UserData;
import org.slf4j.Logger;
@@ -50,7 +53,6 @@ public class TitanGraphInitializer {
private static Logger logger = LoggerFactory.getLogger(TitanGraphInitializer.class.getName());
private static TitanGraph graph;
-
public static boolean createGraph(String titanCfgFile) {
logger.info("** createGraph with {}", titanCfgFile);
try {
@@ -64,9 +66,9 @@ public class TitanGraphInitializer {
logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e);
return false;
}
-
+
createIndexesAndDefaults();
-
+
logger.info("** Titan graph created ");
return true;
@@ -100,13 +102,13 @@ public class TitanGraphInitializer {
checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
Map<String, Object> properties = null;
if (!isVertexExist(checkedProperties)) {
- Vertex vertex = graph.addVertex();
- vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
- properties = user.toGraphMap();
- for (Map.Entry<String, Object> entry : properties.entrySet()) {
- vertex.property(entry.getKey(), entry.getValue());
- }
- }
+ Vertex vertex = graph.addVertex();
+ vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
+ properties = user.toGraphMap();
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
}
private static UserData getDefaultUserAdmin() {
@@ -123,7 +125,6 @@ public class TitanGraphInitializer {
return userData;
}
-
private static void createVertexIndixes() {
logger.info("** createVertexIndixes started");
@@ -186,5 +187,13 @@ public class TitanGraphInitializer {
createVertexIndixes();
createEdgeIndixes();
createDefaultAdminUser();
+ createRootCatalogVertex();
+ }
+
+ private static void createRootCatalogVertex() {
+ Vertex vertex = graph.addVertex();
+ vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId());
+ vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName());
+ graph.tx().commit();
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/ArtifactToolBL.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/ArtifactToolBL.java
index 556d7e0eee..341a56f68a 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/ArtifactToolBL.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/ArtifactToolBL.java
@@ -2,6 +2,7 @@ package org.openecomp.sdc.asdctool.impl.validator;
import java.util.List;
+import org.openecomp.sdc.asdctool.impl.validator.executers.ArtifactValidatorExecuter;
import org.openecomp.sdc.asdctool.impl.validator.executers.IArtifactValidatorExecuter;
import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager;
import org.slf4j.Logger;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java
index 63e95d568b..64d6bc1bde 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java
@@ -10,6 +10,10 @@ import org.openecomp.sdc.asdctool.impl.validator.executers.VfValidatorExecuter;
import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.ArtifactValidationUtils;
import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.ServiceArtifactValidationTask;
import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.VfArtifactValidationTask;
+import org.openecomp.sdc.asdctool.impl.validator.executers.NodeToscaArtifactsValidatorExecuter;
+import org.openecomp.sdc.asdctool.impl.validator.executers.ServiceToscaArtifactsValidatorExecutor;
+import org.openecomp.sdc.asdctool.impl.validator.executers.VFToscaArtifactValidatorExecutor;
+import org.openecomp.sdc.asdctool.impl.validator.ArtifactToolBL;
import org.openecomp.sdc.asdctool.impl.validator.tasks.moduleJson.ModuleJsonTask;
import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager;
import org.openecomp.sdc.be.dao.DAOTitanStrategy;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java
index 7f85d9d972..ceab832c0b 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ArtifactValidatorExecuter.java
@@ -22,14 +22,16 @@ import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
public class ArtifactValidatorExecuter {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/IArtifactValidatorExecuter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/IArtifactValidatorExecuter.java
index 6f9405f992..30bfab146a 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/IArtifactValidatorExecuter.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/IArtifactValidatorExecuter.java
@@ -1,5 +1,14 @@
package org.openecomp.sdc.asdctool.impl.validator.executers;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.asdctool.impl.validator.tasks.TopologyTemplateValidationTask;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+
public interface IArtifactValidatorExecuter {
boolean executeValidations();
String getName();
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/NodeToscaArtifactsValidatorExecuter.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/NodeToscaArtifactsValidatorExecuter.java
index 6715c8a955..c0a2589426 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/NodeToscaArtifactsValidatorExecuter.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/NodeToscaArtifactsValidatorExecuter.java
@@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ServiceToscaArtifactsValidatorExecutor.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ServiceToscaArtifactsValidatorExecutor.java
index 2fe5abef3c..1dd1779398 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ServiceToscaArtifactsValidatorExecutor.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/ServiceToscaArtifactsValidatorExecutor.java
@@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/VFToscaArtifactValidatorExecutor.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/VFToscaArtifactValidatorExecutor.java
index bc22f2e424..69be96c6d3 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/VFToscaArtifactValidatorExecutor.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/VFToscaArtifactValidatorExecutor.java
@@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VfModuleArtifactPayloadEx.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VfModuleArtifactPayloadEx.java
new file mode 100644
index 0000000000..398ce6b2ce
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VfModuleArtifactPayloadEx.java
@@ -0,0 +1,92 @@
+package org.openecomp.sdc.asdctool.impl.validator.utils;
+
+import java.util.List;
+import java.util.Map;
+
+
+
+public class VfModuleArtifactPayloadEx {
+
+ private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription;
+ private Boolean isBase;
+ private List<String> artifacts;
+ private Map< String, Object> properties;
+
+
+
+ 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 getVfModuleModelVersion() {
+ return vfModuleModelVersion;
+ }
+
+ public void setVfModuleModelVersion(String vfModuleModelVersion) {
+ this.vfModuleModelVersion = vfModuleModelVersion;
+ }
+
+ public String getVfModuleModelUUID() {
+ return vfModuleModelUUID;
+ }
+
+ public void setVfModuleModelUUID(String vfModuleModelUUID) {
+ this.vfModuleModelUUID = vfModuleModelUUID;
+ }
+
+ public String getVfModuleModelCustomizationUUID() {
+ return vfModuleModelCustomizationUUID;
+ }
+
+ public void setVfModuleModelCustomizationUUID(String vfModuleModelCustomizationUUID) {
+ this.vfModuleModelCustomizationUUID = vfModuleModelCustomizationUUID;
+ }
+
+ public String getVfModuleModelDescription() {
+ return vfModuleModelDescription;
+ }
+
+ public void setVfModuleModelDescription(String vfModuleModelDescription) {
+ this.vfModuleModelDescription = vfModuleModelDescription;
+ }
+
+ public Boolean getIsBase() {
+ return isBase;
+ }
+
+ public void setIsBase(Boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public List<String> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<String> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
+
+
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactUUIDFixMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactUUIDFixMenu.java
index 5ca8e55412..a2e59464c0 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactUUIDFixMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactUUIDFixMenu.java
@@ -27,14 +27,7 @@ public class ArtifactUUIDFixMenu {
boolean isSuccessful = artifactUuidFix.doFix(fixServices, runMode);
if (isSuccessful) {
log.info("Fixing artifacts UUID for 1707 was finished successfully");
- /* isSuccessful = artifactUuidFix.doFixTosca(fixTosca, fixServices, runMode);
- if (isSuccessful) {
- log.info("Fixing tosca artifacts was finished successfully");
- isSuccessful = artifactUuidFix.doFixTosca(fixTosca, fixServices, runMode);
- } else{
- log.info("Fixing tosca artifacts has failed");
- System.exit(2);
- }*/
+
} else{
log.info("Fixing artifacts UUID for 1707 has failed");
System.exit(2);
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactValidatorTool.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactValidatorTool.java
index f7e8f1fa8b..5ae543cb73 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactValidatorTool.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ArtifactValidatorTool.java
@@ -3,6 +3,7 @@ package org.openecomp.sdc.asdctool.main;
import org.openecomp.sdc.asdctool.impl.validator.ArtifactToolBL;
import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
import org.openecomp.sdc.asdctool.impl.validator.config.ValidationToolConfiguration;
+import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/GetConsumersMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/GetConsumersMenu.java
new file mode 100644
index 0000000000..189348acc6
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/GetConsumersMenu.java
@@ -0,0 +1,57 @@
+package org.openecomp.sdc.asdctool.main;
+
+import fj.data.Either;
+import org.openecomp.sdc.asdctool.cli.CLIToolData;
+import org.openecomp.sdc.asdctool.cli.SpringCLITool;
+import org.openecomp.sdc.asdctool.configuration.GetConsumersConfiguration;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+public class GetConsumersMenu extends SpringCLITool {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(GetConsumersMenu.class);
+
+ public static void main(String[] args) {
+ GetConsumersMenu getConsumersMenu = new GetConsumersMenu();
+ CLIToolData cliToolData = getConsumersMenu.init(args);
+ ConsumerOperation consumersService = cliToolData.getSpringApplicationContext().getBean(ConsumerOperation.class);
+ printConsumers(getConsumersMenu, consumersService);
+ }
+
+ private static void printConsumers(GetConsumersMenu getConsumersMenu, ConsumerOperation consumersService) {
+ Either<List<ConsumerData>, StorageOperationStatus> allConsumers = consumersService.getAll();
+ allConsumers.left().foreachDoEffect(getConsumersMenu::printConsumers);
+ allConsumers.right().foreachDoEffect(getConsumersMenu::printErr);
+ }
+
+ private void printConsumers(List<ConsumerData> consumers) {
+ System.out.println("SDC consumers: ");
+ consumers.forEach(consumer -> {
+ System.out.println("#########################");
+ System.out.println(consumer);
+ });
+ System.exit(0);
+ }
+
+ private void printErr(StorageOperationStatus err) {
+ String errMsg = String.format("failed to fetch consumers. reason: %s", err);
+ LOGGER.error(errMsg);
+ System.err.print(errMsg);
+ System.exit(1);
+ }
+
+ @Override
+ protected String commandName() {
+ return "get-consumers";
+ }
+
+ @Override
+ protected Class<?> getSpringConfigurationClass() {
+ return GetConsumersConfiguration.class;
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java
index 19651ec45a..f192d87867 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java
@@ -10,55 +10,11 @@ import org.openecomp.sdc.asdctool.migration.dao.MigrationTasksDao;
import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
import org.openecomp.sdc.asdctool.migration.resolver.SpringBeansMigrationResolver;
import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
-import org.openecomp.sdc.be.auditing.impl.AuditingManager;
-import org.openecomp.sdc.be.components.ArtifactsResolver;
-import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
-import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ArtifactResolverImpl;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.CompositionBusinessLogic;
-import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
-import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
-import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic;
-import org.openecomp.sdc.be.components.merge.input.InputsValuesMergingBusinessLogic;
-import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
-import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
-import org.openecomp.sdc.be.dao.DAOTitanStrategy;
-import org.openecomp.sdc.be.dao.TitanClientStrategy;
-import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
-import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.config.CatalogModelSpringConfig;
import org.openecomp.sdc.be.dao.config.DAOSpringConfig;
-import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
-import org.openecomp.sdc.be.dao.impl.AuditingDao;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.cache.ComponentCache;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-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.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.PropertyOperation;
-import org.openecomp.sdc.be.tosca.CsarUtils;
-import org.openecomp.sdc.be.tosca.ToscaExportHandler;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.config.CatalogBESpringConfig;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@@ -67,17 +23,10 @@ import org.springframework.context.annotation.Import;
import org.springframework.core.io.FileSystemResource;
@Configuration
-@Import(DAOSpringConfig.class)
+@Import({DAOSpringConfig.class, CatalogBESpringConfig.class, CatalogModelSpringConfig.class})
@ComponentScan({"org.openecomp.sdc.asdctool.migration.tasks",//migration tasks
- "org.openecomp.sdc.be.model.operations.impl",
- "org.openecomp.sdc.be.model.cache",
- "org.openecomp.sdc.be.dao.titan",
- "org.openecomp.sdc.be.components.validation",
- "org.openecomp.sdc.be.dao.cassandra",
- "org.openecomp.sdc.be.model.jsontitan.operations",
- "org.openecomp.sdc.be.dao.jsongraph",
- "org.openecomp.sdc.be.components.merge",
- "org.openecomp.sdc.be.impl"})
+ "org.openecomp.sdc.asdctool.migration.config.mocks"
+ })
public class MigrationSpringConfig {
@Autowired(required=false)
@@ -106,246 +55,10 @@ public class MigrationSpringConfig {
return new MigrationTasksDao();
}
- @Bean(name = "cassandra-client")
- public CassandraClient cassandraClient() {
- return new CassandraClient();
- }
-
-
- @Bean(name = "dao-titan-strategy")
- public TitanClientStrategy daoStrategy() {
- return new DAOTitanStrategy();
- }
-
- @Bean(name = "titan-dao")
- public TitanDao titanDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) {
- return new TitanDao(titanGraphClient);
- }
-
- @Bean(name = "titan-client", initMethod = "createGraph")
- public TitanGraphClient titanClient(@Qualifier("dao-titan-strategy") TitanClientStrategy titanClientStrategy) {
- return new TitanGraphClient(titanClientStrategy);
- }
-
- @Bean(name = "resource-business-logic")
- public ResourceBusinessLogic resourceBusinessLogic() {
- return new ResourceBusinessLogic();
- }
-
-// @Bean(name = "healthCheckBusinessLogic")
-// public HealthCheckBusinessLogic healthCheckBusinessLogic() {
-// return new HealthCheckBusinessLogic();
-// }
-//
-// @Bean(name = "distribution-engine-cluster-health")
-// public DistributionEngineClusterHealth distributionEngineClusterHealth() {
-// return new DistributionEngineClusterHealth();
-// }
-//
-// @Bean(name = "cassandra-health-check")
-// public CassandraHealthCheck cassandraHealthCheck() {
-// return new CassandraHealthCheck();
-// }
-
-// @Bean(name = "switchover-detector")
-// public SwitchoverDetector switchoverDetector() {
-// return new SwitchoverDetector();
-// }
-
- @Bean(name = "service-business-logic")
- public ServiceBusinessLogic serviceBusinessLogic() {
- return new ServiceBusinessLogic();
- }
-
- @Bean(name = "capability-type-operation")
- public CapabilityTypeOperation CapabilityTypeOperation() {
- return new CapabilityTypeOperation();
- }
-
- @Bean(name = "lifecycle-business-logic")
- public LifecycleBusinessLogic lifecycleBusinessLogic() {
- return new LifecycleBusinessLogic();
- }
-
- @Bean(name = "property-operation")
- public PropertyOperation propertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new PropertyOperation(titanGenericDao);
- }
-
- @Bean(name = "csar-operation")
- public CsarOperation csarOperation() {
- return new CsarOperation();
- }
-
- @Bean(name = "vf-component-instance-business-logic")
- public VFComponentInstanceBusinessLogic vFComponentInstanceBusinessLogic() {
- return new VFComponentInstanceBusinessLogic();
- }
-
- @Bean(name = "resource-import-manager")
- public ResourceImportManager resourceImportManager() {
- return new ResourceImportManager();
- }
-
- @Bean(name = "group-business-logic")
- public GroupBusinessLogic groupBusinessLogic() {
- return new GroupBusinessLogic();
- }
-
- @Bean(name = "inputs-business-logic")
- public InputsBusinessLogic inputsBusinessLogic() {
- return new InputsBusinessLogic();
- }
-
- @Bean(name = "composition-business-logic")
- public CompositionBusinessLogic compositionBusinessLogic() {
- return new CompositionBusinessLogic();
- }
-
- @Bean(name = "artifacts-business-logic")
- public ArtifactsBusinessLogic artifactsBusinessLogic() {
- return new ArtifactsBusinessLogic();
- }
-
- @Bean(name = "component-cache")
- public ComponentCache componentCache() {
- return new ComponentCache();
- }
-
- @Bean(name = "componentUtils")
- public ComponentsUtils componentsUtils() {
- return new ComponentsUtils();
- }
-
- @Bean(name = "user-business-logic")
- public UserBusinessLogic userBusinessLogic() {
- return new UserBusinessLogic();
- }
-
- @Bean(name = "graph-lock-operation")
- public GraphLockOperation graphLockOperation() {
- return new GraphLockOperation();
- }
-
- @Bean(name = "titan-generic-dao")
- public TitanGenericDao titanGenericDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) {
- return new TitanGenericDao(titanGraphClient);
- }
-
- @Bean(name = "element-operation")
- public ElementOperation elementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new ElementOperation(titanGenericDao);
- }
-
- @Bean(name = "group-operation")
- public GroupOperation groupOperation() {
- return new GroupOperation();
- }
-
- @Bean(name = "group-instance-operation")
- public GroupInstanceOperation groupInstanceOperation() {
- return new GroupInstanceOperation();
- }
-
- @Bean(name = "group-type-operation")
- public GroupTypeOperation groupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation") PropertyOperation propertyOperation) {
- return new GroupTypeOperation(titanGenericDao, propertyOperation);
- }
-
- @Bean(name = "tosca-operation-facade")
- public ToscaOperationFacade toscaOperationFacade() {
- return new ToscaOperationFacade();
- }
-
- @Bean(name = "distribution-engine")
- public DistributionEngine distributionEngine() {
- return null;
- }
-
- @Bean(name = "audit-cassandra-dao")
- public AuditCassandraDao auditCassandraDao() {
- return new AuditCassandraDao();
- }
-
- @Bean(name = "service-component-instance-business-logic")
- public ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic() {
- return new ServiceComponentInstanceBusinessLogic();
- }
-
- @Bean("tosca-export-handler")
- public ToscaExportHandler toscaExportHandler() {
- return new ToscaExportHandler();
- }
-
- @Bean(name = "component-instance-operation")
- public ComponentInstanceOperation componentInstanceOperation() {
- return new ComponentInstanceOperation();
- }
-
- @Bean(name = "additional-information-business-logic")
- public AdditionalInformationBusinessLogic additionalInformationBusinessLogic() {
- return new AdditionalInformationBusinessLogic();
- }
-
- @Bean(name = "auditing-manager")
- public AuditingManager auditingManager() {
- return new AuditingManager();
- }
-
- @Bean(name = "auditing-dao")
- public AuditingDao auditingDao() {
- return new AuditingDao();
- }
-
- @Bean(name = "elasticsearch-client", initMethod = "initialize")
- public ElasticSearchClient elasticSearchClient() {
- return new ElasticSearchClient();
- }
-
- @Bean(name = "csar-utils")
- public CsarUtils csarUtils() {
- return new CsarUtils();
- }
-
- @Bean(name = "service-distribution-artifacts-builder")
+ @Bean(name = "serviceDistributionArtifactsBuilder")
public ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder() {
return new ServiceDistributionArtifactsBuilder();
}
-
- @Bean(name = "product-business-logic")
- public ProductBusinessLogic productBusinessLogic() {
- return null;
- }
-
- @Bean(name = "dataDefinitionsValuesMergingBusinessLogic")
- public DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic() {
- return new DataDefinitionsValuesMergingBusinessLogic();
- }
-
- @Bean(name = "artifacts-resolver")
- public ArtifactsResolver artifactsResolver() {
- return new ArtifactResolverImpl();
- }
-
- @Bean(name = "InputsValuesMergingBusinessLogic")
- public InputsValuesMergingBusinessLogic InputsValuesMergingBusinessLogic(){
- return new InputsValuesMergingBusinessLogic();
- }
-
- @Bean(name = "GenericTypeBusinessLogic")
- public GenericTypeBusinessLogic genericTypeBusinessLogic(){
- return new GenericTypeBusinessLogic();
- }
-
- @Bean(name ="componentInstanceMergeDataBusinessLogic")
- public ComponentInstanceMergeDataBusinessLogic componentInstanceMergeDataBusinessLogic(){
- return new ComponentInstanceMergeDataBusinessLogic();
- }
-
- @Bean(name ="heatEnvArtifactsMergeBusinessLogic")
- public HeatEnvArtifactsMergeBusinessLogic heatEnvArtifactsMergeBusinessLogic(){
- return new HeatEnvArtifactsMergeBusinessLogic();
- }
@Bean(name = "elasticsearchConfig")
public PropertiesFactoryBean mapper() {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineClusterHealthMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineClusterHealthMock.java
new file mode 100644
index 0000000000..4d34f507e2
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineClusterHealthMock.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.asdctool.migration.config.mocks;
+
+import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth;
+import org.springframework.stereotype.Component;
+
+@Component("distribution-engine-cluster-health")
+public class DistributionEngineClusterHealthMock extends DistributionEngineClusterHealth {
+
+ @Override
+ protected void init() {
+ }
+
+ @Override
+ protected void destroy() {
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineMock.java
new file mode 100644
index 0000000000..36f6814ea0
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DistributionEngineMock.java
@@ -0,0 +1,68 @@
+package org.openecomp.sdc.asdctool.migration.config.mocks;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
+import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
+import org.openecomp.sdc.be.components.impl.ActivationRequestInformation;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Component;
+
+@Component("distributionEngine")
+public class DistributionEngineMock implements IDistributionEngine {
+ @Override
+ public boolean isActive() {
+ return false;
+ }
+
+ @Override
+ public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) {
+ return null;
+ }
+
+ @Override
+ public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) {
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus isEnvironmentAvailable(String envName) {
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus isEnvironmentAvailable() {
+ return null;
+ }
+
+ @Override
+ public void disableEnvironment(String envName) {
+
+ }
+
+ @Override
+ public StorageOperationStatus isReadyForDistribution(Service service, String envName) {
+ return null;
+ }
+
+ @Override
+ public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) {
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) {
+ return null;
+ }
+
+ @Override
+ public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) {
+ return null;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DmaapHealthCheckMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DmaapHealthCheckMock.java
new file mode 100644
index 0000000000..7315bad273
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/DmaapHealthCheckMock.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.asdctool.migration.config.mocks;
+
+import org.openecomp.sdc.be.components.distribution.engine.DmaapHealth;
+import org.springframework.stereotype.Component;
+
+@Component("dmaapHealth")
+public class DmaapHealthCheckMock extends DmaapHealth {
+ @Override
+ public DmaapHealth init() {
+ return null;
+ }
+
+ @Override
+ protected void destroy() {
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/HealthCheckBusinessLogicMock.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/HealthCheckBusinessLogicMock.java
new file mode 100644
index 0000000000..c7ef45e712
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/mocks/HealthCheckBusinessLogicMock.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.asdctool.migration.config.mocks;
+
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+
+@Component("healthCheckBusinessLogic")
+public class HealthCheckBusinessLogicMock extends HealthCheckBusinessLogic {
+
+ @Override
+ @PostConstruct
+ public void init() {
+
+ }
+
+ @Override
+ protected void destroy() {
+
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java
index 003a27a1e4..03d5adfc15 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java
@@ -13,7 +13,7 @@ public class DBVersion implements Comparable<DBVersion>{
/**
* The current db version. should be tested against real db to verify it is compatible to the db version
*/
- public static final DBVersion CURRENT_VERSION = new DBVersion(1710, 0);
+ public static final DBVersion CURRENT_VERSION = new DBVersion(1802, 0);
private DBVersion(BigInteger major, BigInteger minor) {
this.major = major;
@@ -62,8 +62,12 @@ public class DBVersion implements Comparable<DBVersion>{
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
DBVersion dbVersion = (DBVersion) o;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java
index 8c4c090d94..9024e80e71 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java
@@ -21,6 +21,19 @@ public class MigrationResult {
this.migrationStatus = migrationStatus;
}
+ public static MigrationResult success() {
+ MigrationResult success = new MigrationResult();
+ success.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ return success;
+ }
+
+ public static MigrationResult error(String msg) {
+ MigrationResult error = new MigrationResult();
+ error.setMigrationStatus(MigrationStatus.FAILED);
+ error.setMsg(msg);
+ return error;
+ }
+
public enum MigrationStatus {
COMPLETED,
COMPLETED_WITH_ERRORS,
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java
index dc2114dcd7..de6c66d2d7 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java
@@ -1,34 +1,27 @@
package org.openecomp.sdc.asdctool.migration.main;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.DefaultParser;
-import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.openecomp.sdc.asdctool.configuration.ConfigurationUploader;
+import org.openecomp.sdc.asdctool.cli.CLIToolData;
+import org.openecomp.sdc.asdctool.cli.SpringCLITool;
import org.openecomp.sdc.asdctool.migration.config.MigrationSpringConfig;
import org.openecomp.sdc.asdctool.migration.core.SdcMigrationTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.support.AbstractApplicationContext;
-public class MigrationMenu {
+public class MigrationMenu extends SpringCLITool {
- private final static Logger LOGGER = LoggerFactory.getLogger(MigrationMenu.class);
+ private static final Logger LOGGER = LoggerFactory.getLogger(MigrationMenu.class);
public static void main(String[] args) {
- CommandLine commandLine = initCmdLineOptions(args);
- String appConfigDir = commandLine.getOptionValue("c");
- boolean enforceAll = commandLine.hasOption("e");
- ConfigurationUploader.uploadConfigurationFiles(appConfigDir);
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MigrationSpringConfig.class);
- doMigrate(enforceAll, context);
-
+ MigrationMenu migrationMenu = new MigrationMenu();
+ CLIToolData cliToolData = migrationMenu.init(args);
+ boolean enforceAll = cliToolData.getCommandLine().hasOption("e");
+ migrationMenu.doMigrate(enforceAll, cliToolData.getSpringApplicationContext());
}
- private static void doMigrate(boolean enforceAll, AnnotationConfigApplicationContext context) {
+ private void doMigrate(boolean enforceAll, AbstractApplicationContext context) {
SdcMigrationTool migrationTool = context.getBean(SdcMigrationTool.class);
boolean migrate = migrationTool.migrate(enforceAll);
if (migrate) {
@@ -40,38 +33,19 @@ public class MigrationMenu {
}
}
- private static CommandLine initCmdLineOptions(String[] args) {
- Options options = buildCmdLineOptions();
- CommandLineParser parser = new DefaultParser();
- try {
- // parse the command line arguments
- return parser.parse( options, args );
- }
- catch( ParseException exp ) {
- // oops, something went wrong
- System.err.println( "Parsing failed. Reason: " + exp.getMessage() );
- usageAndExit(options);
- }
- return null;
- }
-
- private static void usageAndExit(Options options) {
- HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp( "yy", options );
- System.exit(1);
- }
-
- private static Options buildCmdLineOptions() {
- Option configPath = buildConfigPathOption();
-
+ @Override
+ protected Options buildCmdLineOptions() {
+ Options options = super.buildCmdLineOptions();
Option enforceAll = buildEnforceAllOption();
-
- Options options = new Options();
- options.addOption(configPath);
options.addOption(enforceAll);
return options;
}
+ @Override
+ protected String commandName() {
+ return "sdc-migration";
+ }
+
private static Option buildEnforceAllOption() {
return Option.builder("e")
.longOpt("enforceAll")
@@ -79,13 +53,8 @@ public class MigrationMenu {
.build();
}
- private static Option buildConfigPathOption() {
- return Option.builder("c")
- .longOpt("configFolderPath")
- .required()
- .hasArg()
- .desc("path to sdc configuration folder - required")
- .build();
+ @Override
+ protected Class<?> getSpringConfigurationClass() {
+ return MigrationSpringConfig.class;
}
-
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java
index 22add31eb4..9147ac0239 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java
@@ -1,6 +1,7 @@
package org.openecomp.sdc.asdctool.migration.resolver;
+import org.openecomp.sdc.asdctool.migration.core.task.IMigrationStage;
import java.util.List;
import org.openecomp.sdc.asdctool.migration.core.task.IMigrationStage;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java
index 182996f5e4..9f2f60053b 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java
@@ -1,6 +1,10 @@
package org.openecomp.sdc.asdctool.migration.resolver;
+import org.openecomp.sdc.asdctool.migration.core.task.IMigrationStage;
+import org.openecomp.sdc.asdctool.migration.core.task.IMigrationStage;
+import org.openecomp.sdc.asdctool.migration.core.task.PostMigration;
+import org.openecomp.sdc.asdctool.migration.core.task.PostMigration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java
index 166512d5b4..ca8c4c8a3c 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710.java
@@ -1,20 +1,15 @@
package org.openecomp.sdc.asdctool.migration.tasks.mig1710;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
+import com.google.common.collect.Lists;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
import org.openecomp.sdc.asdctool.migration.core.task.PostMigration;
import org.openecomp.sdc.asdctool.migration.tasks.handlers.XlsOutputHandler;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
@@ -33,6 +28,8 @@ import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
@@ -49,11 +46,22 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
-@Component
+//@Component
public class UpgradeMigration1710 implements PostMigration {
-
+
+ private static final String SERVICE_UUID_RPOPERTY = "providing_service_uuid";
+
+ private static final String SERVICE_INVARIANT_UUID_RPOPERTY = "providing_service_invariant_uuid";
+
private static final String UNKNOWN = "UNKNOWN";
private static final String CHECKOUT_MESSAGE = "checkout upon upgrade migration";
@@ -70,53 +78,48 @@ public class UpgradeMigration1710 implements PostMigration {
@Autowired
private TitanDao titanDao;
-
+
@Autowired
private ToscaOperationFacade toscaOperationFacade;
-
+
@Autowired
private LifecycleBusinessLogic lifecycleBusinessLogic;
-
+
@Autowired
private IUserAdminOperation userAdminOperation;
@Autowired
private ResourceBusinessLogic resourceBusinessLogic;
-
+
@Autowired
private CsarOperation csarOperation;
-
+
@Autowired
- private ServiceComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
@Autowired
private ComponentsUtils componentsUtils;
- private final XlsOutputHandler outputHandler = new XlsOutputHandler("COMPONENT TYPE", "COMPONENT NAME", "COMPONENT UUID", "COMPONENT UNIQUE_ID", "UPGRADE STATUS", "DESCRIPTION");
+ private XlsOutputHandler outputHandler = new XlsOutputHandler("COMPONENT TYPE", "COMPONENT NAME", "COMPONENT UUID", "COMPONENT UNIQUE_ID", "UPGRADE STATUS", "DESCRIPTION");
private User user = null;
- private final LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(CHECKOUT_MESSAGE, LifecycleChanceActionEnum.UPGRADE_MIGRATION);
+ private final LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(CHECKOUT_MESSAGE, LifecycleChanceActionEnum.UPGRADE_MIGRATION);
- private final Map<String,GraphVertex> latestGenericTypes = new HashMap<>();
+ private final Map<String, GraphVertex> latestGenericTypes = new HashMap<>();
+
+ private final Map<String, String> latestOriginResourceVersions = new HashMap<>();
+
+ private final List<String> proxyServiceContainers = new ArrayList<>();
+
+ private final List<String> vfAllottedResources = new ArrayList<>();
+
+ private final List<String> allottedVfContainers = new ArrayList<>();
private boolean isVfcUpgradeRequired = false;
private boolean skipIfUpgradeVfFailed = true;
- /** below methods is defined on package level for testing
- * where Spring object injection is not used **/
- void setUserAdminOperation(IUserAdminOperation userAdminOperation) { this.userAdminOperation = userAdminOperation; }
-
- void setTitanDao(TitanDao titanDao) { this.titanDao = titanDao; }
-
- void setTosckaOperationFacade(ToscaOperationFacade toscaOperationFacade) { this.toscaOperationFacade = toscaOperationFacade; }
-
- void setLifecycleBusinessLogic(LifecycleBusinessLogic lifecycleBusinessLogic) { this.lifecycleBusinessLogic = lifecycleBusinessLogic; }
-
- void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; }
-
-
/***********************************************/
@Override
@@ -124,7 +127,7 @@ public class UpgradeMigration1710 implements PostMigration {
return "Upgrade migration 1710 - post migration task, which is dedicated to upgrade all latest certified (and not checked out) Node types, VFs and Services. ";
}
- private enum UpgradeStatus{
+ private enum UpgradeStatus {
UPGRADED,
NOT_UPGRADED
}
@@ -134,9 +137,8 @@ public class UpgradeMigration1710 implements PostMigration {
LOGGER.info("Starting upgrade migration 1710 process. ");
MigrationResult migrationResult = new MigrationResult();
- try{
- boolean result = true;
-
+ boolean result = true;
+ try {
isVfcUpgradeRequired = !ConfigurationManager.getConfigurationManager().getConfiguration().getSkipUpgradeVSPsFlag();
skipIfUpgradeVfFailed = ConfigurationManager.getConfigurationManager().getConfiguration().getSkipUpgradeFailedVfs();
final String userId = ConfigurationManager.getConfigurationManager().getConfiguration().getAutoHealingOwner();
@@ -144,23 +146,34 @@ public class UpgradeMigration1710 implements PostMigration {
Either<User, ActionStatus> userReq = userAdminOperation.getUserData(userId, false);
if (userReq.isRight()) {
result = false;
- LOGGER.error("Upgrade migration was failed. User {} resolve failed: {} ", userId, userReq.right().value());
- }
- else {
+ LOGGER.error("Upgrade migration failed. User {} resolve failed: {} ", userId, userReq.right().value());
+ } else {
user = userReq.left().value();
- LOGGER.info("User {} will perform upgrade operation", user.toString());
+ LOGGER.info("User {} will perform upgrade operation", user.getUserId());
}
-
- if(result){
+ if (result) {
result = upgradeNodeTypes();
}
- if(result){
+ if (result) {
result = upgradeVFs();
}
- if(result){
+ if (result) {
upgradeServices();
}
if(result){
+ upgradeProxyServiceContainers();
+ }
+ if(result){
+ upgradeAllottedVFs();
+ }
+ if(result){
+ upgradeAllottedVfContainers();
+ }
+ } catch (Exception e) {
+ result = false;
+ LOGGER.error("Error occurred {}. ", e);
+ } finally {
+ if (result) {
LOGGER.info("Upgrade migration 1710 has been successfully finished. ");
titanDao.commit();
migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
@@ -169,43 +182,56 @@ public class UpgradeMigration1710 implements PostMigration {
titanDao.rollback();
migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
}
- } catch(Exception e){
- LOGGER.error("Upgrade migration 1710 was failed. ", e);
- titanDao.rollback();
- migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
- } finally {
outputHandler.writeOutput();
}
return migrationResult;
}
- private StorageOperationStatus upgradeServices() {
+ private void upgradeAllottedVfContainers() {
+ LOGGER.info("Starting upgrade proxy {} service containers upon upgrade migration 1710 process. ", allottedVfContainers.size());
+ for(String currUid : allottedVfContainers){
+ upgradeServiceAndCommitIfNeeded(currUid, component -> true);
+ }
+ }
+
+ private StorageOperationStatus upgradeServices() {
LOGGER.info("Starting upgrade services upon upgrade migration 1710 process. ");
- Map<String, String> latestOriginResourceVersions = new HashMap<>();
Either<List<String>, TitanOperationStatus> getServicesRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.SERVICE);
- if(getServicesRes.isRight()){
+ if (getServicesRes.isRight()) {
return StorageOperationStatus.GENERAL_ERROR;
}
- for(String currUid : getServicesRes.left().value()){
- try{
- if(handleService(currUid, latestOriginResourceVersions)){
- titanDao.commit();
- } else {
- processComponentUpgradeFailure(ComponentTypeEnum.SERVICE.name(), currUid, "");
- }
- } catch(Exception e){
- processComponentUpgradeFailure(ComponentTypeEnum.SERVICE.name(), currUid, e.getMessage());
- }
+ for (String currUid : getServicesRes.left().value()) {
+ upgradeServiceAndCommitIfNeeded(currUid, this::shouldUpgrade);
}
return StorageOperationStatus.OK;
}
- private void processComponentUpgradeFailure(final String name, final String currUid, final String reason) {
- LOGGER.error("Failed to upgrade {} with uniqueId {} due to a reason {}. ", name, currUid, reason);
- titanDao.rollback();
+ private void upgradeServiceAndCommitIfNeeded(String currUid, Predicate<org.openecomp.sdc.be.model.Component> shouldUpgrade) {
+ boolean result = true;
+ try {
+ result = handleService(currUid, shouldUpgrade);
+ } catch (Exception e) {
+ result = false;
+ LOGGER.error("Failed to upgrade Service with uniqueId {} due to a reason {}. ", currUid, e);
+ }
+ finally {
+ if (result) {
+ titanDao.commit();
+ }
+ else {
+ titanDao.rollback();
+ }
+ }
}
+
+ private void upgradeProxyServiceContainers() {
+ LOGGER.info("Starting upgrade proxy service containers upon upgrade migration 1710 process. ");
+ for(String currUid : proxyServiceContainers){
+ upgradeServiceAndCommitIfNeeded(currUid, component -> true);
+ }
+ }
- private boolean handleService(String uniqueId, Map<String, String> latestOriginResourceVersions) {
+ private boolean handleService(String uniqueId, Predicate<org.openecomp.sdc.be.model.Component> shouldUpgrade) {
LOGGER.info("Starting upgrade Service with uniqueId {} upon upgrade migration 1710 process. ", uniqueId);
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getServiceRes = toscaOperationFacade.getToscaElement(uniqueId);
if(getServiceRes.isRight()){
@@ -231,43 +257,53 @@ public class UpgradeMigration1710 implements PostMigration {
if(latestVersionExists(latestGenericTypes.get(derivedFromGenericType), getServiceRes.left().value().getDerivedFromGenericVersion())){
return upgradeService(getServiceRes.left().value());
}
- if(!collectLatestOriginResourceVersions(getServiceRes.left().value(), latestOriginResourceVersions)){
+ if(!collectLatestOriginResourceVersions(getServiceRes.left().value())){
return false;
}
- if(shouldUpgrade(getServiceRes.left().value(), latestOriginResourceVersions)){
+ if(shouldUpgrade.test(getServiceRes.left().value())){
return upgradeService(getServiceRes.left().value());
}
outputHandler.addRecord(getServiceRes.left().value().getComponentType().name(), getServiceRes.left().value().getName(), getServiceRes.left().value().getInvariantUUID(), getServiceRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.COMPLETED.name(), UpgradeStatus.NOT_UPGRADED);
return true;
}
- private boolean collectLatestOriginResourceVersions(org.openecomp.sdc.be.model.Component component, Map<String, String> latestOriginResourceVersions) {
- if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
- for(ComponentInstance instance : component.getComponentInstances()){
- if(instance.getOriginType() != OriginTypeEnum.ServiceProxy && !latestOriginResourceVersions.containsKey(instance.getToscaComponentName())){
- VertexTypeEnum vertexType = ModelConverter.getVertexType(instance.getOriginType().name());
- Either<Resource, StorageOperationStatus> getOriginRes = toscaOperationFacade.getLatestCertifiedByToscaResourceName(instance.getToscaComponentName(), vertexType, JsonParseFlagEnum.ParseMetadata);
- if(getOriginRes.isRight()){
- LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion(), "toscaOperationFacade.getLatestCertifiedByToscaResourceName", getOriginRes.right().value());
- outputHandler.addRecord( component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getOriginRes.right().value());
- return false;
- }
- latestOriginResourceVersions.put(instance.getToscaComponentName(), getOriginRes.left().value().getVersion());
+ private boolean collectLatestOriginResourceVersions(org.openecomp.sdc.be.model.Component component) {
+ if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
+ for (ComponentInstance instance : component.getComponentInstances()) {
+ if (instance.getOriginType() != OriginTypeEnum.ServiceProxy && !latestOriginResourceVersions.containsKey(instance.getToscaComponentName()) && !addComponent(component, instance)) {
+ return false;
}
}
}
return true;
}
- private boolean shouldUpgrade(org.openecomp.sdc.be.model.Component component, Map<String, String> latestOriginResources) {
+ private boolean addComponent(org.openecomp.sdc.be.model.Component component, ComponentInstance instance) {
+ VertexTypeEnum vertexType = ModelConverter.getVertexType(instance.getOriginType().name());
+ Either<Resource, StorageOperationStatus> getOriginRes = toscaOperationFacade.getLatestCertifiedByToscaResourceName(instance.getToscaComponentName(), vertexType, JsonParseFlagEnum.ParseMetadata);
+ if (getOriginRes.isRight()) {
+ LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion(), "toscaOperationFacade.getLatestCertifiedByToscaResourceName", getOriginRes.right().value());
+ outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getOriginRes.right().value());
+ return false;
+ }
+ latestOriginResourceVersions.put(instance.getToscaComponentName(), getOriginRes.left().value().getVersion());
+ return true;
+ }
+
+ private boolean shouldUpgrade(org.openecomp.sdc.be.model.Component component) {
boolean shouldUpgrade = false;
if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
for(ComponentInstance instance : component.getComponentInstances()){
if(instance.getOriginType() == OriginTypeEnum.ServiceProxy){
- LOGGER.info("The service with name {}, invariantUUID {}, version {}, contains Service proxy instance {}, than the service should be upgraded. ", component.getName(), component.getInvariantUUID(), component.getVersion(), instance.getName());
- shouldUpgrade = true;
+ LOGGER.info("The service with name {}, invariantUUID {}, version {}, contains Service proxy instance {}, than the service should be upgraded in the end of the upgrading proccess. ", component.getName(), component.getInvariantUUID(), component.getVersion(), instance.getName());
+ proxyServiceContainers.add(component.getUniqueId());
+ shouldUpgrade = false;
+ break;
+ }
+ if(isAllottedResource(instance.getActualComponentUid())){
+ allottedVfContainers.add(component.getUniqueId());
}
- if(isGreater(latestOriginResources.get(instance.getToscaComponentName()), instance.getComponentVersion())){
+ if(isGreater(latestOriginResourceVersions.get(instance.getToscaComponentName()), instance.getComponentVersion())){
LOGGER.info("The service with name {}, invariantUUID {}, version {}, contains instance {} from outdated version of origin {} {} , than the service should be upgraded. ", component.getName(), component.getInvariantUUID(), component.getVersion(), instance.getName(), instance.getComponentName(), instance.getComponentVersion());
shouldUpgrade = true;
}
@@ -282,19 +318,19 @@ public class UpgradeMigration1710 implements PostMigration {
LOGGER.info("Starting upgrade Service with name {}, invariantUUID {}, version {} upon upgrade migration 1710 process. ", serviceName, service.getInvariantUUID(), service.getVersion());
LOGGER.info("Starting to perform check out of service {}. ", serviceName);
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(service.getComponentType(), service.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
- if(checkouRes.isRight()){
+ if (checkouRes.isRight()) {
LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, service.getComponentType().getValue(), serviceName, service.getInvariantUUID(), service.getVersion(), "lifecycleBusinessLogic.changeComponentState", checkouRes.right().value().getFormattedMessage());
outputHandler.addRecord(service.getComponentType().name(), serviceName, serviceUuid, service.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), checkouRes.right().value().getFormattedMessage());
return false;
}
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateCompositionRes = updateComposition(checkouRes.left().value());
- if(updateCompositionRes.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateCompositionRes = updateComposition(checkouRes.left().value());
+ if (updateCompositionRes.isRight()) {
LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, service.getComponentType().getValue(), serviceName, service.getInvariantUUID(), service.getVersion(), "updateComposition", updateCompositionRes.right().value().getFormattedMessage());
outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), updateCompositionRes.right().value().getFormattedMessage());
return false;
}
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
- if(certifyRes.isRight()){
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
+ if (certifyRes.isRight()) {
LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, service.getComponentType().getValue(), serviceName, service.getInvariantUUID(), service.getVersion(), "performFullCertification", certifyRes.right().value().getFormattedMessage());
outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), certifyRes.right().value().getFormattedMessage());
return false;
@@ -305,9 +341,9 @@ public class UpgradeMigration1710 implements PostMigration {
private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateComposition(org.openecomp.sdc.be.model.Component component) {
Either<ComponentInstance, ResponseFormat> upgradeInstanceRes;
- for(ComponentInstance instance : component.getComponentInstances()){
+ for (ComponentInstance instance : component.getComponentInstances()) {
upgradeInstanceRes = upgradeInstance(component, instance);
- if(upgradeInstanceRes.isRight()) {
+ if (upgradeInstanceRes.isRight()) {
LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion(), "upgradeInstance", upgradeInstanceRes.right().value().getFormattedMessage());
outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), upgradeInstanceRes.right().value().getFormattedMessage());
return Either.right(upgradeInstanceRes.right().value());
@@ -319,43 +355,94 @@ public class UpgradeMigration1710 implements PostMigration {
private Either<ComponentInstance, ResponseFormat> upgradeInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance) {
LOGGER.info("Starting upgrade {} instance {} upon upgrade migration 1710 process. ", component.getComponentType().getValue(), instance.getName());
ComponentInstance newComponentInstance = new ComponentInstance(instance);
- if(instance.getOriginType() == OriginTypeEnum.ServiceProxy){
+ if (instance.getOriginType() == OriginTypeEnum.ServiceProxy) {
return upgradeServiceProxyInstance(component, instance, newComponentInstance);
}
return upgradeResourceInstance(component, instance, newComponentInstance);
}
- private Either<ComponentInstance, ResponseFormat> upgradeResourceInstance(org.openecomp.sdc.be.model.Component component,
- ComponentInstance instance, ComponentInstance newComponentInstance) {
+ private Either<ComponentInstance, ResponseFormat> upgradeResourceInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, ComponentInstance newComponentInstance) {
+
LOGGER.info("Starting upgrade {} instance {} upon upgrade migration 1710 process. ", component.getComponentType().getValue(), instance.getName());
+ Either<ComponentInstance, ResponseFormat> upgradeInstanceRes = null;
VertexTypeEnum vertexType = ModelConverter.getVertexType(instance.getOriginType().name());
Either<Resource, StorageOperationStatus> getOriginRes = toscaOperationFacade.getLatestCertifiedByToscaResourceName(instance.getToscaComponentName(), vertexType, JsonParseFlagEnum.ParseMetadata);
if(getOriginRes.isRight()){
LOGGER.info("Upgrade of {} instance {} upon upgrade migration 1710 process failed due to a reason {}. ",
component.getComponentType().getValue(), instance.getName(), getOriginRes.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginRes.right().value(), instance.getOriginType().getComponentType())));
+ upgradeInstanceRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginRes.right().value(), instance.getOriginType().getComponentType())));
+ }
+ if(upgradeInstanceRes == null){
+ newComponentInstance.setComponentName(getOriginRes.left().value().getName());
+ newComponentInstance.setComponentUid(getOriginRes.left().value().getUniqueId());
+ newComponentInstance.setComponentVersion(getOriginRes.left().value().getVersion());
+ newComponentInstance.setToscaComponentName(((Resource)getOriginRes.left().value()).getToscaResourceName());
+ if(isGreater(getOriginRes.left().value().getVersion(), instance.getComponentVersion())){
+ upgradeInstanceRes = changeAssetVersion(component, instance, newComponentInstance);
+ }
+ if((upgradeInstanceRes == null || upgradeInstanceRes.isLeft()) && isAllottedResource(instance.getComponentUid()) && MapUtils.isNotEmpty(component.getComponentInstancesProperties())){
+ ComponentInstance instanceToUpdate = upgradeInstanceRes == null ? instance : upgradeInstanceRes.left().value();
+ upgradeInstanceRes = Either.left(updateServiceUuidProperty(component, instanceToUpdate, component.getComponentInstancesProperties().get(instance.getUniqueId())));
+ }
}
- newComponentInstance.setComponentName(getOriginRes.left().value().getName());
- newComponentInstance.setComponentUid(getOriginRes.left().value().getUniqueId());
- newComponentInstance.setComponentVersion(getOriginRes.left().value().getVersion());
- newComponentInstance.setToscaComponentName(((Resource)getOriginRes.left().value()).getToscaResourceName());
- if(isGreater(getOriginRes.left().value().getVersion(), instance.getComponentVersion())){
- return changeAssetVersion(component, instance, newComponentInstance);
- }
-
//upgrade nodes contained by CVFC
- if(isVfcUpgradeRequired && newComponentInstance.getOriginType() == OriginTypeEnum.CVFC &&
- !upgradeVf(getOriginRes.left().value().getUniqueId())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ if(upgradeInstanceRes == null && isVfcUpgradeRequired && newComponentInstance.getOriginType() == OriginTypeEnum.CVFC &&
+ !upgradeVf(getOriginRes.left().value().getUniqueId(), false)) {
+ upgradeInstanceRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ if(upgradeInstanceRes == null){
+ upgradeInstanceRes = Either.left(instance);
}
LOGGER.info("Upgrade of {} instance {} upon upgrade migration 1710 process finished successfully. ",
- component.getComponentType().getValue(), instance.getName());
- return Either.left(instance);
+ component.getComponentType().getValue(), instance.getName());
+ return upgradeInstanceRes;
}
+ private ComponentInstance updateServiceUuidProperty(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, List<ComponentInstanceProperty> instanceProperties){
+ if(isAllottedResource(instance.getComponentUid()) && instanceProperties != null){
+ Optional<ComponentInstanceProperty> propertyUuid = instanceProperties.stream().filter(p->p.getName().equals(SERVICE_UUID_RPOPERTY)).findFirst();
+ Optional<ComponentInstanceProperty> propertyInvariantUuid = instanceProperties.stream().filter(p->p.getName().equals(SERVICE_INVARIANT_UUID_RPOPERTY)).findFirst();
+ if(propertyUuid.isPresent() && propertyInvariantUuid.isPresent()){
+ String serviceInvariantUUID = propertyInvariantUuid.get().getValue();
+ Either<List<GraphVertex>, TitanOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(serviceInvariantUUID);
+ if (getLatestOriginServiceRes.isRight()) {
+ return instance;
+ }
+ propertyUuid.get().setValue((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.UUID));
+ componentInstanceBusinessLogic.createOrUpdatePropertiesValues(component.getComponentType(), component.getUniqueId(), instance.getUniqueId(), Lists.newArrayList(propertyUuid.get()), user.getUserId())
+ .right()
+ .forEach(e -> LOGGER.debug("Failed to update property {} of the instance {} of the component {}. ", SERVICE_UUID_RPOPERTY, instance.getUniqueId(), component.getName()));
+ }
+ }
+ return instance;
+ }
+
+ private boolean isAllottedResource(String uniqueId){
+ ComponentParametersView filters = new ComponentParametersView(true);
+ filters.setIgnoreCategories(false);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(uniqueId, filters);
+ if(getResourceRes.isRight()){
+ return false;
+ }
+ if(getResourceRes.left().value().getCategories() != null && getResourceRes.left().value().getCategories().get(0)!= null){
+ return "Allotted Resource".equals(getResourceRes.left().value().getCategories().get(0).getName());
+ }
+ return false;
+ }
+
+ private boolean isAllottedVf(org.openecomp.sdc.be.model.Component component){
+ if(component.getComponentType() != ComponentTypeEnum.RESOURCE){
+ return false;
+ }
+ if(((Resource)component).getResourceType() != ResourceTypeEnum.VF){
+ return false;
+ }
+ return isAllottedResource(component.getUniqueId());
+ }
+
private Either<ComponentInstance, ResponseFormat> upgradeServiceProxyInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, ComponentInstance newComponentInstance) {
Either<List<GraphVertex>, TitanOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(instance.getSourceModelInvariant());
- if(getLatestOriginServiceRes.isRight()){
+ if (getLatestOriginServiceRes.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(getLatestOriginServiceRes.right().value()), instance.getOriginType().getComponentType())));
}
newComponentInstance.setComponentVersion((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.VERSION));
@@ -385,18 +472,18 @@ public class UpgradeMigration1710 implements PostMigration {
LOGGER.info("Starting upgrade node types upon upgrade migration 1710 process. ");
String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
Map<String, List<String>> resourcesForUpgrade = ConfigurationManager.getConfigurationManager().getConfiguration().getResourcesForUpgrade();
- Map<String, org.openecomp.sdc.be.model.Component> upgradedNodeTypesMap = new HashMap<> ();
+ Map<String, org.openecomp.sdc.be.model.Component> upgradedNodeTypesMap = new HashMap<>();
List<String> nodeTypes;
- if(resourcesForUpgrade.containsKey(toscaConformanceLevel)){
- nodeTypes = resourcesForUpgrade.get(toscaConformanceLevel);
- if(nodeTypes !=null && !nodeTypes.isEmpty()){
+ if (resourcesForUpgrade.containsKey(toscaConformanceLevel)) {
+ nodeTypes = resourcesForUpgrade.get(toscaConformanceLevel);
+ if (nodeTypes != null && !nodeTypes.isEmpty()) {
Either<List<String>, TitanOperationStatus> getRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.NODE_TYPE, ComponentTypeEnum.RESOURCE);
- if(getRes.isRight()){
+ if (getRes.isRight()) {
return false;
}
List<String> allNodeTypes = getRes.left().value();
- for(String toscaResourceName: nodeTypes){
+ for (String toscaResourceName : nodeTypes) {
Either<List<GraphVertex>, StorageOperationStatus> status = getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
if (status.isRight()) {
LOGGER.error("Failed to find node type {} ", toscaResourceName);
@@ -416,27 +503,43 @@ public class UpgradeMigration1710 implements PostMigration {
}
private boolean upgradeVFs() {
+ return upgradeVFs(false);
+ }
+
+ private boolean upgradeAllottedVFs() {
+ LOGGER.info("Starting upgrade {} allotted Vfs with upon upgrade migration 1710 process. ", vfAllottedResources.size());
+ return upgradeVFs(true);
+ }
+
+ private boolean upgradeVFs(boolean allottedVfsUpgrade) {
LOGGER.info("Starting upgrade VFs upon upgrade migration 1710 process. ");
Either<List<String>, TitanOperationStatus> getVfsRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.RESOURCE);
- if(getVfsRes.isRight()){
+ if (getVfsRes.isRight()) {
LOGGER.info(UPGRADE_VFS_FAILED);
return false;
}
for (String currUid : getVfsRes.left().value()) {
+ boolean result = true;
try {
- if (!upgradeVf(currUid)) {
- processComponentUpgradeFailure(ComponentTypeEnum.RESOURCE.name(), currUid, "");
- if (!skipIfUpgradeVfFailed) {
- LOGGER.info(UPGRADE_VFS_FAILED);
- return false;
- }
+ result = upgradeVf(currUid, allottedVfsUpgrade);
+ if (!result && !skipIfUpgradeVfFailed) {
+ return false;
}
- titanDao.commit();
} catch (Exception e) {
- processComponentUpgradeFailure(ComponentTypeEnum.RESOURCE.name(), currUid, e.getMessage());
+ LOGGER.error("The exception {} occured upon upgrade VFs. ", e);
+ result = false;
if (!skipIfUpgradeVfFailed) {
- LOGGER.info(UPGRADE_VFS_FAILED);
- return false;
+ return false;
+ }
+ }
+ finally {
+ if (!result) {
+ LOGGER.error("Failed to upgrade RESOURCE with uniqueId {} ", currUid);
+ titanDao.rollback();
+ }
+ else {
+ LOGGER.info("RESOURCE upgrade finished successfully: uniqueId {} ", currUid);
+ titanDao.commit();
}
}
}
@@ -444,27 +547,31 @@ public class UpgradeMigration1710 implements PostMigration {
return true;
}
- private boolean upgradeVf(String uniqueId) {
+ private boolean upgradeVf(String uniqueId, boolean allottedVfsUpgrade) {
LOGGER.info("Starting upgrade VF with uniqueId {} upon upgrade migration 1710 process. ", uniqueId);
Either<String, StorageOperationStatus> latestVersionRes;
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getRes = toscaOperationFacade.getToscaElement(uniqueId);
- if(getRes.isRight()){
+ if (getRes.isRight()) {
LOGGER.debug("Failed to fetch VF with uniqueId {} upon upgrade migration 1710 process. ", uniqueId);
outputHandler.addRecord(ComponentTypeEnum.RESOURCE.name(), UNKNOWN, UNKNOWN, uniqueId, MigrationResult.MigrationStatus.FAILED.name(), getRes.right().value());
return false;
}
- if(StringUtils.isNotEmpty(getRes.left().value().getCsarUUID())){
+ if(!allottedVfsUpgrade && isAllottedVf(getRes.left().value())){
+ vfAllottedResources.add(uniqueId);
+ return true;
+ }
+ if (StringUtils.isNotEmpty(getRes.left().value().getCsarUUID())) {
LOGGER.info("Going to fetch the latest version of VSP with csarUUID {} upon upgrade migration 1710 process. ", getRes.left().value().getCsarUUID());
latestVersionRes = csarOperation.getCsarLatestVersion(getRes.left().value().getCsarUUID(), user);
- if(latestVersionRes.isRight()){
+ if (latestVersionRes.isRight()) {
LOGGER.debug("Failed to fetch the latest version of VSP with csarUUID {} upon upgrade migration 1710 process. ", getRes.left().value().getCsarUUID());
- outputHandler.addRecord(getRes.left().value().getComponentType().name(), getRes.left().value().getName(), getRes.left().value().getUUID(), getRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(),latestVersionRes.right().value());
+ outputHandler.addRecord(getRes.left().value().getComponentType().name(), getRes.left().value().getName(), getRes.left().value().getUUID(), getRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), latestVersionRes.right().value());
return false;
}
- if(isGreater(latestVersionRes.left().value(), getRes.left().value().getCsarVersion())){
+ if (isGreater(latestVersionRes.left().value(), getRes.left().value().getCsarVersion())) {
return upgradeVfWithLatestVsp(getRes.left().value(), latestVersionRes);
}
- if (!isVfcUpgradeRequired){
+ if (!isVfcUpgradeRequired) {
LOGGER.warn("Warning: No need to upgrade VF with name {}, invariantUUID {}, version {} and VSP version {}. No new version of VSP. ", getRes.left().value().getName(), getRes.left().value().getInvariantUUID(), getRes.left().value().getVersion(), getRes.left().value().getCsarVersion());
}
}
@@ -473,9 +580,9 @@ public class UpgradeMigration1710 implements PostMigration {
private boolean upgradeVfWithLatestVsp(org.openecomp.sdc.be.model.Component vf, Either<String, StorageOperationStatus> latestVersionRes) {
LOGGER.info("Starting upgrade vf with name {}, invariantUUID {}, version {} and latest VSP version {} upon upgrade migration 1710 process. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion(), latestVersionRes.left().value());
- LOGGER.info("Starting to perform check out of vf with name {}, invariantUUID {}, version {}. ", vf.getName(),vf.getInvariantUUID(), vf.getVersion());
+ LOGGER.info("Starting to perform check out of vf with name {}, invariantUUID {}, version {}. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion());
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(vf.getComponentType(), vf.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
- if(checkouRes.isRight()){
+ if (checkouRes.isRight()) {
outputHandler.addRecord(vf.getComponentType().name(), vf.getName(), vf.getUUID(), vf.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), checkouRes.right().value().getFormattedMessage());
return false;
}
@@ -485,13 +592,13 @@ public class UpgradeMigration1710 implements PostMigration {
resourceToUpdate.setDerivedFromGenericVersion(((Resource) checkouRes.left().value()).getDerivedFromGenericVersion());
resourceToUpdate.setCsarVersion(Double.toString(Double.parseDouble(latestVersionRes.left().value())));
Either<Resource, ResponseFormat> updateResourceFromCsarRes = resourceBusinessLogic.validateAndUpdateResourceFromCsar(resourceToUpdate, user, null, null, resourceToUpdate.getUniqueId());
- if(updateResourceFromCsarRes.isRight()){
+ if (updateResourceFromCsarRes.isRight()) {
outputHandler.addRecord(resourceToUpdate.getComponentType().name(), resourceToUpdate.getName(), resourceToUpdate.getUUID(), resourceToUpdate.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), updateResourceFromCsarRes.right().value().getFormattedMessage());
LOGGER.info("Failed to update vf with name {}, invariantUUID {}, version {} and latest VSP {}. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion(), latestVersionRes.left().value());
return false;
}
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
- if(certifyRes.isRight()){
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
+ if (certifyRes.isRight()) {
LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getVersion(), LifeCycleTransitionEnum.CERTIFY);
outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), certifyRes.right().value().getFormattedMessage());
return false;
@@ -502,55 +609,55 @@ public class UpgradeMigration1710 implements PostMigration {
}
private boolean upgradeComponentWithLatestGeneric(org.openecomp.sdc.be.model.Component component) {
- String derivedFromGenericType = component.getDerivedFromGenericType();
+ String derivedFromGenericType = component.getDerivedFromGenericType();
String derivedFromGenericVersion = component.getDerivedFromGenericVersion();
org.openecomp.sdc.be.model.Component updatedComponent = component;
- if(StringUtils.isNotEmpty(derivedFromGenericType) && !latestGenericTypes.containsKey(derivedFromGenericType)){
+ if (StringUtils.isNotEmpty(derivedFromGenericType) && !latestGenericTypes.containsKey(derivedFromGenericType)) {
LOGGER.info("Starting upgrade vf with name {}, invariantUUID {}, version {}, latest derived from generic type {}, latest derived from generic version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion(), derivedFromGenericType, derivedFromGenericVersion);
LOGGER.info("Starting to fetch latest generic node type {}. ", derivedFromGenericType);
Either<List<GraphVertex>, TitanOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType);
- if(getDerivedRes.isRight()){
+ if (getDerivedRes.isRight()) {
outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getDerivedRes.right().value());
LOGGER.info("Failed to upgrade component with name {}, invariantUUID {}, version {} and latest generic. Status is {}. ", component.getName(), component.getInvariantUUID(), component.getVersion(), derivedFromGenericType);
return false;
}
latestGenericTypes.put(derivedFromGenericType, getDerivedRes.left().value().get(0));
}
- if(StringUtils.isEmpty(derivedFromGenericType) ||
+ if (StringUtils.isEmpty(derivedFromGenericType) ||
latestVersionExists(latestGenericTypes.get(derivedFromGenericType), derivedFromGenericVersion) ||
- isVfcUpgradeRequired){
- if(StringUtils.isNotEmpty(derivedFromGenericType))
+ isVfcUpgradeRequired) {
+ if (StringUtils.isNotEmpty(derivedFromGenericType))
LOGGER.info("Newer version {} of derived from generic type {} exists. ", latestGenericTypes.get(derivedFromGenericType).getJsonMetadataField(JsonPresentationFields.VERSION), derivedFromGenericType);
else
LOGGER.info("The vf resource with name {}, invariantUUID {}, version {}, has an empty derivedFromGenericType field. ", component.getName(), component.getInvariantUUID(), component.getVersion());
LOGGER.info("Starting to perform check out of vf with name {}, invariantUUID {}, version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion());
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
- if(checkouRes.isRight()){
+ if (checkouRes.isRight()) {
LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CHECKOUT);
outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), checkouRes.right().value().getFormattedMessage());
return false;
}
//update included VFCs, if it is required as per configuration
- if(isVfcUpgradeRequired && CollectionUtils.isNotEmpty(checkouRes.left().value().getComponentInstances())){
+ if (CollectionUtils.isNotEmpty(checkouRes.left().value().getComponentInstances())) {
LOGGER.info("VFC upgrade is required: updating components of vf with name {}, invariantUUID {}, version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion());
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateCompositionRes =
- updateComposition(checkouRes.left().value());
- if(updateCompositionRes.isRight()){
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateCompositionRes =
+ updateComposition(checkouRes.left().value());
+ if (updateCompositionRes.isRight()) {
LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getVersion(), "updateComposition", updateCompositionRes.right().value().getFormattedMessage());
outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), updateCompositionRes.right().value().getFormattedMessage());
return false;
}
}
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
- if(certifyRes.isRight()){
+ if (certifyRes.isRight()) {
LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CERTIFY);
outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), certifyRes.right().value().getFormattedMessage());
return false;
}
updatedComponent = certifyRes.left().value();
} else {
- LOGGER.info("The version {} of derived from generic type {} is up to date. No need to upgrade component with name {}, invariantUUID {} and version {}. ", latestGenericTypes.get(derivedFromGenericType), derivedFromGenericType,component.getName(), component.getInvariantUUID(), component.getVersion());
+ LOGGER.info("The version {} of derived from generic type {} is up to date. No need to upgrade component with name {}, invariantUUID {} and version {}. ", latestGenericTypes.get(derivedFromGenericType), derivedFromGenericType, component.getName(), component.getInvariantUUID(), component.getVersion());
}
LOGGER.info(UPGRADE_COMPONENT_SUCCEEDED, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion());
outputHandler.addRecord(updatedComponent.getComponentType().name(), updatedComponent.getName(), updatedComponent.getUUID(), updatedComponent.getUniqueId(), MigrationResult.MigrationStatus.COMPLETED.name(), updatedComponent.equals(component) ? UpgradeStatus.NOT_UPGRADED : UpgradeStatus.UPGRADED);
@@ -562,46 +669,46 @@ public class UpgradeMigration1710 implements PostMigration {
LOGGER.info("Starting upgrade node type with name {}, invariantUUID {}, version{}. ", nodeTypeV.getMetadataProperty(GraphPropertyEnum.NAME), nodeTypeV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), nodeTypeV.getMetadataProperty(GraphPropertyEnum.VERSION));
LOGGER.info("Starting to find derived to for node type with name {}, invariantUUID {}, version{}. ", nodeTypeV.getMetadataProperty(GraphPropertyEnum.NAME), nodeTypeV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), nodeTypeV.getMetadataProperty(GraphPropertyEnum.VERSION));
Either<List<GraphVertex>, TitanOperationStatus> parentResourceRes = titanDao.getParentVertecies(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseMetadata);
- if(parentResourceRes.isRight() && parentResourceRes.right().value() != TitanOperationStatus.NOT_FOUND ){
+ if (parentResourceRes.isRight() && parentResourceRes.right().value() != TitanOperationStatus.NOT_FOUND) {
return DaoStatusConverter.convertTitanStatusToStorageStatus(parentResourceRes.right().value());
}
List<GraphVertex> derivedResourcesUid = new ArrayList<>();
- if(parentResourceRes.isLeft()){
- for(GraphVertex chV: parentResourceRes.left().value()){
- Optional<String> op = allCertifiedUids.stream().filter(id -> id.equals((String)chV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID))).findAny();
- if(op.isPresent()){
+ if (parentResourceRes.isLeft()) {
+ for (GraphVertex chV : parentResourceRes.left().value()) {
+ Optional<String> op = allCertifiedUids.stream().filter(id -> id.equals((String) chV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID))).findAny();
+ if (op.isPresent()) {
derivedResourcesUid.add(chV);
}
}
}
- String uniqueId = (String)nodeTypeV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID);
+ String uniqueId = (String) nodeTypeV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID);
Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getRes = toscaOperationFacade.getToscaElement(uniqueId);
- if(getRes.isRight()){
+ if (getRes.isRight()) {
LOGGER.info("failed to fetch element with uniqueId {} ", uniqueId);
return getRes.right().value();
}
- org.openecomp.sdc.be.model.Resource nt = (Resource)getRes.left().value();
+ org.openecomp.sdc.be.model.Resource nt = (Resource) getRes.left().value();
boolean isNeedToUpgrade = true;
- if(upgradedNodeTypesMap.containsKey(nt.getToscaResourceName()) || nodeTypes.stream().filter( p -> p.equals(nt.getToscaResourceName())).findAny().isPresent()){
+ if (upgradedNodeTypesMap.containsKey(nt.getToscaResourceName()) || nodeTypes.stream().anyMatch(p -> p.equals(nt.getToscaResourceName()))) {
isNeedToUpgrade = false;
}
- if(isNeedToUpgrade){
+ if (isNeedToUpgrade) {
LOGGER.info("Starting to perform check out of node type with name {}, invariantUUID {}, version {}. ", nt.getName(), nt.getInvariantUUID(), nt.getVersion());
Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(nt.getComponentType(), nt.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
- if(checkouRes.isRight()){
+ if (checkouRes.isRight()) {
return StorageOperationStatus.GENERAL_ERROR;
}
org.openecomp.sdc.be.model.Component upgradetComp = checkouRes.left().value();
boolean res = performFullCertification(upgradetComp).isLeft();
- if(!res){
+ if (!res) {
return StorageOperationStatus.GENERAL_ERROR;
}
upgradedNodeTypesMap.put(nt.getToscaResourceName(), upgradetComp);
titanDao.commit();
}
- for(GraphVertex chV: derivedResourcesUid){
+ for (GraphVertex chV : derivedResourcesUid) {
result = upgradeNodeType(chV, upgradedNodeTypesMap, allCertifiedUids, nodeTypes);
LOGGER.info("Upgrade node type with name {}, invariantUUID {}, version {} has been finished with the status {}", chV.getMetadataProperty(GraphPropertyEnum.NAME), chV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), chV.getMetadataProperty(GraphPropertyEnum.VERSION), result);
}
@@ -610,23 +717,22 @@ public class UpgradeMigration1710 implements PostMigration {
private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> performFullCertification(org.openecomp.sdc.be.model.Component component) {
LOGGER.info("Starting to perform full certification of {} with name {}, invariantUUID {}, version {}. ",
- component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion());
+ component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion());
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, changeInfo, true, false);
- if(changeStateEither.isRight()){
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, changeInfo, true, false);
+ if (changeStateEither.isRight()) {
LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CERTIFICATION_REQUEST);
return changeStateEither;
}
changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), changeStateEither.left().value().getUniqueId(), user, LifeCycleTransitionEnum.START_CERTIFICATION, changeInfo, true, false);
- if(changeStateEither.isRight()){
+ if (changeStateEither.isRight()) {
LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.START_CERTIFICATION);
return changeStateEither;
}
changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), changeStateEither.left().value().getUniqueId(), user, LifeCycleTransitionEnum.CERTIFY, changeInfo, true, false);
- if(changeStateEither.isRight()){
+ if (changeStateEither.isRight()) {
LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CERTIFY);
- }
- else {
+ } else {
LOGGER.info("Full certification of {} with name {}, invariantUUID {}, version {} finished successfully",
changeStateEither.left().value().getComponentType().getValue(), changeStateEither.left().value().getName(),
changeStateEither.left().value().getInvariantUUID(), changeStateEither.left().value().getVersion());
@@ -645,13 +751,13 @@ public class UpgradeMigration1710 implements PostMigration {
}
private boolean latestVersionExists(GraphVertex latestDerivedFrom, String currentVersion) {
- return isGreater((String)latestDerivedFrom.getJsonMetadataField(JsonPresentationFields.VERSION), currentVersion);
+ return isGreater((String) latestDerivedFrom.getJsonMetadataField(JsonPresentationFields.VERSION), currentVersion);
}
private boolean isGreater(String latestVersion, String currentVersion) {
- if(latestVersion != null && currentVersion == null)
+ if (latestVersion != null && currentVersion == null)
return true;
- if(latestVersion == null)
+ if (latestVersion == null)
return false;
return Double.parseDouble(latestVersion) > Double.parseDouble(currentVersion);
}
@@ -661,58 +767,58 @@ public class UpgradeMigration1710 implements PostMigration {
Either<List<String>, TitanOperationStatus> result = null;
Map<String, String> latestCertifiedMap = new HashMap<>();
Map<String, String> latestNotCertifiedMap = new HashMap<>();
-
+
Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = getAllLatestCertifiedComponents(vertexType, componentType);
- if(getComponentsRes.isRight() && getComponentsRes.right().value() != TitanOperationStatus.NOT_FOUND){
+ if (getComponentsRes.isRight() && getComponentsRes.right().value() != TitanOperationStatus.NOT_FOUND) {
LOGGER.error("Failed to fetch all latest certified not checked out components with type {}. Status is {}. ", componentType, getComponentsRes.right().value());
result = Either.right(getComponentsRes.right().value());
}
- if(getComponentsRes.isRight()){
+ if (getComponentsRes.isRight()) {
result = Either.left(new ArrayList<>());
}
- if(result == null){
- for(GraphVertex component : getComponentsRes.left().value()){
- String invariantUUID = (String)component.getJsonMetadataField(JsonPresentationFields.INVARIANT_UUID);
- if(((String)component.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())){
- latestCertifiedMap.put(invariantUUID, (String)component.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
+ if (result == null) {
+ for (GraphVertex component : getComponentsRes.left().value()) {
+ String invariantUUID = (String) component.getJsonMetadataField(JsonPresentationFields.INVARIANT_UUID);
+ if (((String) component.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
+ latestCertifiedMap.put(invariantUUID, (String) component.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
} else {
- latestNotCertifiedMap.put(invariantUUID, (String)component.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
+ latestNotCertifiedMap.put(invariantUUID, (String) component.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
}
}
- result = Either.left(latestCertifiedMap.entrySet().stream().filter(e->!latestNotCertifiedMap.containsKey(e.getKey())).map(e->e.getValue()).collect(Collectors.toList()));
+ result = Either.left(latestCertifiedMap.entrySet().stream().filter(e -> !latestNotCertifiedMap.containsKey(e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()));
}
return result;
}
- private Either<List<GraphVertex>, TitanOperationStatus> getAllLatestCertifiedComponents(VertexTypeEnum vertexType, ComponentTypeEnum componentType){
+ private Either<List<GraphVertex>, TitanOperationStatus> getAllLatestCertifiedComponents(VertexTypeEnum vertexType, ComponentTypeEnum componentType) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
+
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
- if(vertexType == VertexTypeEnum.TOPOLOGY_TEMPLATE && componentType == ComponentTypeEnum.RESOURCE)
+ if (vertexType == VertexTypeEnum.TOPOLOGY_TEMPLATE && componentType == ComponentTypeEnum.RESOURCE)
propertiesNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
return titanDao.getByCriteria(vertexType, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
}
protected Either<List<String>, TitanOperationStatus> findResourcesPathRecursively(GraphVertex nodeTypeV, List<String> allCertifiedUids) {
Either<List<GraphVertex>, TitanOperationStatus> parentResourceRes = titanDao.getParentVertecies(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseMetadata);
- if(parentResourceRes.isRight()){
+ if (parentResourceRes.isRight()) {
return Either.right(parentResourceRes.right().value());
}
List<GraphVertex> derivedResourcesUid = new ArrayList<>();
- for(GraphVertex chV: parentResourceRes.left().value()){
- Optional<String> op = allCertifiedUids.stream().filter(id -> id.equals((String)chV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID))).findAny();
- if(op.isPresent()){
+ for (GraphVertex chV : parentResourceRes.left().value()) {
+ Optional<String> op = allCertifiedUids.stream().filter(id -> id.equals((String) chV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID))).findAny();
+ if (op.isPresent()) {
derivedResourcesUid.add(chV);
}
}
return null;
}
- private Either<List<GraphVertex>, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName){
+ private Either<List<GraphVertex>, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
@@ -728,8 +834,8 @@ public class UpgradeMigration1710 implements PostMigration {
}
List<GraphVertex> resources = highestResources.left().value();
List<GraphVertex> result = new ArrayList<>();
- for(GraphVertex component:resources){
- if(((String)component.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())){
+ for (GraphVertex component : resources) {
+ if (((String) component.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
result.add(component);
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java
new file mode 100644
index 0000000000..9cbb7ec1ce
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1802/SdcCatalogMigration.java
@@ -0,0 +1,137 @@
+package org.openecomp.sdc.asdctool.migration.tasks.mig1802;
+
+import fj.data.Either;
+import org.apache.commons.collections.ListUtils;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.be.dao.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.IdBuilderUtils;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Component
+public class SdcCatalogMigration implements Migration {
+ private static final Logger LOGGER = LoggerFactory.getLogger(SdcCatalogMigration.class);
+ private static final List<ResourceTypeEnum> EXCLUDE_TYPES = Arrays.asList(ResourceTypeEnum.VFCMT, ResourceTypeEnum.Configuration);
+
+ private ToscaElementOperation toscaElementOperation;
+ private TitanDao titanDao;
+
+ public SdcCatalogMigration(TopologyTemplateOperation toscaElementOperation, TitanDao titanDao) {
+ this.toscaElementOperation = toscaElementOperation;
+ this.titanDao = titanDao;
+ }
+
+ @Override
+ public String description() {
+ return "optimize sdc catalog vertices";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.from(BigInteger.valueOf(1802), BigInteger.valueOf(0));
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ TitanOperationStatus status = null;
+ try {
+ status = getOrCreateCatalogRoot()
+ .either(this::associateCatalogRootToCatalogElements,
+ err -> {LOGGER.error("failed to create catalog root. err: {}", err); return err;});
+ return status == TitanOperationStatus.OK ? MigrationResult.success() : MigrationResult.error("failed to create and associate catalog root. error: " + status);
+ } finally {
+ commitOrRollBack(status);
+ }
+ }
+
+ private void commitOrRollBack(TitanOperationStatus status) {
+ if (status == TitanOperationStatus.OK) {
+ titanDao.commit();
+ } else {
+ titanDao.rollback();
+ }
+ }
+
+ private Either<GraphVertex, TitanOperationStatus> getOrCreateCatalogRoot() {
+ LOGGER.info("creating or getting catalog root vertex");
+ return titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT)
+ .right()
+ .bind(this::createRootCatalogVertexOrError);
+ }
+
+
+ private Either<GraphVertex, TitanOperationStatus> createRootCatalogVertexOrError(TitanOperationStatus titanOperationStatus) {
+ return titanOperationStatus == TitanOperationStatus.NOT_FOUND ? createRootCatalogVertex() : Either.right(titanOperationStatus);
+ }
+
+ private Either<GraphVertex, TitanOperationStatus> createRootCatalogVertex() {
+ LOGGER.info("Creating root catalog vertex");
+ GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT);
+ catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId());
+ return titanDao.createVertex(catalogRootVertex);
+ }
+
+ private Either<List<GraphVertex>, TitanOperationStatus> getAllCatalogVertices() {
+ LOGGER.info("fetching all catalog resources");
+ return toscaElementOperation.getListOfHighestComponents(ComponentTypeEnum.RESOURCE, EXCLUDE_TYPES, JsonParseFlagEnum.ParseMetadata)
+ .left()
+ .bind(this::getAllCatalogVertices);
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<List<GraphVertex>, TitanOperationStatus> getAllCatalogVertices(List<GraphVertex> allResourceCatalogVertices) {
+ LOGGER.info("number of resources: {}", allResourceCatalogVertices.size());
+ LOGGER.info("fetching all catalog services");
+ return toscaElementOperation.getListOfHighestComponents(ComponentTypeEnum.SERVICE, EXCLUDE_TYPES, JsonParseFlagEnum.ParseMetadata)
+ .left()
+ .map(allServiceVertices -> ListUtils.union(allServiceVertices, allResourceCatalogVertices));
+ }
+
+ private TitanOperationStatus associateCatalogRootToCatalogElements(GraphVertex root) {
+ return getAllCatalogVertices()
+ .either(catalogVertices -> associateCatalogRootToCatalogElements(root, catalogVertices),
+ err -> err);
+ }
+
+ private TitanOperationStatus associateCatalogRootToCatalogElements(GraphVertex root, List<GraphVertex> catalogElements) {
+ LOGGER.info("number of catalog elements: {}", catalogElements.size());
+ LOGGER.info("connect all catalog elements to root edge");
+ List<GraphVertex> nonConnectedElements = catalogElements.stream().filter(this::edgeNotAlreadyExists).collect(Collectors.toList());
+ int numOfCreatedEdges = 0;
+ for (GraphVertex catalogElement : nonConnectedElements) {
+ TitanOperationStatus edgeCreationStatus = titanDao.createEdge(root, catalogElement, EdgeLabelEnum.CATALOG_ELEMENT, null);
+ if (edgeCreationStatus != TitanOperationStatus.OK) {
+ LOGGER.error("failed to create edge from catalog element to vertex {}", catalogElement.getUniqueId());
+ return edgeCreationStatus;
+ }
+ LOGGER.debug("created edge from catalog root to element {}", catalogElement.getUniqueId());
+ numOfCreatedEdges++;
+ }
+ LOGGER.info("number edges created: {}", numOfCreatedEdges);
+ return TitanOperationStatus.OK;
+ }
+
+ private boolean edgeNotAlreadyExists(GraphVertex catalogElement) {
+ return !catalogElement.getVertex().edges(Direction.IN, EdgeLabelEnum.CATALOG_ELEMENT.name()).hasNext();
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportCassandraTableTool.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportCassandraTableTool.java
new file mode 100644
index 0000000000..9ea2d5ad49
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportCassandraTableTool.java
@@ -0,0 +1,69 @@
+package org.openecomp.sdc.asdctool.simulator.tenant;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Consumer;
+
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Main class of utility imports CSV file into the specified table
+ * The old stuff of the table is removed.
+ *
+ * Accepts 3 mandatory arguments:
+ * 1. Path to configuration folder
+ * 2. Name of the table
+ * 3. Path to the CSV file
+ *
+ * Example of usage:
+ * \src\main\resources\config\ operationalenvironment "C:\Users\dr2032\Documents\env.csv"
+ *
+ * See relevant import handler for example of csv file line.
+ *
+ * The list of supported tables:
+ * 1. operationalenvironment
+ *
+ *
+ * @author dr2032
+ *
+ */
+public class ImportCassandraTableTool {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ImportCassandraTableTool.class);
+
+ private static Map<String, Consumer<String>> mapHandlers = new HashMap<>();
+
+ static {
+ mapHandlers.put(OperationalEvnironmentImportHandler.getTableName().toLowerCase(), OperationalEvnironmentImportHandler::execute);
+ }
+
+ public static void main(String[] args) {
+ if(args.length == 3) {
+ String appConfigDir = args[0];
+ String tableName = args[1];
+ String fileName = args[2];
+
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ new ConfigurationManager(configurationSource);
+
+ Consumer<String> executor = mapHandlers.get(tableName.toLowerCase());
+ if (executor != null) {
+ executor.accept(fileName);
+ }
+ else {
+ LOGGER.warn("Import to table [{}] is not supported yet!", tableName);
+ }
+ }
+ else {
+ LOGGER.warn("Invalid number of arguments. The 1st shoduld be path to config dir, the 2nd - table name and the 3rd - path to CSV file.");
+ }
+
+
+ System.exit(0);
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportTableConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportTableConfig.java
new file mode 100644
index 0000000000..5ce4314361
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/ImportTableConfig.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.asdctool.simulator.tenant;
+
+import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ImportTableConfig {
+ @Bean(name = "cassandra-client")
+ public CassandraClient cassandraClient() {
+ return new CassandraClient();
+ }
+
+ @Bean(name = "operational-environment-dao")
+ public OperationalEnvironmentDao operationalEnvironmentDao() {
+ return new OperationalEnvironmentDao();
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEnvironment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEnvironment.java
new file mode 100644
index 0000000000..1caf073c79
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEnvironment.java
@@ -0,0 +1,119 @@
+package org.openecomp.sdc.asdctool.simulator.tenant;
+
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+
+import com.opencsv.bean.CsvBindByPosition;
+
+/**
+ * Represents line in CSV file should be imported into "operationalenvironment" table.
+ * @author dr2032
+ *
+ */
+public class OperationalEnvironment {
+ @CsvBindByPosition(position = 0)
+ private String environmentId;
+
+ @CsvBindByPosition(position = 1)
+ private String dmaapUebAddress;
+
+ @CsvBindByPosition(position = 2)
+ private String ecompWorkloadContext;
+
+ @CsvBindByPosition(position = 3)
+ private Boolean isProduction;
+
+ @CsvBindByPosition(position = 4)
+ private String lastModified;
+
+ @CsvBindByPosition(position = 5)
+ private String status;
+
+ @CsvBindByPosition(position = 6)
+ private String tenant;
+
+ @CsvBindByPosition(position = 7)
+ private String uebApikey;
+
+ @CsvBindByPosition(position = 8)
+ private String uebSecretKey;
+
+
+
+ public String getLastModified() {
+ return lastModified;
+ }
+
+ public void setLastModified(String lastModified) {
+ this.lastModified = lastModified;
+ }
+
+
+ public String getEnvironmentId() {
+ return environmentId;
+ }
+
+ public void setEnvironmentId(String environmentId) {
+ this.environmentId = environmentId;
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public void setTenant(String tenant) {
+ this.tenant = tenant;
+ }
+
+ public Boolean getIsProduction() {
+ return isProduction;
+ }
+
+ public void setIsProduction(Boolean production) {
+ isProduction = production;
+ }
+
+ public String getEcompWorkloadContext() {
+ return ecompWorkloadContext;
+ }
+
+ public void setEcompWorkloadContext(String ecompWorkloadContext) {
+ this.ecompWorkloadContext = ecompWorkloadContext;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public void setStatus(EnvironmentStatusEnum status) {
+ this.status = status.getName();
+ }
+
+ public String getDmaapUebAddress() {
+ return dmaapUebAddress;
+ }
+
+ public void setDmaapUebAddress(String dmaapUebAddress) {
+ this.dmaapUebAddress = dmaapUebAddress;
+ }
+
+ public String getUebApikey() {
+ return uebApikey;
+ }
+
+ public void setUebApikey(String uebApikey) {
+ this.uebApikey = uebApikey;
+ }
+
+ public String getUebSecretKey() {
+ return uebSecretKey;
+ }
+
+ public void setUebSecretKey(String uebSecretKey) {
+ this.uebSecretKey = uebSecretKey;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEvnironmentImportHandler.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEvnironmentImportHandler.java
new file mode 100644
index 0000000000..d4dbddde3f
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/simulator/tenant/OperationalEvnironmentImportHandler.java
@@ -0,0 +1,99 @@
+package org.openecomp.sdc.asdctool.simulator.tenant;
+
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+import com.opencsv.bean.CsvToBeanBuilder;
+
+/**
+ * Imports CSV file into
+ * Example of line in the file
+ * 00002,135.42.43.45:5757,Context,FALSE,2017-10-11 12:02:01,INITIAL,personal tenant,abcd123456789,bbbbbbbbbbb
+ * Date format is fixed: yyyy-MM-dd HH:mm:ss
+ * @author dr2032
+ *
+ */
+public class OperationalEvnironmentImportHandler {
+ private static final Logger LOGGER = LoggerFactory.getLogger(OperationalEvnironmentImportHandler.class);
+ private static final String TABLE_NAME = Table.SDC_OPERATIONAL_ENVIRONMENT.getTableDescription().getTableName();
+
+ private OperationalEvnironmentImportHandler() {
+
+ }
+
+ public static void execute(String fileName) {
+ try {
+ List<OperationalEnvironment> beans = new CsvToBeanBuilder<OperationalEnvironment>(new FileReader(fileName))
+ .withType(OperationalEnvironment.class).build().parse();
+
+ List<OperationalEnvironmentEntry> entries = map(beans);
+ modifyDb(entries);
+ LOGGER.info("File {} has been successfully imported into the [{}] table.", fileName, TABLE_NAME);
+ } catch (IllegalStateException | FileNotFoundException e) {
+ String errorMessage = String.format("Failed to import file: %s into the [%s] table ", fileName, TABLE_NAME);
+ LOGGER.error(errorMessage, e);
+ }
+ }
+
+ private static List<OperationalEnvironmentEntry> map(List<OperationalEnvironment> beans) {
+ return beans.stream()
+ .map(OperationalEvnironmentImportHandler::map)
+ .collect(Collectors.toList());
+
+ }
+
+ private static OperationalEnvironmentEntry map(OperationalEnvironment perationalEnvironment) {
+ OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
+
+ entry.setEnvironmentId(perationalEnvironment.getEnvironmentId());
+ entry.addDmaapUebAddress(perationalEnvironment.getDmaapUebAddress());
+ entry.setEcompWorkloadContext(perationalEnvironment.getEcompWorkloadContext());
+ entry.setIsProduction(perationalEnvironment.getIsProduction());
+
+ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ try {
+ entry.setLastModified(formatter.parse(perationalEnvironment.getLastModified()));
+ } catch (ParseException e) {
+ LOGGER.error("Faild to pase Date, expected format is [yyyy-MM-dd HH:mm:ss].", e);
+ throw new RuntimeException(e);
+ }
+
+ entry.setStatus(perationalEnvironment.getStatus());
+ entry.setTenant(perationalEnvironment.getTenant());
+ entry.setUebApikey(perationalEnvironment.getUebApikey());
+ entry.setUebSecretKey(perationalEnvironment.getUebSecretKey());
+
+ return entry;
+
+ }
+
+ private static OperationalEnvironmentDao createDaoObj() {
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ImportTableConfig.class);
+ return (OperationalEnvironmentDao) context.getBean("operational-environment-dao");
+ }
+
+ private static void modifyDb(List<OperationalEnvironmentEntry> environments) {
+ OperationalEnvironmentDao daoObj = createDaoObj();
+
+ daoObj.deleteAll();
+
+ environments.forEach(daoObj::save);
+ }
+
+ public static String getTableName() {
+ return TABLE_NAME;
+ }
+
+
+}
diff --git a/asdctool/src/main/resources/config/configuration.yaml b/asdctool/src/main/resources/config/configuration.yaml
index 48529a7c78..c92827e558 100644
--- a/asdctool/src/main/resources/config/configuration.yaml
+++ b/asdctool/src/main/resources/config/configuration.yaml
@@ -31,15 +31,12 @@ appVersion: 1.1.0
artifactGeneratorConfig: Artifact-Generator.properties
resourcesForUpgrade:
5.0:
- - org.openecomp.resource.cp.extCP
- - tosca.nodes.network.Network
- - tosca.nodes.network.Port
- - org.openecomp.resource.cp.nodes.network.SubInterface
+ - tosca.nodes.Root
skipUpgradeFailedVfs: true
skipUpgradeVSPs: true
autoHealingOwner: jh0003
-titanCfgFile: C:\Users\im453s\git\sdc\asdctool\src\main\resources\config\titan.properties
+titanCfgFile: src\main\resources\config\titan.properties
titanMigrationKeySpaceCfgFile: src\main\resources\config\titan-migration.properties
titanInMemoryGraph: false
titanLockTimeout: 1800
@@ -206,7 +203,6 @@ toscaArtifacts:
type: TOSCA_CSAR
description: TOSCA definition package of the asset
-
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
@@ -333,7 +329,7 @@ serviceDeploymentArtifacts:
- xml
AAI_VF_INSTANCE_MODEL:
acceptedTypes:
- - xml
+ - xml
OTHER:
acceptedTypes:
diff --git a/asdctool/src/main/resources/config/error-configuration.yaml b/asdctool/src/main/resources/config/error-configuration.yaml
index d33876a7df..6a4aece245 100644
--- a/asdctool/src/main/resources/config/error-configuration.yaml
+++ b/asdctool/src/main/resources/config/error-configuration.yaml
@@ -100,6 +100,12 @@ errors:
message: "Error: Invalid USER_ID '%1'.",
messageId: "SVC4008"
}
+#---------SVC ------------------------------
+ INVALID_SERVICE_STATE: {
+ code: 409,
+ message: "Error: Invalid service state. Expected state: %1, actual state: %2",
+ messageId: ""
+ }
#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
@@ -593,7 +599,7 @@ errors:
}
#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
- code: 409,
+ code: 403,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
@@ -1669,3 +1675,18 @@ errors:
messageId: "SVC4647"
}
+
+#---------SVC4673------------------------------
+ INVALID_SERVICE_STATE: {
+ code: 409,
+ message: "Error: Invalid service state. Expected state: %1, actual state: %2",
+ messageId: "SVC4673"
+ }
+
+#---------SVC4674------------------------------
+ INVALID_RESPONSE_FROM_PROXY: {
+ code: 502,
+ message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server",
+ messageId: "SVC4674"
+ }
+
diff --git a/asdctool/src/main/resources/scripts/getConsumers.sh b/asdctool/src/main/resources/scripts/getConsumers.sh
new file mode 100644
index 0000000000..d02aac629d
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/getConsumers.sh
@@ -0,0 +1,37 @@
+#!/bin/bash
+
+##############################
+# Get list of SDC consumers
+##############################
+
+
+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.GetConsumersMenu"
+
+command="java $JVM_LOG_FILE -Xmx1024M -cp $JARS $mainClass $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
+
diff --git a/asdctool/src/main/resources/scripts/python/user/exportUsers.py b/asdctool/src/main/resources/scripts/python/user/exportUsers.py
index e32a3b0a21..9e695ad8fd 100644
--- a/asdctool/src/main/resources/scripts/python/user/exportUsers.py
+++ b/asdctool/src/main/resources/scripts/python/user/exportUsers.py
@@ -4,17 +4,17 @@ from StringIO import StringIO
import json
-################################################################################################################################################
-# #
-# Export all active users to file - for 1602+ #
-# #
-# activation : #
-# python exportUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <output file> | --ofile=<output file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python exportUsers.py [-f <output file> | --ofile=<output file> ] #
-# #
-################################################################################################################################################
+####################################################################################################################################################################################
+# #
+# Export all active users to file - for 1602+ #
+# #
+# activation : #
+# python exportUsers.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <output file> | --ofile=<output file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python exportUsers.py [-f <output file> | --ofile=<output file> ] #
+# #
+####################################################################################################################################################################################
ALL_USERS_SUFFIX = '/sdc2/rest/v1/user/users'
@@ -25,19 +25,23 @@ def errorAndExit(errorCode, errorDesc):
print("status=" + str(errorCode))
sys.exit(errorCode)
-def getUsers(beHost, bePort, adminUser):
+def getUsers(scheme, beHost, bePort, adminUser):
try:
buffer = StringIO()
c = pycurl.Curl()
- url = 'http://' + beHost + ':' + bePort + ALL_USERS_SUFFIX
+ url = scheme + '://' + beHost + ':' + bePort + ALL_USERS_SUFFIX
print(url)
c.setopt(c.URL, url)
c.setopt(c.WRITEFUNCTION, buffer.write)
#c.setopt(c.WRITEFUNCTION, lambda x: None)
adminHeader = 'USER_ID: ' + adminUser
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
+
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
res = c.perform()
#print(res)
@@ -63,7 +67,7 @@ def getUsers(beHost, bePort, adminUser):
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <output file> | --ofile=<output file> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <output file> | --ofile=<output file> ]'
def main(argv):
print 'Number of arguments:', len(sys.argv), 'arguments.'
@@ -72,9 +76,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
outputfile = None
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:f:h:",["ip=","port=","ofile="])
+ opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ofile=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -90,14 +95,16 @@ def main(argv):
bePort = arg
elif opt in ("-f", "--ofile"):
outputfile = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', output file =',outputfile
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', output file =',outputfile
if ( outputfile == None ):
usage()
sys.exit(3)
- users = getUsers(beHost, bePort, adminHeader)
+ users = getUsers(scheme, beHost, bePort, adminHeader)
error = users[1]
body = users[0]
diff --git a/asdctool/src/main/resources/scripts/python/user/importUsers.py b/asdctool/src/main/resources/scripts/python/user/importUsers.py
index 669cbbe6f2..984b75bd4c 100644
--- a/asdctool/src/main/resources/scripts/python/user/importUsers.py
+++ b/asdctool/src/main/resources/scripts/python/user/importUsers.py
@@ -4,20 +4,20 @@ from StringIO import StringIO
import json
import copy
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
-
-
-def importUsers(beHost, bePort, users, adminUser):
+#####################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importUsers.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importUsers.py [-f <input file> | --ifile=<input file> ] #
+# #
+#####################################################################################################################################################################################
+
+
+def importUsers(scheme, beHost, bePort, users, adminUser):
result = []
@@ -25,12 +25,12 @@ def importUsers(beHost, bePort, users, adminUser):
#print("Going to add user " + user['userId'])
- getRes = getUser(beHost, bePort, user)
+ getRes = getUser(scheme, beHost, bePort, user)
userId = getRes[0]
error = getRes[1]
#print error
if ( error != None and error == 404 ):
- res = createUser(beHost, bePort, user ,adminUser)
+ res = createUser(scheme, beHost, bePort, user ,adminUser)
result.append(res)
else:
if ( error == 200 ):
@@ -54,7 +54,7 @@ def convertUsersToCreationObject(users):
return cloneUsers
-def getUser(beHost, bePort, user):
+def getUser(scheme, beHost, bePort, user):
userId = user['userId']
try:
@@ -62,12 +62,16 @@ def getUser(beHost, bePort, user):
c = pycurl.Curl()
#print type(userId)
- url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
+ url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
c.setopt(c.URL, url)
#adminHeader = 'USER_ID: ' + adminUser
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
c.setopt(c.WRITEFUNCTION, lambda x: None)
+
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
res = c.perform()
#print("Before get response code")
@@ -87,14 +91,14 @@ def getUser(beHost, bePort, user):
-def createUser(beHost, bePort, user, adminUser):
+def createUser(scheme, beHost, bePort, user, adminUser):
userId = user['userId']
try:
buffer = StringIO()
c = pycurl.Curl()
- url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
+ url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
c.setopt(c.URL, url)
c.setopt(c.POST, 1)
@@ -105,6 +109,10 @@ def createUser(beHost, bePort, user, adminUser):
c.setopt(c.POSTFIELDS, data)
c.setopt(c.WRITEFUNCTION, lambda x: None)
+
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
#print("before perform")
res = c.perform()
#print(res)
@@ -133,7 +141,7 @@ def errorAndExit(errorCode, errorDesc):
sys.exit(errorCode)
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]'
def main(argv):
print 'Number of arguments:', len(sys.argv), 'arguments.'
@@ -141,11 +149,11 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
inputfile = None
-
+ scheme = 'http'
adminUser = 'jh0003'
try:
- opts, args = getopt.getopt(argv,"i:p:f:h:",["ip=","port=","ifile="])
+ opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -161,8 +169,10 @@ def main(argv):
bePort = arg
elif opt in ("-f", "--ifile"):
inputfile = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', users file =',inputfile
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile
if ( inputfile == None ):
usage()
@@ -182,7 +192,7 @@ def main(argv):
#print activeUsers
- resultTable = importUsers(beHost, bePort, activeUsers, adminUser)
+ resultTable = importUsers(scheme, beHost, bePort, activeUsers, adminUser)
g = lambda x: x[1] != 201 and x[1] != 409
diff --git a/asdctool/src/main/resources/scripts/sdc-migration.sh b/asdctool/src/main/resources/scripts/sdc-migration.sh
index bbdd6f0f7b..15e6d6b6e1 100644
--- a/asdctool/src/main/resources/scripts/sdc-migration.sh
+++ b/asdctool/src/main/resources/scripts/sdc-migration.sh
@@ -5,7 +5,7 @@
##############################
# in 1802E we do not want to execute automatic post process
-exit 0
+#exit 0
CURRENT_DIR=`pwd`
BASEDIR=$(dirname $0)
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfigTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfigTest.java
deleted file mode 100644
index c97bffc4d8..0000000000
--- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfigTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package org.openecomp.sdc.asdctool.migration.config;
-
-import org.junit.Test;
-import org.openecomp.sdc.asdctool.migration.core.SdcMigrationTool;
-import org.openecomp.sdc.asdctool.migration.dao.MigrationTasksDao;
-import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
-import org.openecomp.sdc.asdctool.migration.resolver.SpringBeansMigrationResolver;
-import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
-import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
-
-
-public class MigrationSpringConfigTest {
-
- private MigrationSpringConfig createTestSubject() {
- return new MigrationSpringConfig();
- }
-
-
- @Test
- public void testSdcMigrationTool() throws Exception {
- MigrationSpringConfig testSubject;
- MigrationResolver migrationResolver = null;
- SdcRepoService sdcRepoService = null;
- SdcMigrationTool result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.sdcMigrationTool(migrationResolver, sdcRepoService);
- }
-
-
- @Test
- public void testMigrationResolver() throws Exception {
- MigrationSpringConfig testSubject;
- SdcRepoService sdcRepoService = null;
- SpringBeansMigrationResolver result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.migrationResolver(sdcRepoService);
- }
-
-
- @Test
- public void testSdcRepoService() throws Exception {
- MigrationSpringConfig testSubject;
- MigrationTasksDao migrationTasksDao = null;
- SdcRepoService result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.sdcRepoService(migrationTasksDao);
- }
-
-
- @Test
- public void testMigrationTasksDao() throws Exception {
- MigrationSpringConfig testSubject;
- MigrationTasksDao result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.migrationTasksDao();
- }
-
-
- @Test
- public void testCassandraClient() throws Exception {
- MigrationSpringConfig testSubject;
- CassandraClient result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.cassandraClient();
- }
-} \ No newline at end of file
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java
index 2cb5e2999c..0c1b32efd2 100644
--- a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/UpgradeMigration1710Test.java
@@ -1,26 +1,17 @@
package org.openecomp.sdc.asdctool.migration.tasks.mig1710;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
+import com.google.common.collect.Lists;
+import fj.data.Either;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.tasks.handlers.XlsOutputHandler;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -31,21 +22,19 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
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.ComponentInstance;
-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.*;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import com.google.common.collect.Lists;
-
-import fj.data.Either;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class UpgradeMigration1710Test {
@@ -53,7 +42,9 @@ public class UpgradeMigration1710Test {
private final static String CONF_LEVEL = "5.0";
private final User user = new User();
- private UpgradeMigration1710 migration;
+
+ @InjectMocks
+ private UpgradeMigration1710 migration = new UpgradeMigration1710();
@Mock
private IUserAdminOperation userAdminOperation;
@Mock
@@ -66,6 +57,9 @@ public class UpgradeMigration1710Test {
private ComponentsUtils componentUtils;
@Mock
private ConfigurationSource configurationSource;
+ @Mock
+ private XlsOutputHandler outputHandler;
+
private static ConfigurationManager configurationManager;
private static List<String> resources = Stream.of("org.openecomp.resource.cp.extCP").collect(Collectors.toList());
private static Map<String, List<String>> resourcesForUpgrade;
@@ -78,12 +72,6 @@ public class UpgradeMigration1710Test {
@Before
public void setUp() {
- migration = new UpgradeMigration1710();
- migration.setUserAdminOperation(userAdminOperation);
- migration.setTitanDao(titanDao);
- migration.setTosckaOperationFacade(toscaOperationFacade);
- migration.setLifecycleBusinessLogic(lifecycleBusinessLogic);
-
user.setUserId(USER);
configurationManager = new ConfigurationManager(configurationSource);
configurationManager.setConfiguration(new Configuration());
@@ -106,11 +94,13 @@ public class UpgradeMigration1710Test {
final boolean failOnVfUpgrade = true;
final boolean upgradeServices = false;
final boolean exceptionOnVfUpgrade = false;
- final boolean upgradeFVC = false;
+ final boolean upgradeVFC = false;
configurationManager.getConfiguration().setSkipUpgradeFailedVfs(false);
resolveUserAndDefineUpgradeLevel();
- upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeFVC);
+ upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeVFC);
assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
+ verify(titanDao, times(1)).commit();
+ verify(titanDao, times(2)).rollback();
}
@Test
@@ -118,11 +108,13 @@ public class UpgradeMigration1710Test {
final boolean failOnVfUpgrade = false;
final boolean upgradeServices = false;
final boolean exceptionOnVfUpgrade = true;
- final boolean upgradeFVC = false;
+ final boolean upgradeVFC = false;
configurationManager.getConfiguration().setSkipUpgradeFailedVfs(false);
resolveUserAndDefineUpgradeLevel();
- upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeFVC);
+ upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeVFC);
assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
+ verify(titanDao, times(1)).commit();
+ verify(titanDao, times(2)).rollback();
}
@Test
@@ -130,11 +122,13 @@ public class UpgradeMigration1710Test {
final boolean failOnVfUpgrade = false;
final boolean upgradeServices = true;
final boolean exceptionOnFvUpgrade = true;
- final boolean upgradeFVC = false;
+ final boolean upgradeVFC = false;
configurationManager.getConfiguration().setSkipUpgradeFailedVfs(true);
resolveUserAndDefineUpgradeLevel();
- upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeFVC);
+ upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC);
assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
+ verify(titanDao, times(2)).commit();
+ verify(titanDao, times(3)).rollback();
}
@@ -143,10 +137,12 @@ public class UpgradeMigration1710Test {
final boolean failOnVfUpgrade = false;
final boolean upgradeServices = true;
final boolean exceptionOnFvUpgrade = false;
- final boolean upgradeFVC = false;
+ final boolean upgradeVFC = false;
resolveUserAndDefineUpgradeLevel();
- upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeFVC);
+ upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC);
assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
+ verify(titanDao, times(2)).commit();
+ verify(titanDao, times(3)).rollback();
}
@Test
@@ -154,11 +150,11 @@ public class UpgradeMigration1710Test {
final boolean failOnVfUpgrade = false;
final boolean upgradeServices = true;
final boolean exceptionOnFvUpgrade = false;
- final boolean upgradeFVC = true;
+ final boolean upgradeVFC = true;
resolveUserAndDefineUpgradeLevel();
- upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeFVC);
+ upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC);
configurationManager.getConfiguration().setSkipUpgradeVSPs(false);
- migration.setComponentsUtils(componentUtils);
+// migration.setComponentsUtils(componentUtils);
assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
}
@@ -187,7 +183,7 @@ public class UpgradeMigration1710Test {
when(titanDao.getByCriteria(any(), any(), any(), any()))
.thenReturn(Either.left(components));
- when(titanDao.getParentVertecies(any(), any(), any()))
+ when(titanDao.getParentVertecies(any(GraphVertex.class), any(), any()))
//1th node to upgrade
.thenReturn(Either.left(components))
//parent of the 1th node - stop recursion
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000000..b80295eff8
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,1436 @@
+import java.awt.Color
+import java.util.concurrent.Callable
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+
+import static Services.*
+import static ServiceControl.*
+import java.awt.AWTException
+import java.awt.Font
+import java.awt.Image
+import java.awt.Menu
+import java.awt.MenuItem
+import java.awt.PopupMenu
+import java.awt.SystemTray
+import java.awt.TrayIcon
+import java.awt.event.ActionEvent
+import java.awt.event.ActionListener
+import javax.swing.JOptionPane
+import javax.imageio.ImageIO
+
+
+group 'com.att.ecomp'
+version '1.01-SNAPSHOT'
+
+apply plugin: 'groovy'
+apply plugin: 'java'
+apply plugin: "org.hidetake.ssh"
+apply plugin: 'java-gradle-plugin'
+apply plugin: 'idea'
+
+sourceCompatibility = 1.8
+
+buildscript {
+ repositories {
+ jcenter()
+ mavenCentral()
+ }
+ dependencies {
+ classpath 'org.codehaus.groovy:groovy-all:2.4.12'
+ classpath "org.hidetake:gradle-ssh-plugin:2.9.0"
+ }
+}
+
+enum Services {
+ BACKEND , //be
+ FRONTEND , //fe
+ DB , //cassandra
+ CACHING , //elawsrticsearch
+ SECURITY , //webseal
+ ALL //all services
+}
+enum ServiceControl {
+ HEALTH ,
+ START ,
+ RESTART ,
+ STOP ,
+ KILL
+}
+//env variables
+//fill YOUR_WINDOWS_USER_HOME
+project.ext.set("NEW_VAG",Boolean.FALSE) //flags to use new vagrant configuration
+project.ext.set("IS_HOTSWAP",Boolean.FALSE) //flags to use new vagrant configuration
+project.ext.set("PROJECT_PATH", System.getenv("SDC")) //ex. 'C:\\GIT_WORK\\asdc\\sdc')
+project.ext.set("VAGRANT_HOME", NEW_VAG ? System.getenv("NEW_VAG") : System.getenv("VAG")) //ex. 'C:\\GIT_WORK\\vagrant-asdc-all-in-one')
+project.ext.set("USER_HOME", "${System.getenv("USERPROFILE")}\\.ssh")
+project.ext.set("BE_REMOTE", NEW_VAG ? '/opt/app/jetty/base/be' : '/home/vagrant/catalog-be' )
+project.ext.set("FE_REMOTE", NEW_VAG ? '/opt/app/jetty/base/fe' : '/home/vagrant/catalog-fe' )
+project.ext.set("VAGRANT_USER", NEW_VAG ? 'm11981' : 'vagrant' )
+project.ext.set("RSA_PRIVATE_KEY_PATH", NEW_VAG ? "$VAGRANT_HOME/id_rsa" : '' )
+project.ext.set("VAGRANT_PASSWORD", NEW_VAG ? 'Aa123456' : 'vagrant' )
+project.ext.set("X_FOLDER",'/xFolder' )
+project.ext.set("BE_DEPENDENCIES", 'common-be,common-app-api,catalog-dao,catalog-model,security-utils' )
+project.ext.set("command", [ (ALL) : [ (HEALTH) : { NEW_VAG ? 'sudo curl -i http://localhost:8181/sdc1/rest/healthCheck' : 'curl -i localhost:8080/sdc2/rest/healthCheck' } ,
+ (KILL) : { NEW_VAG ? 'sudo pkill java' : 'pkill java'} ] , // TODO: refine kill only for services
+ (BACKEND) : [ (START) : { NEW_VAG ? 'sudo service jettyBE start' : 'service catalog-be start'} ,
+ (STOP) : { NEW_VAG ? 'sudo service jettyBE stop' : 'service catalog-be stop'} ,
+ (RESTART) : { NEW_VAG ? 'sudo service jettyBE restart' : 'service catalog-be restart'}] ,
+ (DB) : [ (START) : { NEW_VAG ? 'sudo service cassandra start' : 'start-asdc-storage.sh' } ,
+ (STOP) : { NEW_VAG ? 'sudo service cassandra stop' : 'service cassandra stop'} ,
+ (RESTART) : { NEW_VAG ? 'sudo service cassandra restart' : 'service cassandra restart'} ] ,
+ (FRONTEND): [ (START) : { NEW_VAG ? 'sudo service jettyFE start' : 'service catalog-fe start' } ,
+ (STOP) : { NEW_VAG ? 'sudo service jettyFE stop' : 'service catalog-fe stop'} ,
+ (RESTART) : { NEW_VAG ? 'sudo service jettyFE restart' : 'service catalog-fe restart' } ] ,
+ (CACHING): [ (START) : { NEW_VAG ? 'sudo service elasticsearch start' : 'echo "starting es is not yet supported"' } ],
+ (SECURITY): [ (START) : { NEW_VAG ? 'sudo docker start sdc-WebSeal-Simulator' : 'service webseal-simulator start' } ,
+ (STOP) : { NEW_VAG ? 'sudo docker stop sdc-WebSeal-Simulator' : 'service webseal-simulator stop'} ,
+ (RESTART) : { NEW_VAG ? 'sudo docker restart sdc-WebSeal-Simulator' : 'service webseal-simulator restart'}]
+ ] ) //abstraction level to shell scripts , support old and new vagrant bash commands
+
+//icons
+project.ext.set("warnImg",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADvSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPb/enUwzdh4E0xzttxHNQRoABOUCQYYmj+9QrCBACQHUoMM4AYga74ZDiRAmvnEwHwQGywGBOiGgA1A16wmJYjQDAJANkgMmyEosYBVMzIAuuTWs/cM6iuhfCCAGwDWrAHxKyFw68ZNuCE40wGygcga0AEkEEHRiIxxASzqUKKRHIAwAJgo4BgXwKIGxQUgf8MwOsAlh+EFUMDBMAxgE0MGoLwAignSMFQPzmgkDjAwAACSmn13nChk1QAAAABJRU5ErkJggg==')
+project.ext.set("okImg1",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAD4SURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYLbSRh8wfc9/C5jmbLmPagjQACYoEwwwNLMxgzHMIJAcSA0ygBuArFm81gyi+ddfCAaywWJAgG4I2AB0zdxWkhCNMABkg8SwGYISC1g1IwOgS74ee87wsvkUVADJAJjpyIDbRAxMfz3zCkwjA5ghONMB2DVIBiDbigwggQiKRmSMC2BRhxKN5ACEAcBEAce4ABY1LFAaDLAFJAwgyyGHB4YXQAEHwzCATQwZgPICKCZIw1A9OKOROMDAAAA4gXvZorg7ZgAAAABJRU5ErkJggg==')
+project.ext.set("okImg2" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADjSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPbWZ7Jg2lvqMZjmbLmPagjQACYoEwywaQYBGBskB1KDDOAGIGuetFsUTCMDmBi6IWAD0DUra3OA2cgAJIbNEJRYwKUZGdy9+oMhz/U1lIdkADZnwwwDaUIHMENwpgNk16DbigwggQiKRmSMC2BRhxKN5ACEAcBEAce4ABY1LFAaDLAFJAwgyyGHB4YXQAEHwzCATQwZgPICKCZIw1A9OKOROMDAAAAZD3X55epfOAAAAABJRU5ErkJggg==')
+project.ext.set("errorImg" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAADlSURBVDhPY2RgYPgPxGQDiAGLXkB4UMD56DuD9YFUhj179oD5Li4uDEcdZjN8l+ME8+EgTgLTAJDm7zWKYPZbGRUwLfzkDpjmbLmPagjQACYoEwywaQYBGBskB1KDDOAGIGtexisCppEBTAzdELAB6Jrd+QXAbGQAEsNmCEos4NKMDHZ+/MAQ9fkNlIdkADZnwwwDaUIHyIaADMDAQAP/AwMPjEFsbGpAGGs6AEUPsnfgzsaiDiUayQUgF2A4jaAXoHpQXAByNgyjA1xyGF4A+RuGYQCbGDLA6gWCGKoHJSGRDhgYAL/hkunRq+joAAAAAElFTkSuQmCC')
+project.ext.set("unavailableImg" , 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAABJ0AAASdAHeZh94AAAAB3RJTUUH4QwNDgEDrNoaqgAAAOhJREFUOMulkz8OgjAUhz8MQ7mBkwnnkBAH4mbCCdxcXLwAoxdwYXHjBCRupoMheg4TJ29QNhwshMofSfpLOry2v6/vta8OUGEhF4DsbUx6L8XytkNKCUAURTxWZ9TCM93buQb8mFXiI4E43gCQ5xeQPt7x2YG4fWa0OQwDhBANRCVdyGyKOQyDJhuV+HgvZQLGzABCiEGI036FPnNbZVlSFPfvnWg1gJpea72OjPh6lUZcQ5yhPkjTkxHv94fpfcB23t81PftmWMr9e+pQZjobd6zuobX2fViXAFCRvSv9GtOH9ji23/kDswRrCVqtQOAAAAAASUVORK5CYII=')
+
+
+//health params
+project.ext.set("trayIcon", null)
+project.ext.set("lastStatus", null)
+project.ext.set("isStopHealthCheck", false)
+project.ext.set("isHaltHealth", new AtomicBoolean(false) )
+project.ext.set("startedAwait", Long.MAX_VALUE)
+project.ext.set("logFile", 'C:/ProgramData/all.log')
+project.ext.set("pomList" , ["${System?.getenv('SDC')}/catalog-fe/pom.xml" ,"${System?.getenv('SDC')}/catalog-be/pom.xml" ] ) //empty list will scan all openecomp poms
+project.ext.set("pomChangesMap" , [:] )
+project.ext.set("beConfigFilesToCopyMapping" , [ 'src/main/resources/config/*.yaml' : 'config/catalog-be/' ,
+ 'src/main/resources/config/*.properties' : 'config/catalog-be/'] )
+
+//menu item strings
+project.ext.set("toggleHealthString" , "Halt Health" )
+//menu item
+project.ext.set("toggleHealthItemView" , null )
+
+//other
+project.ext.set("IS_MVN_INSTALL",false)
+project.ext.set("executor" , null )
+project.ext.set("lockObj" , new Object() )
+/*compile?.doLast {
+ println "2. hello compile2"
+}*/
+
+/*def post(String host , String serviceName,String msg){
+ // POST
+ def post = new URL("$host/$serviceName").openConnection();
+ def message = '{"message":"this is a message"}'
+ post.setRequestMethod("POST")
+ post.setDoOutput(true)
+ post.setRequestProperty("Content-Type", "application/json")
+ post.getOutputStream().write(message.getBytes("UTF-8"));
+ def postRC = post.getResponseCode();
+ println(postRC);
+ if( postRC.equals(200)) {
+ println(post.getInputStream().getText());
+ }
+}
+
+def postStat( long operationTime, String user , String meta ){
+ def host = 'http://135.76.123.70:8888'
+ def params = "user=$user&meta=$meta"
+ post host , "UserStats" , params
+}*/
+
+
+def hash( List list ){
+ def map = list?.collectEntries { File file -> [(file?.absolutePath) : file?.text?.hashCode() ]}
+
+ map
+}
+
+def pomChanges(){
+ long started = System.currentTimeMillis()
+ if ( !pomList )
+ listPom()
+ //find hash changes
+ def changes = pomList?.findAll {
+ def File file = new File(it);
+ pomChangesMap[it] != file?.text?.hashCode()
+ }
+ println "\n\n[MasterD][POM]--> detected changes for -> $changes"
+ //update changes in map
+ changes?.each { pomChangesMap[it] = new File(it)?.text?.hashCode() }
+ println "\n\n[MasterD][POM]--> pom map -> $pomChangesMap"
+
+ println """
+ ****** POM changes detection finished after -> ${System.currentTimeMillis()- started}ms ******
+ """
+
+ changes
+}
+//list pom with updated file hashes
+def listPom(){
+ long started = System.currentTimeMillis()
+ if (!pomList) {
+ def tree = fileTree( PROJECT_PATH ).include '**/pom.xml'//.filter { it.isFile() && it?.toString()?.toLowerCase()?.endsWith('pom.xml') }
+ //println "$PROJECT_PATH list is ->${ list?.collect { it?.absolutePath } }"
+ //flatten and filter openecomp poms
+ pomList = tree?.flatten()?.findAll { File file -> file?.text?.contains('org.openecomp.sdc') }?.collect {File file -> file?.absolutePath }
+ }
+ pomChangesMap = pomList.collectEntries { absolutePath ->[ ( absolutePath ) : new File(absolutePath)?.text?.hashCode() ] }
+
+ println """ [MasterD][Init] intializing POM detector
+
+ ********* POM listing finished after -> ${System.currentTimeMillis()- started}ms *********
+ """
+ return pomList
+}
+
+
+task initialization(){
+ listPom()
+ executor = Executors.newCachedThreadPool();
+}
+
+def parallel( closure ){
+ executor?.submit(new Callable<Object>(){
+ @Override
+ public Object call() {
+ closure();
+ return null;
+ }
+ })
+}
+/*class Preferences {
+ def String Username
+ def String IsNewVagrant
+ def String IsRapidMode
+}
+
+def initXFolder(){
+ def folder = new File(X_FOLDER);
+ folder?.exists() ?: folder?.mkdirs()
+
+ new File("${folder?.absolutePath}/$PREFERENCES_FILENAME")
+}*/
+
+task tester{
+ /*doLast{
+ //postStat(10000, "shay" , "report/index")
+ listPom()
+ new File('catalog-be\\pom.xml') << "#hello"
+ pomChanges()
+ }*/
+}
+
+
+def fetchFilesByExtention(remote, local , ext ){
+ ssh.run {
+ def started = System.currentTimeMillis()
+ println "folder diff"
+ session(remotes.vagrant) {
+ //execute "cd /home/vagrant/catalog-be/tmp ; ls -lt | grep catalog-be" //todo- use my dates to filter
+ get from: remote , into: local , filter: { it?.absolutePath =~ /jetty.*catalog-be.*\.dir.*\.$ext/ } // { it?.absolutePath =~ /.*catalog-be.*dir.*classes.*/ }
+ }
+ println "fetched files in ${System.currentTimeMillis() - started} ms"
+ }
+}
+
+def updateRemoteFile(String remote , String local){
+ ssh.run {
+ def to = "$BE_REMOTE${remote[remote?.indexOf("tmp\\")..remote.size()-1].replaceAll("\\\\","/")}"
+ println "copying $local \nto\n $to"
+ session(remotes.vagrant) {
+ put from: local , into: to }
+ }
+}
+
+def compareAndSwap(){
+ def final LIMIT = 10
+ def newClasses = new File("$PROJECT_PATH\\catalog-be\\target\\classes")
+ def File jettyClasses ;
+ //locate classes
+ println "traversing.."
+ new File("build/hotswap").traverse { if (it?.directory && it?.name?.equals("classes")){
+ jettyClasses = it
+ return;
+ } }
+ def jettyClassesList = []
+ jettyClasses?.traverse { jettyClassesList << it }
+
+ println "$jettyClasses"
+ //Sort compiled classes
+ def files = []
+ newClasses?.traverse { files << it }
+ def result = files.sort{ a,b -> b.lastModified() <=> a.lastModified() }
+ println "show only last $LIMIT changes"
+ result[0..LIMIT]?.each{ println it?.lastModified() +" | "+ it?.name + (it?.directory ? "[Directory]" : "") } //show only last 10 changes
+
+ //update
+ def changesMap = [ : ] //<old,new>
+ println "updating changes"
+ result[0..LIMIT]?.each { File f -> def File other = jettyClassesList.find{ File other-> other?.absolutePath?.endsWith(f?.name) };
+ if ( !(f.directory) && f?.text?.hashCode() != other?.text?.hashCode() )
+ updateRemoteFile( other?.getAbsolutePath() , f?.getAbsolutePath() )
+ } //use hashing
+}
+
+task hotswap(){
+ doLast {
+ new File("build/hotswap")?.deleteDir()
+ new File("build/hotswap")?.mkdirs()
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ fetchFilesByExtention( "$BE_REMOTE/tmp/" , 'build/hotswap' , "class")
+ compareAndSwap()
+ }
+}
+
+remotes {
+ vagrant {
+ host = '127.0.0.1'
+ port = 2222
+ user = VAGRANT_USER
+ password = VAGRANT_PASSWORD
+ identity = NEW_VAG ? new File(RSA_PRIVATE_KEY_PATH) : null
+ }
+
+}
+
+def gitLatest(){
+
+}
+
+def newEcoSystem(){
+ //cleanTitan()
+ backupDB() //and clean all
+ //restoreDB() //restore latest
+ createSchema()
+ fillSchema()
+ postCreate()
+ startAll()
+ //todo- conside updating from git
+ updaterBEFull()
+ updaterFE()
+}
+def importHeatTypes(){
+ //todo- impl
+}
+def postCreate(){
+ importNormative()
+ importHeatTypes()
+}
+def fillSchema(){
+ // add conformence level
+}
+def createSchemaPreStep(){
+ //todo- DB up
+}
+def createSchemaPostStep(){
+ ////todo- impl create amdocs dox
+}
+def createSchema(){
+ createSchemaPreStep()
+ //todo- create schema
+ //todo- create titan
+ createSchemaPostStep()
+}
+
+def cleanTitan(){
+ execSafe{
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ execute "cqlsh -e 'DROP KEYSPACE titan;'"
+ println "[MasterD][DB_DROP]-> Dropped 'titan' KEYSPACE."
+ }
+ }
+ }
+}
+task cleanTitan {
+ doLast{
+ cleanTitan()
+ }
+}
+
+task fetchE2EDB(){
+ doLast{
+ fetchE2EDB()
+ }
+}
+def fetchE2EDB(){
+ execSafe{
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ def tmp = '$CASSANDRA_HOME/backup/e2e'
+ //execute 'mkdir $CASSANDRA_HOME/backup/e2e/'
+ //execute 'wget http://135.76.210.202:8080/ETE_backup_files/latest_ETE_backup_file.zip -P /vagrant/db'
+ println "[MasterD] download finished, unzipping.."
+ execute "unzip -u $tmp/latest_ETE_backup_file.zip" //execute 'unzip -u /vagrant/db/latest_ETE_backup_file.zip'//'
+ def folder = execute "cd $tmp; ls -d -- */"
+ println "[MasterD] unzipping finished into -> $folder , untaring.."
+ execute "tar zxf $tmp/$folder/* --strip 3 -C" +'$CASSANDRA_HOME/data | pv -l >/dev/null'
+ println "[MasterD][E2E_DB]-> Downloaded & unzipped e2e data successfully."
+ }
+ }
+ }
+}
+def copyExplodedBE() {
+ execSafe{
+ println "[MasterD][BackEnd] copying exploded war."
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ long started = System.currentTimeMillis()
+ def dirPath = "${PROJECT_PATH}/catalog-be/target/catalog-be-1.1.0-SNAPSHOT"
+ def dir = new File(dirPath);
+ println "[MasterD][BackEnd] copying ${dir?.directorySize()/(1024*1024)} MB, from ${dir?.name} to $BE_REMOTE/webapps"
+ ssh.run {
+ session(remotes.vagrant) {
+ execute "rm -R $BE_REMOTE/webapps/catalog-be-1.1.0-SNAPSHOT"
+ put from: dir?.absolutePath , into: "$BE_REMOTE/webapps"
+ }
+ }
+ println "[MasterD][BackEnd] Successfully copied exploded war in ${System.currentTimeMillis()-started}ms."
+ }
+}
+task copyExplodedBE(){
+ doLast{
+ copyExplodedBE()
+ }
+}
+def backupDB() {
+ execSafe{
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ execute 'mkdir -p $CASSANDRA_HOME/backup'
+ def res = execute 'mv $CASSANDRA_HOME/data $CASSANDRA_HOME/backup/data_$(date +\'%Y_%m_%d__%H:%M:%S\')'
+ println "[MasterD][DB_BACKUP]-> snapshot DB finished. $res"
+ }
+ }
+ }
+}
+task backupDB{
+ doLast{
+ backupDB()
+ }
+}
+
+def restoreDB(){
+ execSafe{
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ println "[MasterD]-> restoring DB"
+ execute 'mkdir -p $CASSANDRA_HOME/data'
+ def res = execute 'mv $CASSANDRA_HOME/backup/data_*/* $CASSANDRA_HOME/data'
+ println "[MasterD]-> DB restore FINISHED!! $res"
+ }
+ }
+ }
+}
+task restoreDB() {
+ doLast {
+ restoreDB()
+ }
+}
+
+def vm( ){
+ exec{
+ if (VAGRANT_HOME){
+ workingDir VAGRANT_HOME //vagrant path
+ println "*****************\nworking dir -> $VAGRANT_HOME"
+ commandLine "cmd","/c", "vagrant up"
+ //args = [ ]
+ } else {
+ println "[MasterD]--> please define windows enviroment variable VAG pointing to vagrant project"
+ }
+ }
+}
+
+task vm{
+ doLast{
+ vm()
+ }
+}
+
+def copyFE() {
+ println "[MasterD][FrontEnd] starting war copy."
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ long started = System.currentTimeMillis()
+ def target = "${PROJECT_PATH}/catalog-fe/target/"
+ def files = GFileUtils.listFiles( new File(target) , ["war"] as String[] , false);
+ files?.each{ File file ->
+ if (!file?.name?.contains('classes')){
+ println "[MasterD][FrontEnd] copying ${file.length()/(1024*1024)} MB, from ${file?.name} to $FE_REMOTE/webapps"
+ ssh.run {
+ session(remotes.vagrant) {
+ put from: file?.absolutePath , into: "$FE_REMOTE/webapps"
+ }
+ }
+ }
+
+ }
+ println "[MasterD][FrontEnd] Successfully copied war in ${System.currentTimeMillis()-started}ms."
+}
+
+task deployFE{
+ doLast {
+ copyFE()
+ }
+}
+
+
+def copyBE(){
+ println "[MasterD][BackEnd] starting war copy."
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ def target = "${PROJECT_PATH}/catalog-be/target/"
+ def files = GFileUtils.listFiles( new File(target) , ["war"] as String[] , false);
+ long started = System.currentTimeMillis()
+ files?.each{ File file ->
+ if (!file?.name?.contains('classes')){
+ println "[MasterD][BackEnd] copying ${file.length()/(1024*1024)} MB, from ${file?.name} to $BE_REMOTE/webapps"
+ ssh.run {
+ session(remotes.vagrant) {
+ put from: file?.absolutePath , into: "$BE_REMOTE/webapps"
+ }
+ }
+ }
+ }
+ println "[MasterD][BackEnd] SUCCESSFULY copied be war in ${System.currentTimeMillis()-started}ms."
+}
+
+task deployBE {
+ doLast {
+ copyBE()
+ }
+}
+def compileFE(){
+ exec{
+ println "[MasterD][FE]--> compiling project at -> ${PROJECT_PATH}\\catalog-fe"
+ workingDir "${PROJECT_PATH}" //vagrant path
+ commandLine 'cmd','/c','mvn -T 2 compile -pl catalog-fe,catalog-ui -am -Pcatalog -Dmaven.test.skip'
+ }
+}
+task compileFE(){
+ doLast{
+ compileFE()
+ }
+}
+def compileBE(){
+ exec{
+ println "[MasterD][BE]--> compiling project at -> ${PROJECT_PATH}\\catalog-be"
+ workingDir "${PROJECT_PATH}" //vagrant path
+ commandLine 'cmd','/c','mvn -T 2 compile -pl catalog-be -Pcatalog -Dmaven.test.skip'
+ }
+}
+task compileBE{
+ doLast{
+ compileBE()
+ }
+}
+
+def compile(){
+ exec{
+ println "[MasterD]--> compiling project at -> ${PROJECT_PATH}"
+ workingDir "${PROJECT_PATH}" //vagrant path
+ commandLine 'cmd','/c','mvn -T 2 compile -am -Pcatalog -Dmaven.test.skip'
+ }
+}
+
+task compile{
+ doLast{
+ compile()
+ }
+}
+def compileDependencies(){
+ def cmd = IS_MVN_INSTALL ? 'install' : 'compile'
+ exec{
+ println "[MasterD]--> compiling BE dependencies -> $BE_DEPENDENCIES [ SKIPPING TESTS!! ]"
+ workingDir "${PROJECT_PATH}" //vagrant path
+ commandLine 'cmd','/c',"mvn $cmd -pl $BE_DEPENDENCIES -Pcatalog -Dmaven.test.skip" //commandLine 'cmd', '/c','mvn -T 1C package -pl catalog-model,catalog-dao,catalog-be -P catalog -Dmaven.test.skip'
+ }
+}
+task compileDependencies {
+ doLast{
+ compileDependencies()
+ }
+}
+def compileWar(){
+ def cmd = IS_MVN_INSTALL ? 'install' : 'compile'
+ exec{
+ println "--> compiling project at -> ${PROJECT_PATH}\\catalog-be"
+ workingDir "${PROJECT_PATH}" //vagrant path
+ commandLine 'cmd','/c',"mvn -T 1 $cmd war:war -pl catalog-be -Pcatalog -Dmaven.test.skip" //commandLine 'cmd', '/c','mvn -T 1C package -pl catalog-model,catalog-dao,catalog-be -P catalog -Dmaven.test.skip'
+ }
+}
+task compileWar(){
+ doLast{
+ compileWar()
+ }
+}
+
+//deprecated - use deployBE()
+task be() {
+ doLast{
+ def started = System.currentTimeMillis();
+ exec{
+ println "[MasterD]--> copying be... [from $VAGRANT_HOME]"
+ workingDir VAGRANT_HOME //vagrant path
+ commandLine 'cmd','/c', 'copy_war_be.bat','localhost' , "$PROJECT_PATH\\catalog-be\\target\\catalog-be*.war" , "$BE_REMOTE/webapps"
+ //args = [ ]
+ }
+ println """
+ **** copying finished in -> ${System.currentTimeMillis() - started}ms ****
+ """
+ }
+}
+
+task beConfig( ) {
+ doLast{
+ exec{
+ workingDir "${System.env.VAG}" //vagrant path
+ commandLine 'cmd','/c','copy_war_be_with_configuration','localhost' , "$PROJECT_PATH\\catalog-be\\target\\catalog-be*.war" , "$BE_REMOTE/webapps"
+ //args = [ ]
+ }
+ }
+
+}
+task feConfig( ) {
+ doLast{
+ exec{
+ workingDir "${System.env.VAG}" //vagrant path
+ commandLine 'cmd','/c','copy_war_fe_with_configuration','localhost' , "$PROJECT_PATH\\catalog-fe\\target\\catalog-fe*.war" , "$FE_REMOTE/webapps"
+ //args = [ ]
+ }
+ }
+
+}
+
+task fe() {
+ doLast{
+ exec {
+ workingDir "${System.env.VAG}" //vagrant path
+ commandLine 'cmd','/c', 'copy_war_fe.bat', 'localhost', "$PROJECT_PATH\\catalog-fe\\target\\catalog-fe*.war", "$FE_REMOTE/webapps"
+ //args = [ ]
+ }
+ }
+}
+
+def installAllProject(){
+ exec{
+ println "[MasterD]--> Compiling&Installing project at -> ${PROJECT_PATH}"
+ workingDir "${PROJECT_PATH}" //vagrant path
+ commandLine 'cmd','/c','mvn -T 2 clean install -U -Pcatalog -Dmaven.test.skip'
+ }
+}
+task installAllProject {
+ doLast {
+ installAllProject()
+ }
+}
+
+task installAll {
+ doLast{
+ println '[MasterD]--> Finished!!'
+ }
+}
+installAll.dependsOn { tasks.findAll { task -> task.name.startsWith('install_') } }
+
+def install_BE(){
+ exec {
+ println '[MasterD][Install]--> Installing BE!!'
+ workingDir "${PROJECT_PATH}"
+ commandLine 'cmd','/c', 'mvn clean install -pl catalog-be -am -Pcatalog -Dmaven.test.skip'
+ //args = [ ]
+ }
+}
+
+task install_BE() {
+ doLast{
+ install_BE()
+ }
+}
+
+def install_FE() {
+ exec {
+ workingDir "${PROJECT_PATH}"
+ commandLine 'cmd','/c', 'mvn clean install -pl catalog-ui,catalog-fe -am -Pcatalog -Dmaven.test.skip'
+ }
+}
+task install_FE() {
+ doLast {
+ install_FE()
+ }
+}
+
+def updaterBERapid(){
+ /* if ( ticket() > PREVIOUS_BUILD_VAR ){
+ PREVIOUS_BUILD_VAR = ticket()*/
+ def started = System.currentTimeMillis();
+ println "[MasterD][Rapid]--> compiling changes using maven"
+ compileWar()
+ println "[MasterD][Rapid]--> copying war"
+ copyBE() //use this if you want to deploy entire war //hotswap.execute()
+ restartBackend()
+ println msg(" redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
+}
+task updaterBERapid(){
+ doLast {
+ updaterBERapid()
+ }
+}
+def updaterBE(){
+ def started = System.currentTimeMillis();
+ IS_MVN_INSTALL = pomChanges() ? true : false
+ println "[MasterD]--> compiling changes using maven"
+ compileDependencies()
+ compileWar()
+ println "[MasterD]--> copying war"
+ IS_HOTSWAP ? copyExplodedBE() : copyBE() //execute() //use this if you want to deploy entire war //hotswap.execute()
+ restartBackend()
+ println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
+}
+task updaterBE(){
+ doLast {
+ updaterBE()
+ }
+}
+def copyBEConfiguration(){
+/* execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ println msg("Stopping BackEnd Server")
+ execute command[BACKEND][STOP]()
+ }
+ }
+ }*/
+}
+def updaterBEFull(){
+ def started = System.currentTimeMillis();
+ compile()
+ println "[MasterD]--> copying war"
+ copyBE() //use this if you want to deploy entire war //hotswap.execute()
+ copyBEConfiguration()
+ println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
+}
+task updaterBEFull(){
+ doLast {
+ updaterBEFull()
+ }
+}
+def copyFEConfiguration(){
+ //todo- implement
+}
+def updaterFE(){
+ def started = System.currentTimeMillis();
+ println "[MasterD]--> compiling changes using maven"
+ compileFE()
+ println "[MasterD]--> copying war"
+ copyFE() //.execute() //use this if you want to deploy entire war //hotswap.execute()
+ copyFEConfiguration()
+ println msg("redeploy finished in -> ${System.currentTimeMillis() - started}ms ")
+}
+task updaterFE(){
+ doLast {
+ updaterFE()
+ }
+}
+def stopBackend(){
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ println msg("Stopping BackEnd Server")
+ execute command[BACKEND][STOP]()
+ }
+ }
+ }
+}
+task stopBackend(){
+ doLast {
+ stopBackend()
+ }
+}
+
+def startBackend(){
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ println msg("[MasterD] starting backend sever")
+
+ execute command[BACKEND][START]()
+ }
+ }
+ }
+ println """[MasterD]-> finished !!
+ """
+}
+task startBackend(){
+ doLast{
+ startBackend()
+ }
+}
+
+def restartBackend(){
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ println msg("[MasterD] restarting backend sever")
+
+ execute command[BACKEND][RESTART]()
+ }
+ }
+ }
+ println """[MasterD]-> finished !!
+ """
+}
+//todo- remove this if you want to auto-deploy on every file save
+/*
+compileJava.doFirst{
+ updater?.execute()
+}*/
+
+enum STATUS { UP, DOWN , UNKNOWN , UNAVAILABLE }
+
+task health(){
+ doLast {
+ prepareTray()
+ }
+}
+
+def execSafe( closure){
+ if (!lockObj) {
+ [0..4].forEach( {println "Critical ERROR : lock object is not initialized\n\nCritical ERROR : cannot run tasks\n"}() )
+ return;
+ }
+ synchronized (lockObj){
+ boolean prev = isHaltHealth.get()
+ try {
+ isHaltHealth.set(true)
+ closure()
+ } catch (Exception e) {
+ println e
+ } finally {
+ isHaltHealth.set(prev)
+ }
+ }
+}
+
+def fetchFiles( remote, local ){
+ ssh.run {
+ session(remotes.vagrant) {
+ //execute "cd /home/vagrant/catalog-be/tmp ; ls -lt | grep catalog-be" //todo- use my dates to filter
+ def f = get from: remote , into: local
+ println f?.name
+ //return f
+ }
+ //println "fetched files in ${System.currentTimeMillis() - started} ms"
+ }
+
+ //return null
+}
+
+
+def killJava(){
+ execSafe {
+ def res
+ ssh.run {
+ session( remotes.vagrant ) {
+ println """ *-*-****************************-*-*
+ killing all java proccesses
+ *-*-****************************-*-*
+ """
+ res = execute command[ALL][KILL]()
+ }
+ }
+ println res?.toString()
+ }
+}
+
+def importNormative(){
+ execSafe {
+ ssh.run {
+ session(remotes.vagrant) {
+ println """ *-*-************************************-*-*
+ importNormative
+ *-*-************************************-*-*
+ """
+ execute "python -v $BE_REMOTE/scripts/import/tosca/importNormativeAll.py"
+ }
+ }
+ }
+}
+
+def startAll(){
+ def startCassandra = """
+ #!/bin/bash
+
+ cassandra&
+ elasticsearch -d
+
+ #Wait until ES is up
+ until curl localhost:9200/_cluster/health;
+ do
+ printf "."
+ sleep 3
+ done
+
+ # Create Elastic Mapping if not exist in ES
+ createESMapping.sh
+ """
+ execSafe {
+ ssh.run {
+ session(remotes.vagrant) {
+ println """ *-*-************************************-*-*
+ starting all SDC services(DB,BE,FE,Webseal)
+ *-*-************************************-*-*
+ """
+ if ( NEW_VAG ){
+ execute command[DB][START]()
+ Thread.sleep(5000)
+ execute command[CACHING][START]()
+ }
+ else
+ execute startCassandra
+ //[0..4]?.forEach( Thread?.sleep(2000) )
+ Thread?.sleep(10000)
+ Thread?.sleep(10000)
+ execute command[BACKEND][START]()
+ execute command[FRONTEND][START]()
+ execute command[SECURITY][START]()
+ }
+ }
+ }
+}
+
+
+/*def clearLog(type: Delete){
+ delete{
+ delete 'C:/ProgramData/all.log'
+ followSymlinks = true
+ }
+}*/
+task clearLog(type: Delete){
+ doLast{
+ delete 'C:/ProgramData/all.log'
+ followSymlinks = true
+ }
+}
+def logBE(){
+ try{
+ println "\n*** logging BE all.log ***\n"
+
+ ssh.run {
+ session( remotes.vagrant ) {
+ //String now = execute 'echo \"\$(date +\'%Y_%m_%d\')\"'
+ //println "\n\n*******************************************************\n\n"+now?.toString()
+ clearLog?.execute() //todo- remove this .execute()
+ fetchFiles( '/home/vagrant/catalog-be/logs/SDC/SDC-BE/all.log' , 'C:/ProgramData') //"%USERPROFILE%\AppData\Local\")
+ //project.ext.set( "logFile" , 'C:/ProgramData/all.log' )
+
+ // -f /home/vagrant/catalog-fe/logs/*$now.stderrout.log -f /home/vagrant/catalog-be/logs/*$now.stderrout.log -f /home/vagrant/catalog-be/logs/ASDC/ASDC-BE/debug.log*'
+ }
+ }
+
+ parallel {
+ exec {
+ //if ( logFile ){
+ String notepad = 'C:\\Program Files (x86)\\Notepad++\\notepad++.exe'
+ println "logging $logFile to notepad++ [$notepad]"
+ commandLine 'cmd','/c' , notepad ,logFile
+ }
+ }
+ }catch(Exception e){
+ println "cannot open logs!!!"
+ e.printStackTrace()
+ }
+}
+task logBE(){
+ doLast{
+ logBE()
+ }
+}
+
+def toggleHealthPolling(){
+ isHaltHealth.set(!isHaltHealth.get())
+}
+//converts predefined icon to Image
+def Image convert( imageName ){
+ String encodedimage = project.ext.get(imageName);
+ byte[] byteImage = encodedimage?.split(',')[1]?.decodeBase64()
+ Image image = ImageIO.read(new ByteArrayInputStream(byteImage));
+}
+
+def refreshMenu(String imageName){
+ switch( imageName ) {
+ case 'unavailableImg' : toggleHealthString = "Resume Health"; break;
+ default : toggleHealthString = "Halt Health";
+ }
+ if (((MenuItem)toggleHealthItemView).getLabel() != toggleHealthString)
+ ((MenuItem)toggleHealthItemView).setLabel(toggleHealthString);
+}
+def startDB(){
+ println "[MasterD] Starting database.."
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ execute command[DB][START]()
+ }
+ }
+ }
+}
+task startDB(){
+ doLast {
+ startDB()
+ }
+}
+def stopDB(){
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ execute command[DB][STOP]()
+ }
+ }
+ }
+}
+task stopDB(){
+ doLast {
+ stopDB()
+ }
+}
+def startFE(){
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ execute command[FRONTEND][START]()
+ }
+ }
+ }
+}
+task startFE(){
+ doLast {
+ startFE()
+ }
+}
+def stopFE(){
+ execSafe {
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ ssh.run {
+ session(remotes.vagrant) {
+ execute command[FRONTEND][STOP]()
+ }
+ }
+ }
+}
+task stopFE(){
+ doLast {
+ stopFE()
+ }
+}
+
+def ActionListener newListener( closure ){
+ ActionListener listener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ closure()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+ listener
+}
+
+ext.updateTray = { STATUS status ->
+ lastStatus = status
+ if (SystemTray.isSupported()) {
+ // get the SystemTray instance
+ SystemTray tray = SystemTray.getSystemTray();
+ // load an image
+ String imageName = status==STATUS.UP ? (Math.random()>0.5 ?'okImg1':'okImg2') : status==STATUS.UNAVAILABLE ? 'unavailableImg' : status==STATUS.DOWN ? 'errorImg' : 'warnImg'
+ Image image = convert imageName
+ if (trayIcon != null) {
+ trayIcon.setImage(image)
+ refreshMenu(imageName);
+ return ;
+ }
+ //region -> Menu UI
+ // create a popup menu
+ PopupMenu popup = new PopupMenu();
+ // create menu item for the default action
+
+ MenuItem hotswapItem = new MenuItem("===> WAR <===");
+ hotswapItem.setFont(new Font("MONOSPACED" , Font.BOLD ,15f ))
+
+ //region Multilevel Menus
+ Menu deployMasterMenu = new Menu("DeployMaster");
+ Menu backendMenu = new Menu("Backend");
+ Menu frontendMenu = new Menu("Frontend");
+ Menu dbMenu = new Menu("Database");
+ try{
+ deployMasterMenu.setFont(new Font("Cooper Black" ,Font.BOLD ,14f ))
+ backendMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
+ frontendMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
+ dbMenu.setFont(new Font("Cooper Black" ,Font.PLAIN ,13f ))
+ }catch(Exception e){
+ println e
+ }
+
+ //DeployMaster Menu
+ MenuItem updaterBeWithDependenciesItem = new MenuItem("[BE] Quick Compile -> Deploy");
+ MenuItem updaterFullBeItem = new MenuItem("[BE] Full Install -> Deploy");
+ MenuItem updaterFeItem = new MenuItem("[FE] Quick Compile -> Deploy");
+ MenuItem updaterFullFeItem = new MenuItem("[FE] Full Install -> Deploy");
+
+ //Menu UI build
+
+ deployMasterMenu.add(updaterFullBeItem);
+ deployMasterMenu.add(updaterBeWithDependenciesItem);
+
+ deployMasterMenu.addSeparator();
+ deployMasterMenu.add(updaterFullFeItem);
+ deployMasterMenu.add(updaterFeItem);
+
+
+ //BE menu
+ MenuItem startItem = new MenuItem("[BE] Start");
+ MenuItem stopItem = new MenuItem("[BE] Stop BackEnd");
+ MenuItem copyBeWarItem = new MenuItem("[BE] Copy War");
+ backendMenu.add(startItem);
+ backendMenu.add(stopItem);
+ backendMenu.add(copyBeWarItem);
+
+ //FE menu
+ MenuItem startFEItem = new MenuItem("[FE] Start");
+ MenuItem stopFEItem = new MenuItem("[FE] Stop");
+ MenuItem copyFeWarItem = new MenuItem("[FE] Copy War");
+ frontendMenu.add(startFEItem);
+ frontendMenu.add(stopFEItem);
+ frontendMenu.add(copyFeWarItem);
+
+ //DB menu
+ MenuItem startDBItem = new MenuItem("[DB] Start");
+ MenuItem stopDBItem = new MenuItem("[DB] Stop");
+ MenuItem backupDBItem = new MenuItem("[DB] Backup");
+ MenuItem restoreDBItem = new MenuItem("[DB] Restore");
+ dbMenu.add(startDBItem);
+ dbMenu.add(stopDBItem);
+ dbMenu.add(backupDBItem);
+ dbMenu.add(restoreDBItem);
+ //endregion
+
+
+ MenuItem killItem = new MenuItem("Kill All");
+ MenuItem startAllItem = new MenuItem("Start All");
+ MenuItem importItem = new MenuItem("Import Normative");
+ MenuItem healthInfoItem = new MenuItem("[Info] Health");
+ MenuItem toggleHealthItem = new MenuItem(toggleHealthString);
+ MenuItem logsItem = new MenuItem("Logs [Beta]");
+ MenuItem exitItem = new MenuItem("Exit");
+
+ toggleHealthItemView = toggleHealthItem;
+
+ popup.add(hotswapItem);
+ popup?.addSeparator();
+ popup.add(deployMasterMenu);
+ popup?.addSeparator();
+ popup.add(backendMenu)
+ popup.add(frontendMenu)
+ popup.add(dbMenu)
+ popup?.addSeparator();
+ popup.add(startAllItem);
+ popup.add(killItem);
+ popup?.addSeparator();
+ popup.add(toggleHealthItem);
+ popup.add(healthInfoItem);
+ popup?.addSeparator();
+ popup.add(importItem);
+ popup.add(logsItem);
+ popup?.addSeparator();
+ popup.add(exitItem);
+ //endregion UI
+ // construct a TrayIcon
+ trayIcon = new TrayIcon(image, "HealthTray", popup);
+
+ //region -> Button actions
+ def listenerHotswap = newListener { project.ext.set("IS_HOTSWAP", !IS_HOTSWAP); hotswapItem?.setLabel( IS_HOTSWAP ? "==> HotSwap <==" : "===> WAR <===") }
+ // create a action listener to listen for default action executed on the tray icon
+ def listenerFullBE = newListener { parallel { install_BE(); IS_HOTSWAP ? copyExplodedBE() : copyBE(); restartBackend() } }
+ def listenerFullFE = newListener { parallel { install_FE(); copyFE() } }
+ ActionListener listenerFE = newListener { parallel { updaterFE() } }
+ ActionListener listenerBE = newListener { parallel { updaterBE() } }
+ ActionListener exitListener = newListener {
+ executor?.isShutdown() ?: executor?.shutdown()
+ tray.remove(trayIcon);
+ project.ext.set("isStopHealthCheck", true)
+ println "Shutting down.. bye bye.."
+ }
+ ActionListener stopBackendListener = newListener { stopBackend() }
+ ActionListener startBEListener = newListener { parallel { startBackend() } }
+ ActionListener killJavaListener = newListener { killJava() }
+
+ ActionListener startAllListener = newListener { parallel { startAll() } }
+
+ ActionListener listener5 = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel { importNormative() }
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ };
+
+ ActionListener listener6 = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel { healthPopup() }
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ };
+
+ ActionListener listener7 = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ logBE()//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ };
+ ActionListener listener8 = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ toggleHealthPolling()//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ };
+ ActionListener copyBeWarListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel { copyBE() }//.execute()//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ };
+
+ ActionListener startDBListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel {
+ startDB()
+ }//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+ ActionListener stopDBListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ stopDB()//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+ ActionListener dbBackupListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel {
+ backupDB()//tasks.logger.execute()
+ }
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+ ActionListener feStartListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel {
+ startFE()
+ }//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+ ActionListener feStopListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ stopFE()//tasks.logger.execute()
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+ ActionListener feCopyListener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ try {
+ parallel {
+ copyFE() //.execute()//tasks.logger.execute()
+ }
+ } catch (AWTException e1) {
+ System.err.println(e1);
+ }
+ }
+ }
+
+
+ //def listenerFullModules = newListener { parallel { installAllProject() } }
+ //region -> Button<=Listener
+ hotswapItem.addActionListener(listenerHotswap)
+ updaterFeItem.addActionListener(listenerFE)
+ updaterFullBeItem.addActionListener( listenerFullBE )
+ updaterBeWithDependenciesItem.addActionListener( listenerBE )
+ updaterFullFeItem.addActionListener( listenerFullFE )
+ stopItem.addActionListener(stopBackendListener)
+ startItem.addActionListener(startBEListener)
+ copyBeWarItem.addActionListener(copyBeWarListener);
+ killItem.addActionListener(killJavaListener)
+ startAllItem.addActionListener(startAllListener)
+ importItem.addActionListener(listener5)
+ healthInfoItem.addActionListener(listener6)
+ toggleHealthItem.addActionListener(listener8)
+ logsItem.addActionListener(listener7)
+ exitItem.addActionListener(exitListener)
+
+ startDBItem.addActionListener( startDBListener )
+ stopDBItem.addActionListener( stopDBListener )
+ backupDBItem.addActionListener( dbBackupListener )
+ copyFeWarItem.addActionListener( feCopyListener )
+ startFEItem.addActionListener( feStartListener )
+ stopFEItem.addActionListener( feStopListener )
+ //endregion
+ //endregion
+ // set the TrayIcon properties
+
+ // ...
+ // add the tray image
+ try {
+ tray.add(trayIcon);
+
+ } catch (AWTException e) {
+ System.err.println(e);
+ }
+ // ...
+ } else {
+ println "Java TrayIcon Option is not supported in your System, try enabling it. Bye Bye"
+ }
+
+}
+
+def prepareTray(){
+ long UPDATE_THRESHOLD = 3500
+ float SCALAR = 1
+ ssh.settings {
+ knownHosts = allowAnyHosts
+ }
+ while(!isStopHealthCheck) {
+ if (!isHaltHealth.get()) { //if await or await is more then 60 second return health check
+ ssh.run {
+ session(remotes.vagrant) {
+ try {
+ def healthOutput = execute command[ALL][HEALTH]()
+ if (healthOutput?.contains("Failed command .* with status 7") || healthOutput?.contains("Problem accessing /sdc2/rest/healthCheck"))
+ updateTray(STATUS.DOWN)
+ def statusCollecion = healthOutput?.findAll "\"healthCheckStatus\": \".*\""
+ def upCount = statusCollecion?.count { it?.contains("UP") }
+ def downCount = statusCollecion?.count { it?.contains("DOWN") }
+ def uknownCount = (statusCollecion?.size() - upCount) - downCount
+ println " UP -> $upCount | downCount=$downCount | uknownCount=$uknownCount "
+ (uknownCount > 0 || (downCount > 0 && upCount > 0)) ? updateTray(STATUS.UNKNOWN) : ((upCount > 0) ? updateTray(STATUS.UP) : updateTray(STATUS.DOWN))
+ SCALAR = 1
+ } catch (Exception e) {
+ updateTray(STATUS.DOWN)
+ println e
+ SCALAR = Math.min(SCALAR * 1.1, 5) //slow down on errors
+ }
+ //green color effects
+ if (lastStatus && lastStatus == STATUS.UP) {
+ trayIcon.setImage(convert(Math.random() > 0.5 ? 'okImg1' : 'okImg2'))
+ //randomly green change color
+ }
+ Thread.yield()
+ Thread?.sleep((long) (UPDATE_THRESHOLD * SCALAR))
+ }
+ }
+ }else{
+ updateTray(STATUS.UNAVAILABLE)
+ Thread.yield()
+ }
+ }
+}
+
+def healthPopup(){
+ ssh.run {
+ session(remotes.vagrant) {
+ def healthOutput = execute command[ALL][HEALTH]()
+ JOptionPane.showMessageDialog(null,
+ healthOutput,
+ "HEALTH",
+ JOptionPane.INFORMATION_MESSAGE);
+ }
+ }
+}
+
+project.ext.set("msg", { content -> """
+ ************************************************************************************************
+ ************************************************************************************************
+ ******* *********
+ ************** ****************
+ $content
+
+ ************************************************************************************************
+ ************************************************************************************************
+ """} )
diff --git a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/noContent.yml b/catalog-be/DME2preferredRouter.txt
index e69de29bb2..e69de29bb2 100644
--- a/asdc-tests/src/test/resources/CI/tests/importToscaResourceByCreateUrl/noContent.yml
+++ b/catalog-be/DME2preferredRouter.txt
diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml
index 1b2a92ddbf..fb966f4402 100644
--- a/catalog-be/pom.xml
+++ b/catalog-be/pom.xml
@@ -115,25 +115,10 @@
<scope>compile</scope>
</dependency>
- <!-- slf4j + logback -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
- <scope>compile</scope>
- </dependency>
-
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
- <version>${logback.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
+ <version>${logback.version}</version>
<scope>compile</scope>
</dependency>
@@ -141,7 +126,7 @@
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
- <version>${snakeyaml.version}</version>
+ <version>${snakeyaml.version}</version>
<scope>compile</scope>
</dependency>
@@ -176,18 +161,60 @@
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.glassfish.jersey.ext</groupId>
+ <artifactId>jersey-spring4</artifactId>
+ <version>${jersey-bom.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-web</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-beans</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ </exclusion>
+ <!-- Transitive dependency of spring-bridge -->
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ </exclusion>
+ </exclusions>
+
+ </dependency>
+
+ <!--asm-all-repackaged is a jersey dependency. in current version jersey depends on a version that was compiled using java 9 compiler
+ currently our jetty (v9.3.6) does not support java 9. as soon as jetty gets upgraded we will remove this dependency-->
+ <dependency>
+ <groupId>org.glassfish.hk2.external</groupId>
+ <artifactId>asm-all-repackaged</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.glassfish.jersey.ext</groupId>
+ <artifactId>jersey-bean-validation</artifactId>
+ </dependency>
+
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
+ <version>${httpcore.version}</version>
<scope>compile</scope>
</dependency>
@@ -201,7 +228,7 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
- <version>${commons-codec}</version>
+ <version>${commons-codec}</version>
<scope>compile</scope>
</dependency>
<!-- http client END -->
@@ -209,7 +236,7 @@
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
- <version>${servlet-api.version}</version>
+ <version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
@@ -351,7 +378,7 @@
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
- <version>${elastic-search.version}</version>
+ <version>${elastic-search.version}</version>
<scope>compile</scope>
</dependency>
@@ -384,23 +411,18 @@
<scope>compile</scope>
</dependency>
+
+
<!-- CAMBRIA CLIENT for U-EB -->
<dependency>
<groupId>com.att.nsa</groupId>
<artifactId>cambriaClient</artifactId>
- <version>0.0.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.att.nsa</groupId>
- <artifactId>saClientLibrary</artifactId>
- <version>0.0.1</version>
+ <version>1.2.1-oss</version>
<scope>compile</scope>
<exclusions>
<exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
+ <groupId>com.att.nsa</groupId>
+ <artifactId>saClientLibrary</artifactId>
</exclusion>
</exclusions>
</dependency>
@@ -520,8 +542,46 @@
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId>
+ <artifactId>dmaapClient</artifactId>
+ <version>1.1.1</version>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.att.aft</groupId>
+ <artifactId>dme2</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.att.aft</groupId>
+ <artifactId>dme2</artifactId>
+ <version>3.1.200-oss</version>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.jms</groupId>
+ <artifactId>jms</artifactId>
+ <version>1.1</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ <version>3.1.0</version>
+ <scope>provided</scope>
+ </dependency>
+
<!-- TEST -->
<dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-bundle</artifactId>
<version>${jersey-bom.version}</version>
@@ -529,17 +589,37 @@
<scope>test</scope>
</dependency>
+ <!--<dependency>-->
+ <!--<groupId>org.glassfish.jersey.test-framework.providers</groupId>-->
+ <!--<artifactId>jersey-test-framework-provider-inmemory</artifactId>-->
+ <!--<version>${jersey-bom.version}</version>-->
+ <!--<scope>test</scope>-->
+ <!--</dependency>-->
+
+ <dependency>
+ <groupId>org.glassfish.jersey.core</groupId>
+ <artifactId>jersey-client</artifactId>
+ <version>${jersey-bom.version}</version>
+ <!--<scope>test</scope>-->
+ </dependency>
+
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock</artifactId>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
- <version>${jetty.version}</version>
+ <version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
- <version>${jetty.version}</version>
+ <version>${jetty.version}</version>
<scope>test</scope>
</dependency>
@@ -553,14 +633,6 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <version>${assertj.version}</version>
<scope>test</scope>
</dependency>
@@ -577,6 +649,18 @@
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>io.cucumber</groupId>
+ <artifactId>cucumber-java</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>io.cucumber</groupId>
+ <artifactId>cucumber-junit</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
@@ -614,6 +698,41 @@
</plugin>
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>copy-dependencies</id>
+ <phase>package</phase>
+ <goals>
+ <goal>copy-dependencies</goal>
+ </goals>
+ <configuration>
+ <includeScope>compile</includeScope>
+ </configuration>
+ </execution>
+ <execution>
+ <id>copy-installed</id>
+ <phase>install</phase>
+ <goals>
+ <goal>copy</goal>
+ </goals>
+ <configuration>
+ <artifactItems>
+ <artifactItem>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>${project.artifactId}</artifactId>
+ <version>${project.version}</version>
+ <type>${project.packaging}</type>
+ </artifactItem>
+ </artifactItems>
+ <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-backend/</outputDirectory>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-maven-plugin</artifactId>
<version>${jcabi.plugin.version}</version>
@@ -627,6 +746,71 @@
</plugin>
<plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>2.6</version>
+ <executions>
+ <execution>
+ <id>copy-normatives</id>
+ <phase>install</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-normatives/files/default</outputDirectory>
+ <resources>
+ <resource>
+ <directory>./target</directory>
+ <includes>
+ <include>normatives.tar.gz</include>
+ </includes>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+
+ <execution>
+ <id>copy-static-configuration-files</id>
+ <phase>install</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.parent.basedir}/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default</outputDirectory>
+ <resources>
+ <resource>
+ <directory>${project.parent.basedir}/catalog-be/src/main/resources/config</directory>
+ <includes>
+ <include>Artifact-Generator.properties</include>
+ <include>error-configuration.yaml</include>
+ <include>ecomp-error-configuration.yaml</include>
+ <include>logback.xml</include>
+ </includes>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+
+ <execution>
+ <id>copy-tosca-folder</id>
+ <!-- here the phase you need -->
+ <phase>install</phase>
+ <goals>
+ <goal>copy-resources</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.parent.basedir}/asdctool/tosca</outputDirectory>
+ <resources>
+ <resource>
+ <directory>${project.parent.basedir}/catalog-be/src/main/resources/import/tosca</directory>
+ <filtering>true</filtering>
+ </resource>
+ </resources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
@@ -691,6 +875,33 @@
</filesets>
</configuration>
</execution>
+
+ <execution>
+ <id>clean-static-files</id>
+ <phase>clean</phase>
+ <goals>
+ <goal>clean</goal>
+ </goals>
+ <configuration>
+ <filesets>
+ <!-- tosca files -->
+ <fileset>
+ <directory>${project.parent.basedir}/asdctool/tosca</directory>
+ <followSymlinks>false</followSymlinks>
+ </fileset>
+ <!-- static configuration files -->
+ <fileset>
+ <directory>${project.parent.basedir}/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default</directory>
+ <includes>
+ <include>Artifact-Generator.properties</include>
+ <include>error-configuration.yaml</include>
+ <include>ecomp-error-configuration.yaml</include>
+ <include>logback.xml</include>
+ </includes>
+ </fileset>
+ </filesets>
+ </configuration>
+ </execution>
</executions>
</plugin>
@@ -753,16 +964,16 @@
</build>
<profiles>
- <profile>
- <id>catalog</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
-
- <build>
- <finalName>${project.artifactId}-${project.version}</finalName>
- </build>
- </profile>
+ <profile>
+ <id>catalog</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+
+ <build>
+ <finalName>${project.artifactId}-${project.version}</finalName>
+ </build>
+ </profile>
<profile>
<id>docker-staging</id>
<properties>
@@ -874,7 +1085,7 @@
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
- <version>0.23.0</version>
+ <version>${fabric8.version}</version>
<configuration>
<verbose>true</verbose>
diff --git a/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz b/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz
index 873c8e00ce..474e9c70ae 100644
--- a/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz
+++ b/catalog-be/sdc-backend-init/chef-repo/cookbooks/sdc-catalog-be-setup/files/default/normatives.tar.gz
Binary files differ
diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
index 825dd54061..9bb4c33dec 100644
--- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
+++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
@@ -659,3 +659,56 @@ environmentContext:
- Needed_Non-Revenue
- Useful_Non-Revenue
- General_Non-Revenue
+
+dmaapConsumerConfiguration:
+ hosts: olsd004.wnsnet.attws.com:3905
+ consumerGroup: asdc
+ consumerId: mama
+ timeoutMs: 15000
+ limit: 1
+ pollingInterval: 2
+ topic: com.att.sdc.23911-SDCforTestDev-v001
+ latitude: 32.109333
+ longitude: 34.855499
+ version: 1.0
+ serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+ environment: TEST
+ partner: BOT_R
+ routeOffer: MR1
+ protocol: https
+ contenttype: application/json
+ dme2TraceOn: true
+ aftEnvironment: AFTUAT
+ aftDme2ConnectionTimeoutMs: 15000
+ aftDme2RoundtripTimeoutMs: 240000
+ aftDme2ReadTimeoutMs: 50000
+ dme2preferredRouterFilePath: DME2preferredRouter.txt
+ timeLimitForNotificationHandleMs: 120000
+ credential:
+ username: m09875@sdc.att.com
+ password: hmXYcznAljMSisdy8zgcag==
+
+dmeConfiguration:
+ dme2Search: DME2SEARCH
+ dme2Resolve: DME2RESOLVE
+
+excludedPolicyTypesMapping:
+ # VF:
+ # - a.b.c
+ # - c.d.e
+ #CR:
+ # - x.y.z
+
+excludedGroupTypesMapping:
+ CR:
+ - org.openecomp.groups.VfModule
+ - org.openecomp.groups.heat.HeatStack
+ - tosca.groups.Root
+ VF:
+ - org.openecomp.groups.VfModule
+ - org.openecomp.groups.heat.HeatStack
+ - tosca.groups.Root
+ Service:
+ - org.openecomp.groups.VfModule
+ - org.openecomp.groups.heat.HeatStack
+ - tosca.groups.Root \ No newline at end of file
diff --git a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb
index 3491035fcf..f85ce4acde 100644
--- a/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb
+++ b/catalog-be/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-distribution-engine-configuration.yaml.erb
@@ -43,4 +43,40 @@ createTopic:
startDistributionEngine: true
#This is false by default, since ONAP Dmaap currently doesn't support https
-useHttpsWithDmaap: false \ No newline at end of file
+useHttpsWithDmaap: false
+opEnvRecoveryIntervalSec: 180
+allowedTimeBeforeStaleSec: 300
+
+aaiConfig:
+ httpRequestConfig:
+ serverRootUrl: https://aai-uint3.test.att.com:8443
+ resourceNamespaces:
+ operationalEnvironments: /aai/v12/cloud-infrastructure/operational-environments
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 5000
+ connectTimeoutMs: 1000
+ clientCertificate:
+ keyStore: /opt/app/jetty/base/be/etc/non-prod.jks
+ keyStorePassword: hmXYcznAljMSisdy8zgcag==
+ headers:
+ X-FromAppId: asdc
+ numOfRetries: 3
+
+msoConfig:
+ httpRequestConfig:
+ serverRootUrl: http://127.0.0.1:8080/onap/mso/infra/modelDistributions/v1
+ resourceNamespaces:
+ distributions: /distributions
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 2000
+ connectTimeoutMs: 500
+ basicAuthorization:
+ userName: asdc
+ password: OTLEp5lfVhYdyw5EAtTUBQ==
+ numOfRetries: 3
+
+currentArtifactInstallationTimeout: 120
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java
new file mode 100644
index 0000000000..eed347f781
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.api;
+
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+
+import java.util.List;
+
+public interface AuditEventFactory {
+
+ String getLogMessage();
+ AuditingGenericEvent getDbEvent();
+ List<Pair<String, String>> getQueryParams();
+
+ //TODO remove together with ES related code
+ String getAuditingEsType();
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java
deleted file mode 100644
index b6cd4320f4..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/IAuditingManager.java
+++ /dev/null
@@ -1,29 +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.auditing.api;
-
-import java.util.EnumMap;
-
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-
-public interface IAuditingManager {
- void auditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields);
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java
new file mode 100644
index 0000000000..b68ee0db23
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java
@@ -0,0 +1,28 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.AuthEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditAuthRequestEventFactory extends AuditBaseEventFactory {
+
+ private final static String LOG_STR = "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\"";
+
+ final private AuthEvent event;
+
+ public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus) {
+ super(AuditingActionEnum.AUTH_REQUEST);
+ event = new AuthEvent(getAction().getName(), commonFields, authUser, authUrl, realm, authStatus);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getUrl(), event.getUser(), event.getAuthStatus(), event.getRealm());
+ }
+
+
+
+ @Override
+ public AuditingGenericEvent getDbEvent() { return event; }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java
new file mode 100644
index 0000000000..8636c1b01d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java
@@ -0,0 +1,114 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.apache.commons.lang.StringUtils;
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.common.api.Constants;
+
+import java.util.Collections;
+import java.util.List;
+
+public abstract class AuditBaseEventFactory implements AuditEventFactory {
+
+ //TODO imanzon: Check if requestId and serviceInstanceId fields are required for all tables.
+ //Currently they are included even if they ahs null value. If they should not appear then
+ //createTable code should be updated so that they need to be removed from the tables
+ private AuditingActionEnum action;
+
+ public AuditBaseEventFactory(AuditingActionEnum action) {
+ this.action = action;
+ }
+
+ public AuditingActionEnum getAction() {
+ return action;
+ }
+
+ public static String buildUserNameExtended(User user) {
+ if (user == null) {
+ return null;
+ }
+
+ StringBuilder builder = new StringBuilder();
+ appendIfNotEmpty(user.getUserId(), builder);
+
+ String firstName = replaceNullNameWithEmpty(user.getFirstName());
+ String lastName = replaceNullNameWithEmpty(user.getLastName());
+
+ if (appendIfNotEmpty(firstName, builder)) {
+ appendIfNotEmpty(lastName, builder, " ");
+ }
+ else {
+ appendIfNotEmpty(lastName, builder);
+ }
+ appendIfNotEmpty(user.getEmail(), builder);
+ appendIfNotEmpty(user.getRole(), builder);
+
+ return builder.toString();
+ }
+
+ private static boolean appendIfNotEmpty(String value, StringBuilder builder) {
+ return appendIfNotEmpty(value, builder, ", ");
+ }
+
+ protected static boolean appendIfNotEmpty(String value, StringBuilder builder, String delimiter) {
+ if (StringUtils.isEmpty(value)) {
+ return false;
+ }
+ addDelimiterIfNeeded(builder, delimiter);
+ builder.append(value);
+ return true;
+ }
+
+ private static void addDelimiterIfNeeded(StringBuilder builder, String delimiter) {
+ if (builder.length() > 0) {
+ builder.append(delimiter);
+ }
+ }
+
+ protected static String buildUserName(User user) {
+ if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
+ return Constants.EMPTY_STRING;
+ }
+ StringBuilder sb = new StringBuilder();
+ String firstName = replaceNullNameWithEmpty(user.getFirstName());
+ if (!firstName.isEmpty()) {
+ sb.append(firstName);
+ sb.append(" ");
+ }
+ String lastName = replaceNullNameWithEmpty(user.getLastName());
+ if (!lastName.isEmpty()) {
+ sb.append(lastName);
+ }
+ sb.append("(").append(user.getUserId()).append(")");
+ return sb.toString();
+ }
+
+ public static String buildValue(String value) {
+ if (value == null) {
+ return Constants.EMPTY_STRING;
+ }
+ return value;
+ }
+
+ protected static String replaceNullNameWithEmpty(String name) {
+ if (name != null && !name.trim().contains(Constants.NULL_STRING)) {
+ return name;
+ }
+ return Constants.EMPTY_STRING;
+ }
+
+ @Override
+ //TODO implement in derived classes for ci testing
+ public List<Pair<String, String>> getQueryParams() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public String getAuditingEsType() {
+ return this.action.getAuditingEsType();
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java
new file mode 100644
index 0000000000..01c82e88da
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java
@@ -0,0 +1,42 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.openecomp.sdc.be.model.ConsumerDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ConsumerEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditConsumerEventFactory extends AuditBaseEventFactory {
+
+ protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" ECOMP_USER = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ private final ConsumerEvent event;
+
+ public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, ConsumerDefinition ecompUser) {
+ super(action);
+ event = new ConsumerEvent(getAction().getName(), commonFields, buildConsumerName(ecompUser), buildUserName(modifier));
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getEcompUser(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+
+
+ static String buildConsumerName(ConsumerDefinition consumer) {
+ StringBuilder ecompUser = new StringBuilder();
+ if (consumer != null) {
+ appendIfNotEmpty(consumer.getConsumerName(), ecompUser, ",");
+ appendIfNotEmpty(consumer.getConsumerSalt(), ecompUser, ",");
+ appendIfNotEmpty(consumer.getConsumerPassword(), ecompUser, ",");
+ }
+ return ecompUser.toString();
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java
new file mode 100644
index 0000000000..95dddec3ad
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent;
+
+public class AuditEcompOpEnvEventFactory extends AuditBaseEventFactory {
+ private static final String LOG_STR = "ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ID = \"%s\"" +
+ " OPERATIONAL_ENVIRONMENT_NAME = \"%s\" OPERATIONAL_ENVIRONMENT_TYPE = \"%s\" TENANT_CONTEXT = \"%s\"";
+
+ private final EcompOperationalEnvironmentEvent event;
+
+ public AuditEcompOpEnvEventFactory(AuditingActionEnum action, String operationalEnvironmentId, String operationalEnvironmentName,
+ String operationalEnvironmentType, String operationalEnvironmentAction, String tenantContext) {
+ super(action);
+ event = new EcompOperationalEnvironmentEvent(getAction().getName(), operationalEnvironmentId, operationalEnvironmentName,
+ operationalEnvironmentType, operationalEnvironmentAction, tenantContext);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getOperationalEnvironmentAction()),
+ buildValue(event.getOperationalEnvironmentId()), buildValue(event.getOperationalEnvironmentName()),
+ buildValue(event.getOperationalEnvironmentType()), buildValue(event.getTenantContext()));
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() { return event; }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java
new file mode 100644
index 0000000000..3400016ff0
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditResourceEventFactoryMananger.java
@@ -0,0 +1,76 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditArtifactResourceAdminEventFactory;
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditCertificationResourceAdminEventFactory;
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditCreateUpdateResourceAdminEventFactory;
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditDistStateChangeRequestResourceAdminEventFactory;
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditDistStateChangeResourceAdminEventFactory;
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditResourceEventFactoryMananger {
+
+
+ public static AuditBaseEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams,
+ ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did, String toscaNodeType) {
+ AuditBaseEventFactory factory = null;
+
+ switch (action) {
+ case IMPORT_RESOURCE:
+ factory = new AuditImportResourceAdminEventFactory(commonFields, prevParams, currParams,
+ resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, toscaNodeType);
+ break;
+ case CREATE_RESOURCE:
+ case UPDATE_RESOURCE_METADATA:
+ factory = new AuditCreateUpdateResourceAdminEventFactory(action, commonFields, prevParams, currParams,
+ resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING);
+ break;
+ case CHECKIN_RESOURCE:
+ case CHECKOUT_RESOURCE:
+ case UNDO_CHECKOUT_RESOURCE:
+ case CERTIFICATION_REQUEST_RESOURCE:
+ case START_CERTIFICATION_RESOURCE:
+ case CERTIFICATION_SUCCESS_RESOURCE:
+ case FAIL_CERTIFICATION_RESOURCE:
+ case CANCEL_CERTIFICATION_RESOURCE:
+ factory = new AuditCertificationResourceAdminEventFactory(action, commonFields, prevParams, currParams,
+ resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did);
+ break;
+ case ARTIFACT_UPLOAD:
+ case ARTIFACT_DELETE:
+ case ARTIFACT_METADATA_UPDATE:
+ case ARTIFACT_PAYLOAD_UPDATE:
+ case ARTIFACT_DOWNLOAD:
+ factory = new AuditArtifactResourceAdminEventFactory(action, commonFields, prevParams, currParams,
+ resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did);
+ break;
+// case DOWNLOAD_ARTIFACT:
+// factory = new AuditDownloadArtifactExternalApiEventFactory(commonFields, String resourceType, String resourceName,
+// String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+// String invariantUuid, User modifier, String artifactData);
+// break;
+ case DISTRIBUTION_STATE_CHANGE_REQUEST:
+ factory = new AuditDistStateChangeRequestResourceAdminEventFactory(commonFields, prevParams, currParams,
+ resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did);
+ break;
+ case DISTRIBUTION_STATE_CHANGE_APPROV:
+ case DISTRIBUTION_STATE_CHANGE_REJECT:
+ factory = new AuditDistStateChangeResourceAdminEventFactory(action, commonFields, prevParams, currParams,
+ resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did);
+ break;
+ default:
+ throw new UnsupportedOperationException();
+ }
+ return factory;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java
index ed0fd6de0e..69c4eb82a0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatConstants.java
@@ -24,276 +24,301 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
class AuditingLogFormatConstants {
- private AuditingLogFormatConstants() {}
-
- static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME};
-
- static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC
- };
-
- static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY,
- AuditingFieldsKeysEnum.AUDIT_STATUS
- };
-
- static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
- AuditingFieldsKeysEnum.AUDIT_STATUS
- };
-
- static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT
- };
-
- static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE
-
- };
-
- static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_USER_UID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_USER_UID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_AUTH_URL,
- AuditingFieldsKeysEnum.AUDIT_AUTH_USER,
- AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS,
- AuditingFieldsKeysEnum.AUDIT_AUTH_REALM
- };
-
- static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_ECOMP_USER,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME,
- AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME,
- AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_USER_DETAILS,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_DETAILS,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
- static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_USER_BEFORE,
- AuditingFieldsKeysEnum.AUDIT_USER_AFTER,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
- static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
- static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
- static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
- static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
- AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID,
- AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID,
- AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
-
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
-
- AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID,
- AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
-
- static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = {
- AuditingFieldsKeysEnum.AUDIT_ACTION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
- AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME,
- AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
-
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
- AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
-
- AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
- AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
- AuditingFieldsKeysEnum.AUDIT_STATUS,
- AuditingFieldsKeysEnum.AUDIT_DESC
- };
+ private AuditingLogFormatConstants() {}
+
+ static final AuditingFieldsKeysEnum[] DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME};
+
+ static final AuditingFieldsKeysEnum[] DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] GET_UEB_CLUSTER_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] DISTRIBUTION_DEPLOY_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] DISTRIBUTION_STATUS_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+// AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, - check if required
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] DISTRIBUTION_NOTIFY_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID
+ };
+
+ static final AuditingFieldsKeysEnum[] ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY,
+ AuditingFieldsKeysEnum.AUDIT_STATUS
+ };
+
+ static final AuditingFieldsKeysEnum[] CREATE_TOPIC_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME,
+ AuditingFieldsKeysEnum.AUDIT_STATUS
+ };
+
+ static final AuditingFieldsKeysEnum[] ACTIVATE_DISTRIBUTION_ARRAY ={
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] CHANGE_DISTRIBUTION_STATUS_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT
+ };
+
+ static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE
+
+ };
+
+ static final AuditingFieldsKeysEnum[] USER_ACCESS_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_USER_UID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] USER_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_USER_UID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] AUTH_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_AUTH_URL,
+ AuditingFieldsKeysEnum.AUDIT_AUTH_USER,
+ AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_AUTH_REALM
+ };
+
+ static final AuditingFieldsKeysEnum[] ECOMP_USER_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_ECOMP_USER,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] CATEGORY_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME,
+ AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME,
+ AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] GET_USERS_LIST_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_USER_DETAILS,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_DETAILS,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+ static final AuditingFieldsKeysEnum[] USER_ADMIN_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_USER_BEFORE,
+ AuditingFieldsKeysEnum.AUDIT_USER_AFTER,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+ static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+ static final AuditingFieldsKeysEnum[] EXTERNAL_GET_ASSET_TEMPLATE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+ static AuditingFieldsKeysEnum[] ECOMP_OPERATIONAL_ENVIRONMENT_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID,
+ AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME,
+ AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT
+ };
+ static final AuditingFieldsKeysEnum[] EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+ static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARTIFACT_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+ AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] EXTERNAL_CRUD_API_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+
+ AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static AuditingFieldsKeysEnum[] EXTERNAL_ACTIVATE_SERVICE_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
+
+ static final AuditingFieldsKeysEnum[] EXTERNAL_LYFECYCLE_API_ARRAY = {
+ AuditingFieldsKeysEnum.AUDIT_ACTION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID,
+ AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME,
+ AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID,
+
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE,
+ AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,
+
+ AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID,
+ AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID,
+ AuditingFieldsKeysEnum.AUDIT_STATUS,
+ AuditingFieldsKeysEnum.AUDIT_DESC
+ };
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java
index 8fb5c4116e..ee4b70c0f6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingLogFormatUtil.java
@@ -20,12 +20,6 @@
package org.openecomp.sdc.be.auditing.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.Formatter;
-import java.util.Locale;
-
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
@@ -34,240 +28,269 @@ import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Formatter;
+import java.util.Locale;
+import java.util.Map;
+
public class AuditingLogFormatUtil {
- // When adding any new fields here, please keep the convention <fieldName>=
- // <value>, with the space between them.
- private static Logger log = LoggerFactory.getLogger(AuditingLogFormatUtil.class.getName());
-
- // This is the key by which audit marker is recognized in logback.xml
- private static String AUDIT_MARKER_STR = "AUDIT_MARKER";
-
- public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR);
-
- protected static void logAuditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
-
- StringBuilder sb = new StringBuilder();
- Formatter formatter = new Formatter(sb, Locale.US);
- log.trace("logAuditEvent - start");
-
- try {
-
- // Common fields
- String modifier = getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID));
- Object statusObj = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- String status = null;
- if (statusObj != null) {
- status = String.valueOf(statusObj);
- }
- String desc = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- String action = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
-
- AuditingActionEnum auditEventType = AuditingActionEnum.getActionByName(action);
- StringBuilder formattedEvent = getFormattedEvent(auditingFields, modifier, status, desc, action, auditEventType);
- String formattedString = formattedEvent.toString();
-
- // This is the only way to fix DE166225 without major refactoring,
- // after it was previously agreed with Ella that activity type will
- // be the method name.
-
- if (auditEventType.equals(AuditingActionEnum.AUTH_REQUEST)) {
- HttpRequestAuthentication(formattedString);
- } else {
- log.info(auditMarker, formattedString);
- }
- } catch (Exception e) {
- log.debug("unexpected error occurred: {}", e.getMessage(), e);
-
- } finally {
- formatter.close();
- log.trace("logAuditEvent - end");
- }
-
- }
-
- private static void HttpRequestAuthentication(String formattedString) {
- log.info(auditMarker, formattedString);
- }
-
- private static StringBuilder getFormattedEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields, String modifier, String status, String desc, String action, AuditingActionEnum auditEventType) {
-
- StringBuilder formattedString = new StringBuilder();
-
- switch (auditEventType) {
- case ADD_USER:
- case DELETE_USER:
- case UPDATE_USER:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ADMIN_TEMPLATE_ARRAY, auditingFields);
-
- break;
- case USER_ACCESS:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ACCESS_TEMPLATE_ARRAY, auditingFields);
- break;
- case DISTRIBUTION_REGISTER:
- case DISTRIBUTION_UN_REGISTER:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY, auditingFields);
- break;
- case UPDATE_RESOURCE_METADATA:
- case CREATE_RESOURCE:
- case IMPORT_RESOURCE:
- ArrayList<AuditingFieldsKeysEnum> createResourceList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY));
- createResourceList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY));
- if (auditEventType == AuditingActionEnum.IMPORT_RESOURCE) {
- createResourceList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE);
- }
- AuditingFieldsKeysEnum[] createResourceArray = new AuditingFieldsKeysEnum[100];
- createResourceArray = createResourceList.toArray(createResourceArray);
- formattedString = buildStringAccrodingToArray(createResourceArray, auditingFields);
- break;
- case CHECKIN_RESOURCE:
- case CHECKOUT_RESOURCE:
- case UNDO_CHECKOUT_RESOURCE:
- case CERTIFICATION_REQUEST_RESOURCE:
- case START_CERTIFICATION_RESOURCE:
- case CERTIFICATION_SUCCESS_RESOURCE:
- case FAIL_CERTIFICATION_RESOURCE:
- case CANCEL_CERTIFICATION_RESOURCE:
- ArrayList<AuditingFieldsKeysEnum> checkinFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY));
- checkinFieldsList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT);
- checkinFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY));
- AuditingFieldsKeysEnum[] checkinFieldsArray = new AuditingFieldsKeysEnum[100];
- checkinFieldsArray = checkinFieldsList.toArray(checkinFieldsArray);
- String comment = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT);
- if (comment == null || comment.equals(Constants.NULL_STRING)) {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, Constants.EMPTY_STRING);
- }
- formattedString = buildStringAccrodingToArray(checkinFieldsArray, auditingFields);
- break;
- case ARTIFACT_UPLOAD:
- case ARTIFACT_DELETE:
- case ARTIFACT_METADATA_UPDATE:
- case ARTIFACT_PAYLOAD_UPDATE:
- case ARTIFACT_DOWNLOAD:
- ArrayList<AuditingFieldsKeysEnum> artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ;
- artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
- artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
- artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
- artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
- AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100];
- artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray);
- formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
- break;
- case DOWNLOAD_ARTIFACT:
- ArrayList<AuditingFieldsKeysEnum> downloadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
- AuditingFieldsKeysEnum[] downloadArtifactFieldsArray = new AuditingFieldsKeysEnum[100];
- artifactFieldsArray = downloadArtifactFieldsList.toArray(downloadArtifactFieldsArray);
- formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
- break;
- case DISTRIBUTION_STATE_CHANGE_REQUEST:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ACTIVATE_DISTRIBUTION_ARRAY, auditingFields);
- break;
- case DISTRIBUTION_STATE_CHANGE_APPROV:
- case DISTRIBUTION_STATE_CHANGE_REJECT:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CHANGE_DISTRIBUTION_STATUS_ARRAY, auditingFields);
- break;
- case CREATE_DISTRIBUTION_TOPIC:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CREATE_TOPIC_TEMPLATE_ARRAY, auditingFields);
- break;
- case ADD_KEY_TO_TOPIC_ACL:
- case REMOVE_KEY_FROM_TOPIC_ACL:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY, auditingFields);
- break;
- case DISTRIBUTION_STATUS:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_STATUS_TEMPLATE_ARRAY, auditingFields);
- break;
- case DISTRIBUTION_NOTIFY:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_NOTIFY_ARRAY, auditingFields);
- break;
- case DISTRIBUTION_DEPLOY:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DEPLOY_ARRAY, auditingFields);
- break;
- case GET_UEB_CLUSTER:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_UEB_CLUSTER_ARRAY, auditingFields);
- break;
- case DISTRIBUTION_ARTIFACT_DOWNLOAD:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY, auditingFields);
- break;
- case AUTH_REQUEST:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.AUTH_TEMPLATE_ARRAY, auditingFields);
- break;
- case ADD_ECOMP_USER_CREDENTIALS:
- case GET_ECOMP_USER_CREDENTIALS:
- case DELETE_ECOMP_USER_CREDENTIALS:
- case UPDATE_ECOMP_USER_CREDENTIALS:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_USER_TEMPLATE_ARRAY, auditingFields);
- break;
- case ADD_CATEGORY:
- case ADD_SUB_CATEGORY:
- case ADD_GROUPING:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CATEGORY_TEMPLATE_ARRAY, auditingFields);
- break;
- case GET_USERS_LIST:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_USERS_LIST_TEMPLATE_ARRAY, auditingFields);
- break;
- case GET_CATEGORY_HIERARCHY:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY, auditingFields);
- break;
- case GET_ASSET_LIST:
- case GET_FILTERED_ASSET_LIST:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY, auditingFields);
- break;
- case GET_ASSET_METADATA:
- case GET_TOSCA_MODEL:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_TEMPLATE_ARRAY, auditingFields);
- break;
- case ARTIFACT_UPLOAD_BY_API:
- case ARTIFACT_DELETE_BY_API:
- case ARTIFACT_UPDATE_BY_API:
- ArrayList<AuditingFieldsKeysEnum> uploadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARTIFACT_ARRAY));
- AuditingFieldsKeysEnum[] uploadArtifactFieldsArray = new AuditingFieldsKeysEnum[100];
- artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray);
- formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
- break;
- case CREATE_RESOURCE_BY_API:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields);
- break;
- case CHANGE_LIFECYCLE_BY_API:
- formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields);
- break;
- default:
- break;
- }
-
- return formattedString;
- }
-
- private static StringBuilder buildStringAccrodingToArray(AuditingFieldsKeysEnum[] sortedFieldsArray, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- StringBuilder formattedString = new StringBuilder();
- for (int i = 0; i < sortedFieldsArray.length; i++) {
- AuditingFieldsKeysEnum key = sortedFieldsArray[i];
-
- Object fieldVal = auditingFields.get(key);
- if (fieldVal != null) {
- formattedString.append(key.getDisplayName()).append(" = \"").append(fieldVal).append("\"");
- if (i < sortedFieldsArray.length - 1) {
- formattedString.append(" ");
- }
- }
- }
- return formattedString;
- }
-
- protected static String getModifier(String modifierName, String modifierUid) {
- if (modifierUid == null || modifierUid.equals(Constants.EMPTY_STRING)) {
- return Constants.EMPTY_STRING;
- }
- StringBuilder sb = new StringBuilder();
- if (modifierName != null) {
- sb.append(modifierName);
- }
- sb.append("(").append(modifierUid).append(")");
- return sb.toString();
- }
-
- protected static String getUser(String userData) {
- StringBuilder sb = new StringBuilder();
- sb.append(userData);
- return sb.toString();
- }
+ // When adding any new fields here, please keep the convention <fieldName>=
+ // <value>, with the space between them.
+ private static final Logger log = LoggerFactory.getLogger(AuditingLogFormatUtil.class);
+
+ // This is the key by which audit marker is recognized in logback.xml
+ private static String AUDIT_MARKER_STR = "AUDIT_MARKER";
+
+ public static final Marker auditMarker = MarkerFactory.getMarker(AUDIT_MARKER_STR);
+
+ protected static String logAuditEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+
+ StringBuilder sb = new StringBuilder();
+ Formatter formatter = new Formatter(sb, Locale.US);
+ log.trace("logAuditEvent - start");
+
+ String formattedString = "";
+
+ try {
+
+ // Common fields
+ String modifier = getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID));
+ Object statusObj = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ String status = null;
+ if (statusObj != null) {
+ status = String.valueOf(statusObj);
+ }
+ String desc = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ String action = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+
+ AuditingActionEnum auditEventType = AuditingActionEnum.getActionByName(action);
+ StringBuilder formattedEvent = getFormattedEvent(auditingFields, modifier, status, desc, action, auditEventType);
+ formattedString = formattedEvent.toString();
+
+ // This is the only way to fix DE166225 without major refactoring,
+ // after it was previously agreed with Ella that activity type will
+ // be the method name.
+
+ if (auditEventType.equals(AuditingActionEnum.AUTH_REQUEST)) {
+ HttpRequestAuthentication(formattedString);
+ } else {
+ log.info(auditMarker, formattedString);
+ }
+ } catch (Exception e) {
+ log.debug("unexpected error occurred: {}", e.getMessage(), e);
+
+ } finally {
+ formatter.close();
+ log.trace("logAuditEvent - end");
+ }
+ return formattedString;
+
+ }
+
+ protected static void logAuditEvent(final String formattedString) {
+ log.trace("logAuditEvent - start");
+ log.info(auditMarker, formattedString);
+ log.trace("logAuditEvent - end");
+ }
+
+
+ private static void HttpRequestAuthentication(String formattedString) {
+ log.info(auditMarker, formattedString);
+ }
+
+ private static StringBuilder getFormattedEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields, String modifier, String status, String desc, String action, AuditingActionEnum auditEventType) {
+
+ StringBuilder formattedString = new StringBuilder();
+
+ switch (auditEventType) {
+ case ADD_USER:
+ case DELETE_USER:
+ case UPDATE_USER:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ADMIN_TEMPLATE_ARRAY, auditingFields);
+
+ break;
+ case USER_ACCESS:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.USER_ACCESS_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case DISTRIBUTION_REGISTER:
+ case DISTRIBUTION_UN_REGISTER:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_REGISTRATION_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case UPDATE_RESOURCE_METADATA:
+ case CREATE_RESOURCE:
+ case IMPORT_RESOURCE:
+ ArrayList<AuditingFieldsKeysEnum> createResourceList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY));
+ createResourceList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY));
+ if (auditEventType == AuditingActionEnum.IMPORT_RESOURCE) {
+ createResourceList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE);
+ }
+ AuditingFieldsKeysEnum[] createResourceArray = new AuditingFieldsKeysEnum[100];
+ createResourceArray = createResourceList.toArray(createResourceArray);
+ formattedString = buildStringAccrodingToArray(createResourceArray, auditingFields);
+ break;
+ case CHECKIN_RESOURCE:
+ case CHECKOUT_RESOURCE:
+ case UNDO_CHECKOUT_RESOURCE:
+ case CERTIFICATION_REQUEST_RESOURCE:
+ case START_CERTIFICATION_RESOURCE:
+ case CERTIFICATION_SUCCESS_RESOURCE:
+ case FAIL_CERTIFICATION_RESOURCE:
+ case CANCEL_CERTIFICATION_RESOURCE:
+ ArrayList<AuditingFieldsKeysEnum> checkinFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY));
+ checkinFieldsList.add(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT);
+ checkinFieldsList.addAll(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_SUFFIX_ARRAY));
+ AuditingFieldsKeysEnum[] checkinFieldsArray = new AuditingFieldsKeysEnum[100];
+ checkinFieldsArray = checkinFieldsList.toArray(checkinFieldsArray);
+ String comment = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT);
+ if (comment == null || comment.equals(Constants.NULL_STRING)) {
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, Constants.EMPTY_STRING);
+ }
+ formattedString = buildStringAccrodingToArray(checkinFieldsArray, auditingFields);
+ break;
+ case ARTIFACT_UPLOAD:
+ case ARTIFACT_DELETE:
+ case ARTIFACT_METADATA_UPDATE:
+ case ARTIFACT_PAYLOAD_UPDATE:
+ case ARTIFACT_DOWNLOAD:
+ ArrayList<AuditingFieldsKeysEnum> artifactFieldsSet = new ArrayList<>(Arrays.asList(AuditingLogFormatConstants.CREATE_RESOURCE_TEMPLATE_PREFIX_ARRAY)) ;
+ artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
+ artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
+ artifactFieldsSet.add(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
+ artifactFieldsSet.addAll(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
+ AuditingFieldsKeysEnum[] artifactFieldsArray = new AuditingFieldsKeysEnum[100];
+ artifactFieldsArray = artifactFieldsSet.toArray(artifactFieldsArray);
+ formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
+ break;
+ case DOWNLOAD_ARTIFACT:
+ ArrayList<AuditingFieldsKeysEnum> downloadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_DOWNLOAD_ARTIFACT_ARRAY));
+ AuditingFieldsKeysEnum[] downloadArtifactFieldsArray = new AuditingFieldsKeysEnum[100];
+ artifactFieldsArray = downloadArtifactFieldsList.toArray(downloadArtifactFieldsArray);
+ formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
+ break;
+ case DISTRIBUTION_STATE_CHANGE_REQUEST:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ACTIVATE_DISTRIBUTION_ARRAY, auditingFields);
+ break;
+ case DISTRIBUTION_STATE_CHANGE_APPROV:
+ case DISTRIBUTION_STATE_CHANGE_REJECT:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CHANGE_DISTRIBUTION_STATUS_ARRAY, auditingFields);
+ break;
+ case CREATE_DISTRIBUTION_TOPIC:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CREATE_TOPIC_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case ADD_KEY_TO_TOPIC_ACL:
+ case REMOVE_KEY_FROM_TOPIC_ACL:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ADD_REMOVE_TOPIC_KEY_ACL_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case DISTRIBUTION_STATUS:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_STATUS_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case DISTRIBUTION_NOTIFY:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_NOTIFY_ARRAY, auditingFields);
+ break;
+ case DISTRIBUTION_DEPLOY:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DEPLOY_ARRAY, auditingFields);
+ break;
+ case GET_UEB_CLUSTER:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_UEB_CLUSTER_ARRAY, auditingFields);
+ break;
+ case DISTRIBUTION_ARTIFACT_DOWNLOAD:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.DISTRIBUTION_DOWNLOAD_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case AUTH_REQUEST:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.AUTH_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case ADD_ECOMP_USER_CREDENTIALS:
+ case GET_ECOMP_USER_CREDENTIALS:
+ case DELETE_ECOMP_USER_CREDENTIALS:
+ case UPDATE_ECOMP_USER_CREDENTIALS:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_USER_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case ADD_CATEGORY:
+ case ADD_SUB_CATEGORY:
+ case ADD_GROUPING:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.CATEGORY_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case GET_USERS_LIST:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_USERS_LIST_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case GET_CATEGORY_HIERARCHY:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.GET_CATEGORY_HIERARCHY_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case GET_ASSET_LIST:
+ case GET_FILTERED_ASSET_LIST:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_LIST_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case GET_ASSET_METADATA:
+ case GET_TOSCA_MODEL:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_GET_ASSET_TEMPLATE_ARRAY, auditingFields);
+ break;
+ case ARTIFACT_UPLOAD_BY_API:
+ case ARTIFACT_DELETE_BY_API:
+ case ARTIFACT_UPDATE_BY_API:
+ ArrayList<AuditingFieldsKeysEnum> uploadArtifactFieldsList = new ArrayList(Arrays.asList(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARTIFACT_ARRAY));
+ AuditingFieldsKeysEnum[] uploadArtifactFieldsArray = new AuditingFieldsKeysEnum[100];
+ artifactFieldsArray = uploadArtifactFieldsList.toArray(uploadArtifactFieldsArray);
+ formattedString = buildStringAccrodingToArray(artifactFieldsArray, auditingFields);
+ break;
+ case CREATE_RESOURCE_BY_API:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_CRUD_API_ARRAY, auditingFields);
+ break;
+ case CHANGE_LIFECYCLE_BY_API:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_LYFECYCLE_API_ARRAY, auditingFields);
+ break;
+ case ACTIVATE_SERVICE_BY_API:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.EXTERNAL_ACTIVATE_SERVICE_ARRAY, auditingFields);
+ break;
+ case CREATE_ENVIRONMENT:
+ case UPDATE_ENVIRONMENT:
+ case DELETE_ENVIRONMENT:
+ case UNKNOWN_ENVIRONMENT_NOTIFICATION:
+ case UNSUPPORTED_ENVIRONMENT_TYPE:
+ formattedString = buildStringAccrodingToArray(AuditingLogFormatConstants.ECOMP_OPERATIONAL_ENVIRONMENT_ARRAY, auditingFields);
+ break;
+ default:
+ break;
+ }
+
+ return formattedString;
+ }
+
+ private static StringBuilder buildStringAccrodingToArray(AuditingFieldsKeysEnum[] sortedFieldsArray, Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ StringBuilder formattedString = new StringBuilder();
+ for (int i = 0; i < sortedFieldsArray.length; i++) {
+ AuditingFieldsKeysEnum key = sortedFieldsArray[i];
+
+ Object fieldVal = auditingFields.get(key);
+ if (fieldVal != null) {
+ formattedString.append(key.getDisplayName()).append(" = \"").append(fieldVal).append("\"");
+ if (i < sortedFieldsArray.length - 1) {
+ formattedString.append(" ");
+ }
+ }
+ }
+ return formattedString;
+ }
+
+ protected static String getModifier(String modifierName, String modifierUid) {
+ if (modifierUid == null || modifierUid.equals(Constants.EMPTY_STRING)) {
+ return Constants.EMPTY_STRING;
+ }
+ StringBuilder sb = new StringBuilder();
+ if (modifierName != null) {
+ sb.append(modifierName);
+ }
+ sb.append("(").append(modifierUid).append(")");
+ return sb.toString();
+ }
+
+ protected static String getUser(String userData) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(userData);
+ return sb.toString();
+ }
+
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java
index aa5afa4a8e..19eab0a409 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java
@@ -20,12 +20,7 @@
package org.openecomp.sdc.be.auditing.impl;
-import java.util.EnumMap;
-import java.util.Map.Entry;
-
-import javax.annotation.Resource;
-
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
@@ -39,99 +34,134 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-@Component("auditingManager")
-public class AuditingManager implements IAuditingManager {
-
- private static Logger log = LoggerFactory.getLogger(AuditingManager.class.getName());
-
- @Resource
- private AuditingDao auditingDao;
- @Autowired
- private AuditCassandraDao cassandraDao;
-
- @Override
- public void auditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- try {
- boolean disableAudit = ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit();
- if (disableAudit) {
- return;
- }
- // Adding UUID from thread local
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, ThreadLocalsHolder.getUuid());
-
- Object status = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, String.valueOf(status));
-
- // normalizing empty string values - US471661
- normalizeEmptyAuditStringValues(auditingFields);
-
- // Format modifier
- formatModifier(auditingFields);
-
- // Format user
- formatUser(auditingFields);
-
- // Logging the event
- AuditingLogFormatUtil.logAuditEvent(auditingFields);
-
- // Determining the type of the auditing data object
- AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION));
- log.info("audit event {} of type {}", actionEnum.getName(), actionEnum.getAuditingEsType());
- ActionStatus addRecordStatus = auditingDao.addRecord(auditingFields, actionEnum.getAuditingEsType());
- if (!addRecordStatus.equals(ActionStatus.OK)) {
- log.warn("Failed to persist auditing event: {}", addRecordStatus.name());
- }
-
- AuditingGenericEvent recordForCassandra = AuditRecordFactory.createAuditRecord(auditingFields);
- if (recordForCassandra != null) {
- CassandraOperationStatus result = cassandraDao.saveRecord(recordForCassandra);
- if (!result.equals(CassandraOperationStatus.OK)) {
- log.warn("Failed to persist to cassandra auditing event: {}", addRecordStatus.name());
- }
- }
-
- } catch (Exception e) {
- // Error during auditing shouldn't terminate flow
- log.warn("Error during auditEvent: {}", e);
- }
- }
-
- private void formatUser(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- if (auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID) != null) {
- String userDetails = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID);
-
- String user = AuditingLogFormatUtil.getUser(userDetails);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user);
- }
- }
-
- private void formatModifier(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- String modifier = AuditingLogFormatUtil.getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID));
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier);
- auditingFields.remove(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME);
- }
-
- private void normalizeEmptyAuditStringValues(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- for (Entry<AuditingFieldsKeysEnum, Object> auditingEntry : auditingFields.entrySet()) {
- if (auditingEntry.getKey().getValueClass().equals(String.class)) {
- String auditingValue = (String) auditingEntry.getValue();
- boolean isEmpty = false;
- if (auditingValue != null) {
- String trimmedValue = auditingValue.trim();
- if ((trimmedValue.equals(Constants.EMPTY_STRING)) || trimmedValue.equals(Constants.NULL_STRING) || trimmedValue.equals(Constants.DOUBLE_NULL_STRING)) {
- isEmpty = true;
- }
- } else {// is null
- isEmpty = true;
- }
- // Normalizing to ""
- if (isEmpty) {
- auditingEntry.setValue(Constants.EMPTY_STRING);
- }
- }
- }
- }
+import java.util.Map;
+import java.util.Map.Entry;
+
+@Component
+public class AuditingManager {
+
+ private static final Logger log = LoggerFactory.getLogger(AuditingManager.class);
+ private final AuditingDao auditingDao;
+ private final AuditCassandraDao cassandraDao;
+
+ public AuditingManager(AuditingDao auditingDao, AuditCassandraDao cassandraDao) {
+ this.auditingDao = auditingDao;
+ this.cassandraDao = cassandraDao;
+ }
+
+ // TODO remove after completing refactoring
+ public String auditEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ String msg = "";
+ try {
+ boolean disableAudit = ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit();
+ if (disableAudit) {
+ return null;
+ }
+ // Adding UUID from thread local
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, ThreadLocalsHolder.getUuid());
+
+ Object status = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, String.valueOf(status));
+
+ // normalizing empty string values - US471661
+ normalizeEmptyAuditStringValues(auditingFields);
+
+ // Format modifier
+ formatModifier(auditingFields);
+
+ // Format user
+ formatUser(auditingFields);
+
+ // Logging the event
+ msg = AuditingLogFormatUtil.logAuditEvent(auditingFields);
+
+ // Determining the type of the auditing data object
+ AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION));
+ log.info("audit event {} of type {}", actionEnum.getName(), actionEnum.getAuditingEsType());
+ ActionStatus addRecordStatus = auditingDao.addRecord(auditingFields, actionEnum.getAuditingEsType());
+ if (!addRecordStatus.equals(ActionStatus.OK)) {
+ log.warn("Failed to persist auditing event: {}", addRecordStatus);
+ }
+
+ AuditingGenericEvent recordForCassandra = AuditRecordFactory.createAuditRecord(auditingFields);
+ if (recordForCassandra != null) {
+ saveEventToCassandra(recordForCassandra);
+ }
+
+ } catch (Exception e) {
+ // Error during auditing shouldn't terminate flow
+ log.warn("Error during auditEvent: {}", e);
+ }
+ return msg;
+ }
+
+
+ public String auditEvent(AuditEventFactory factory) {
+ if (ConfigurationManager.getConfigurationManager().getConfiguration().isDisableAudit()) {
+ return null;
+ }
+ AuditingGenericEvent event = factory.getDbEvent();
+ // Logging the event
+ //TODO - change this call after EELF Audit stuff merge
+ String msg = factory.getLogMessage();
+ AuditingLogFormatUtil.logAuditEvent(msg);
+
+ //TODO - remove this method after we got rid of ES
+ saveEventToElasticSearch(factory, event);
+ saveEventToCassandra(event);
+ return msg;
+ }
+
+ private void saveEventToCassandra(AuditingGenericEvent event) {
+ CassandraOperationStatus result = cassandraDao.saveRecord(event);
+ if (!result.equals(CassandraOperationStatus.OK)) {
+ log.warn("Failed to persist to cassandra auditing event: {}", result.name());
+ }
+ }
+
+ private void saveEventToElasticSearch(AuditEventFactory factory, AuditingGenericEvent event) {
+ ActionStatus addRecordStatus = auditingDao.addRecord(event, factory.getAuditingEsType());
+ if (!addRecordStatus.equals(ActionStatus.OK)) {
+ log.warn("Failed to persist auditing event: {}", addRecordStatus.name());
+ }
+ }
+
+
+ private void formatUser(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ if (auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID) != null) {
+ String userDetails = (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_UID);
+
+ String user = AuditingLogFormatUtil.getUser(userDetails);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user);
+ }
+ }
+
+ private void formatModifier(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ String modifier = AuditingLogFormatUtil.getModifier((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME), (String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID));
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier);
+ auditingFields.remove(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME);
+ }
+
+ private void normalizeEmptyAuditStringValues(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ for (Entry<AuditingFieldsKeysEnum, Object> auditingEntry : auditingFields.entrySet()) {
+ if (auditingEntry.getKey().getValueClass().equals(String.class)) {
+ String auditingValue = (String) auditingEntry.getValue();
+ boolean isEmpty = false;
+ if (auditingValue != null) {
+ String trimmedValue = auditingValue.trim();
+ if ((trimmedValue.equals(Constants.EMPTY_STRING)) || trimmedValue.equals(Constants.NULL_STRING) || trimmedValue.equals(Constants.DOUBLE_NULL_STRING)) {
+ isEmpty = true;
+ }
+ } else {// is null
+ isEmpty = true;
+ }
+ // Normalizing to ""
+ if (isEmpty) {
+ auditingEntry.setValue(Constants.EMPTY_STRING);
+ }
+ }
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java
new file mode 100644
index 0000000000..84c3a0392d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddCategoryEventFactory.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.auditing.impl.category;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditAddCategoryEventFactory extends AuditCategoryEventFactory {
+
+ public AuditAddCategoryEventFactory(CommonAuditData commonFields, User modifier,
+ String categoryName, String subCategoryName, String groupingName, String resourceType) {
+ super(AuditingActionEnum.ADD_CATEGORY, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java
new file mode 100644
index 0000000000..6ee7624ddf
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddGroupingCategoryEventFactory.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.auditing.impl.category;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditAddGroupingCategoryEventFactory extends AuditCategoryEventFactory {
+
+ public AuditAddGroupingCategoryEventFactory(CommonAuditData commonFields, User modifier, String categoryName,
+ String subCategoryName, String groupingName, String resourceType) {
+ super(AuditingActionEnum.ADD_GROUPING, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java
new file mode 100644
index 0000000000..241d0c0fc5
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditAddSubCategoryEventFactory.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.auditing.impl.category;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditAddSubCategoryEventFactory extends AuditCategoryEventFactory {
+
+ public AuditAddSubCategoryEventFactory(CommonAuditData commonFields, User modifier,
+ String categoryName, String subCategoryName, String groupingName, String resourceType) {
+ super(AuditingActionEnum.ADD_SUB_CATEGORY, commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java
new file mode 100644
index 0000000000..9a2d7b09a8
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.be.auditing.impl.category;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public abstract class AuditCategoryEventFactory extends AuditBaseEventFactory {
+
+ private final CategoryEvent event;
+
+ protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" CATEGORY_NAME = \"%s\" SUB_CATEGORY_NAME = \"%s\"" +
+ " GROUPING_NAME = \"%s\" RESOURCE_TYPE = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(),
+ event.getGroupingName(), event.getResourceType(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier,
+ String categoryName, String subCategoryName, String groupingName, String resourceType) {
+ super(action);
+ event = new CategoryEvent(getAction().getName(), commonFields, buildUserName(modifier), categoryName,
+ subCategoryName, groupingName, resourceType);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java
new file mode 100644
index 0000000000..8c4de3c43d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.auditing.impl.category;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.GetCategoryHierarchyEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory {
+
+ private final GetCategoryHierarchyEvent event;
+
+ protected static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditGetCategoryHierarchyEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, String details) {
+ super(action);
+ event = new GetCategoryHierarchyEvent(getAction().getName(), commonFields, buildUserName(modifier), details);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java
new file mode 100644
index 0000000000..907d73546f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddKeyDistribEngineEventFactory.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditAddKeyDistribEngineEventFactory extends AuditAddRemoveKeyDistribEngineEventFactory {
+
+ public AuditAddKeyDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java
new file mode 100644
index 0000000000..5ad7380051
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistribEngineEventFactory.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public abstract class AuditAddRemoveKeyDistribEngineEventFactory extends AuditDistribEngineEventFactory{
+
+ private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " +
+ "API_KEY = \"%s\" STATUS = \"%s\"";
+
+ public AuditAddRemoveKeyDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(action, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+
+ @Override
+ public String getLogMessage() {
+ String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : buildValue(event.getDstatusTopic());
+ return String.format(LOG_STR, event.getAction(), event.getEnvironmentName(), topicName,
+ event.getRole(), event.getApiKey(), event.getStatus());
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java
new file mode 100644
index 0000000000..7825cca0e9
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistribEngineEventFactory.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditCreateTopicDistribEngineEventFactory extends AuditDistribEngineEventFactory{
+
+ private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" STATUS = \"%s\"";
+
+ public AuditCreateTopicDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+
+ @Override
+ public String getLogMessage() {
+ String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : buildValue(event.getDstatusTopic());
+ return String.format(LOG_STR, event.getAction(), event.getEnvironmentName(), topicName, event.getStatus());
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java
new file mode 100644
index 0000000000..cb86f5059c
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDeployEventFactory.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditDistribDeployEventFactory extends AuditBaseEventFactory {
+
+ private DistributionDeployEvent event;
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " +
+ "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
+ event.getCurrVersion(), event.getModifier(), event.getDid(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditDistribDeployEventFactory(CommonAuditData commonFields, String currentVersion,
+ String did, User modifier, String resourceName, String resourceType) {
+
+ super(AuditingActionEnum.DISTRIBUTION_DEPLOY);
+ this.event = new DistributionDeployEvent(getAction().getName(), commonFields, did, buildUserName(modifier),
+ currentVersion, resourceName, resourceType);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java
new file mode 100644
index 0000000000..e8453b1d0b
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribDownloadEventFactory.java
@@ -0,0 +1,33 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
+
+public class AuditDistribDownloadEventFactory extends AuditBaseEventFactory {
+
+ private DistributionDownloadEvent event;
+
+ private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditDistribDownloadEventFactory(CommonAuditData commonFields, DistributionData distributionData) {
+
+ super(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD);
+ this.event = new DistributionDownloadEvent(getAction().getName(), commonFields, distributionData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceUrl(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java
new file mode 100644
index 0000000000..3ebacb49d9
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribEngineEventFactory.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public abstract class AuditDistribEngineEventFactory extends AuditBaseEventFactory{
+
+ protected final DistributionEngineEvent event;
+
+ public AuditDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(action);
+ event = new DistributionEngineEvent(getAction().getName(), commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java
new file mode 100644
index 0000000000..80c4590b8d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribNotificationEventFactory.java
@@ -0,0 +1,39 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData;
+
+public class AuditDistribNotificationEventFactory extends AuditBaseEventFactory {
+
+ private DistributionNotificationEvent event;
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " +
+ "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\" DID = \"%s\" " +
+ "TOPIC_NAME = \"%s\" STATUS = \"%s\" DESC = \"%s\" TENANT = \"%s\" VNF_WORKLOAD_CONTEXT = \"%s\" ENV_ID = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
+ event.getCurrVersion(), event.getModifier(), event.getCurrState(), event.getDid(), event.getTopicName(), event.getStatus(), event.getDesc(),
+ event.getTenant(), event.getVnfWorkloadContext(), event.getEnvId());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditDistribNotificationEventFactory(CommonAuditData commonFields, String currentState, String currentVersion,
+ String did, User modifier, String resourceName,
+ String resourceType, String topicName, OperationalEnvAuditData opEnvFields) {
+
+ super(AuditingActionEnum.DISTRIBUTION_NOTIFY);
+ this.event = new DistributionNotificationEvent(getAction().getName(), commonFields, did, AuditBaseEventFactory.buildUserName(modifier),
+ currentState, currentVersion,resourceName, resourceType, topicName, opEnvFields);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java
new file mode 100644
index 0000000000..3d71a200a3
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistribStatusEventFactory.java
@@ -0,0 +1,33 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditDistribStatusEventFactory extends AuditBaseEventFactory {
+
+ private DistributionStatusEvent event;
+
+ private static final String LOG_STR = "ACTION = \"%s\" DID = \"%s\" CONSUMER_ID = \"%s\" " +
+ "TOPIC_NAME = \"%s\" RESOURCE_URL = \"%s\" STATUS_TIME = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(), event.getResoureURL(),
+ event.getStatusTime(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditDistribStatusEventFactory(CommonAuditData commonFields, String did, String consumerId, String topicName,
+ String resourceURL, String statusTime) {
+
+ super(AuditingActionEnum.DISTRIBUTION_STATUS);
+ this.event = new DistributionStatusEvent(getAction().getName(), commonFields, did, consumerId, topicName, resourceURL, statusTime);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java
new file mode 100644
index 0000000000..79d524a0dc
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditGetUebClusterEventFactory.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGetUebClusterEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory {
+
+ private AuditingGetUebClusterEvent event;
+
+ private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" STATUS = \"%s\" STATUS_DESC = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditGetUebClusterEventFactory(CommonAuditData commonFields, String consumerId) {
+
+ super(AuditingActionEnum.GET_UEB_CLUSTER);
+ this.event = new AuditingGetUebClusterEvent(getAction().getName(), commonFields, consumerId);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java
new file mode 100644
index 0000000000..2dbcde7b2c
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistribEngineEventFactory.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public abstract class AuditRegUnregDistribEngineEventFactory extends AuditDistribEngineEventFactory {
+
+ private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" API_KEY = \"%s\" D_ENV = \"%s\" STATUS = \"%s\"" +
+ " DESC = \"%s\" DNOTIF_TOPIC = \"%s\" DSTATUS_TOPIC = \"%s\"";
+
+ public AuditRegUnregDistribEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String consumerId,
+ String distStatusTopic, String distNotifTopic, String apiKey, String envName, String role) {
+ super(action, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getApiKey(), event.getEnvironmentName(),
+ event.getStatus(), event.getDesc(), event.getDnotifTopic(),event.getDstatusTopic());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java
new file mode 100644
index 0000000000..e2ce0312f7
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegisterDistribEngineEventFactory.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditRegisterDistribEngineEventFactory extends AuditRegUnregDistribEngineEventFactory {
+
+ public AuditRegisterDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(AuditingActionEnum.DISTRIBUTION_REGISTER, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java
new file mode 100644
index 0000000000..fe7f335c77
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRemoveKeyDistribEngineEventFactory.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditRemoveKeyDistribEngineEventFactory extends AuditAddRemoveKeyDistribEngineEventFactory {
+
+ public AuditRemoveKeyDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java
new file mode 100644
index 0000000000..d402d38e25
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditUnregisterDistribEngineEventFactory.java
@@ -0,0 +1,12 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditUnregisterDistribEngineEventFactory extends AuditRegUnregDistribEngineEventFactory {
+
+ public AuditUnregisterDistribEngineEventFactory(CommonAuditData commonFields, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ super(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, commonFields, consumerId, distStatusTopic, distNotifTopic, apiKey, envName, role);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java
new file mode 100644
index 0000000000..942dae0507
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java
@@ -0,0 +1,26 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditActivateServiceExternalApiEventFactory extends AuditExternalApiEventFactory {
+
+ protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
+ " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
+
+ public AuditActivateServiceExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.ACTIVATE_SERVICE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getResourceType(), event.getConsumerId(),
+ event.getResourceURL(), event.getModifier(), event.getStatus(), event.getServiceInstanceId(),
+ event.getInvariantUuid(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java
new file mode 100644
index 0000000000..5e6256368e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java
@@ -0,0 +1,25 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public abstract class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFactory {
+
+ protected static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" RESOURCE_NAME = \"%s\" " +
+ "RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditAssetExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getResourceName(),
+ event.getResourceType(), event.getServiceInstanceId(), event.getStatus(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java
new file mode 100644
index 0000000000..1a41d7d5f8
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetGetMetadataExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditAssetGetMetadataExternalApiEventFactory extends AuditAssetExternalApiEventFactory {
+
+ public AuditAssetGetMetadataExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.GET_ASSET_METADATA, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java
new file mode 100644
index 0000000000..13558881c5
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java
@@ -0,0 +1,24 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public abstract class AuditAssetListExternalApiEventFactory extends AuditExternalApiEventFactory {
+
+ protected static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getConsumerId(), event.getResourceURL(),
+ event.getStatus(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java
new file mode 100644
index 0000000000..060cbd395e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditChangeLifecycleExternalApiEventFactory extends AuditExternalApiEventFactory {
+
+ protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
+ " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\"" +
+ " PREV_STATE = \"%s\" CURR_STATE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditChangeLifecycleExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(),
+ event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(),
+ event.getCurrState(), event.getServiceInstanceId(), event.getInvariantUuid(), event.getStatus(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java
new file mode 100644
index 0000000000..07bac13495
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java
@@ -0,0 +1,28 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditCreateResourceExternalApiEventFactory extends AuditExternalApiEventFactory {
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
+ " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
+ " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
+
+ public AuditCreateResourceExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(),
+ event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(),
+ event.getCurrState(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), event.getStatus(),
+ event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java
new file mode 100644
index 0000000000..fd8be4cc47
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public abstract class AuditCrudExternalApiArtifactEventFactory extends AuditExternalApiEventFactory {
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
+ " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\"" +
+ " STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditCrudExternalApiArtifactEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(action, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(),
+ event.getResourceURL(), event.getModifier(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(),
+ event.getArtifactData(), event.getStatus(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java
new file mode 100644
index 0000000000..c2827b1e5d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDeleteArtByApiCrudExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditDeleteArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory {
+
+ public AuditDeleteArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.ARTIFACT_DELETE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java
new file mode 100644
index 0000000000..134dfd2921
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalApiEventFactory {
+
+ private static final String LOG_STR = "CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditDownloadArtifactExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getConsumerId(), event.getResourceURL(),event.getStatus(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java
new file mode 100644
index 0000000000..4e233dee27
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java
@@ -0,0 +1,25 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ExternalApiEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public abstract class AuditExternalApiEventFactory extends AuditBaseEventFactory {
+
+ protected final ExternalApiEvent event;
+
+ public AuditExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(action);
+ event = new ExternalApiEvent(getAction().getName(), commonFields, resourceType, resourceName, consumerId, resourceUrl,
+ prevParams, currParams, AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData) ;
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() { return event; }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java
new file mode 100644
index 0000000000..e97614551f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetAssetListExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditGetAssetListExternalApiEventFactory extends AuditAssetListExternalApiEventFactory {
+
+ public AuditGetAssetListExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.GET_ASSET_LIST, commonFields, resourceType, resourceName,
+ consumerId, resourceUrl, prevParams, currParams, invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java
new file mode 100644
index 0000000000..379124dc4a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetFilteredAssetListExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditGetFilteredAssetListExternalApiEventFactory extends AuditAssetListExternalApiEventFactory {
+
+ public AuditGetFilteredAssetListExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.GET_FILTERED_ASSET_LIST, commonFields, resourceType, resourceName,
+ consumerId, resourceUrl, prevParams, currParams, invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java
new file mode 100644
index 0000000000..168cd1b150
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditGetToscaModelExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditGetToscaModelExternalApiEventFactory extends AuditAssetExternalApiEventFactory {
+
+ public AuditGetToscaModelExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.GET_TOSCA_MODEL, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java
new file mode 100644
index 0000000000..5af8ff3d0d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUpdateArtByApiCrudExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditUpdateArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory {
+
+ public AuditUpdateArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.ARTIFACT_UPDATE_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java
new file mode 100644
index 0000000000..02af363f46
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditUploadArtByApiCrudExternalApiEventFactory.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditUploadArtByApiCrudExternalApiEventFactory extends AuditCrudExternalApiArtifactEventFactory {
+
+ public AuditUploadArtByApiCrudExternalApiEventFactory(CommonAuditData commonFields, String resourceType, String resourceName,
+ String consumerId, String resourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String invariantUuid, User modifier, String artifactData) {
+ super(AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, commonFields, resourceType, resourceName, consumerId, resourceUrl, prevParams, currParams,
+ invariantUuid, modifier, artifactData);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java
new file mode 100644
index 0000000000..9bda0d22d6
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java
@@ -0,0 +1,33 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.api.Constants;
+
+public class AuditArtifactResourceAdminEventFactory extends AuditResourceAdminEventFactory {
+
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
+ " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
+ " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+
+ public AuditArtifactResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did) {
+ super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+ }
+
+ @Override
+ public String getLogMessage() {
+ //TODO: check wheather or not "CONSUMER_ID =...RESOURCE_URL = " should be filled out - the info id not in the event
+ return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()),
+ buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()),
+ buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()),
+ buildValue(event.getCurrState()), buildValue(event.getPrevArtifactUUID()), buildValue(event.getCurrArtifactUUID()),
+ buildValue(event.getArtifactData()), buildValue(event.getStatus()), buildValue(event.getDesc()));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java
new file mode 100644
index 0000000000..f5302957e1
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.api.Constants;
+
+public class AuditCertificationResourceAdminEventFactory extends AuditResourceAdminEventFactory {
+
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
+ " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
+ " COMMENT = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditCertificationResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did) {
+ super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()),
+ buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()),
+ buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()),
+ buildValue(event.getCurrState()), buildValue(event.getComment()), buildValue(event.getStatus()), buildValue(event.getDesc()));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java
new file mode 100644
index 0000000000..db76b78106
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditCreateUpdateResourceAdminEventFactory extends AuditResourceAdminEventFactory {
+
+
+ protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
+ " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
+ " STATUS = \"%s\" DESC = \"%s\"";
+
+
+ public AuditCreateUpdateResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did, String toscaNodeType) {
+ super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, toscaNodeType);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), buildValue(event.getResourceName()), buildValue(event.getResourceType()),
+ buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()),
+ buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()),
+ buildValue(event.getCurrState()), event.getStatus(), event.getDesc());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java
new file mode 100644
index 0000000000..62f95de6bd
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.api.Constants;
+
+public class AuditDistStateChangeRequestResourceAdminEventFactory extends AuditResourceAdminEventFactory {
+
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
+ " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" +
+ " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditDistStateChangeRequestResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did) {
+ super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()),
+ buildValue(event.getServiceInstanceId()), buildValue(event.getCurrVersion()), buildValue(event.getModifier()),
+ buildValue(event.getCurrState()), buildValue(event.getDprevStatus()), buildValue(event.getDcurrStatus()),
+ buildValue(event.getDid()), buildValue(event.getStatus()), buildValue(event.getDesc()));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java
new file mode 100644
index 0000000000..3fd41b9681
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.api.Constants;
+
+public class AuditDistStateChangeResourceAdminEventFactory extends AuditResourceAdminEventFactory {
+
+
+ private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
+ " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" +
+ " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" STATUS = \"%s\" DESC = \"%s\" COMMENT = \"%s\"";
+
+
+ public AuditDistStateChangeResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams,
+ ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did) {
+ super(action, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getResourceName()), buildValue(event.getResourceType()),
+ buildValue(event.getServiceInstanceId()), buildValue(event.getCurrVersion()), buildValue(event.getModifier()),
+ buildValue(event.getCurrState()), buildValue(event.getDprevStatus()), buildValue(event.getDcurrStatus()),
+ buildValue(event.getStatus()), buildValue(event.getDesc()), buildValue(event.getComment()));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java
new file mode 100644
index 0000000000..64da0fd6db
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResourceAdminEventFactory {
+
+
+ private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\"" ;
+
+
+ public AuditImportResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did, String toscaNodeType) {
+ super(AuditingActionEnum.IMPORT_RESOURCE, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, artifactData, comment, did, toscaNodeType);
+ }
+
+ public AuditImportResourceAdminEventFactory(CommonAuditData commonFields, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String resourceType, String resourceName,
+ String invariantUuid, User modifier, String toscaNodeType) {
+ super(AuditingActionEnum.IMPORT_RESOURCE, commonFields, prevParams, currParams, resourceType, resourceName, invariantUuid,
+ modifier, null, null, null, toscaNodeType);
+ }
+
+ @Override public String getLogMessage() {
+ return String.format(LOG_STR_TOSCA, event.getAction(), buildValue(event.getResourceName()), buildValue(event.getResourceType()),
+ buildValue(event.getServiceInstanceId()), buildValue(event.getInvariantUUID()), buildValue(event.getPrevVersion()),
+ buildValue(event.getCurrVersion()), buildValue(event.getModifier()), buildValue(event.getPrevState()),
+ buildValue(event.getCurrState()), buildValue(event.getStatus()), buildValue(event.getDesc()), buildValue(event.getToscaNodeType()));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java
new file mode 100644
index 0000000000..2a188d2c1a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+
+public abstract class AuditResourceAdminEventFactory extends AuditBaseEventFactory {
+
+ protected final ResourceAdminEvent event;
+
+ public AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceAuditData prevParams,
+ ResourceAuditData currParams, String resourceType, String resourceName, String invariantUuid,
+ User modifier, String artifactData, String comment, String did, String toscaNodeType) {
+ super(action);
+
+ this.event = new ResourceAdminEvent(action.getName(), commonFields, prevParams, currParams, resourceType,
+ resourceName, invariantUuid, AuditBaseEventFactory.buildUserName(modifier),
+ artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType);
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java
new file mode 100644
index 0000000000..c7ea8cc428
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.be.auditing.impl.usersadmin;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.GetUsersListEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditGetUsersListEventFactory extends AuditBaseEventFactory {
+ private final GetUsersListEvent event;
+
+ private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier,
+ String userDetails) {
+ super(AuditingActionEnum.GET_USERS_LIST);
+ event = new GetUsersListEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(modifier), userDetails);
+ }
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java
new file mode 100644
index 0000000000..4f97ae12c9
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.be.auditing.impl.usersadmin;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.UserAccessEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditUserAccessEventFactory extends AuditBaseEventFactory {
+
+ protected final static String LOG_STR = "ACTION = \"%s\" USER = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ private final UserAccessEvent event;
+
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, event.getAction(), event.getUserUid(), event.getStatus(), event.getDesc());
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+
+ public AuditUserAccessEventFactory(CommonAuditData commonFields, User user) {
+ super(AuditingActionEnum.USER_ACCESS);
+ event = new UserAccessEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(user));
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java
new file mode 100644
index 0000000000..9c19c49b2d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java
@@ -0,0 +1,33 @@
+package org.openecomp.sdc.be.auditing.impl.usersadmin;
+
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+
+public class AuditUserAdminEventFactory extends AuditBaseEventFactory {
+
+ final private UserAdminEvent event;
+
+ protected final static String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" USER_BEFORE = \"%s\" USER_AFTER = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+
+ @Override
+ public String getLogMessage() {
+ return String.format(LOG_STR, buildValue(event.getAction()), buildValue(event.getModifier()), buildValue(event.getUserBefore()),
+ buildValue(event.getUserAfter()), buildValue(event.getStatus()), buildValue(event.getDesc()));
+ }
+
+ @Override
+ public AuditingGenericEvent getDbEvent() {
+ return event;
+ }
+
+ public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, User userBefore, User userAfter) {
+ super(action);
+ event = new UserAdminEvent(getAction().getName(), commonFields, AuditBaseEventFactory.buildUserName(modifier),
+ AuditBaseEventFactory.buildUserNameExtended(userBefore),
+ AuditBaseEventFactory.buildUserNameExtended(userAfter));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java
deleted file mode 100644
index 824b70073e..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTask.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.components.clean;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import org.apache.commons.lang3.concurrent.BasicThreadFactory;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.CleanComponentsConfiguration;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.common.config.EcompErrorName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
-@Component("asdcComponentsCleaner")
-public class AsdcComponentsCleanerTask implements Runnable {
-
- private static Logger log = LoggerFactory.getLogger(AsdcComponentsCleanerTask.class.getName());
-
- @javax.annotation.Resource
- private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null;
-
- private List<NodeTypeEnum> componentsToClean;
- private long cleaningIntervalInMinutes;
-
- private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build());
- ScheduledFuture<?> scheduledFuture = null;
-
- @PostConstruct
- public void init() {
- log.trace("Enter init method of AsdcComponentsCleaner");
- Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
- CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration();
-
- if (cleanComponentsConfiguration == null) {
- log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration");
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, "AsdcComponentsCleanerTask.init()", "AsdcComponentsCleanerTask.init()");
- BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", "fecth configuration");
- return;
-
- }
- componentsToClean = new ArrayList<NodeTypeEnum>();
- List<String> components = cleanComponentsConfiguration.getComponentsToClean();
- if (components == null) {
- log.info("no component were configured for cleaning");
- }
- for (String component : components) {
- NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component);
- if (typeEnum != null)
- componentsToClean.add(typeEnum);
- }
-
- long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes();
-
- if (intervalInMinutes < 1) {
- log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default");
- intervalInMinutes = 60;
- }
- cleaningIntervalInMinutes = intervalInMinutes;
-
- startTask();
-
- log.trace("End init method of AsdcComponentsCleaner");
- }
-
- @PreDestroy
- public void destroy() {
- this.stopTask();
- shutdownExecutor();
- }
-
- public void startTask() {
-
- log.debug("start task for cleaning components");
-
- try {
-
- if (scheduledService != null) {
- log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes);
- scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, TimeUnit.MINUTES);
-
- }
- } catch (Exception e) {
- log.debug("unexpected error occured", e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", e.getMessage());
-
- }
- }
-
- public void stopTask() {
- if (scheduledFuture != null) {
- boolean result = scheduledFuture.cancel(true);
- log.debug("Stop cleaning task. result = {}", result);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- if (false == result) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, "try to stop the polling task");
- BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", "try to stop the polling task");
- }
- scheduledFuture = null;
- }
-
- }
-
- private void shutdownExecutor() {
- if (scheduledService == null)
- return;
-
- scheduledService.shutdown(); // Disable new tasks from being submitted
- try {
- // Wait a while for existing tasks to terminate
- if (!scheduledService.awaitTermination(60, TimeUnit.SECONDS)) {
- scheduledService.shutdownNow(); // Cancel currently executing
- // tasks
- // Wait a while for tasks to respond to being cancelled
- if (!scheduledService.awaitTermination(60, TimeUnit.SECONDS))
- log.debug("Pool did not terminate");
- }
- } catch (InterruptedException ie) {
- // (Re-)Cancel if current thread also interrupted
- scheduledService.shutdownNow();
- // Preserve interrupt status
- Thread.currentThread().interrupt();
- }
- }
-
- @Override
- public void run() {
- try {
- componentsCleanBusinessLogic.cleanComponents(componentsToClean);
- } catch (Exception e) {
- log.error("unexpected error occured", e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeComponentCleanerSystemError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", e.getMessage());
- }
-
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java
deleted file mode 100644
index b12b55ba8b..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/clean/ComponentsCleanBusinessLogic.java
+++ /dev/null
@@ -1,89 +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.components.clean;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import fj.data.Either;
-
-@Component("componentsCleanBusinessLogic")
-public class ComponentsCleanBusinessLogic extends BaseBusinessLogic {
-
- @Autowired
- private ResourceBusinessLogic resourceBusinessLogic;
-
- @Autowired
- private ServiceBusinessLogic serviceBusinessLogic;
-
- private static Logger log = LoggerFactory.getLogger(ComponentsCleanBusinessLogic.class.getName());
-
- public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean) {
-
- Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents = new HashMap<NodeTypeEnum, Either<List<String>, ResponseFormat>>();
-
- log.trace("start cleanComponents");
- for (NodeTypeEnum type : componentsToClean) {
- switch (type) {
- case Resource:
- processDeletionForType(cleanedComponents, NodeTypeEnum.Resource, resourceBusinessLogic);
- break;
- case Service:
- processDeletionForType(cleanedComponents, NodeTypeEnum.Service, serviceBusinessLogic);
- break;
- default:
- log.debug("{} component type does not have cleaning method defined", type);
- break;
- }
- }
-
- log.trace("end cleanComponents");
- return cleanedComponents;
- }
-
- private void processDeletionForType(Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) {
- Either<List<String>, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents();
- if (deleteMarkedResources.isRight()) {
- log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage());
- } else {
- if (log.isDebugEnabled()) {
- StringBuilder sb = new StringBuilder("list of deleted components - type " + type + ": ");
- for (String id : deleteMarkedResources.left().value()) {
- sb.append(id).append(", ");
- }
- log.debug(sb.toString());
- }
- }
- cleanedComponents.put(type, deleteMarkedResources);
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java
new file mode 100644
index 0000000000..0ee2dabf08
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java
@@ -0,0 +1,1681 @@
+package org.openecomp.sdc.be.components.csar;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import fj.data.Either;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
+import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
+import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
+import org.openecomp.sdc.be.info.MergedArtifactInfo;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.heat.HeatParameterType;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
+
+
+@org.springframework.stereotype.Component("csarArtifactsAndGroupsBusinessLogic")
+public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
+
+ private static final Logger log = LoggerFactory.getLogger(CsarArtifactsAndGroupsBusinessLogic.class);
+ private final Gson gson = new Gson();
+ private static final Pattern pattern = Pattern.compile("\\..(.*?)\\..");
+ @Autowired
+ protected ArtifactsBusinessLogic artifactsBusinessLogic;
+
+ public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
+ String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
+ boolean shouldLock, boolean inTransaction) {
+
+ log.debug("parseResourceArtifactsInfoFromFile start");
+ return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier())
+ .left()
+ .bind( p-> createResourceArtifacts(csarInfo, resource, p, createdArtifacts,shouldLock, inTransaction))
+ .right()
+ .map(rf -> { componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); return rf;})
+ .left()
+ .bind( c -> getResourcetFromGraph(c));
+ }
+
+
+ public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
+ String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
+ boolean shouldLock, boolean inTransaction){
+
+ Resource updatedResource = resource;
+
+ Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(
+ updatedResource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
+ if (parseResourceInfoFromYamlEither.isRight()) {
+ ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ return Either.right(responseFormat);
+ }
+
+ List<GroupDefinition> groups = updatedResource.getGroups();
+ Map<String, ArtifactDefinition> deplymentArtifact = updatedResource.getDeploymentArtifacts();
+ if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
+ if(groups != null){
+ List<GroupDefinition> listToDelete = groups.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
+ groupBusinessLogic.deleteGroups(updatedResource, listToDelete);
+ }
+ return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(),
+ createdNewArtifacts, shouldLock, inTransaction);
+ }
+
+ List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = deplymentArtifact.values().stream().collect(Collectors.toList());
+
+ int labelCounter = createdDeplymentArtifactsAfterDelete.size();
+
+
+ ////////////////////////////////////// create set parsed
+ ////////////////////////////////////// artifacts///////////////////////////////////////////
+ Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
+
+
+ List<ArtifactTemplateInfo> artifactsWithoutGroups = null;
+ if (parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)) {
+ artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT);
+ parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT);
+ }
+ Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
+
+ Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(csarInfo, updatedResource, createdNewArtifacts, shouldLock, inTransaction,
+ createdDeplymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection);
+ if(parsedArtifactsPerGroupEither.isRight()){
+ log.error("Failed to parse artifacts. Status is {} ", parsedArtifactsPerGroupEither.right().value());
+ return Either.right(parsedArtifactsPerGroupEither.right().value());
+ }
+
+ Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = parsedArtifactsPerGroupEither.left().value();
+
+ // find master in group
+ Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(
+ groups, deplymentArtifact);
+
+ ///////////////////////////////// find artifacts to
+ ///////////////////////////////// delete////////////////////////////////////////////////////
+
+
+ Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<>();
+ Set<ArtifactDefinition> artifactsToDelete = findArtifactThatNotInGroupToDelete(parsedGroup, createdDeplymentArtifactsAfterDelete);
+
+ Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
+ Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup,
+ artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
+
+ List<ArtifactDefinition> deletedArtifacts = new ArrayList<>();;
+ Either<Resource, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(
+ updatedResource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts);
+ if (deletedArtifactsEither.isRight()) {
+ log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
+
+ return Either.right(deletedArtifactsEither.right().value());
+
+ }
+ updatedResource = deletedArtifactsEither.left().value();
+
+ // need to update resource if we updated artifacts
+ if (!deletedArtifacts.isEmpty()) {
+ for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
+ ArtifactDefinition artToRemove = null;
+ for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
+ if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
+ artToRemove = artFromResource;
+ break;
+ }
+ }
+ if (artToRemove != null) {
+ createdDeplymentArtifactsAfterDelete.remove(artToRemove);
+ }
+
+ }
+ }
+
+ ////////////// dissociate, associate or create
+ ////////////// artifacts////////////////////////////
+ Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo,
+ updatedResource, createdNewArtifacts, labelCounter, shouldLock, inTransaction,
+ createdDeplymentArtifactsAfterDelete, mergedgroup, deletedArtifacts);
+ groups = updatedResource.getGroups();
+ if (assDissotiateEither.isRight()) {
+ log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
+
+ return Either.right(assDissotiateEither.right().value());
+
+ }
+ updatedResource = assDissotiateEither.left().value();
+ deplymentArtifact = updatedResource.getDeploymentArtifacts();
+ createdDeplymentArtifactsAfterDelete.clear();
+ if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
+ for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
+ createdDeplymentArtifactsAfterDelete.add(entry.getValue());
+ }
+ }
+
+ // update vfModule names
+ Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
+ if (groups != null && !groups.isEmpty()) {
+ Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
+ .validateUpdateVfGroupNamesOnGraph(groups, updatedResource, inTransaction);
+ if (validateUpdateVfGroupNamesRes.isRight()) {
+ return Either.right(validateUpdateVfGroupNamesRes.right().value());
+ }
+ List<GroupDefinition> heatGroups = null;
+
+ heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
+
+ for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
+
+ if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
+ updatedGroupDef.getMembers().clear();
+ }
+ Map<String, String> members = new HashMap<>();
+ Set<String> artifactsGroup = new HashSet<>();
+ artifactsGroup.addAll(updatedGroupDef.getArtifacts());
+ associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups,
+ artifactsGroup, members);
+ if (!members.isEmpty()) {
+ updatedGroupDef.setMembers(members);
+
+ }
+
+ }
+
+ }
+
+ //////////////// create new artifacts in update
+ //////////////// flow////////////////////////////
+ List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<>();
+
+ for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
+ ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
+ boolean isNewGroup = true;
+ for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact
+ .entrySet()) {
+ Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
+ Set<ArtifactDefinition> group = groupArtifacts.keySet();
+ for (ArtifactDefinition artifactInfo : group) {
+ if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
+ parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
+ isNewGroup = false;
+ }
+ }
+ }
+ if (isNewGroup) {
+ newArtifactsGroup.add(parsedArtifactMaster);
+ }
+
+ }
+ if (!newArtifactsGroup.isEmpty()) {
+ Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
+ int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
+ Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic
+ .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter);
+ if (validateGroupNamesRes.isRight()) {
+ return Either.right(validateGroupNamesRes.right().value());
+ }
+ Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource,
+ newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter,
+ shouldLock, inTransaction);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ }
+
+ // updatedGroup
+ if (!groupForAssociateWithMembers.isEmpty()) {
+
+ List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e)
+ .collect(Collectors.toList());
+
+ Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic
+ .updateGroups(updatedResource, groupsId);
+ if (updateVersionEither.isRight()) {
+ log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
+
+ return Either.right(updateVersionEither.right().value());
+
+ }
+ }
+ if (artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()) {
+ for (ArtifactTemplateInfo t : artifactsWithoutGroups) {
+ List<ArtifactTemplateInfo> arrtifacts = new ArrayList<ArtifactTemplateInfo>();
+ arrtifacts.add(t);
+ Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource,
+ arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock,
+ inTransaction);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ }
+
+ }
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
+ .getToscaElement(updatedResource.getUniqueId());
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource);
+
+ return Either.right(responseFormat);
+
+ }
+ return Either.left(eitherGerResource.left().value());
+ }
+
+ private Set<ArtifactDefinition> findArtifactThatNotInGroupToDelete(
+ Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
+ List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) {
+ Set<ArtifactDefinition> artifactsToDelete = new HashSet<>();
+ for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
+ Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
+ for (ArtifactTemplateInfo template : artifactsNames) {
+ if(template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())){
+ Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny();
+ if(op.isPresent()){
+ if(!op.get().getArtifactType().equalsIgnoreCase(template.getType())){
+ artifactsToDelete.add(op.get());
+ }
+
+ }
+ }
+ }
+ }
+
+ return artifactsToDelete;
+ }
+
+
+ private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource,
+ Map<String, List<ArtifactTemplateInfo>> artifactsMap,
+ List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
+
+ Either<Resource, ResponseFormat> resStatus = Either.left(resource);
+
+ Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
+
+ for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
+ if (groupTemplateList != null) {
+ resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList,
+ createdArtifacts, 0, shouldLock, inTransaction);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ }
+ }
+
+ return resStatus;
+
+ }
+
+
+ private Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> createArtifactsTemplateCollection(CsarInfo csarInfo, Resource resource,
+ List<ArtifactDefinition> createdNewArtifacts, boolean shouldLock, boolean inTransaction,
+ List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, int labelCounter,
+ Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection) {
+
+ Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<>();
+
+ for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
+
+ for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
+ if (parsedGroupTemplate.getGroupName() != null) {
+ parsedGroupTemplate.setGroupName("");
+ Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<>();
+ parsedArtifactsNames.add(parsedGroupTemplate);
+ List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
+ if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
+ createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
+ }
+ parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
+ } else {
+ List<ArtifactTemplateInfo> arrtifacts = new ArrayList<>();
+ arrtifacts.add(parsedGroupTemplate);
+ Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo,
+ resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete,
+ labelCounter, shouldLock, inTransaction);
+ if (resStatus.isRight()) {
+ return Either.right(resStatus.right().value());
+ }
+
+ }
+ }
+
+ }
+ return Either.left(parsedGroup);
+ }
+
+ @SuppressWarnings({ "unchecked", "static-access" })
+ public Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(
+ Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
+
+ try {
+ JsonObject jsonElement = new JsonObject();
+ jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
+
+ JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
+ if (importStructureElement == null || importStructureElement.isJsonNull()) {
+ log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected formatr, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
+ }
+
+ Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<>();
+ artifactTemplateMap = ComponentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
+ if (artifactTemplateMap.isEmpty()) {
+ log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected formatr, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
+ }
+
+ Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
+ Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<>();
+ List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
+ for (String artifactsTypeKey : artifactsTypeKeys) {
+
+ Either <List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListEither = parseArtifactTemplateList(artifactFileName,
+ artifactTemplateMap, allGroups, artifactsTypeKey);
+ if(artifactTemplateInfoListEither.isRight()){
+ return Either.right(artifactTemplateInfoListEither.right().value());
+ }
+ artifactsMap.put(artifactsTypeKey, artifactTemplateInfoListEither.left().value());
+ }
+ int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
+ Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic
+ .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
+ if (validateGroupNamesRes.isRight()) {
+ return Either.right(validateGroupNamesRes.right().value());
+ }
+ return Either.left(artifactsMap);
+ } catch (Exception e) {
+ log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
+ log.debug("failed with exception.", e);
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected format, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
+ }
+
+ }
+
+ private Either< List<ArtifactTemplateInfo>, ResponseFormat> parseArtifactTemplateList(String artifactFileName,
+ Map<String, List<Map<String, Object>>> artifactTemplateMap, List<ArtifactTemplateInfo> allGroups,
+ String artifactsTypeKey) {
+ List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
+ Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(
+ artifactsTypeKey, o);
+ if (artifactTemplateInfoListPairStatus.isRight()) {
+ log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected format, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(artifactTemplateInfoListPairStatus.right().value());
+ }
+ List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
+ if (artifactTemplateInfoList == null) {
+ log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected format, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(
+ componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
+
+ }
+ if (!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) {
+ allGroups.addAll(artifactTemplateInfoList);
+ }
+ return Either.left(artifactTemplateInfoList);
+ }
+
+ private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey,
+ List<Map<String, Object>> jsonObject) {
+ List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<>();
+ for (Map<String, Object> o : jsonObject) {
+ Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo
+ .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList,
+ null);
+ if (artifacttemplateInfoStatus.isRight()) {
+ return Either.right(artifacttemplateInfoStatus.right().value());
+ }
+
+ ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
+ if (artifacttemplateInfo != null) {
+ artifactTemplateInfoList.add(artifacttemplateInfo);
+ }
+
+ }
+ return Either.left(artifactTemplateInfoList);
+ }
+
+
+
+ private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo,
+ Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
+ List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shouldLock, boolean inTransaction) {
+ Either<Resource, ResponseFormat> resStatus = Either.left(resource);
+ List<GroupDefinition> createdGroups = resource.getGroups();
+ List<GroupDefinition> heatGroups = null;
+ if (createdGroups != null && !createdGroups.isEmpty()) {
+
+ heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
+
+ }
+ List<GroupDefinition> needToCreate = new ArrayList<>();
+ for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
+ String groupName = groupTemplateInfo.getGroupName();
+ Set<String> artifactsGroup = new HashSet<>();
+ Set<String> artifactsUUIDGroup = new HashSet<>();
+
+ log.debug("createDeploymentArtifactsFromCsar start");
+ resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup,
+ artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
+ log.debug("createDeploymentArtifactsFromCsar end");
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ if (groupName != null && !groupName.isEmpty()) {
+
+ Either<GroupDefinition, ResponseFormat> groupDefinitionEither = buildGroupDefinition(createdArtifacts, heatGroups, groupTemplateInfo,
+ groupName, artifactsGroup, artifactsUUIDGroup);
+ if (groupDefinitionEither.isRight()) {
+ return Either.right(groupDefinitionEither.right().value());
+ }
+ needToCreate.add(groupDefinitionEither.left().value());
+ }
+ }
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreUsers(false);
+ componentParametersView.setIgnoreArtifacts(false);
+ componentParametersView.setIgnoreGroups(false);
+
+ componentParametersView.setIgnoreComponentInstances(false);
+
+ Either<Resource, StorageOperationStatus> component = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId(), componentParametersView);
+
+ if (component.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic
+ .addGroups(component.left().value(), needToCreate);
+ if (createGroups.isRight()) {
+ return Either.right(createGroups.right().value());
+ }
+
+ return Either.left(component.left().value());
+ }
+
+ private Either<GroupDefinition, ResponseFormat> buildGroupDefinition(List<ArtifactDefinition> createdArtifacts,
+ List<GroupDefinition> heatGroups, ArtifactTemplateInfo groupTemplateInfo, String groupName,
+ Set<String> artifactsGroup, Set<String> artifactsUUIDGroup) {
+
+ Map<String, String> members = new HashMap<>();
+
+ associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
+
+ List<String> artifactsList = new ArrayList<>(artifactsGroup);
+ List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup);
+
+ GroupDefinition groupDefinition = new GroupDefinition();
+ groupDefinition.setName(groupName);
+ groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
+ groupDefinition.setArtifacts(artifactsList);
+ groupDefinition.setArtifactsUuid(artifactsUUIDList);
+
+ if (!members.isEmpty()) {
+ groupDefinition.setMembers(members);
+ }
+ List<GroupProperty> properties = new ArrayList<>();
+ GroupProperty prop = new GroupProperty();
+ prop.setName(Constants.IS_BASE);
+ prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
+ properties.add(prop);
+ Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation
+ .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
+ if (getLatestGroupTypeRes.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
+ }
+ properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties,
+ createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
+ groupDefinition.convertFromGroupProperties(properties);
+ log.debug("createGroup start");
+ return Either.left(groupDefinition);
+ }
+
+ private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath,
+ Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter,
+ boolean shoudLock, boolean inTransaction) {
+ Either<Resource, ResponseFormat> resStatus = Either.left(resource);
+
+ String artifactUid = "";
+ String artifactEnvUid = "";
+ String artifactUUID = "";
+
+
+ // check if artifacts already exist
+ Either<ArtifactDefinition, ResponseFormat> createdArtifactEther = checkIfArtifactAlreadyExist(artifactTemplateInfo, createdArtifacts);
+ if(createdArtifactEther.isRight()){
+ return Either.right(createdArtifactEther.right().value());
+ }
+ ArtifactDefinition createdArtifact = createdArtifactEther.left().value();
+ if(createdArtifact == null){
+
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource,
+ artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, inTransaction);
+ if (newArtifactEither.isRight()) {
+ resStatus = Either.right(newArtifactEither.right().value());
+ return resStatus;
+ }
+ ArtifactDefinition newArtifact = newArtifactEither.left().value();
+ artifactUid = newArtifact.getUniqueId();
+ artifactUUID = newArtifact.getArtifactUUID();
+
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
+ || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic
+ .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
+ resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
+ csarInfo.getModifier(), resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ }
+ }else{
+ artifactUid = createdArtifact.getUniqueId();
+ artifactUUID = createdArtifact.getArtifactUUID();
+ artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
+ }
+ artifactsGroup.add(artifactUid);
+ artifactsUUIDGroup.add(artifactUUID);
+ if (!artifactEnvUid.isEmpty()) {
+ artifactsGroup.add(artifactEnvUid);
+ }
+
+ List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null) {
+ for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
+ resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup,
+ artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock,
+ inTransaction);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ }
+ }
+ return resStatus;
+ }
+
+ private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
+ String artifactEnvUid = "";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
+ || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
+ }
+ return artifactEnvUid;
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> checkIfArtifactAlreadyExist(ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts){
+
+ ArtifactDefinition res = null;
+ String artifactFileName = artifactTemplateInfo.getFileName();
+ Optional<ArtifactDefinition> op = createdArtifacts.stream().filter(a -> a.getArtifactName().equals(artifactFileName)).findAny();
+ if(op.isPresent()){
+ res = op.get();
+ if (!res.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
+ log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName,
+ artifactTemplateInfo.getType(), res.getArtifactType());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected formatr, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+ artifactTemplateInfo.getType(), res.getArtifactType()));
+ }
+ }
+ return Either.left(res);
+
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource,
+ String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts,
+ int label, boolean inTransaction) {
+ int updatedlabel = label;
+ final String artifactFileName = artifactTemplateInfo.getFileName();
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils
+ .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName,
+ artifactFileName, componentsUtils);
+ if (artifactContententStatus.isRight()) {
+ return Either.right(artifactContententStatus.right().value());
+ }
+ updatedlabel += createdArtifacts.size();
+
+ Map<String, Object> json = ArtifactUtils.buildJsonForArtifact(artifactTemplateInfo,
+ artifactContententStatus.left().value().getValue(), updatedlabel);
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(
+ resource, csarInfo.getModifier(), json,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE));
+
+ if (uploadArtifactToService.isRight()) {
+ return Either.right(uploadArtifactToService.right().value());
+ }
+
+ ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
+ if (currentInfo.getHeatParameters() != null) {
+
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo,
+ artifactTemplateInfo, currentInfo, false);
+ if (updateEnvEither.isRight()) {
+ log.debug("failed to update parameters to artifact {}", artifactFileName);
+ return Either.right(updateEnvEither.right().value());
+
+ }
+ currentInfo = updateEnvEither.left().value();
+
+ }
+
+ createdArtifacts.add(currentInfo);
+
+ return Either.left(currentInfo);
+
+ }
+
+
+
+ private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo,
+ ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
+
+ Resource updatedResource = resource;
+ Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
+ if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
+
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils
+ .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(),
+ CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
+ componentsUtils);
+ if (artifactparamsStatus.isRight()) {
+ resStatus = Either.right(artifactparamsStatus.right().value());
+ return resStatus;
+ }
+ Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(
+ ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(),
+ artifactparamsStatus.left().value().getValue(), false);
+
+ if (propsStatus.isLeft()) {
+ List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
+ resStatus = updateHeatParams(updatedResource, currentInfo, updatedHeatEnvParams);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+
+ }
+ }
+ if (isUpdateEnv) {
+ ComponentParametersView parametersView = new ComponentParametersView();
+ parametersView.disableAll();
+ parametersView.setIgnoreComponentInstances(false);
+ parametersView.setIgnoreUsers(false);
+ parametersView.setIgnoreArtifacts(false);
+ parametersView.setIgnoreGroups(false);
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
+ .getToscaElement(updatedResource.getUniqueId(), parametersView);
+
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource);
+
+ resStatus = Either.right(responseFormat);
+ return resStatus;
+
+ }
+
+ updatedResource = eitherGerResource.left().value();
+ Map<String, ArtifactDefinition> artifacts = updatedResource.getDeploymentArtifacts();
+ Optional<ArtifactDefinition> op = artifacts.values().stream().filter(
+ p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId()))
+ .findAny();
+ if (op.isPresent()) {
+ ArtifactDefinition artifactInfoHeatEnv = op.get();
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation
+ .updateArifactOnResource(artifactInfoHeatEnv, updatedResource.getUniqueId(),
+ artifactInfoHeatEnv.getUniqueId(), null, null);
+ if (updateArifactOnResource.isRight()) {
+ log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}",
+ updatedResource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(),
+ artifactInfoHeatEnv.getArtifactLabel());
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
+ }
+ resStatus = Either.left(updateArifactOnResource.left().value());
+ }
+ }
+ return resStatus;
+ }
+
+ private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType,
+ String fileName, byte[] content, boolean is64Encoded) {
+ // extract heat parameters
+ String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils
+ .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
+ if (heatParameters.isRight()) {
+ log.debug("File {} is not in expected key-value form in csar ", fileName);
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid",
+ ErrorSeverity.ERROR);
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
+
+ }
+ return Either.left(heatParameters.left().value());
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> updateHeatParams(Resource resource,
+ ArtifactDefinition currentInfo, List<HeatParameterDefinition> updatedHeatEnvParams) {
+
+ Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
+ List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
+
+ if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null
+ && !currentHeatEnvParams.isEmpty()) {
+
+ String paramName;
+ for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
+
+ paramName = heatEnvParam.getName();
+ for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
+ if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
+
+ String updatedParamValue = heatEnvParam.getCurrentValue();
+ if (updatedParamValue == null) {
+ updatedParamValue = heatEnvParam.getDefaultValue();
+ }
+ HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
+ if (!paramType.getValidator().isValid(updatedParamValue, null)) {
+ ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status,
+ ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
+ resStatus = Either.right(responseFormat);
+ return resStatus;
+ }
+ currHeatParam.setCurrentValue(
+ paramType.getConverter().convert(updatedParamValue, null, null));
+
+ break;
+ }
+ }
+ }
+ currentInfo.setListHeatParameters(currentHeatEnvParams);
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation
+ .updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(),
+ null, null);
+ if (updateArifactOnResource.isRight()) {
+ log.debug(
+ "Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}",
+ resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
+ }
+ resStatus = Either.left(updateArifactOnResource.left().value());
+ }
+ return resStatus;
+ }
+
+
+
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(
+ Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation) {
+
+ String jsonStr = gson.toJson(json);
+
+ String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr);
+ ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr,
+ ArtifactDefinition.class);
+ String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic
+ .validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation,
+ artifactUniqueId, artifactDefinitionFromJson, origMd5, jsonStr, null, null, user,
+ resource, false, true, false);
+ if (uploadArtifactToService.isRight()) {
+ return Either.right(uploadArtifactToService.right().value());
+ }
+
+ return Either.left(uploadArtifactToService.left().value());
+ }
+
+ private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts,
+ List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups,
+ Set<String> artifactsGroup, Map<String, String> members) {
+ if (heatGroups != null && !heatGroups.isEmpty()) {
+ for (GroupDefinition heatGroup : heatGroups) {
+ List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
+ if (grpoupProps != null) {
+ associatemembersToVFgroups(createdArtifacts, artifactsFromResource, grpoupProps, artifactsGroup, heatGroup, members);
+ }
+ }
+
+ }
+ }
+
+ private void associatemembersToVFgroups(List<ArtifactDefinition> createdArtifacts,List<ArtifactDefinition> artifactsFromResource, List<GroupProperty> grpoupProps, Set<String> artifactsGroup, GroupDefinition heatGroup, Map<String, String> members){
+ Optional<GroupProperty> op = grpoupProps.stream()
+ .filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
+ if (op.isPresent()) {
+ GroupProperty prop = op.get();
+ String heatFileNAme = prop.getValue();
+ if (null == heatFileNAme || heatFileNAme.isEmpty()) {
+ return;
+ }
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+ for (String artifactId : artifactsGroup) {
+ Optional<ArtifactDefinition> opArt = createdArtifacts.stream()
+ .filter(p -> p.getUniqueId().equals(artifactId)).findAny();
+ if (opArt.isPresent()) {
+ artifacts.add(opArt.get());
+ }
+ if (artifactsFromResource != null) {
+ opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId))
+ .findAny();
+ if (opArt.isPresent()) {
+ artifacts.add(opArt.get());
+ }
+ }
+ }
+ Optional<ArtifactDefinition> resOp = artifacts.stream()
+ .filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
+ if (resOp.isPresent()) {
+ members.putAll(heatGroup.getMembers());
+ }
+ }
+ }
+
+ public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName,
+ List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup,
+ GroupTypeDefinition groupType) {
+ Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager()
+ .getConfiguration().getVfModuleProperties();
+ vfModuleProperties.entrySet().forEach(p -> {
+ GroupProperty prop = new GroupProperty();
+ prop.setName(p.getKey());
+ if (isBase) {
+ prop.setValue(p.getValue().getForBaseModule());
+ prop.setDefaultValue(p.getValue().getForBaseModule());
+ } else {
+ prop.setValue(p.getValue().getForNonBaseModule());
+ prop.setDefaultValue(p.getValue().getForNonBaseModule());
+ }
+ properties.add(prop);
+
+ });
+ GroupProperty proplabel = new GroupProperty();
+ proplabel.setName("vf_module_label");
+
+ Matcher matcher = pattern.matcher(moduleName);
+
+ if (matcher.find()) {
+ proplabel.setValue(matcher.group(1));
+ proplabel.setDefaultValue(matcher.group(1));
+ } else {
+ proplabel.setValue(moduleName);
+ proplabel.setDefaultValue(moduleName);
+ }
+ properties.add(proplabel);
+
+ GroupProperty propvolume = new GroupProperty();
+ propvolume.setName("volume_group");
+ boolean isVolume = false;
+ for (String artifactId : artifactsInGroup) {
+ ArtifactDefinition artifactDef = null;
+ artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
+ if (artifactDef != null
+ && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ isVolume = true;
+ break;
+ }
+ }
+ propvolume.setValue(String.valueOf(isVolume));
+ propvolume.setDefaultValue(String.valueOf(isVolume));
+ properties.add(propvolume);
+ mergeWithGroupTypeProperties(properties, groupType.getProperties());
+ return properties;
+ }
+
+ private void mergeWithGroupTypeProperties(List<GroupProperty> properties,
+ List<PropertyDefinition> groupTypeProperties) {
+
+ Map<String, GroupProperty> propertiesMap = properties.stream()
+ .collect(Collectors.toMap(p -> p.getName(), p -> p));
+ for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
+ if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
+ properties.add(new GroupProperty(groupTypeProperty));
+ }
+ }
+ }
+
+ private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(
+ Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact,
+ Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete,
+ Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts,
+ List<ArtifactDefinition> createdDeplymentArtifacts) {
+ Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<>();
+ for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact
+ .entrySet()) {
+ Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
+ boolean isNeedToDeleteGroup = true;
+ List<ArtifactDefinition> listToDelete = null;
+ for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
+ listToDelete = createdArtifactMap.get(maserArtifact);
+ for (ArtifactDefinition artToDelete : listToDelete) {
+ findArtifactToDelete(parsedGroup, artifactsToDelete, artToDelete, createdDeplymentArtifacts);
+ }
+ if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
+ GroupDefinition group = groupListEntry.getKey();
+ for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
+ if (CollectionUtils.isNotEmpty(group.getArtifacts())
+ && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
+ group.getArtifacts().remove(artifactDefinition.getUniqueId());
+
+ }
+ if (CollectionUtils.isNotEmpty(group.getArtifactsUuid())
+ && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
+ group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
+
+ }
+ }
+
+ }
+
+ for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
+ if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
+ MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
+ mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
+ mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
+ mergedgroup.put(groupListEntry.getKey(), mergedGroup);
+ isNeedToDeleteGroup = false;
+
+ }
+ }
+
+ }
+ if (isNeedToDeleteGroup) {
+ groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
+ }
+
+ }
+ return mergedgroup;
+ }
+
+ private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
+ Set<ArtifactDefinition> artifactsToDelete, ArtifactDefinition artifact,
+ List<ArtifactDefinition> createdDeplymentArtifacts) {
+ boolean isNeedToDeleteArtifact = true;
+ String artifactType = artifact.getArtifactType();
+ ArtifactDefinition generatedFromArt = null;
+ if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
+ Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream()
+ .filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
+ if (op.isPresent()) {
+ generatedFromArt = op.get();
+ }
+
+ }
+
+ for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
+ Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
+ for (ArtifactTemplateInfo template : artifactsNames) {
+ if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName())
+ && artifactType.equalsIgnoreCase(template.getType())) {
+ isNeedToDeleteArtifact = false;
+ break;
+
+ } else {
+
+ if (generatedFromArt != null) {
+ if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName())
+ && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
+ isNeedToDeleteArtifact = false;
+ break;
+ }
+ }
+ }
+ }
+
+ }
+ if (isNeedToDeleteArtifact) {
+ artifactsToDelete.add(artifact);
+
+ }
+ }
+
+ private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(
+ List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
+ Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<>();
+
+ for (GroupDefinition group : groups) {
+ Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<>();
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+ List<String> artifactsList = group.getArtifacts();
+ if (artifactsList != null && !artifactsList.isEmpty()) {
+
+ ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts,
+ artifactsList);
+ if (masterArtifact != null) {
+ gupsMap.put(masterArtifact, artifacts);
+ }
+ groupArtifact.put(group, gupsMap);
+
+ }
+ }
+ return groupArtifact;
+ }
+
+ private Either<Resource, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource,
+ User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
+ Map<String, List<ArtifactDefinition>> groupToDelete, List<ArtifactDefinition> deletedArtifacts) {
+
+ Resource updatedResource = resource;
+
+ String resourceId = updatedResource.getUniqueId();
+ if (!artifactsToDelete.isEmpty()) {
+ for (ArtifactDefinition artifact : artifactsToDelete) {
+ String artifactType = artifact.getArtifactType();
+ ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
+ if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic
+ .handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE,
+ ComponentTypeEnum.RESOURCE, updatedResource, shouldLock, inTransaction);
+ if (handleDelete.isRight()) {
+ return Either.right(handleDelete.right().value());
+ }
+
+ deletedArtifacts.add(handleDelete.left().value().left().value());
+ }
+
+ }
+ }
+ if (!groupToDelete.isEmpty()) {
+ log.debug("try to delete group");
+ List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
+ List<GroupDefinition> groups = updatedResource.getGroups();
+ for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
+ Optional<GroupDefinition> op = groups.stream()
+ .filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
+ if (op.isPresent()) {
+ groupDefinitionstoDelete.add(op.get());
+ }
+
+ }
+ if (!groupDefinitionstoDelete.isEmpty()) {
+ Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, groupDefinitionstoDelete);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
+ }
+ }
+ }
+ List<GroupDefinition> oldGroups = updatedResource.getGroups();
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
+ .getToscaElement(updatedResource.getUniqueId());
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource);
+
+ return Either.right(responseFormat);
+
+ }
+ updatedResource = eitherGerResource.left().value();
+ updatedResource.setGroups(oldGroups);
+ return Either.left(updatedResource);
+ }
+
+ private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList,
+ Set<ArtifactTemplateInfo> parsedArtifactsName) {
+
+ for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
+ parsedArtifactsName.add(parsedGroupTemplate);
+ List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
+ createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
+ }
+ }
+ }
+
+ private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo,
+ Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
+ List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource,
+ int labelCounter, boolean shouldLock, boolean inTransaction) {
+
+ Resource updatedResource = resource;
+
+ Either<Resource, ResponseFormat> resStatus = Either.left(updatedResource);
+ List<GroupDefinition> createdGroups = updatedResource.getGroups();
+ List<GroupDefinition> heatGroups = null;
+ if (createdGroups != null && !createdGroups.isEmpty()) {
+ heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
+ }
+
+ List<GroupDefinition> needToAdd = new ArrayList<>();
+ for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
+ String groupName = groupTemplateInfo.getGroupName();
+ Set<String> artifactsGroup = new HashSet<>();
+ Set<String> artifactsUUIDGroup = new HashSet<>();
+
+ resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup,
+ groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock,
+ inTransaction);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ if (groupName != null && !groupName.isEmpty()) {
+ Map<String, String> members = new HashMap<>();
+ associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup,
+ members);
+
+ List<String> artifactsList = new ArrayList<>(artifactsGroup);
+ List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup);
+
+ GroupDefinition groupDefinition = new GroupDefinition();
+ groupDefinition.setName(groupName);
+ groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
+ groupDefinition.setArtifacts(artifactsList);
+ groupDefinition.setArtifactsUuid(artifactsUUIDList);
+
+ if (!members.isEmpty()) {
+ groupDefinition.setMembers(members);
+ }
+
+ List<GroupProperty> properties = new ArrayList<>();
+ GroupProperty prop = new GroupProperty();
+ prop.setName(Constants.IS_BASE);
+ prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
+ properties.add(prop);
+
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+ createdArtifacts.addAll(createdNewArtifacts);
+ createdArtifacts.addAll(artifactsFromResource);
+ Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation
+ .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
+ if (getLatestGroupTypeRes.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
+ }
+ properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties,
+ createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
+ groupDefinition.convertFromGroupProperties(properties);
+
+ needToAdd.add(groupDefinition);
+ }
+ }
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreArtifacts(false);
+ componentParametersView.setIgnoreGroups(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+
+ Either<Resource, StorageOperationStatus> component = toscaOperationFacade
+ .getToscaElement(updatedResource.getUniqueId(), componentParametersView);
+ if (component.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ updatedResource = component.left().value();
+
+ Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd);
+ if (addGroups.isRight()) {
+ return Either.right(addGroups.right().value());
+ }
+
+ return resStatus;
+ }
+
+ private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
+ Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter,
+ boolean shoudLock, boolean inTransaction) {
+ Either<Resource, ResponseFormat> resStatus = Either.left(resource);
+ String artifactFileName = artifactTemplateInfo.getFileName();
+ String artifactUid = "";
+ String artifactUUID = "";
+ String artifactEnvUid = "";
+ boolean alreadyExist = false;
+
+ // check if artifacts already exist
+ if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
+ for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
+ if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
+ artifactUid = artifactFromResource.getUniqueId();
+ artifactUUID = artifactFromResource.getArtifactUUID();
+ if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
+ log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName,
+ artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected formatr, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+ artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
+ }
+ alreadyExist = true;
+ artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
+ break;
+ }
+
+ }
+
+ }
+ if (!alreadyExist) {
+ for (ArtifactDefinition createdArtifact : createdArtifacts) {
+ if (createdArtifact.getArtifactName().equals(artifactFileName)) {
+ artifactUid = createdArtifact.getUniqueId();
+ artifactUUID = createdArtifact.getArtifactUUID();
+
+ if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
+ log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName,
+ artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected formatr, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+ artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
+ }
+ alreadyExist = true;
+ artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
+ break;
+ }
+
+ }
+ }
+ // if not exist need to create
+ if (!alreadyExist) {
+
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource,
+ ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, inTransaction);
+ if (newArtifactEither.isRight()) {
+ resStatus = Either.right(newArtifactEither.right().value());
+ return resStatus;
+ }
+ ArtifactDefinition newArtifact = newArtifactEither.left().value();
+ artifactUid = newArtifact.getUniqueId();
+ artifactUUID = newArtifact.getArtifactUUID();
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
+ || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic
+ .createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
+ resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
+ csarInfo.getModifier(), resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ }
+ }
+
+ artifactsGroup.add(artifactUid);
+ artifactsUUIDGroup.add(artifactUUID);
+ if (!artifactEnvUid.isEmpty()) {
+ artifactsGroup.add(artifactEnvUid);
+ }
+
+ List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null) {
+ for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
+ resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup,
+ relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock,
+ inTransaction);
+ if (resStatus.isRight()) {
+ return resStatus;
+ }
+ }
+ }
+ return resStatus;
+ }
+
+ private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo,
+ Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
+ boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete,
+ Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
+ Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<>();
+ Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<>();
+ Either<Resource, ResponseFormat> resEither = Either.left(resource);
+ for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
+ List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue()
+ .getListToDissotiateArtifactFromGroup(deletedArtifacts);
+ GroupDefinition grDef = entry.getKey();
+ if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
+ for (ArtifactDefinition art : dissArtifactsInGroup) {
+ grDef.getArtifacts().remove(art.getUniqueId());
+ grDef.getArtifactsUuid().remove(art.getArtifactUUID());
+ }
+ }
+
+ List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
+ if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) {
+ artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
+ }
+
+ List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue()
+ .getListToUpdateArtifactInGroup();
+ if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) {
+ artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
+ }
+ }
+
+ if (!artifactsToUpdateMap.isEmpty()) {
+ List<ArtifactDefinition> updatedArtifacts = new ArrayList<>();
+ for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap
+ .entrySet()) {
+ List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry
+ .getValue();
+ GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
+
+ for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
+ String prevUUID = artifact.getKey().getArtifactUUID();
+ String prevId = artifact.getKey().getUniqueId();
+ String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey());
+ Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(
+ csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
+ artifact.getRight().getRelatedArtifactsInfo());
+ if (updateArtifactEither.isRight()) {
+ log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
+ resEither = Either.right(updateArtifactEither.right().value());
+ return resEither;
+ }
+ ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
+ if (!prevUUID.equals(artAfterUpdate.getArtifactUUID())
+ || !prevId.equals(artAfterUpdate.getUniqueId())) {
+ groupToUpdate.getArtifacts().remove(prevId);
+ groupToUpdate.getArtifactsUuid().remove(prevUUID);
+ groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
+ groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
+ }
+ Optional<ArtifactDefinition> op = updatedArtifacts.stream()
+ .filter(p -> p.getGeneratedFromId() != null
+ && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId()))
+ .findAny();
+ if (op.isPresent()) {
+ ArtifactDefinition artifactInfoHeatEnv = op.get();
+ groupToUpdate.getArtifacts().remove(prevHeatEnvId);
+ groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId());
+ }
+
+ }
+ }
+ }
+
+ for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
+ List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
+ Set<String> arifactsUids = new HashSet<>();
+ Set<String> arifactsUuids = new HashSet<>();
+ for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
+ // to
+ // find
+ // artifact
+ // in
+ // resource
+ boolean isCreate = true;
+ for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
+ if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
+ arifactsUids.add(createdArtifact.getUniqueId());
+ arifactsUuids.add(createdArtifact.getArtifactUUID());
+ isCreate = false;
+ String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
+ if (!heatEnvId.isEmpty()) {
+ arifactsUids.add(heatEnvId);
+ Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream()
+ .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
+ if (op.isPresent()) {
+ this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(),
+ resource.getComponentType().getNodeType());
+
+ }
+ }
+
+ break;
+ }
+
+ }
+ if (isCreate) { // check if already created
+ for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
+ if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
+ arifactsUids.add(createdNewArtifact.getUniqueId());
+ arifactsUuids.add(createdNewArtifact.getArtifactUUID());
+ isCreate = false;
+ String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
+ if (!heatEnvId.isEmpty()) {
+ arifactsUids.add(heatEnvId);
+ }
+ break;
+ }
+ }
+ }
+
+ if (isCreate) {
+ Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo,
+ resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, inTransaction);
+ if (createArtifactEither.isRight()) {
+ resEither = Either.right(createArtifactEither.right().value());
+ return resEither;
+ }
+ ArtifactDefinition createdArtifact = createArtifactEither.left().value();
+ arifactsUids.add(createdArtifact.getUniqueId());
+ arifactsUuids.add(createdArtifact.getArtifactUUID());
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
+ if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
+ || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic
+ .createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
+ resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
+ csarInfo.getModifier(), resource, null);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
+ arifactsUids.add(heatEnvId);
+ }
+ }
+
+ }
+ if (arifactsUids != null && !arifactsUids.isEmpty()) {
+ List<String> artifactsToAssociate = new ArrayList<>();
+ artifactsToAssociate.addAll(arifactsUids);
+ GroupDefinition assotiateGroup = associateEntry.getKey();
+ assotiateGroup.getArtifacts().addAll(arifactsUids);
+ assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
+ }
+ }
+
+ ComponentParametersView parametersView = new ComponentParametersView();
+ parametersView.disableAll();
+ parametersView.setIgnoreComponentInstances(false);
+ parametersView.setIgnoreUsers(false);
+ parametersView.setIgnoreArtifacts(false);
+ parametersView.setIgnoreGroups(false);
+
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId(), parametersView);
+
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+
+ resEither = Either.right(responseFormat);
+ return resEither;
+
+ }
+ resEither = Either.left(eitherGerResource.left().value());
+ return resEither;
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo,
+ Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
+
+ Either<ArtifactDefinition, ResponseFormat> resStatus = null;
+ String artifactFileName = artifactTemplateInfo.getFileName();
+
+ // check if artifacts already exist
+ for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
+ if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
+ if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
+ log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName,
+ artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "Artifact file is not in expected formatr, fileName " + artifactFileName,
+ "Artifact internals are invalid", ErrorSeverity.ERROR);
+ resStatus = Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+ artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
+ return resStatus;
+ }
+ resStatus = Either.left(updatedArtifact);
+ return resStatus;
+ }
+
+ }
+
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils
+ .getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(),
+ CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
+ if (artifactContententStatus.isRight()) {
+ resStatus = Either.right(artifactContententStatus.right().value());
+ return resStatus;
+ }
+
+ Map<String, Object> json = ArtifactUtils.buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName,
+ oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(),
+ oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(),
+ artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts, oldArtifact.getIsFromCsar());
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(
+ resource, csarInfo.getModifier(), json,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE));
+
+ if (uploadArtifactToService.isRight()) {
+ resStatus = Either.right(uploadArtifactToService.right().value());
+ return resStatus;
+ }
+ ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
+ updatedArtifacts.add(currentInfo);
+
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo,
+ artifactTemplateInfo, currentInfo, true);
+ if (updateEnvEither.isRight()) {
+ log.debug("failed to update parameters to artifact {}", artifactFileName);
+ resStatus = Either.right(updateEnvEither.right().value());
+ return resStatus;
+ }
+
+ updatedArtifacts.add(updateEnvEither.left().value());
+ resStatus = Either.left(currentInfo);
+
+ return resStatus;
+
+ }
+
+ public Either<Resource, ResponseFormat> deleteVFModules(Resource resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) {
+ Resource updatedResource = resource;
+ List<GroupDefinition> groupsToDelete = updatedResource.getGroups();
+ if(groupsToDelete != null && !groupsToDelete.isEmpty()){
+ List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
+ if(vfGroupsToDelete != null && !vfGroupsToDelete.isEmpty()){
+ for(GroupDefinition gr : vfGroupsToDelete){
+ List<String> artifacts = gr.getArtifacts();
+ for (String artifactId : artifacts) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
+ updatedResource, shouldLock, inTransaction);
+ if (handleDelete.isRight()) {
+ log.debug("Couldn't delete artifact {}", artifactId);
+ return Either.right(handleDelete.right().value());
+ }
+ }
+
+ }
+ groupBusinessLogic.deleteGroups(updatedResource, vfGroupsToDelete);
+
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId());
+ if (eitherGetResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource);
+
+ return Either.right(responseFormat);
+
+ }
+ updatedResource = eitherGetResource.left().value();
+ }
+ }
+ return Either.left(updatedResource);
+ }
+
+ private Either<Resource, ResponseFormat> getResourcetFromGraph(Resource component){
+ log.debug("getResource start");
+ return toscaOperationFacade.getToscaElement(component.getUniqueId())
+ .right()
+ .map(rf -> componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(rf), component))
+ .left()
+ .map (c -> (Resource) c);
+
+
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java
new file mode 100644
index 0000000000..0519f435e3
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java
@@ -0,0 +1,84 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import org.apache.http.conn.ConnectTimeoutException;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.SupplierThrows;
+import org.openecomp.sdc.common.http.client.api.HttpExecuteException;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.client.api.Responses;
+import org.openecomp.sdc.common.http.config.ExternalServiceConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import java.net.ConnectException;
+import java.net.SocketTimeoutException;
+import java.util.Properties;
+import java.util.UUID;
+
+@Component
+public class AaiRequestHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(AaiRequestHandler.class);
+ private ExternalServiceConfig aaiConfig;
+
+ protected static final String OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM = "operationalEnvironments";
+ protected static final String OPERATIONAL_ENV_RESOURCE = "/operational-environment";
+
+ @PostConstruct
+ public void init() {
+ logger.debug("AaiRequestHandler has been initialized.");
+
+ aaiConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getAaiConfig();
+ logger.debug("AaiRequestHandler Configuration={}", aaiConfig);
+ }
+
+
+ public HttpResponse<String> getOperationalEnvById(String id) {
+ Properties headers = createHeaders();
+ String url = String.format("%s%s%s/%s",
+ aaiConfig.getHttpRequestConfig().getServerRootUrl(),
+ aaiConfig.getHttpRequestConfig().getResourceNamespaces().get(OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM),
+ OPERATIONAL_ENV_RESOURCE, id);
+
+ SupplierThrows<HttpResponse<String>, Exception> httpGet = () -> HttpRequest.get(url, headers, aaiConfig.getHttpClientConfig());
+ long maxRetries = aaiConfig.getHttpClientConfig().getNumOfRetries();
+ try {
+ return FunctionalInterfaces.retryMethodOnException(httpGet, this::retryOnException, maxRetries);
+ }
+ catch (Exception e) {
+ logger.debug("Request failed with exception {}", getCause(e).getMessage());
+ return Responses.INTERNAL_SERVER_ERROR;
+ }
+ }
+
+
+ private boolean retryOnException(Exception e) {
+ Throwable cause = getCause(e);
+ return !(cause instanceof ConnectTimeoutException || cause instanceof ConnectException || cause instanceof SocketTimeoutException);
+ }
+
+
+ private Throwable getCause(Exception e) {
+ if (e instanceof HttpExecuteException) {
+ return e.getCause();
+ }
+ return e;
+ }
+
+
+ private Properties createHeaders() {
+ Properties headers = new Properties();
+ headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
+ headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+ headers.put(Constants.X_TRANSACTION_ID_HEADER, UUID.randomUUID().toString());
+
+ return headers;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java
index e1a1270fe3..9c46c68cd8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java
@@ -20,177 +20,185 @@
package org.openecomp.sdc.be.components.distribution.engine;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+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.common.api.ArtifactTypeEnum;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-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.common.api.ArtifactTypeEnum;
-
public class ArtifactInfoImpl implements IArtifactInfo {
- private String artifactName;
- private ArtifactTypeEnum artifactType;
- private String artifactURL;
- private String artifactChecksum;
- private String artifactDescription;
- private Integer artifactTimeout;
- private String artifactUUID;
- private String artifactVersion;
- private String generatedFromUUID;
- private List<String> relatedArtifacts;
-
- public ArtifactInfoImpl() {
- }
-
- private ArtifactInfoImpl(ArtifactDefinition artifactDef, String generatedFromUUID, List<String> relatedArtifacts) {
- artifactName = artifactDef.getArtifactName();
- artifactType = ArtifactTypeEnum.findType(artifactDef.getArtifactType());
- artifactChecksum = artifactDef.getArtifactChecksum();
- artifactDescription = artifactDef.getDescription();
- artifactTimeout = artifactDef.getTimeout();
- artifactUUID = artifactDef.getArtifactUUID();
- artifactVersion = artifactDef.getArtifactVersion();
- this.relatedArtifacts = relatedArtifacts;
- this.generatedFromUUID = generatedFromUUID;
- }
-
- public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection<ArtifactDefinition> list) {
- List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
- Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId));
- if (list != null) {
- for (ArtifactDefinition artifactDef : list) {
- String generatedFromUUID = null;
- if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) {
- ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0);
- generatedFromUUID = artifactFrom.getArtifactUUID();
- }
- ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts()));
- String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName());
- artifactInfoImpl.setArtifactURL(artifactURL);
- ret.add(artifactInfoImpl);
- }
- }
- return ret;
-
- }
-
- public static List<ArtifactInfoImpl> convertServiceArtifactToArtifactInfoImpl(Service service, Collection<ArtifactDefinition> list) {
- List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
- Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId));
- if (list != null) {
- for (ArtifactDefinition artifactDef : list) {
- String generatedFromUUID = null;
- if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) {
- ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0);
- generatedFromUUID = artifactFrom.getArtifactUUID();
- }
- ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts()));
- String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName());
- artifactInfoImpl.setArtifactURL(artifactURL);
- ret.add(artifactInfoImpl);
- }
- }
- return ret;
-
- }
-
- private static List<String> getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map<String, ArtifactDefinition> artifacts) {
- List<String> requiredArtifacts = null;
- if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) {
- requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(art -> art.getArtifactUUID()).collect(Collectors.toList());
- }
- return requiredArtifacts;
- }
-
- public String getArtifactName() {
- return artifactName;
- }
-
- public void setArtifactName(String artifactName) {
- this.artifactName = artifactName;
- }
-
- public ArtifactTypeEnum getArtifactType() {
- return artifactType;
- }
-
- public void setArtifactType(ArtifactTypeEnum artifactType) {
- this.artifactType = artifactType;
- }
-
- public String getArtifactURL() {
- return artifactURL;
- }
-
- public void setArtifactURL(String artifactURL) {
- this.artifactURL = artifactURL;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public void setArtifactChecksum(String artifactChecksum) {
- this.artifactChecksum = artifactChecksum;
- }
-
- public String getArtifactDescription() {
- return artifactDescription;
- }
-
- public void setArtifactDescription(String artifactDescription) {
- this.artifactDescription = artifactDescription;
- }
-
- public Integer getArtifactTimeout() {
- return artifactTimeout;
- }
-
- public void setArtifactTimeout(Integer artifactTimeout) {
- this.artifactTimeout = artifactTimeout;
- }
-
- public List<String> getRelatedArtifacts() {
- return relatedArtifacts;
- }
-
- public void setRelatedArtifacts(List<String> relatedArtifacts) {
- this.relatedArtifacts = relatedArtifacts;
- }
-
- @Override
- public String toString() {
- return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout="
- + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]";
- }
-
- 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;
- }
+ private String artifactName;
+ private ArtifactTypeEnum artifactType;
+ private String artifactURL;
+ private String artifactChecksum;
+ private String artifactDescription;
+ private Integer artifactTimeout;
+ private String artifactUUID;
+ private String artifactVersion;
+ private String generatedFromUUID;
+ private List<String> relatedArtifacts;
+
+ public ArtifactInfoImpl() {
+ }
+
+ private ArtifactInfoImpl(ArtifactDefinition artifactDef, String generatedFromUUID, List<String> relatedArtifacts) {
+ artifactName = artifactDef.getArtifactName();
+ artifactType = ArtifactTypeEnum.findType(artifactDef.getArtifactType());
+ artifactChecksum = artifactDef.getArtifactChecksum();
+ artifactDescription = artifactDef.getDescription();
+ artifactTimeout = artifactDef.getTimeout();
+ artifactUUID = artifactDef.getArtifactUUID();
+ artifactVersion = artifactDef.getArtifactVersion();
+ this.relatedArtifacts = relatedArtifacts;
+ this.generatedFromUUID = generatedFromUUID;
+ }
+
+ public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection<ArtifactDefinition> list) {
+ List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
+ Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId));
+ if (list != null) {
+ for (ArtifactDefinition artifactDef : list) {
+ String generatedFromUUID = null;
+ if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) {
+ ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0);
+ generatedFromUUID = artifactFrom.getArtifactUUID();
+ }
+ ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts()));
+ String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName());
+ artifactInfoImpl.setArtifactURL(artifactURL);
+ ret.add(artifactInfoImpl);
+ }
+ }
+ ret.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout);
+ return ret;
+
+ }
+
+ public static List<ArtifactInfoImpl> convertServiceArtifactToArtifactInfoImpl(Service service, Collection<ArtifactDefinition> list) {
+ List<ArtifactInfoImpl> ret = new ArrayList<ArtifactInfoImpl>();
+ Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId));
+ if (list != null) {
+ for (ArtifactDefinition artifactDef : list) {
+ String generatedFromUUID = null;
+ if (artifactDef.getGeneratedFromId() != null && !artifactDef.getGeneratedFromId().isEmpty()) {
+ ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0);
+ generatedFromUUID = artifactFrom.getArtifactUUID();
+ }
+ ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts()));
+ String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName());
+ artifactInfoImpl.setArtifactURL(artifactURL);
+ ret.add(artifactInfoImpl);
+ }
+ }
+ return ret;
+
+ }
+
+ private static List<String> getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map<String, ArtifactDefinition> artifacts) {
+ List<String> requiredArtifacts = null;
+ if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) {
+ requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(art -> art.getArtifactUUID()).collect(Collectors.toList());
+ }
+ return requiredArtifacts;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public ArtifactTypeEnum getArtifactType() {
+ return artifactType;
+ }
+
+ public void setArtifactType(ArtifactTypeEnum artifactType) {
+ this.artifactType = artifactType;
+ }
+
+ public String getArtifactURL() {
+ return artifactURL;
+ }
+
+ public void setArtifactURL(String artifactURL) {
+ this.artifactURL = artifactURL;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getArtifactDescription() {
+ return artifactDescription;
+ }
+
+ public void setArtifactDescription(String artifactDescription) {
+ this.artifactDescription = artifactDescription;
+ }
+
+ public Integer getArtifactTimeout() {
+ return artifactTimeout;
+ }
+
+ public void setArtifactTimeout(Integer artifactTimeout) {
+ this.artifactTimeout = artifactTimeout;
+ }
+
+ public List<String> getRelatedArtifacts() {
+ return relatedArtifacts;
+ }
+
+ public void setRelatedArtifacts(List<String> relatedArtifacts) {
+ this.relatedArtifacts = relatedArtifacts;
+ }
+
+ @Override
+ public String toString() {
+ return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout="
+ + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]";
+ }
+
+ 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;
+ }
+
+ public void updateArtifactTimeout(){
+ int currentConfigTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getCurrentArtifactInstallationTimeout();
+ if(artifactTimeout == null || artifactTimeout < currentConfigTimeout)
+ artifactTimeout = currentConfigTimeout;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java
index 149ea2286a..3251f3d047 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java
@@ -20,67 +20,67 @@
package org.openecomp.sdc.be.components.distribution.engine;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
+
import java.util.ArrayList;
import java.util.List;
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-
public class CambriaErrorResponse {
- public static final int HTTP_OK = 200;
+ public static final int HTTP_OK = 200;
- public static final int HTTP_INTERNAL_SERVER_ERROR = 500;
+ public static final int HTTP_INTERNAL_SERVER_ERROR = 500;
- CambriaOperationStatus operationStatus;
- Integer httpCode;
- List<String> variables = new ArrayList<String>();
+ CambriaOperationStatus operationStatus;
+ Integer httpCode;
+ List<String> variables = new ArrayList<String>();
- public CambriaErrorResponse() {
- super();
- }
+ public CambriaErrorResponse() {
+ super();
+ }
- public CambriaErrorResponse(CambriaOperationStatus operationStatus) {
- super();
- this.operationStatus = operationStatus;
- }
+ public CambriaErrorResponse(CambriaOperationStatus operationStatus) {
+ super();
+ this.operationStatus = operationStatus;
+ }
- public CambriaErrorResponse(CambriaOperationStatus operationStatus, Integer httpCode) {
- super();
- this.operationStatus = operationStatus;
- this.httpCode = httpCode;
- }
+ public CambriaErrorResponse(CambriaOperationStatus operationStatus, Integer httpCode) {
+ super();
+ this.operationStatus = operationStatus;
+ this.httpCode = httpCode;
+ }
- public CambriaOperationStatus getOperationStatus() {
- return operationStatus;
- }
+ public CambriaOperationStatus getOperationStatus() {
+ return operationStatus;
+ }
- public void setOperationStatus(CambriaOperationStatus operationStatus) {
- this.operationStatus = operationStatus;
- }
+ public void setOperationStatus(CambriaOperationStatus operationStatus) {
+ this.operationStatus = operationStatus;
+ }
- public Integer getHttpCode() {
- return httpCode;
- }
+ public Integer getHttpCode() {
+ return httpCode;
+ }
- public void setHttpCode(Integer httpCode) {
- this.httpCode = httpCode;
- }
+ public void setHttpCode(Integer httpCode) {
+ this.httpCode = httpCode;
+ }
- public void addVariable(String variable) {
- variables.add(variable);
- }
+ public void addVariable(String variable) {
+ variables.add(variable);
+ }
- public List<String> getVariables() {
- return variables;
- }
+ public List<String> getVariables() {
+ return variables;
+ }
- public void setVariables(List<String> variables) {
- this.variables = variables;
- }
+ public void setVariables(List<String> variables) {
+ this.variables = variables;
+ }
- @Override
- public String toString() {
- return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]";
- }
+ @Override
+ public String toString() {
+ return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]";
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
index c496715a02..d6fee9a9d3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
@@ -20,25 +20,7 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.security.GeneralSecurityException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-import org.openecomp.sdc.common.config.EcompErrorName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+import com.att.nsa.apiClient.credentials.ApiCredential;
import com.att.nsa.apiClient.http.HttpException;
import com.att.nsa.apiClient.http.HttpObjectNotFoundException;
import com.att.nsa.cambria.client.CambriaBatchingPublisher;
@@ -53,574 +35,591 @@ import com.att.nsa.cambria.client.CambriaConsumer;
import com.att.nsa.cambria.client.CambriaIdentityManager;
import com.att.nsa.cambria.client.CambriaPublisher.message;
import com.att.nsa.cambria.client.CambriaTopicManager;
+import com.google.common.annotations.VisibleForTesting;
import com.google.gson.Gson;
-
import fj.data.Either;
+import org.apache.http.HttpStatus;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.security.GeneralSecurityException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@Component("cambriaHandler")
public class CambriaHandler {
- private static Logger logger = LoggerFactory.getLogger(CambriaHandler.class.getName());
+ private static final Logger logger = LoggerFactory.getLogger(CambriaHandler.class);
+
+ private static final String PARTITION_KEY = "asdc" + "aa";
+
+ private final String SEND_NOTIFICATION = "send notification";
+
+ private Gson gson = new Gson();
+
+ private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionStatusTopic().getConsumerId();
+
+
+
+ /**
+ * process the response error from Cambria client
+ *
+ * @param message
+ * @return
+ */
+ private Integer processMessageException(String message) {
+
+ String[] patterns = { "(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)" };
+
+ Integer result = checkPattern(patterns[0], message, 2);
+ if (result != null) {
+ return result;
+ }
+ result = checkPattern(patterns[1], message, 2);
+
+ return result;
+
+ }
+
+ /**
+ * check whether the message has a match with a given pattern inside it
+ *
+ * @param patternStr
+ * @param message
+ * @param groupIndex
+ * @return
+ */
+ private Integer checkPattern(String patternStr, String message, int groupIndex) {
+ Integer result = null;
+
+ Pattern pattern = Pattern.compile(patternStr);
+ Matcher matcher = pattern.matcher(message);
+ boolean find = matcher.find();
+ if (find) {
+ String httpCode = matcher.group(groupIndex);
+ if (httpCode != null) {
+ try {
+ result = Integer.valueOf(httpCode);
+ } catch (NumberFormatException e) {
+ logger.debug("Failed to parse http code {}", httpCode);
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * retrieve all topics from U-EB server
+ *
+ * @param hostSet
+ * @return
+ */
+ public Either<Set<String>, CambriaErrorResponse> getTopics(List<String> hostSet) {
+
+ CambriaTopicManager createTopicManager = null;
+ try {
+
+ createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet));
+
+ Set<String> topics = createTopicManager.getTopics();
+
+ if (topics == null || true == topics.isEmpty()) {
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null);
+ return Either.right(cambriaErrorResponse);
+ }
+
+ return Either.left(topics);
+
+ } catch (IOException | GeneralSecurityException e) {
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ CambriaErrorResponse cambriaErrorResponse = processError(e);
+
+ logger.debug("Failed to fetch topics from U-EB server", e);
+ writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get topics");
+
+ return Either.right(cambriaErrorResponse);
+ } finally {
+ if (createTopicManager != null) {
+ createTopicManager.close();
+ }
+ }
+
+ }
+
+ /**
+ * process the error message from Cambria client.
+ *
+ * set Cambria status and http code in case we succeed to fetch it
+ *
+ * @return
+ */
+ private CambriaErrorResponse processError(Exception e) {
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse();
+
+ Integer httpCode = processMessageException(e.getMessage());
+
+ if (httpCode != null) {
+ cambriaErrorResponse.setHttpCode(httpCode);
+ switch (httpCode.intValue()) {
+
+ case 401:
+ cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR);
+ break;
+ case 409:
+ cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.TOPIC_ALREADY_EXIST);
+ break;
+ case 500:
+ cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.INTERNAL_SERVER_ERROR);
+ break;
+ default:
+ cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR);
+ }
+ } else {
+
+ boolean found = false;
+ Throwable throwable = e.getCause();
+ if (throwable != null) {
+ String message = throwable.getMessage();
+
+ Throwable cause = throwable.getCause();
+
+ if (cause != null) {
+ Class<?> clazz = cause.getClass();
+ String className = clazz.getName();
+ if (className.endsWith("UnknownHostException")) {
+ cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.UNKNOWN_HOST_ERROR);
+ cambriaErrorResponse.addVariable(message);
+ found = true;
+ }
+ }
+ }
+
+ if (false == found) {
+ cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR);
+ cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+
+ return cambriaErrorResponse;
+ }
+
+ /**
+ * write the error to the log
+ *
+ * @param cambriaErrorResponse
+ * @param errorMessage
+ * @param methodName
+ * @param operationDesc
+ */
+ private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String errorMessage, String methodName, String operationDesc) {
+
+ String httpCode = cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode());
+
+ switch (cambriaErrorResponse.getOperationStatus()) {
+ case UNKNOWN_HOST_ERROR:
+ String hostname = cambriaErrorResponse.getVariables().get(0);
+ BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode);
+ break;
+ case AUTHENTICATION_ERROR:
+ BeEcompErrorManager.getInstance().logBeUebAuthenticationError(methodName, httpCode);
+ break;
+ case CONNNECTION_ERROR:
+ BeEcompErrorManager.getInstance().logBeUebConnectionError(methodName, httpCode);
+ break;
+
+ case INTERNAL_SERVER_ERROR:
+ BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc);
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * create a topic if it does not exists in the topicsList
+ *
+ * @param hostSet
+ * - list of U-EB servers
+ * @param apiKey
+ * @param secretKey
+ * @param topicName
+ * - topic to create
+ * @param partitionCount
+ * @param replicationCount
+ * @return
+ */
+ public CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) {
+
+ CambriaTopicManager createTopicManager = null;
+ try {
+
+ createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey));
+
+ createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount);
+
+ } catch (HttpException | IOException | GeneralSecurityException e) {
+
+ logger.debug("Failed to create topic {}", topicName, e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ CambriaErrorResponse cambriaErrorResponse = processError(e);
+
+ if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) {
+ writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "create topic");
+ }
+
+ return cambriaErrorResponse;
+
+ } finally {
+ if (createTopicManager != null) {
+ createTopicManager.close();
+ }
+ }
+ return new CambriaErrorResponse(CambriaOperationStatus.OK);
+
+ }
+
+ public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) {
+ CambriaTopicManager createTopicManager = null;
+ try {
+ createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey));
+
+ if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
+ createTopicManager.revokeProducer(topicName, subscriberApiKey);
+ } else {
+ createTopicManager.revokeConsumer(topicName, subscriberApiKey);
+ }
+
+ } catch (HttpObjectNotFoundException | GeneralSecurityException e) {
+ logger.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage());
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND);
+ return cambriaErrorResponse;
+
+ } catch (HttpException | IOException e) {
+ logger.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ CambriaErrorResponse cambriaErrorResponse = processError(e);
+
+ writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase());
+
+ return cambriaErrorResponse;
+ } finally {
+ if (createTopicManager != null) {
+ createTopicManager.close();
+ }
+ }
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+ return cambriaErrorResponse;
+ }
+
+ /**
+ *
+ * register a public key (subscriberId) to a given topic as a CONSUMER or PRODUCER
+ *
+ * @param hostSet
+ * @param managerApiKey
+ * @param managerSecretKey
+ * @param subscriberApiKey
+ * @param subscriberTypeEnum
+ * @param topicName
+ * @return
+ */
+ public CambriaErrorResponse registerToTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) {
+
+ CambriaTopicManager createTopicManager = null;
+ try {
+ createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey));
+
+ if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
+ createTopicManager.allowProducer(topicName, subscriberApiKey);
+ } else {
+ createTopicManager.allowConsumer(topicName, subscriberApiKey);
+ }
+
+ } catch (HttpObjectNotFoundException | GeneralSecurityException e) {
+ logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage());
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND);
+ return cambriaErrorResponse;
+
+ } catch (HttpException | IOException e) {
+ logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ CambriaErrorResponse cambriaErrorResponse = processError(e);
+
+ writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase());
+
+ return cambriaErrorResponse;
+ } finally {
+ if (createTopicManager != null) {
+ createTopicManager.close();
+ }
+ }
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+ return cambriaErrorResponse;
+ }
+
+ /**
+ * create and retrieve a Cambria Consumer for a specific topic
+ *
+ * @param hostSet
+ * @param topicName
+ * @param apiKey
+ * @param secretKey
+ * @param consumerId
+ * @param consumerGroup
+ * @param timeoutMS
+ * @return
+ * @throws Exception
+ */
+ public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception {
+
+ CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHosts(hostSet).waitAtServer(timeoutMS).build();
+ consumer.setApiCredentials(apiKey, secretKey);
+ return consumer;
+ }
+
+ public void closeConsumer(CambriaConsumer consumer) {
+
+ if (consumer != null) {
+ consumer.close();
+ }
+
+ }
+
+ /**
+ * use the topicConsumer to fetch messages from topic. in case no messages were fetched, empty ArrayList will be returned (not error)
+ *
+ * @param topicConsumer
+ * @return
+ */
+ public Either<Iterable<String>, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) {
+
+ try {
+ Iterable<String> messages = topicConsumer.fetch();
+ if (messages == null) {
+ messages = new ArrayList<String>();
+ }
+ return Either.left(messages);
+
+ } catch (IOException e) {
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ CambriaErrorResponse cambriaErrorResponse = processError(e);
+
+ logger.debug("Failed to fetch from U-EB topic. error={}", e.getMessage());
+ writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get messages from topic");
+
+ return Either.right(cambriaErrorResponse);
+
+ } catch (Exception e) {
+ logger.debug("Failed to fetch from U-EB topic", e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ return Either.right(cambriaErrorResponse);
+ }
+ }
+
+ /**
+ * Publish notification message to a given queue
+ *
+ * @param topicName
+ * @param uebPublicKey
+ * @param uebSecretKey
+ * @param uebServers
+ * @param data
+ * @return
+ */
+ public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data) {
+
+ CambriaBatchingPublisher createSimplePublisher = null;
+
+ try {
+
+ String json = gson.toJson(data);
+ logger.trace("Before sending notification data {} to topic {}", json, topicName);
+
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
+ createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
- private static final String PARTITION_KEY = "asdc" + "aa";
-
- private final String SEND_NOTIFICATION = "send notification";
-
- private Gson gson = new Gson();
-
- public static boolean useHttpsWithDmaap = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().isUseHttpsWithDmaap();
+ int result = createSimplePublisher.send(PARTITION_KEY, json);
+ try {
+ Thread.sleep(1 * 1000);
+ } catch (InterruptedException e) {
+ logger.debug("Failed during sleep after sending the message.", e);
+ }
- /**
- * process the response error from Cambria client
- *
- * @param message
- * @return
- */
- private Integer processMessageException(String message) {
-
- String[] patterns = { "(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)" };
-
- Integer result = checkPattern(patterns[0], message, 2);
- if (result != null) {
- return result;
- }
- result = checkPattern(patterns[1], message, 2);
-
- return result;
-
- }
-
- /**
- * check whether the message has a match with a given pattern inside it
- *
- * @param patternStr
- * @param message
- * @param groupIndex
- * @return
- */
- private Integer checkPattern(String patternStr, String message, int groupIndex) {
- Integer result = null;
-
- Pattern pattern = Pattern.compile(patternStr);
- Matcher matcher = pattern.matcher(message);
- boolean find = matcher.find();
- if (find) {
- String httpCode = matcher.group(groupIndex);
- if (httpCode != null) {
- try {
- result = Integer.valueOf(httpCode);
- } catch (NumberFormatException e) {
- logger.debug("Failed to parse http code {}", httpCode);
- }
- }
- }
- return result;
- }
-
- /**
- * retrieve all topics from U-EB server
- *
- * @param hostSet
- * @return
- */
- public Either<Set<String>, CambriaErrorResponse> getTopics(List<String> hostSet) {
-
- CambriaTopicManager createTopicManager = null;
- try {
-
- createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet));
-
- Set<String> topics = createTopicManager.getTopics();
-
- if (topics == null || true == topics.isEmpty()) {
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null);
- return Either.right(cambriaErrorResponse);
- }
-
- return Either.left(topics);
-
- } catch (IOException | GeneralSecurityException e) {
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- CambriaErrorResponse cambriaErrorResponse = processError(e);
-
- logger.debug("Failed to fetch topics from U-EB server", e);
- writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get topics");
-
- return Either.right(cambriaErrorResponse);
- } finally {
- if (createTopicManager != null) {
- createTopicManager.close();
- }
- }
-
- }
-
- /**
- * process the error message from Cambria client.
- *
- * set Cambria status and http code in case we succeed to fetch it
- *
- * @return
- */
- private CambriaErrorResponse processError(Exception e) {
-
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse();
-
- Integer httpCode = processMessageException(e.getMessage());
-
- if (httpCode != null) {
- cambriaErrorResponse.setHttpCode(httpCode);
- switch (httpCode.intValue()) {
-
- case 401:
- cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR);
- break;
- case 409:
- cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.TOPIC_ALREADY_EXIST);
- break;
- case 500:
- cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.INTERNAL_SERVER_ERROR);
- break;
- default:
- cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR);
- }
- } else {
-
- boolean found = false;
- Throwable throwable = e.getCause();
- if (throwable != null) {
- String message = throwable.getMessage();
-
- Throwable cause = throwable.getCause();
-
- if (cause != null) {
- Class<?> clazz = cause.getClass();
- String className = clazz.getName();
- if (className.endsWith("UnknownHostException")) {
- cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.UNKNOWN_HOST_ERROR);
- cambriaErrorResponse.addVariable(message);
- found = true;
- }
- }
- }
-
- if (false == found) {
- cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR);
- cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
- }
-
- return cambriaErrorResponse;
- }
-
- /**
- * write the error to the log
- *
- * @param cambriaErrorResponse
- * @param errorMessage
- * @param methodName
- * @param operationDesc
- */
- private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String errorMessage, String methodName, String operationDesc) {
-
- String httpCode = (cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode()));
-
- switch (cambriaErrorResponse.getOperationStatus()) {
- case UNKNOWN_HOST_ERROR:
- String hostname = cambriaErrorResponse.getVariables().get(0);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebUnkownHostError, methodName, hostname);
- BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode);
- break;
- case AUTHENTICATION_ERROR:
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebAuthenticationError, methodName, httpCode);
- BeEcompErrorManager.getInstance().logBeUebAuthenticationError(methodName, httpCode);
- break;
- case CONNNECTION_ERROR:
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebConnectionError, methodName, httpCode);
- BeEcompErrorManager.getInstance().logBeUebConnectionError(methodName, httpCode);
- break;
-
- case INTERNAL_SERVER_ERROR:
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, methodName, operationDesc);
- BeEcompErrorManager.getInstance().logBeUebSystemError(methodName, operationDesc);
- break;
- default:
- break;
- }
-
- }
-
- /**
- * create a topic if it does not exists in the topicsList
- *
- * @param hostSet
- * - list of U-EB servers
- * @param apiKey
- * @param secretKey
- * @param topicName
- * - topic to create
- * @param partitionCount
- * @param replicationCount
- * @return
- */
- public CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) {
-
- CambriaTopicManager createTopicManager = null;
- try {
-
- createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(apiKey, secretKey));
-
- createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount);
-
- } catch (HttpException | IOException | GeneralSecurityException e) {
-
- logger.debug("Failed to create topic {}", topicName, e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- CambriaErrorResponse cambriaErrorResponse = processError(e);
-
- if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) {
- writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "create topic");
- }
-
- return cambriaErrorResponse;
-
- } finally {
- if (createTopicManager != null) {
- createTopicManager.close();
- }
- }
- return new CambriaErrorResponse(CambriaOperationStatus.OK);
-
- }
-
- public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) {
- CambriaTopicManager createTopicManager = null;
- try {
- createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey));
-
- if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
- createTopicManager.revokeProducer(topicName, subscriberApiKey);
- } else {
- createTopicManager.revokeConsumer(topicName, subscriberApiKey);
- }
-
- } catch (HttpObjectNotFoundException | GeneralSecurityException e) {
- logger.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebObjectNotFoundError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage());
-
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND);
- return cambriaErrorResponse;
-
- } catch (HttpException | IOException e) {
- logger.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- CambriaErrorResponse cambriaErrorResponse = processError(e);
-
- writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase());
-
- return cambriaErrorResponse;
- } finally {
- if (createTopicManager != null) {
- createTopicManager.close();
- }
- }
-
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
- return cambriaErrorResponse;
- }
-
- /**
- *
- * register a public key (subscriberId) to a given topic as a CONSUMER or PRODUCER
- *
- * @param hostSet
- * @param topicName
- * @param managerApiKey
- * @param managerSecretKey
- * @param subscriberApiKey
- * @param subscriberTypeEnum
- * @return
- */
- public CambriaErrorResponse registerToTopic(Collection<String> hostSet, String topicName, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum) {
-
- CambriaTopicManager createTopicManager = null;
- try {
- createTopicManager = buildCambriaClient(new TopicManagerBuilder().usingHosts(hostSet).authenticatedBy(managerApiKey, managerSecretKey));
-
- if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
- createTopicManager.allowProducer(topicName, subscriberApiKey);
- } else {
- createTopicManager.allowConsumer(topicName, subscriberApiKey);
- }
-
- } catch (HttpObjectNotFoundException | GeneralSecurityException e) {
- logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebObjectNotFoundError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage());
-
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND);
- return cambriaErrorResponse;
-
- } catch (HttpException | IOException e) {
- logger.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- CambriaErrorResponse cambriaErrorResponse = processError(e);
-
- writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase());
-
- return cambriaErrorResponse;
- } finally {
- if (createTopicManager != null) {
- createTopicManager.close();
- }
- }
-
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
- return cambriaErrorResponse;
- }
-
- /**
- * create and retrieve a Cambria Consumer for a specific topic
- *
- * @param hostSet
- * @param topicName
- * @param apiKey
- * @param secretKey
- * @param consumerId
- * @param consumerGroup
- * @param timeoutMS
- * @return
- * @throws Exception
- */
- public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception {
-
- CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(hostSet).withSocketTimeout(timeoutMS).build();
- consumer.setApiCredentials(apiKey, secretKey);
- return consumer;
- }
-
- public void closeConsumer(CambriaConsumer consumer) {
-
- if (consumer != null) {
- consumer.close();
- }
-
- }
-
- /**
- * use the topicConsumer to fetch messages from topic. in case no messages were fetched, empty ArrayList will be returned (not error)
- *
- * @param topicConsumer
- * @return
- */
- public Either<Iterable<String>, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) {
-
- try {
- Iterable<String> messages = topicConsumer.fetch();
- if (messages == null) {
- messages = new ArrayList<String>();
- }
- return Either.left(messages);
-
- } catch (IOException e) {
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- CambriaErrorResponse cambriaErrorResponse = processError(e);
-
- logger.debug("Failed to fetch from U-EB topic. error={}", e.getMessage());
- writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, "get messages from topic");
-
- return Either.right(cambriaErrorResponse);
-
- } catch (Exception e) {
- logger.debug("Failed to fetch from U-EB topic", e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
+ logger.debug("After sending notification data to topic {}. result is {}", topicName, result);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
+ CambriaErrorResponse response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- return Either.right(cambriaErrorResponse);
- }
- }
+ return response;
- /**
- * Publish notification message to a given queue
- *
- * @param topicName
- * @param uebPublicKey
- * @param uebSecretKey
- * @param uebServers
- * @param data
- * @return
- */
- public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data) {
+ } catch (IOException | GeneralSecurityException e) {
+ logger.debug("Failed to send notification {} to topic {} ", data, topicName, e);
- CambriaBatchingPublisher createSimplePublisher = null;
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
- try {
+ CambriaErrorResponse cambriaErrorResponse = processError(e);
- String json = gson.toJson(data);
- logger.trace("Before sending notification data {} to topic {}", json, topicName);
+ writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION);
- createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(uebServers).build();
- createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
-
- int result = createSimplePublisher.send(PARTITION_KEY, json);
-
- try {
- Thread.sleep(1 * 1000);
- } catch (InterruptedException e) {
- logger.debug("Failed during sleep after sending the message.", e);
- }
-
- logger.debug("After sending notification data to topic {}. result is {}", topicName, result);
-
- CambriaErrorResponse response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
-
- return response;
+ return cambriaErrorResponse;
+ } finally {
+ if (createSimplePublisher != null) {
+ logger.debug("Before closing publisher");
+ createSimplePublisher.close();
+ logger.debug("After closing publisher");
+ }
+ }
+ }
- } catch (IOException | GeneralSecurityException e) {
- logger.debug("Failed to send notification {} to topic {} ", data, topicName, e);
+ public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data, long waitBeforeCloseTimeout) {
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
+ CambriaBatchingPublisher createSimplePublisher = null;
- CambriaErrorResponse cambriaErrorResponse = processError(e);
+ CambriaErrorResponse response = null;
+ try {
- writeErrorToLog(cambriaErrorResponse, e.getMessage(), methodName, SEND_NOTIFICATION);
+ String json = gson.toJson(data);
+ logger.debug("Before sending notification data {} to topic {}", json, topicName);
- return cambriaErrorResponse;
- } finally {
- if (createSimplePublisher != null) {
- logger.debug("Before closing publisher");
- createSimplePublisher.close();
- logger.debug("After closing publisher");
- }
- }
- }
+ createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
+ createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
- private String convertListToString(List<String> list) {
- StringBuilder builder = new StringBuilder();
+ int result = createSimplePublisher.send(PARTITION_KEY, json);
- if (list != null) {
- for (int i = 0; i < list.size(); i++) {
- builder.append(list.get(i));
- if (i < list.size() - 1) {
- builder.append(",");
- }
- }
- }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ logger.debug("Failed during sleep after sending the message.", e);
+ }
- return builder.toString();
- }
+ logger.debug("After sending notification data to topic {}. result is {}", topicName, result);
- public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data, long waitBeforeCloseTimeout) {
+ } catch (IOException | GeneralSecurityException e) {
+ logger.debug("Failed to send notification {} to topic {} ", data, topicName, e);
- CambriaBatchingPublisher createSimplePublisher = null;
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
- CambriaErrorResponse response = null;
- try {
+ response = processError(e);
- String json = gson.toJson(data);
- logger.debug("Before sending notification data {} to topic {}", json, topicName);
+ writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION);
- createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHttps(useHttpsWithDmaap).usingHosts(uebServers).build();
- createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
+ return response;
- int result = createSimplePublisher.send(PARTITION_KEY, json);
+ }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- logger.debug("Failed during sleep after sending the message.", e);
- }
+ logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout);
+ try {
+ List<message> messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS);
+ if (messagesInQ != null && false == messagesInQ.isEmpty()) {
+ logger.debug("Cambria client returned {} non sent messages.", messagesInQ.size());
+ response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+ writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION);
+ } else {
+ logger.debug("No message left in the queue after closing cambria publisher");
+ response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
+ }
+ } catch (IOException | InterruptedException e) {
+ logger.debug("Failed to close cambria publisher", e);
+ response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+ writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION);
+ }
+ logger.debug("After closing publisher");
- logger.debug("After sending notification data to topic {}. result is {}", topicName, result);
+ return response;
- } catch (IOException | GeneralSecurityException e) {
- logger.debug("Failed to send notification {} to topic {} ", data, topicName, e);
+ }
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
+ public CambriaErrorResponse getApiKey(String server, String apiKey) {
- response = processError(e);
+ CambriaErrorResponse response = null;
- writeErrorToLog(response, e.getMessage(), methodName, SEND_NOTIFICATION);
+ List<String> hostSet = new ArrayList<>();
+ hostSet.add(server);
+ try {
+ CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet));
+ createIdentityManager.getApiKey(apiKey);
- return response;
+ response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
- }
+ } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) {
+ logger.debug("Failed to fetch api key {} from server {}", apiKey, server, e);
- logger.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout);
- try {
- List<message> messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, TimeUnit.SECONDS);
- if (messagesInQ != null && false == messagesInQ.isEmpty()) {
- logger.debug("Cambria client returned {} non sent messages.", messagesInQ.size());
- response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
- writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION);
- } else {
- logger.debug("No message left in the queue after closing cambria publisher");
- response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
- }
- } catch (IOException | InterruptedException e) {
- logger.debug("Failed to close cambria publisher", e);
- response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
- writeErrorToLog(response, "closing publisher returned non sent messages", methodName, SEND_NOTIFICATION);
- }
- logger.debug("After closing publisher");
+ response = processError(e);
- return response;
+ }
- }
+ return response;
+ }
- public CambriaErrorResponse getApiKey(String server, String apiKey) {
+ public Either<ApiCredential, CambriaErrorResponse> createUebKeys(List<String> hostSet) {
+ Either<ApiCredential, CambriaErrorResponse> result;
- CambriaErrorResponse response = null;
+ try {
+ CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet));
- List<String> hostSet = new ArrayList<>();
- hostSet.add(server);
- CambriaIdentityManager createIdentityManager = null;
- try {
- createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet));
- createIdentityManager.getApiKey(apiKey);
- response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
+ String description = String.format("ASDC Key for %s", CONSUMER_ID);
+ ApiCredential credential = createIdentityManager.createApiKey("", description);
+ createIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret());
+ result = Either.left(credential);
- } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) {
- logger.debug("Failed to fetch api key {} from server ", apiKey, server, e);
+ } catch (Exception e) {
+ logger.debug("Failed to create ueb keys for servers {}",hostSet, e);
- response = processError(e);
+ result = Either.right(processError(e));
- }
+ }
- return response;
- }
+ return result;
+ }
- private static <T extends CambriaClient> T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<? extends CambriaClient> client) throws MalformedURLException, GeneralSecurityException {
- if (useHttpsWithDmaap) {
- client.usingHttps();
- }
- return (T)client.build();
- }
+ @VisibleForTesting
+ <T extends CambriaClient> T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<? extends CambriaClient> client) throws MalformedURLException, GeneralSecurityException {
+ return (T)client.build();
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java
new file mode 100644
index 0000000000..94fff3cfaa
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.aft.dme2.api.DME2Exception;
+import com.att.aft.dme2.api.DME2Manager;
+import com.att.aft.dme2.iterator.DME2EndpointIterator;
+import com.att.aft.dme2.iterator.factory.DME2EndpointIteratorFactory;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class DME2EndpointIteratorCreator {
+
+ public DME2EndpointIterator create(String lookupURI) throws DME2Exception {
+ // Initializing DME2Manager instance
+ DME2Manager manager = DME2Manager.getDefaultInstance();
+ // Returning an instance of the DME2EndpointIteratorFactory
+ return (DME2EndpointIterator) DME2EndpointIteratorFactory.getInstance().getIterator(lookupURI, null, null, manager);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java
deleted file mode 100644
index 5e4c08275f..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DeConfigurationStatus.java
+++ /dev/null
@@ -1,40 +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.components.distribution.engine;
-
-public enum DeConfigurationStatus {
-
- OK(""), MISSING_CONFIGURATION("");
-
- private String description;
-
- DeConfigurationStatus(String description) {
- this.description = description;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
index bd3d74e323..7d2d4680b5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
@@ -20,361 +20,340 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
@Component("distributionEngine")
public class DistributionEngine implements IDistributionEngine {
- public static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE);
-
- public static void main(String[] args) {
-
- List<String> servers = new ArrayList<>();
-
- servers.add("uebsb91kcdc.it.att.com:3904");
- servers.add("uebsb91kcdc.it.att.com:3904");
- servers.add("uebsb91kcdc.it.att.com:3904");
-
- YamlToObjectConverter converter = new YamlToObjectConverter();
- DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class);
-
- DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null);
- distributionEngineInitTask.startTask();
-
- }
-
- @javax.annotation.Resource
- private ComponentsUtils componentUtils;
-
- @javax.annotation.Resource
- private DistributionNotificationSender distributionNotificationSender;
-
- @javax.annotation.Resource
- private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
-
- @javax.annotation.Resource
- private DistributionEngineClusterHealth distributionEngineClusterHealth;
-
- private static Logger logger = LoggerFactory.getLogger(DistributionEngine.class.getName());
-
- private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<String, DistributionEngineInitTask>();
- private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<String, DistributionEnginePollingTask>();
-
- private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<String, AtomicBoolean>();
-
- @Override
- public boolean isActive() {
-
- if (true == envNamePerInitTask.isEmpty()) {
- return false;
- }
-
- for (DistributionEngineInitTask task : envNamePerInitTask.values()) {
- boolean active = task.isActive();
- if (active == false) {
- return false;
- }
- }
- return true;
- }
-
- @PostConstruct
- private void init() {
-
- logger.trace("Enter init method of DistributionEngine");
-
- DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
-
- boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine();
- logger.debug("Distribution engine activation parameter is {}", startDistributionEngine);
- if (false == startDistributionEngine) {
- logger.info("The disribution engine is disabled");
-
- this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled();
-
- return;
- }
-
- boolean isValidConfig = validateConfiguration(distributionEngineConfiguration);
-
- if (false == isValidConfig) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase");
- BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase");
-
- this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError();
- return;
- }
-
- List<String> environments = distributionEngineConfiguration.getEnvironments();
-
- for (String envName : environments) {
-
- DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask(distributionEngineConfiguration, envName, componentUtils, distributionEngineClusterHealth);
-
- logger.debug("Init task for environment {}", envName);
-
- AtomicBoolean status = new AtomicBoolean(false);
- envNamePerStatus.put(envName, status);
- DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l, distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask);
- distributionEngineInitTask.startTask();
- envNamePerInitTask.put(envName, distributionEngineInitTask);
- envNamePerPollingTask.put(envName, distributionEnginePollingTask);
- }
-
- logger.debug("Init UEB health check");
- distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus);
-
- logger.trace("Exit init method of DistributionEngine");
-
- }
-
- @PreDestroy
- public void shutdown() {
- logger.info("distribution engine shutdown - start");
- if (envNamePerInitTask != null) {
- for (DistributionEngineInitTask task : envNamePerInitTask.values()) {
- task.destroy();
- }
- }
- if (envNamePerPollingTask != null) {
- for (DistributionEnginePollingTask task : envNamePerPollingTask.values()) {
- task.destroy();
- }
- }
-
- }
-
- /**
- * validate mandatory configuration parameters received
- *
- * @param deConfiguration
- * @return
- */
- protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) {
-
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- boolean result = true;
- result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers") && result;
- result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result;
- result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result;
- result = isValidParam(deConfiguration.getUebSecretKey(), methodName, "uebSecretKey") && result;
- result = isValidParam(deConfiguration.getDistributionNotifTopicName(), methodName, "distributionNotifTopicName") && result;
- result = isValidParam(deConfiguration.getDistributionStatusTopicName(), methodName, "distributionStatusTopicName") && result;
- result = isValidObject(deConfiguration.getCreateTopic(), methodName, "createTopic") && result;
- result = isValidObject(deConfiguration.getDistributionStatusTopic(), methodName, "distributionStatusTopic") && result;
- result = isValidObject(deConfiguration.getInitMaxIntervalSec(), methodName, "initMaxIntervalSec") && result;
- result = isValidObject(deConfiguration.getInitRetryIntervalSec(), methodName, "initRetryIntervalSec") && result;
- result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerId(), methodName, "consumerId") && result;
- result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result;
- result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result;
- result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result;
-
- return result;
- }
-
- private boolean isValidServers(List<String> uebServers, String methodName, String paramName) {
-
- if (uebServers == null || uebServers.size() == 0) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName);
- BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
- return false;
- }
-
- if (uebServers.size() < 2) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeConfigurationInvalidListSizeError, methodName, paramName, "2");
- BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2);
- return false;
- }
-
- for (String serverFqdn : uebServers) {
- if (false == isValidFqdn(serverFqdn)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, methodName, paramName, serverFqdn);
- BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn);
- return false;
- }
- }
-
- return true;
- }
-
- private boolean isValidFqdn(String serverFqdn) {
-
- try {
- Matcher matcher = FQDN_PATTERN.matcher(serverFqdn);
- return matcher.matches();
-
- } catch (Exception e) {
- logger.debug("Failed to match value of address {}", serverFqdn, e);
- return false;
- }
-
- }
-
- private boolean isEmptyParam(String param) {
-
- if (param == null || true == param.isEmpty()) {
- return true;
- }
-
- return false;
- }
-
- private boolean isValidParam(String paramValue, String methodName, String paramName) {
-
- if (isEmptyParam(paramValue)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName);
- BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
- return false;
- }
- return true;
-
- }
-
- private boolean isValidParam(List<String> paramValue, String methodName, String paramName) {
-
- if (isEmptyList(paramValue)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName);
- BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
- return false;
- }
- return true;
-
- }
-
- private boolean isValidObject(Object paramValue, String methodName, String paramName) {
-
- if (paramValue == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingConfigurationError, methodName, paramName);
- BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
- return false;
- }
- return true;
-
- }
-
- private boolean isEmptyList(List<String> list) {
- if (list == null || true == list.isEmpty()) {
- return true;
- }
- return false;
- }
-
- private String getEnvironmentErrorDescription(StorageOperationStatus status) {
-
- switch (status) {
- case DISTR_ENVIRONMENT_NOT_AVAILABLE:
- return "environment is unavailable";
- case DISTR_ENVIRONMENT_NOT_FOUND:
- return "environment is not configured in our system";
- case DISTR_ENVIRONMENT_SENT_IS_INVALID:
- return "environment name is invalid";
-
- default:
- return "unkhown";
-
- }
- }
-
- public StorageOperationStatus isEnvironmentAvailable(String envName) {
-
- if (envName == null || true == envName.isEmpty()) {
-
- return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID;
- }
-
- AtomicBoolean status = envNamePerStatus.get(envName);
- if (status == null) {
- return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND;
- }
-
- if (false == status.get()) {
- return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE;
- }
- return StorageOperationStatus.OK;
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(DistributionEngine.class);
+ private static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE);
- public StorageOperationStatus isEnvironmentAvailable() {
+ @Autowired
+ private EnvironmentsEngine environmentsEngine;
- String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
+ @Resource
+ private DistributionNotificationSender distributionNotificationSender;
- return isEnvironmentAvailable(envName);
- }
+ @Resource
+ private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
- @Override
- public void disableEnvironment(String envName) {
- // TODO disable tasks
- AtomicBoolean status = envNamePerStatus.get(envName);
- status.set(false);
- }
+ @Resource
+ private DistributionEngineClusterHealth distributionEngineClusterHealth;
- @Override
- public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) {
+ @Resource
+ private ServiceDistributionValidation serviceDistributionValidation;
- logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName);
+ private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>();
+ private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>();
+ private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
- DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+ /**
+ * The main method for testing only
+ * @param args
+ */
+ public static void main(String[] args) {
- String distributionNotifTopicName = deConfiguration.getDistributionNotifTopicName();
- String topicName = DistributionEngineInitTask.buildTopicName(distributionNotifTopicName, envName);
+ List<String> servers = new ArrayList<>();
+ String server = "uebsb91kcdc.it.att.com:3904";
+ servers.add(server);
+ servers.add(server);
+ servers.add(server);
- StorageOperationStatus sendNotification = distributionNotificationSender.sendNotification(topicName, distributionId, deConfiguration, envName, notificationData, service, userId, modifierName);
+ YamlToObjectConverter converter = new YamlToObjectConverter();
+ DistributionEngineConfiguration distributionEngineConfiguration = converter.convert("src/test/resources/config/catalog-be/distribEngine1/distribution-engine-configuration.yaml", DistributionEngineConfiguration.class);
- logger.debug("Finish notifyService. status is {}", sendNotification);
+ DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(2l, distributionEngineConfiguration, "PROD", new AtomicBoolean(false), null, null, null);
+ distributionEngineInitTask.startTask();
+
+ }
- return sendNotification;
- }
+ @Override
+ public boolean isActive() {
- @Override
- public Either<INotificationData, StorageOperationStatus> isReadyForDistribution(Service service, String distributionId, String envName) {
- StorageOperationStatus status = isEnvironmentAvailable(envName);
- if (status != StorageOperationStatus.OK) {
- String envErrorDec = getEnvironmentErrorDescription(status);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING,
- "Environment name " + envName + " is not available. Reason : " + envErrorDec);
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec);
- return Either.right(status);
- }
+ if (envNamePerInitTask.isEmpty()) {
+ return false;
+ }
- Either<Boolean, StorageOperationStatus> isServiceContainsDeploymentArtifactsStatus = serviceDistributionArtifactsBuilder.isServiceContainsDeploymentArtifacts(service);
- if (isServiceContainsDeploymentArtifactsStatus.isRight()) {
- StorageOperationStatus operationStatus = isServiceContainsDeploymentArtifactsStatus.right().value();
- return Either.right(operationStatus);
- } else {
- Boolean isDeploymentArtifactExists = isServiceContainsDeploymentArtifactsStatus.left().value();
- if (isDeploymentArtifactExists == null || isDeploymentArtifactExists.booleanValue() == false) {
- return Either.right(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND);
- }
- }
+ for (DistributionEngineInitTask task : envNamePerInitTask.values()) {
+ boolean active = task.isActive();
+ if (!active) {
+ return false;
+ }
+ }
+ return true;
+ }
- INotificationData value = serviceDistributionArtifactsBuilder.buildResourceInstanceForDistribution(service, distributionId);
- value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service);
+ @PostConstruct
+ private void init() {
+
+ LOGGER.trace("Enter init method of DistributionEngine");
+
+ DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+
+ boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine();
+ LOGGER.debug("Distribution engine activation parameter is {}", startDistributionEngine);
+ if (!startDistributionEngine) {
+ LOGGER.info("The disribution engine is disabled");
- return Either.left(value);
- }
+ this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled();
+
+ return;
+ }
+
+ boolean isValidConfig = validateConfiguration(distributionEngineConfiguration);
+
+ if (!isValidConfig) {
+ BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase");
+
+ this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError();
+ return;
+ }
+
+ List<String> environments = distributionEngineConfiguration.getEnvironments();
+
+ for (String envName : environments) {
+ LOGGER.debug("init task for environment {}", envName);
+ AtomicBoolean status = new AtomicBoolean(false);
+ envNamePerStatus.put(envName, status);
+ environmentsEngine.connectUebTopicForDistributionConfTopic(envName, status, envNamePerInitTask, envNamePerPollingTask);
+ }
+
+ LOGGER.debug("init UEB health check");
+ distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus);
+
+ LOGGER.trace("Exit init method of DistributionEngine");
+
+ }
+
+ @PreDestroy
+ public void shutdown() {
+ LOGGER.info("distribution engine shutdown - start");
+ if (envNamePerInitTask != null) {
+ for (DistributionEngineInitTask task : envNamePerInitTask.values()) {
+ task.destroy();
+ }
+ }
+ if (envNamePerPollingTask != null) {
+ for (DistributionEnginePollingTask task : envNamePerPollingTask.values()) {
+ task.destroy();
+ }
+ }
+
+ }
+
+ /**
+ * validate mandatory configuration parameters received
+ *
+ * @param deConfiguration
+ * @return
+ */
+ protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) {
+
+ String methodName = "validateConfiguration";
+
+ boolean result = true;
+ result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers") && result;
+ result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result;
+ result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result;
+ result = isValidParam(deConfiguration.getUebSecretKey(), methodName, "uebSecretKey") && result;
+ result = isValidParam(deConfiguration.getDistributionNotifTopicName(), methodName, "distributionNotifTopicName") && result;
+ result = isValidParam(deConfiguration.getDistributionStatusTopicName(), methodName, "distributionStatusTopicName") && result;
+ result = isValidObject(deConfiguration.getCreateTopic(), methodName, "createTopic") && result;
+ result = isValidObject(deConfiguration.getDistributionStatusTopic(), methodName, "distributionStatusTopic") && result;
+ result = isValidObject(deConfiguration.getInitMaxIntervalSec(), methodName, "initMaxIntervalSec") && result;
+ result = isValidObject(deConfiguration.getInitRetryIntervalSec(), methodName, "initRetryIntervalSec") && result;
+ result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerId(), methodName, "consumerId") && result;
+ result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result;
+ result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result;
+ result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result;
+
+ return result;
+ }
+
+ private boolean isValidServers(List<String> uebServers, String methodName, String paramName) {
+
+ if (uebServers == null || uebServers.isEmpty()) {
+ BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
+ return false;
+ }
+
+ if (uebServers.size() < 2) {
+ BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2);
+ return false;
+ }
+
+ for (String serverFqdn : uebServers) {
+ if (!isValidFqdn(serverFqdn)) {
+ BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn);
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private boolean isValidFqdn(String serverFqdn) {
+
+ try {
+ Matcher matcher = FQDN_PATTERN.matcher(serverFqdn);
+ return matcher.matches();
+
+ } catch (Exception e) {
+ LOGGER.debug("Failed to match value of address {}", serverFqdn, e);
+ return false;
+ }
+ }
+
+ private boolean isValidParam(String paramValue, String methodName, String paramName) {
+
+ if (StringUtils.isEmpty(paramValue)) {
+ BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isValidParam(List<String> paramValue, String methodName, String paramName) {
+
+ if (CollectionUtils.isEmpty(paramValue)) {
+ BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isValidObject(Object paramValue, String methodName, String paramName) {
+
+ if (paramValue == null) {
+ BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
+ return false;
+ }
+ return true;
+
+ }
+
+ private String getEnvironmentErrorDescription(StorageOperationStatus status) {
+
+ switch (status) {
+ case DISTR_ENVIRONMENT_NOT_AVAILABLE:
+ return "environment is unavailable";
+ case DISTR_ENVIRONMENT_NOT_FOUND:
+ return "environment is not configured in our system";
+ case DISTR_ENVIRONMENT_SENT_IS_INVALID:
+ return "environment name is invalid";
+ default:
+ return "unkhown";
+ }
+ }
+
+ @Override
+ public StorageOperationStatus isEnvironmentAvailable(String envName) {
+
+ if (envName == null || envName.isEmpty()) {
+
+ return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID;
+ }
+
+ AtomicBoolean status = envNamePerStatus.get(envName);
+ if (status == null) {
+ return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND;
+ }
+
+ if (!status.get()) {
+ return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE;
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public StorageOperationStatus isEnvironmentAvailable() {
+
+ String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
+
+ return isEnvironmentAvailable(envName);
+ }
+
+ @Override
+ public void disableEnvironment(String envName) {
+ AtomicBoolean status = envNamePerStatus.get(envName);
+ status.set(false);
+ }
+
+ @Override
+ public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) {
+ return notifyService(distributionId, service, notificationData, envName, envName, userId, modifierName);
+ }
+
+ @Override
+ public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) {
+ LOGGER.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, userId, modifierName);
+ String topicName = buildTopicName(envName);
+ ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId))
+ .map(EnvironmentMessageBusData::new)
+ .map(messageBusData -> distributionNotificationSender.sendNotification(topicName, distributionId, messageBusData, notificationData, service, userId, modifierName))
+ .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE);
+ LOGGER.debug("Finish notifyService. status is {}", notifyServiceStatus);
+ return notifyServiceStatus;
+ }
+
+ private String buildTopicName(String envName) {
+ DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+ String distributionNotifTopicName = deConfiguration.getDistributionNotifTopicName();
+ return DistributionEngineInitTask.buildTopicName(distributionNotifTopicName, envName);
+ }
+
+ @Override
+ public StorageOperationStatus isReadyForDistribution(Service service, String envName) {
+ StorageOperationStatus status = isEnvironmentAvailable(envName);
+ if (status != StorageOperationStatus.OK) {
+ String envErrorDec = getEnvironmentErrorDescription(status);
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec);
+ return status;
+ }
+
+ return verifyServiceHasDeploymentArtifacts(service);
+ }
+
+ @Override
+ public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) {
+ if (!serviceDistributionArtifactsBuilder.verifyServiceContainsDeploymentArtifacts(service)) {
+ return StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND;
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ @Override
+ public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) {
+ return environmentsEngine.getEnvironmentById(opEnvId);
+ }
+
+ @Override
+ public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) {
+ INotificationData value = serviceDistributionArtifactsBuilder.buildResourceInstanceForDistribution(service, distributionId, workloadContext);
+ value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service);
+ return value;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
index 85a868f156..9599879006 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
@@ -20,22 +20,6 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
@@ -47,311 +31,318 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+
@Component("distribution-engine-cluster-health")
public class DistributionEngineClusterHealth {
- protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck";
+ protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck";
- private static Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT);
+ private static final Logger healthLogger = LoggerFactory.getLogger(UEB_HEALTH_LOG_CONTEXT);
- private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck";
+ private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck";
- boolean lastHealthState = false;
+ boolean lastHealthState = false;
- Object lockOject = new Object();
+ Object lockOject = new Object();
- private long reconnectInterval = 5;
+ private long reconnectInterval = 5;
- private long healthCheckReadTimeout = 20;
+ private long healthCheckReadTimeout = 20;
- private static Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class.getName());
+ private static final Logger logger = LoggerFactory.getLogger(DistributionEngineClusterHealth.class);
- private List<String> uebServers = null;
+ private List<String> uebServers = null;
- private String publicApiKey = null;
+ private String publicApiKey = null;
- public enum HealthCheckInfoResult {
+ public enum HealthCheckInfoResult {
- OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
- UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
- NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
- DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
+ OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
+ UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
+ NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
+ DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription()));
- private HealthCheckInfo healthCheckInfo;
+ private HealthCheckInfo healthCheckInfo;
- HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
- this.healthCheckInfo = healthCheckInfo;
- }
+ HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
+ this.healthCheckInfo = healthCheckInfo;
+ }
- public HealthCheckInfo getHealthCheckInfo() {
- return healthCheckInfo;
- }
+ public HealthCheckInfo getHealthCheckInfo() {
+ return healthCheckInfo;
+ }
- }
+ }
- private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
+ private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
- private Map<String, AtomicBoolean> envNamePerStatus = null;
+ private Map<String, AtomicBoolean> envNamePerStatus = null;
- private ScheduledFuture<?> scheduledFuture = null;
+ private ScheduledFuture<?> scheduledFuture = null;
- ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "UEB-Health-Check-Task");
- }
- });
+ ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "UEB-Health-Check-Task");
+ }
+ });
- HealthCheckScheduledTask healthCheckScheduledTask = null;
+ HealthCheckScheduledTask healthCheckScheduledTask = null;
- public enum ClusterStatusDescription {
+ public enum ClusterStatusDescription {
- OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration");
+ OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration");
- private String desc;
+ private String desc;
- ClusterStatusDescription(String desc) {
- this.desc = desc;
- }
+ ClusterStatusDescription(String desc) {
+ this.desc = desc;
+ }
- public String getDescription() {
- return desc;
- }
+ public String getDescription() {
+ return desc;
+ }
- }
+ }
- /**
- * Health Check Task Scheduler.
- *
- * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server.
- *
- *
- * @author esofer
- *
- */
- public class HealthCheckScheduledTask implements Runnable {
+ /**
+ * Health Check Task Scheduler.
+ *
+ * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server.
+ *
+ *
+ * @author esofer
+ *
+ */
+ public class HealthCheckScheduledTask implements Runnable {
- List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();
+ List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();
- public HealthCheckScheduledTask(List<String> uebServers) {
+ public HealthCheckScheduledTask(List<String> uebServers) {
- logger.debug("Create health check calls for servers {}", uebServers);
- if (uebServers != null) {
- for (String server : uebServers) {
- healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey));
- }
- }
- }
+ logger.debug("Create health check calls for servers {}", uebServers);
+ if (uebServers != null) {
+ for (String server : uebServers) {
+ healthCheckCalls.add(new UebHealthCheckCall(server, publicApiKey));
+ }
+ }
+ }
- @Override
- public void run() {
+ @Override
+ public void run() {
- healthLogger.trace("Executing UEB Health Check Task - Start");
+ healthLogger.trace("Executing UEB Health Check Task - Start");
- boolean healthStatus = verifyAtLeastOneEnvIsUp();
+ boolean healthStatus = verifyAtLeastOneEnvIsUp();
- if (true == healthStatus) {
- boolean queryUebStatus = queryUeb();
- if (queryUebStatus == lastHealthState) {
- return;
- }
+ if (true == healthStatus) {
+ boolean queryUebStatus = queryUeb();
+ if (queryUebStatus == lastHealthState) {
+ return;
+ }
- synchronized (lockOject) {
- if (queryUebStatus != lastHealthState) {
- logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
- lastHealthState = queryUebStatus;
- logAlarm(lastHealthState);
- if (true == queryUebStatus) {
- healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
- } else {
- healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
- }
- }
- }
- } else {
- healthLogger.trace("Not all UEB Environments are up");
- }
-
- }
-
- /**
- * verify that at least one environment is up.
- *
- */
- private boolean verifyAtLeastOneEnvIsUp() {
-
- boolean healthStatus = false;
+ synchronized (lockOject) {
+ if (queryUebStatus != lastHealthState) {
+ logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
+ lastHealthState = queryUebStatus;
+ logAlarm(lastHealthState);
+ if (true == queryUebStatus) {
+ healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
+ } else {
+ healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
+ }
+ }
+ }
+ } else {
+ healthLogger.trace("Not all UEB Environments are up");
+ }
+
+ }
+
+ /**
+ * verify that at least one environment is up.
+ *
+ */
+ private boolean verifyAtLeastOneEnvIsUp() {
+
+ boolean healthStatus = false;
- if (envNamePerStatus != null) {
- Collection<AtomicBoolean> values = envNamePerStatus.values();
- if (values != null) {
- for (AtomicBoolean status : values) {
- if (true == status.get()) {
- healthStatus = true;
- break;
- }
- }
- }
- }
-
- return healthStatus;
- }
-
- /**
- * executor for the query itself
- */
- ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "UEB-Health-Check-Thread");
- }
- });
-
- /**
- * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers.
- *
- *
- * @return
- */
- private boolean queryUeb() {
-
- Boolean result = false;
- int retryNumber = 1;
- for (UebHealthCheckCall healthCheckCall : healthCheckCalls) {
- try {
-
- healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer());
-
- Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall);
- result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS);
-
- healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result);
-
- if (result != null && true == result.booleanValue()) {
- break;
- }
-
- } catch (Exception e) {
- String message = e.getMessage();
- if (message == null) {
- message = e.getClass().getName();
- }
- healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message);
- healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e);
- }
- retryNumber++;
-
- }
-
- return result;
-
- }
-
- public List<UebHealthCheckCall> getHealthCheckCalls() {
- return healthCheckCalls;
- }
-
- }
-
- @PostConstruct
- private void init() {
-
- logger.trace("Enter init method of DistributionEngineClusterHealth");
-
- Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds();
- if (reconnectIntervalConfig != null) {
- reconnectInterval = reconnectIntervalConfig.longValue();
- }
- Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout();
- if (healthCheckReadTimeoutConfig != null) {
- healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue();
- }
-
- DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
-
- this.uebServers = distributionEngineConfiguration.getUebServers();
- this.publicApiKey = distributionEngineConfiguration.getUebPublicKey();
-
- this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers);
-
- logger.trace("Exit init method of DistributionEngineClusterHealth");
-
- }
-
- @PreDestroy
- private void destroy() {
-
- if (scheduledFuture != null) {
- scheduledFuture.cancel(true);
- scheduledFuture = null;
- }
-
- if (healthCheckScheduler != null) {
- healthCheckScheduler.shutdown();
- }
-
- }
-
- /**
- * Start health check task.
- *
- * @param envNamePerStatus
- * @param startTask
- */
- public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) {
- this.envNamePerStatus = envNamePerStatus;
-
- if (startTask == true && this.scheduledFuture == null) {
- this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
- }
- }
-
- public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) {
- startHealthCheckTask(envNamePerStatus, true);
- }
-
- private void logAlarm(boolean lastHealthState) {
- if (lastHealthState == true) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery, UEB_HEALTH_CHECK_STR);
- BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR);
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, UEB_HEALTH_CHECK_STR);
- BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR);
- }
- }
-
- public HealthCheckInfo getHealthCheckInfo() {
- return healthCheckInfo;
- }
-
- /**
- * change the health check to DISABLE
- */
- public void setHealthCheckUebIsDisabled() {
- healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo();
- }
-
- /**
- * change the health check to NOT CONFGIURED
- */
- public void setHealthCheckUebConfigurationError() {
- healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo();
- }
-
- public void setHealthCheckOkAndReportInCaseLastStateIsDown() {
-
- if (lastHealthState == true) {
- return;
- }
- synchronized (lockOject) {
- if (lastHealthState == false) {
- logger.debug("Going to update health check state to available");
- lastHealthState = true;
- healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
- logAlarm(lastHealthState);
- }
- }
-
- }
+ if (envNamePerStatus != null) {
+ Collection<AtomicBoolean> values = envNamePerStatus.values();
+ if (values != null) {
+ for (AtomicBoolean status : values) {
+ if (true == status.get()) {
+ healthStatus = true;
+ break;
+ }
+ }
+ }
+ }
+
+ return healthStatus;
+ }
+
+ /**
+ * executor for the query itself
+ */
+ ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "UEB-Health-Check-Thread");
+ }
+ });
+
+ /**
+ * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers.
+ *
+ *
+ * @return
+ */
+ private boolean queryUeb() {
+
+ Boolean result = false;
+ int retryNumber = 1;
+ for (UebHealthCheckCall healthCheckCall : healthCheckCalls) {
+ try {
+
+ healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer());
+
+ Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall);
+ result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS);
+
+ healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result);
+
+ if (result != null && true == result.booleanValue()) {
+ break;
+ }
+
+ } catch (Exception e) {
+ String message = e.getMessage();
+ if (message == null) {
+ message = e.getClass().getName();
+ }
+ healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message);
+ healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e);
+ }
+ retryNumber++;
+
+ }
+
+ return result;
+
+ }
+
+ public List<UebHealthCheckCall> getHealthCheckCalls() {
+ return healthCheckCalls;
+ }
+
+ }
+
+ @PostConstruct
+ protected void init() {
+
+ logger.trace("Enter init method of DistributionEngineClusterHealth");
+
+ Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds();
+ if (reconnectIntervalConfig != null) {
+ reconnectInterval = reconnectIntervalConfig.longValue();
+ }
+ Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout();
+ if (healthCheckReadTimeoutConfig != null) {
+ healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue();
+ }
+
+ DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+
+ this.uebServers = distributionEngineConfiguration.getUebServers();
+ this.publicApiKey = distributionEngineConfiguration.getUebPublicKey();
+
+ this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers);
+
+ logger.trace("Exit init method of DistributionEngineClusterHealth");
+
+ }
+
+ @PreDestroy
+ protected void destroy() {
+
+ if (scheduledFuture != null) {
+ scheduledFuture.cancel(true);
+ scheduledFuture = null;
+ }
+
+ if (healthCheckScheduler != null) {
+ healthCheckScheduler.shutdown();
+ }
+
+ }
+
+ /**
+ * Start health check task.
+ *
+ * @param envNamePerStatus
+ * @param startTask
+ */
+ public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) {
+ this.envNamePerStatus = envNamePerStatus;
+
+ if (startTask == true && this.scheduledFuture == null) {
+ this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
+ }
+ }
+
+ public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) {
+ startHealthCheckTask(envNamePerStatus, true);
+ }
+
+ private void logAlarm(boolean lastHealthState) {
+ if (lastHealthState == true) {
+ BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR);
+ } else {
+ BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR);
+ }
+ }
+
+ public HealthCheckInfo getHealthCheckInfo() {
+ return healthCheckInfo;
+ }
+
+ /**
+ * change the health check to DISABLE
+ */
+ public void setHealthCheckUebIsDisabled() {
+ healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo();
+ }
+
+ /**
+ * change the health check to NOT CONFGIURED
+ */
+ public void setHealthCheckUebConfigurationError() {
+ healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo();
+ }
+
+ public void setHealthCheckOkAndReportInCaseLastStateIsDown() {
+
+ if (lastHealthState == true) {
+ return;
+ }
+ synchronized (lockOject) {
+ if (lastHealthState == false) {
+ logger.debug("Going to update health check state to available");
+ lastHealthState = true;
+ healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
+ logAlarm(lastHealthState);
+ }
+ }
+
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java
index 1eeaa1229e..1759f69b3e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java
@@ -20,274 +20,268 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
public class DistributionEngineInitTask implements Runnable {
- public static final String INIT_DISTRIBUTION_ENGINE_FLOW = "initDistributionEngine";
- public static final String ALREADY_EXISTS = "ALREADY_EXISTS";
- public static final String CONSUMER = "CONSUMER";
- public static final String PRODUCER = "PRODUCER";
- public static final String CREATED = "CREATED";
- public static final String FAILED = "FAILED";
- public static final Integer HTTP_OK = 200;
-
- private Long delayBeforeStartFlow = 0l;
- private DistributionEngineConfiguration deConfiguration;
- private String envName;
- private long retryInterval;
- private long currentRetryInterval;
- private long maxInterval;
- // private boolean active = false;
- boolean maximumRetryInterval = false;
- private AtomicBoolean status = null;
- ComponentsUtils componentsUtils = null;
- DistributionEnginePollingTask distributionEnginePollingTask = null;
-
- private CambriaHandler cambriaHandler = new CambriaHandler();
-
- public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask) {
- super();
- this.delayBeforeStartFlow = delayBeforeStartFlow;
- this.deConfiguration = deConfiguration;
- this.envName = envName;
- this.retryInterval = deConfiguration.getInitRetryIntervalSec();
- this.currentRetryInterval = retryInterval;
- this.maxInterval = deConfiguration.getInitMaxIntervalSec();
- this.status = status;
- this.componentsUtils = componentsUtils;
- this.distributionEnginePollingTask = distributionEnginePollingTask;
- }
-
- private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
-
- private static Logger logger = LoggerFactory.getLogger(DistributionEngineInitTask.class.getName());
-
- ScheduledFuture<?> scheduledFuture = null;
-
- public void startTask() {
- if (scheduledExecutorService != null) {
- Integer retryInterval = deConfiguration.getInitRetryIntervalSec();
- logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow);
- this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS);
-
- }
- }
-
- public void restartTask() {
-
- this.stopTask();
-
- logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval);
-
- long lastCurrentInterval = currentRetryInterval;
- incrementRetryInterval();
-
- this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS);
-
- }
-
- protected void incrementRetryInterval() {
- if (currentRetryInterval < maxInterval) {
- currentRetryInterval *= 2;
- if (currentRetryInterval > maxInterval) {
- setMaxRetryInterval();
- }
- } else {
- setMaxRetryInterval();
- }
- }
-
- private void setMaxRetryInterval() {
- currentRetryInterval = maxInterval;
- maximumRetryInterval = true;
- logger.debug("Set next retry init interval to {}", maxInterval);
- }
-
- public void stopTask() {
- if (scheduledFuture != null) {
- boolean result = scheduledFuture.cancel(true);
- logger.debug("Stop reinit task. result = {}", result);
- if (false == result) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task");
- BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task");
- }
- scheduledFuture = null;
- }
- }
-
- public void destroy() {
- this.stopTask();
- if (scheduledExecutorService != null) {
- scheduledExecutorService.shutdown();
- }
- }
-
- @Override
- public void run() {
-
- boolean result = false;
- result = initFlow();
-
- if (true == result) {
- this.stopTask();
- this.status.set(true);
- if (this.distributionEnginePollingTask != null) {
- String topicName = buildTopicName(deConfiguration.getDistributionStatusTopicName(), envName);
- logger.debug("start polling distribution status topic {}", topicName);
- this.distributionEnginePollingTask.startTask(topicName);
- }
- } else {
- if (false == maximumRetryInterval) {
- this.restartTask();
- }
- }
- }
-
- /**
- * run initialization flow
- *
- * @return
- */
- public boolean initFlow() {
-
- logger.trace("Start init flow for environment {}", this.envName);
-
- Set<String> topicsList = null;
- Either<Set<String>, CambriaErrorResponse> getTopicsRes = null;
-
- getTopicsRes = cambriaHandler.getTopics(deConfiguration.getUebServers());
- if (getTopicsRes.isRight()) {
- CambriaErrorResponse status = getTopicsRes.right().value();
- if (status.getOperationStatus() == CambriaOperationStatus.NOT_FOUND) {
- topicsList = new HashSet<>();
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server");
-
- BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server");
-
- return false;
- }
- } else {
- topicsList = getTopicsRes.left().value();
- }
-
- String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName);
- logger.debug("Going to handle topic {}", notificationTopic);
-
- boolean status = createTopicIfNotExists(topicsList, notificationTopic);
- if (false == status) {
- return false;
- }
-
- CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER);
-
- CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus();
-
- if (createStatus != CambriaOperationStatus.OK) {
- return false;
- }
-
- String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName);
- logger.debug("Going to handle topic {}", statusTopic);
- status = createTopicIfNotExists(topicsList, statusTopic);
- if (false == status) {
- return false;
- }
-
- CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER);
-
- if (registerConcumerStatus.getOperationStatus() != CambriaOperationStatus.OK) {
- return false;
- }
-
- return true;
- }
-
- private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) {
- CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(deConfiguration.getUebServers(), topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebPublicKey(), subscriberType);
-
- String role = CONSUMER;
- if (subscriberType == SubscriberTypeEnum.PRODUCER) {
- role = PRODUCER;
- }
- auditRegistration(topicName, registerStatus, role);
- return registerStatus;
- }
-
- private void auditRegistration(String notificationTopic, CambriaErrorResponse registerProducerStatus, String role) {
- if (componentsUtils != null) {
- Integer httpCode = registerProducerStatus.getHttpCode();
- String httpCodeStr = String.valueOf(httpCode);
- this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, notificationTopic, role, deConfiguration.getUebPublicKey(), httpCodeStr);
- }
- }
-
- private boolean createTopicIfNotExists(Set<String> topicsList, String topicName) {
-
- if (topicsList.contains(topicName)) {
- if (componentsUtils != null) {
- this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS);
- }
- return true;
- }
-
- CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(deConfiguration.getUebServers(), deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(),
- deConfiguration.getCreateTopic().getReplicationCount());
-
- CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus();
- if (status == CambriaOperationStatus.TOPIC_ALREADY_EXIST) {
- if (componentsUtils != null) {
- this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS);
- }
- } else if (status == CambriaOperationStatus.OK) {
- if (componentsUtils != null) {
- this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, CREATED);
- }
- } else {
- if (componentsUtils != null) {
- this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, FAILED);
- }
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName);
-
- BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName);
-
- return false;
- }
-
- return true;
- }
-
- public static String buildTopicName(String topicName, String environment) {
- return topicName + "-" + environment.toUpperCase();
- }
-
- public boolean isActive() {
- return this.status.get();
- }
-
- public long getCurrentRetryInterval() {
- return currentRetryInterval;
- }
-
- protected void setCambriaHandler(CambriaHandler cambriaHandler) {
- this.cambriaHandler = cambriaHandler;
- }
+ public static final String INIT_DISTRIBUTION_ENGINE_FLOW = "initDistributionEngine";
+ public static final String ALREADY_EXISTS = "ALREADY_EXISTS";
+ public static final String CONSUMER = "CONSUMER";
+ public static final String PRODUCER = "PRODUCER";
+ public static final String CREATED = "CREATED";
+ public static final String FAILED = "FAILED";
+ public static final Integer HTTP_OK = 200;
+
+ private Long delayBeforeStartFlow = 0l;
+ private DistributionEngineConfiguration deConfiguration;
+ private String envName;
+ private long retryInterval;
+ private long currentRetryInterval;
+ private long maxInterval;
+ boolean maximumRetryInterval = false;
+ private AtomicBoolean status = null;
+ ComponentsUtils componentsUtils = null;
+ DistributionEnginePollingTask distributionEnginePollingTask = null;
+ private OperationalEnvironmentEntry environmentEntry;
+
+ private CambriaHandler cambriaHandler = new CambriaHandler();
+
+ public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) {
+ super();
+ this.delayBeforeStartFlow = delayBeforeStartFlow;
+ this.deConfiguration = deConfiguration;
+ this.envName = envName;
+ this.retryInterval = deConfiguration.getInitRetryIntervalSec();
+ this.currentRetryInterval = retryInterval;
+ this.maxInterval = deConfiguration.getInitMaxIntervalSec();
+ this.status = status;
+ this.componentsUtils = componentsUtils;
+ this.distributionEnginePollingTask = distributionEnginePollingTask;
+ this.environmentEntry = environmentEntry;
+ }
+
+ private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
+
+ private static final Logger logger = LoggerFactory.getLogger(DistributionEngineInitTask.class);
+
+ ScheduledFuture<?> scheduledFuture = null;
+
+ public void startTask() {
+ if (scheduledExecutorService != null) {
+ Integer retryInterval = deConfiguration.getInitRetryIntervalSec();
+ logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow);
+ this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS);
+
+ }
+ }
+
+ public void restartTask() {
+
+ this.stopTask();
+
+ logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval);
+
+ long lastCurrentInterval = currentRetryInterval;
+ incrementRetryInterval();
+
+ this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS);
+
+ }
+
+ protected void incrementRetryInterval() {
+ if (currentRetryInterval < maxInterval) {
+ currentRetryInterval *= 2;
+ if (currentRetryInterval > maxInterval) {
+ setMaxRetryInterval();
+ }
+ } else {
+ setMaxRetryInterval();
+ }
+ }
+
+ private void setMaxRetryInterval() {
+ currentRetryInterval = maxInterval;
+ maximumRetryInterval = true;
+ logger.debug("Set next retry init interval to {}", maxInterval);
+ }
+
+ public void stopTask() {
+ if (scheduledFuture != null) {
+ boolean result = scheduledFuture.cancel(true);
+ logger.debug("Stop reinit task. result = {}", result);
+ if (false == result) {
+ BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to stop the reinit task");
+ }
+ scheduledFuture = null;
+ }
+ }
+
+ public void destroy() {
+ this.stopTask();
+ if (scheduledExecutorService != null) {
+ scheduledExecutorService.shutdown();
+ }
+ }
+
+ @Override
+ public void run() {
+
+ boolean result = false;
+ result = initFlow();
+
+ if (true == result) {
+ this.stopTask();
+ this.status.set(true);
+ if (this.distributionEnginePollingTask != null) {
+ String topicName = buildTopicName(deConfiguration.getDistributionStatusTopicName(), envName);
+ logger.debug("start polling distribution status topic {}", topicName);
+ this.distributionEnginePollingTask.startTask(topicName);
+ }
+ } else {
+ if (false == maximumRetryInterval) {
+ this.restartTask();
+ }
+ }
+ }
+
+ /**
+ * run initialization flow
+ *
+ * @return
+ */
+ public boolean initFlow() {
+
+ logger.trace("Start init flow for environment {}", this.envName);
+
+ Set<String> topicsList = null;
+ Either<Set<String>, CambriaErrorResponse> getTopicsRes = null;
+
+ getTopicsRes = cambriaHandler.getTopics(environmentEntry.getDmaapUebAddress().stream().collect(Collectors.toList()));
+ if (getTopicsRes.isRight()) {
+ CambriaErrorResponse status = getTopicsRes.right().value();
+ if (status.getOperationStatus() == CambriaOperationStatus.NOT_FOUND) {
+ topicsList = new HashSet<>();
+ } else {
+ BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try retrieve list of topics from U-EB server");
+ return false;
+ }
+ } else {
+ topicsList = getTopicsRes.left().value();
+ }
+
+ String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName);
+ logger.debug("Going to handle topic {}", notificationTopic);
+
+ boolean status = createTopicIfNotExists(topicsList, notificationTopic);
+ if (false == status) {
+ return false;
+ }
+
+ CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER);
+
+ CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus();
+
+ if (createStatus != CambriaOperationStatus.OK) {
+ return false;
+ }
+
+ String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName);
+ logger.debug("Going to handle topic {}", statusTopic);
+ status = createTopicIfNotExists(topicsList, statusTopic);
+ if (false == status) {
+ return false;
+ }
+
+ CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER);
+
+ if (registerConcumerStatus.getOperationStatus() != CambriaOperationStatus.OK) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) {
+ CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), environmentEntry.getUebApikey(), subscriberType, topicName);
+
+ String role = CONSUMER;
+ if (subscriberType == SubscriberTypeEnum.PRODUCER) {
+ role = PRODUCER;
+ }
+ auditRegistration(topicName, registerStatus, role);
+ return registerStatus;
+ }
+
+ private void auditRegistration(String notificationTopic, CambriaErrorResponse registerProducerStatus, String role) {
+ if (componentsUtils != null) {
+ Integer httpCode = registerProducerStatus.getHttpCode();
+ String httpCodeStr = String.valueOf(httpCode);
+ this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName, notificationTopic, role, environmentEntry.getUebApikey(), httpCodeStr);
+ }
+ }
+
+ private boolean createTopicIfNotExists(Set<String> topicsList, String topicName) {
+
+ if (topicsList.contains(topicName)) {
+ if (componentsUtils != null) {
+ this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS);
+ }
+ return true;
+ }
+
+ CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(),
+ deConfiguration.getCreateTopic().getReplicationCount());
+
+ CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus();
+ if (status == CambriaOperationStatus.TOPIC_ALREADY_EXIST) {
+ if (componentsUtils != null) {
+ this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, ALREADY_EXISTS);
+ }
+ } else if (status == CambriaOperationStatus.OK) {
+ if (componentsUtils != null) {
+ this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, CREATED);
+ }
+ } else {
+ if (componentsUtils != null) {
+ this.componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, topicName, null, null, FAILED);
+ }
+ BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName);
+ return false;
+ }
+
+ return true;
+ }
+
+ public static String buildTopicName(String topicName, String environment) {
+ return topicName + "-" + environment.toUpperCase();
+ }
+
+ public boolean isActive() {
+ return this.status.get();
+ }
+
+ public long getCurrentRetryInterval() {
+ return currentRetryInterval;
+ }
+
+ protected void setCambriaHandler(CambriaHandler cambriaHandler) {
+ this.cambriaHandler = cambriaHandler;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java
index fc7c473d6b..b4f4863284 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java
@@ -20,188 +20,189 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
+import com.att.nsa.cambria.client.CambriaConsumer;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
+import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionStatusTopicConfig;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.att.nsa.cambria.client.CambriaConsumer;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
public class DistributionEnginePollingTask implements Runnable {
- public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling";
-
- private String topicName;
- private ComponentsUtils componentUtils;
- private int fetchTimeoutInSec = 15;
- private int pollingIntervalInSec;
- private String consumerId;
- private String consumerGroup;
- private DistributionEngineConfiguration distributionEngineConfiguration;
-
- private CambriaHandler cambriaHandler = new CambriaHandler();
- private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build());
-
- private static Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class.getName());
-
- ScheduledFuture<?> scheduledFuture = null;
- private CambriaConsumer cambriaConsumer = null;
-
- private DistributionEngineClusterHealth distributionEngineClusterHealth = null;
-
- public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, String envName, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth) {
-
- this.componentUtils = componentUtils;
- this.distributionEngineConfiguration = distributionEngineConfiguration;
- DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic();
- this.pollingIntervalInSec = statusConfig.getPollingIntervalSec();
- this.fetchTimeoutInSec = statusConfig.getFetchTimeSec();
- this.consumerGroup = statusConfig.getConsumerGroup();
- this.consumerId = statusConfig.getConsumerId();
- this.distributionEngineClusterHealth = distributionEngineClusterHealth;
- }
-
- public void startTask(String topicName) {
-
- this.topicName = topicName;
- logger.debug("start task for polling topic {}", topicName);
- if (fetchTimeoutInSec < 15) {
- logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default");
- fetchTimeoutInSec = 15;
- }
- try {
- cambriaConsumer = cambriaHandler.createConsumer(distributionEngineConfiguration.getUebServers(), topicName, distributionEngineConfiguration.getUebPublicKey(), distributionEngineConfiguration.getUebSecretKey(), consumerId, consumerGroup,
- fetchTimeoutInSec * 1000);
-
- if (scheduledPollingService != null) {
- logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec);
- scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS);
-
- }
- } catch (Exception e) {
- logger.debug("unexpected error occured", e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
- }
- }
-
- public void stopTask() {
- if (scheduledFuture != null) {
- boolean result = scheduledFuture.cancel(true);
- logger.debug("Stop polling task. result = {}", result);
- if (false == result) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "try to stop the polling task");
- BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task");
- }
- scheduledFuture = null;
- }
- if (cambriaConsumer != null) {
- logger.debug("close consumer");
- cambriaHandler.closeConsumer(cambriaConsumer);
- }
-
- }
-
- public void destroy() {
- this.stopTask();
- shutdownExecutor();
- }
-
- @Override
- public void run() {
- logger.trace("run() method. polling queue {}", topicName);
-
- try {
- // init error
- if (cambriaConsumer == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly");
- BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly");
- stopTask();
- return;
- }
-
- Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer);
- // fetch error
- if (fetchResult.isRight()) {
- CambriaErrorResponse errorResponse = fetchResult.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value());
- BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + fetchResult.right().value());
-
- // TODO: if status== internal error (connection problem) change
- // state to inactive
- // in next try, if succeed - change to active
- return;
- }
-
- // success
- Iterable<String> messages = fetchResult.left().value();
- for (String message : messages) {
- logger.trace("received message {}", message);
- try {
- DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class);
- componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(),
- String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason());
-
- distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown();
-
- } catch (Exception e) {
- logger.debug("failed to convert message to object", e);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUebSystemError, DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
- BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
- }
-
- }
- } catch (Exception e) {
- logger.debug("unexpected error occured", e);
- String methodName = new Object() {
- }.getClass().getEnclosingMethod().getName();
-
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, methodName, e.getMessage());
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
- }
-
- }
-
- private void shutdownExecutor() {
- if (scheduledPollingService == null)
- return;
-
- scheduledPollingService.shutdown(); // Disable new tasks from being
- // submitted
- try {
- // Wait a while for existing tasks to terminate
- if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
- scheduledPollingService.shutdownNow(); // Cancel currently
- // executing tasks
- // Wait a while for tasks to respond to being cancelled
- if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
- logger.debug("Pool did not terminate");
- }
- } catch (InterruptedException ie) {
- // (Re-)Cancel if current thread also interrupted
- scheduledPollingService.shutdownNow();
- // Preserve interrupt status
- Thread.currentThread().interrupt();
- }
- }
+ public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling";
+
+ private String topicName;
+ private ComponentsUtils componentUtils;
+ private int fetchTimeoutInSec = 15;
+ private int pollingIntervalInSec;
+ private String consumerId;
+ private String consumerGroup;
+
+ private CambriaHandler cambriaHandler = new CambriaHandler();
+ private Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ private DistributionCompleteReporter distributionCompleteReporter;
+
+ private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build());
+
+ private static final Logger logger = LoggerFactory.getLogger(DistributionEnginePollingTask.class);
+
+ ScheduledFuture<?> scheduledFuture = null;
+ private CambriaConsumer cambriaConsumer = null;
+
+ private DistributionEngineClusterHealth distributionEngineClusterHealth = null;
+
+ private OperationalEnvironmentEntry environmentEntry;
+
+ public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, OperationalEnvironmentEntry environmentEntry) {
+
+ this.componentUtils = componentUtils;
+ DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic();
+ this.pollingIntervalInSec = statusConfig.getPollingIntervalSec();
+ this.fetchTimeoutInSec = statusConfig.getFetchTimeSec();
+ this.consumerGroup = statusConfig.getConsumerGroup();
+ this.consumerId = statusConfig.getConsumerId();
+ this.distributionEngineClusterHealth = distributionEngineClusterHealth;
+ this.environmentEntry = environmentEntry;
+ this.distributionCompleteReporter = distributionCompleteReporter;
+ }
+
+ public void startTask(String topicName) {
+
+ this.topicName = topicName;
+ logger.debug("start task for polling topic {}", topicName);
+ if (fetchTimeoutInSec < 15) {
+ logger.warn("fetchTimeout value should be greater or equal to 15 sec. use default");
+ fetchTimeoutInSec = 15;
+ }
+ try {
+ cambriaConsumer = cambriaHandler.createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), consumerId, consumerGroup,
+ fetchTimeoutInSec * 1000);
+
+ if (scheduledPollingService != null) {
+ logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec);
+ scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS);
+
+ }
+ } catch (Exception e) {
+ logger.debug("unexpected error occured", e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
+ }
+ }
+
+ public void stopTask() {
+ if (scheduledFuture != null) {
+ boolean result = scheduledFuture.cancel(true);
+ logger.debug("Stop polling task. result = {}", result);
+ if (false == result) {
+ BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "try to stop the polling task");
+ }
+ scheduledFuture = null;
+ }
+ if (cambriaConsumer != null) {
+ logger.debug("close consumer");
+ cambriaHandler.closeConsumer(cambriaConsumer);
+ }
+
+ }
+
+ public void destroy() {
+ this.stopTask();
+ shutdownExecutor();
+ }
+
+ @Override
+ public void run() {
+ logger.trace("run() method. polling queue {}", topicName);
+
+ try {
+ // init error
+ if (cambriaConsumer == null) {
+ BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "polling task was not initialized properly");
+ stopTask();
+ return;
+ }
+
+ Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer);
+ // fetch error
+ if (fetchResult.isRight()) {
+ CambriaErrorResponse errorResponse = fetchResult.right().value();
+ BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + errorResponse);
+
+ // TODO: if status== internal error (connection problem) change
+ // state to inactive
+ // in next try, if succeed - change to active
+ return;
+ }
+
+ // success
+ Iterable<String> messages = fetchResult.left().value();
+ for (String message : messages) {
+ logger.trace("received message {}", message);
+ try {
+ DistributionStatusNotification notification = gson.fromJson(message, DistributionStatusNotification.class);
+ handleDistributionNotificationMsg(notification);
+ distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown();
+ } catch (Exception e) {
+ logger.debug("failed to convert message to object", e);
+ BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
+ }
+
+ }
+ } catch (Exception e) {
+ logger.debug("unexpected error occured", e);
+ String methodName = new Object() {
+ }.getClass().getEnclosingMethod().getName();
+
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
+ }
+
+ }
+
+ private void handleDistributionNotificationMsg(DistributionStatusNotification notification) {
+ componentUtils.auditDistributionStatusNotification(AuditingActionEnum.DISTRIBUTION_STATUS, notification.getDistributionID(), notification.getConsumerID(), topicName, notification.getArtifactURL(),
+ String.valueOf(notification.getTimestamp()), notification.getStatus().name(), notification.getErrorReason());
+ if (notification.isDistributionCompleteNotification()) {
+ distributionCompleteReporter.reportDistributionComplete(notification);
+ }
+ }
+
+ private void shutdownExecutor() {
+ if (scheduledPollingService == null)
+ return;
+
+ scheduledPollingService.shutdown(); // Disable new tasks from being
+ // submitted
+ try {
+ // Wait a while for existing tasks to terminate
+ if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
+ scheduledPollingService.shutdownNow(); // Cancel currently
+ // executing tasks
+ // Wait a while for tasks to respond to being cancelled
+ if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
+ logger.debug("Pool did not terminate");
+ }
+ } catch (InterruptedException ie) {
+ // (Re-)Cancel if current thread also interrupted
+ scheduledPollingService.shutdownNow();
+ // Preserve interrupt status
+ Thread.currentThread().interrupt();
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
index 16a0a1dc31..62af4b8514 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
@@ -20,20 +20,13 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionException;
-
-import javax.annotation.PreDestroy;
-
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@@ -41,79 +34,83 @@ import org.springframework.stereotype.Component;
@Component("distributionNotificationSender")
public class DistributionNotificationSender {
- protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending";
-
- private static Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class.getName());
-
- // final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
- // final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL
- // + "resources/%s/%s/artifacts/%s";
- // final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
-
- @javax.annotation.Resource
- InterfaceLifecycleOperation interfaceLifecycleOperation;
-
- @javax.annotation.Resource
- protected ComponentsUtils componentUtils;
-
- ExecutorService executorService = null;
-
- CambriaHandler cambriaHandler = new CambriaHandler();
-
- NotificationExecutorService notificationExecutorService = new NotificationExecutorService();
-
- public DistributionNotificationSender() {
- super();
-
- DistributionNotificationTopicConfig distributionNotificationTopic = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionNotificationTopic();
-
- executorService = notificationExecutorService.createExcecutorService(distributionNotificationTopic);
- }
-
- @PreDestroy
- public void shutdown() {
- logger.debug("Going to close notificationExecutorService");
- if (executorService != null) {
-
- long maxWaitingTime = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds();
-
- notificationExecutorService.shutdownAndAwaitTermination(executorService, maxWaitingTime + 1);
- }
- }
-
- public StorageOperationStatus sendNotification(String topicName, String distributionId, DistributionEngineConfiguration deConfiguration, String envName, INotificationData notificationData, Service service, String userId, String modifierName) {
-
- Runnable task = new PublishNotificationRunnable(envName, distributionId, service, notificationData, deConfiguration, topicName, userId, modifierName, cambriaHandler, componentUtils, ThreadLocalsHolder.getUuid());
- try {
- executorService.submit(task);
- } catch (RejectedExecutionException e) {
- logger.warn("Failed to submit task. Number of threads exceeeds", e);
- return StorageOperationStatus.OVERLOAD;
- }
-
- return StorageOperationStatus.OK;
- }
-
- /**
- * Audit the publishing notification in case of internal server error.
- *
- * @param topicName
- * @param status
- * @param distributionId
- * @param envName
- */
- private void auditDistributionNotificationInternalServerError(String topicName, StorageOperationStatus status, String distributionId, String envName) {
-
- if (this.componentUtils != null) {
- this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, "", " ", "Service", " ", " ", " ", envName, " ", topicName, distributionId, "Error: Internal Server Error. " + status, " ");
- }
- }
-
- protected CambriaErrorResponse publishNotification(INotificationData data, DistributionEngineConfiguration deConfiguration, String topicName) {
-
- CambriaErrorResponse status = cambriaHandler.sendNotification(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data);
+ protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending";
+
+ private static final Logger logger = LoggerFactory.getLogger(DistributionNotificationSender.class);
+
+ @javax.annotation.Resource
+ protected ComponentsUtils componentUtils;
+ private CambriaHandler cambriaHandler = new CambriaHandler();
+ private DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+
+ public ActionStatus sendNotification(String topicName, String distributionId, EnvironmentMessageBusData messageBusData, INotificationData notificationData, Service service, String userId, String modifierName) {
+ long startTime = System.currentTimeMillis();
+ CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, messageBusData.getUebPublicKey(), messageBusData.getUebPrivateKey(), messageBusData.getDmaaPuebEndpoints(), notificationData,
+ deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds());
+ logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode());
+ auditDistributionNotification(topicName, distributionId, status, service, messageBusData.getEnvId(), userId, modifierName, notificationData.getWorkloadContext(), messageBusData.getTenant());
+ long endTime = System.currentTimeMillis();
+ logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime));
+ return convertCambriaResponse(status);
+ }
+
+ private void auditDistributionNotification(String topicName, String distributionId, CambriaErrorResponse status, Service service, String envId, String userId, String modifierName, String workloadContext, String tenant) {
+ if (this.componentUtils != null) {
+ Integer httpCode = status.getHttpCode();
+ String httpCodeStr = String.valueOf(httpCode);
+
+ String desc = getDescriptionFromErrorResponse(status);
+
+ this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, service.getUUID(), service.getName(), "Service", service.getVersion(), userId, modifierName, envId, service.getLifecycleState().name(), topicName,
+ distributionId, desc, httpCodeStr, workloadContext, tenant);
+ }
+ }
+
+ private String getDescriptionFromErrorResponse(CambriaErrorResponse status) {
+
+ CambriaOperationStatus operationStatus = status.getOperationStatus();
+
+ switch (operationStatus) {
+ case OK:
+ return "OK";
+ case AUTHENTICATION_ERROR:
+ return "Error: Authentication problem towards U-EB server";
+ case INTERNAL_SERVER_ERROR:
+ return "Error: Internal U-EB server error";
+ case UNKNOWN_HOST_ERROR:
+ return "Error: Cannot reach U-EB server host";
+ case CONNNECTION_ERROR:
+ return "Error: Cannot connect to U-EB server";
+ case OBJECT_NOT_FOUND:
+ return "Error: object not found in U-EB server";
+ default:
+ return "Error: Internal Cambria server problem";
+
+ }
+
+ }
+
+ private ActionStatus convertCambriaResponse(CambriaErrorResponse status) {
+ CambriaOperationStatus operationStatus = status.getOperationStatus();
+
+ switch (operationStatus) {
+ case OK:
+ return ActionStatus.OK;
+ case AUTHENTICATION_ERROR:
+ return ActionStatus.AUTHENTICATION_ERROR;
+ case INTERNAL_SERVER_ERROR:
+ return ActionStatus.GENERAL_ERROR;
+ case UNKNOWN_HOST_ERROR:
+ return ActionStatus.UNKNOWN_HOST;
+ case CONNNECTION_ERROR:
+ return ActionStatus.CONNNECTION_ERROR;
+ case OBJECT_NOT_FOUND:
+ return ActionStatus.OBJECT_NOT_FOUND;
+ default:
+ return ActionStatus.GENERAL_ERROR;
+
+ }
+ }
- return status;
- }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java
index 73a0336361..006aa26082 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java
@@ -22,63 +22,67 @@ package org.openecomp.sdc.be.components.distribution.engine;
public class DistributionStatusNotification {
- String distributionID;
- String consumerID;
- long timestamp;
- String artifactURL;
- DistributionStatusNotificationEnum status;
- String errorReason;
-
- public String getDistributionID() {
- return distributionID;
- }
-
- public void setDistributionID(String distributionId) {
- this.distributionID = distributionId;
- }
-
- public String getConsumerID() {
- return consumerID;
- }
-
- public void setConsumerID(String consumerId) {
- this.consumerID = consumerId;
- }
-
- public long getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- }
-
- public String getArtifactURL() {
- return artifactURL;
- }
-
- public void setArtifactURL(String artifactURL) {
- this.artifactURL = artifactURL;
- }
-
- public DistributionStatusNotificationEnum getStatus() {
- return status;
- }
-
- public void setStatus(DistributionStatusNotificationEnum status) {
- this.status = status;
- }
-
- public String getErrorReason() {
- return errorReason;
- }
-
- public void setErrorReason(String errorReason) {
- this.errorReason = errorReason;
- }
-
- @Override
- public String toString() {
- return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]";
- }
+ String distributionID;
+ String consumerID;
+ long timestamp;
+ String artifactURL;
+ DistributionStatusNotificationEnum status;
+ String errorReason;
+
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ public void setDistributionID(String distributionId) {
+ this.distributionID = distributionId;
+ }
+
+ public String getConsumerID() {
+ return consumerID;
+ }
+
+ public void setConsumerID(String consumerId) {
+ this.consumerID = consumerId;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getArtifactURL() {
+ return artifactURL;
+ }
+
+ public void setArtifactURL(String artifactURL) {
+ this.artifactURL = artifactURL;
+ }
+
+ public DistributionStatusNotificationEnum getStatus() {
+ return status;
+ }
+
+ public void setStatus(DistributionStatusNotificationEnum status) {
+ this.status = status;
+ }
+
+ public String getErrorReason() {
+ return errorReason;
+ }
+
+ public void setErrorReason(String errorReason) {
+ this.errorReason = errorReason;
+ }
+
+ public boolean isDistributionCompleteNotification() {
+ return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK.equals(status) || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR.equals(status);
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]";
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java
index bd77f3915a..65aa18ee97 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java
@@ -22,5 +22,5 @@ package org.openecomp.sdc.be.components.distribution.engine;
public enum DistributionStatusNotificationEnum {
- DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED
+ DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED, COMPONENT_DONE_ERROR, COMPONENT_DONE_OK, DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java
new file mode 100644
index 0000000000..3d35a84d7a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java
@@ -0,0 +1,91 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.nsa.mr.client.MRClientFactory;
+import com.att.nsa.mr.client.MRConsumer;
+import fj.data.Either;
+import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
+import org.openecomp.sdc.security.SecurityUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.io.File;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.Properties;
+
+/**
+ * Allows to create DMAAP client of type MRConsumer according received configuration parameters
+ */
+@Component("dmaapClientFactory")
+public class DmaapClientFactory {
+ private static final Logger logger = LoggerFactory.getLogger(DmaapClientFactory.class);
+
+ /**
+ * Creates DMAAP consumer according to received parameters
+ * @param parameters
+ * @return an instance object of type MRConsumer
+ * @throws IOException
+ */
+ public MRConsumer create(DmaapConsumerConfiguration parameters) throws Exception {
+ MRConsumer consumer = MRClientFactory.createConsumer(buildProperties(parameters));
+ logger.info("MRConsumer created for topic {}", parameters.getTopic());
+ return consumer;
+ }
+
+ private Properties buildProperties(DmaapConsumerConfiguration parameters) throws Exception{
+ Properties props = new Properties();
+ Either<String,String> passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() );
+ if (passkey.isRight()){
+ throw new GeneralSecurityException("invalid password, cannot build properties");
+ }
+ props.setProperty("Latitude", Double.toString(parameters.getLatitude()));
+ props.setProperty("Longitude", Double.toString(parameters.getLongitude()));
+ props.setProperty("Version", parameters.getVersion());
+ props.setProperty("ServiceName", parameters.getServiceName());
+ props.setProperty("Environment", parameters.getEnvironment());
+ props.setProperty("Partner", parameters.getPartner());
+ props.setProperty("routeOffer", parameters.getRouteOffer());
+ props.setProperty("Protocol", parameters.getProtocol());
+ props.setProperty("username", parameters.getCredential().getUsername());
+ props.setProperty("password", passkey.left().value() );
+ props.setProperty("contenttype", parameters.getContenttype());
+ props.setProperty("host", parameters.getHosts());
+ props.setProperty("topic", parameters.getTopic());
+ props.setProperty("group", parameters.getConsumerGroup());
+ props.setProperty("id", parameters.getConsumerId());
+ props.setProperty("timeout", Integer.toString(parameters.getTimeoutMs()));
+ props.setProperty("limit", Integer.toString(parameters.getLimit()));
+ props.setProperty("AFT_DME2_REQ_TRACE_ON", Boolean.toString(parameters.isDme2TraceOn()));
+ props.setProperty("AFT_ENVIRONMENT", parameters.getAftEnvironment());
+ props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", Integer.toString(parameters.getAftDme2ConnectionTimeoutMs()));
+ props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", Integer.toString(parameters.getAftDme2RoundtripTimeoutMs()));
+ props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", Integer.toString(parameters.getAftDme2ReadTimeoutMs()));
+
+ String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath();
+ ensureFileExists(dme2PreferredRouterFilePath);
+ props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath);
+
+ props.setProperty("TransportType", "DME2");
+ props.setProperty("SubContextPath", "/");
+ props.setProperty("MethodType", "GET");
+ props.setProperty("authKey", "");
+ props.setProperty("authDate", "");
+ props.setProperty("filter", "");
+ props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", "");
+ props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "");
+ props.setProperty("sessionstickinessrequired", "no");
+
+ return props;
+ }
+
+ private void ensureFileExists(String filePath) throws IOException {
+ File file = new File(filePath);
+ if(file.createNewFile()) {
+ logger.info("The file {} has been created on the disk", file.getAbsolutePath());
+ }
+ else{
+ logger.info("The file {} already exists", file.getAbsolutePath());
+ }
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java
new file mode 100644
index 0000000000..e0661f4b22
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java
@@ -0,0 +1,76 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.nsa.mr.client.MRConsumer;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+/**
+ * Allows consuming DMAAP topic according to received consumer parameters
+ * Allows processing received messages.
+ */
+@Service
+public class DmaapConsumer {
+ private final ExecutorFactory executorFactory;
+ private final DmaapClientFactory dmaapClientFactory;
+ private static final Logger logger = LoggerFactory.getLogger(DmaapClientFactory.class);
+
+ @Autowired
+ private DmaapHealth dmaapHealth;
+ /**
+ * Allows to create an object of type DmaapConsumer
+ * @param executorFactory
+ * @param dmaapClientFactory
+ */
+ @Autowired
+ public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory) {
+ this.executorFactory = executorFactory;
+ this.dmaapClientFactory = dmaapClientFactory;
+ }
+
+ /**
+ * Allows consuming DMAAP topic according to received consumer parameters
+ * @param notificationReceived
+ * @param exceptionHandler
+ * @throws Exception
+ */
+ public void consumeDmaapTopic(Consumer<String> notificationReceived, UncaughtExceptionHandler exceptionHandler) throws Exception {
+
+ DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration();
+ String topic = dmaapConsumerParams.getTopic();
+ logger.info("Starting to consume topic {} for DMAAP consumer with the next parameters {}. ", topic, dmaapConsumerParams);
+ MRConsumer consumer = dmaapClientFactory.create(dmaapConsumerParams);
+ ScheduledExecutorService pollExecutor = executorFactory.createScheduled(topic + "Client");
+ ExecutorService notificationExecutor = executorFactory.create(topic + "Consumer", exceptionHandler);
+
+ pollExecutor.scheduleWithFixedDelay(() -> {
+ logger.info("Trying to fetch messages from topic: {}", topic);
+ boolean isTopicAvailable = false;
+ try {
+ Iterable<String> messages = consumer.fetch();
+ isTopicAvailable = true ;
+ if (messages != null) {
+ for (String msg : messages) {
+ logger.info("The DMAAP message {} received. The topic is {}.", msg, topic);
+ notificationExecutor.execute(() -> notificationReceived.accept(msg));
+ }
+ }
+ //successfully fetched
+ }
+ catch (Exception e) {
+ logger.error("The exception {} occured upon fetching DMAAP message", e);
+ }
+ dmaapHealth.report( isTopicAvailable );
+ }, 0L, dmaapConsumerParams.getPollingInterval(), TimeUnit.SECONDS);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java
new file mode 100644
index 0000000000..ba5e9f7c9c
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java
@@ -0,0 +1,220 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import org.apache.commons.validator.routines.UrlValidator;
+import org.apache.http.client.utils.URIUtils;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.commons.lang3.StringUtils.*;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE;
+
+@Component("dmaapHealth")
+public class DmaapHealth {
+
+
+ protected static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaap.healthcheck";
+ private static final String DMAAP_HEALTH_CHECK_STR = "dmaapHealthCheck";
+ private static final Logger log = LoggerFactory.getLogger(DmaapHealth.class);
+ private static final Logger logHealth = LoggerFactory.getLogger(DMAAP_HEALTH_LOG_CONTEXT);
+ private HealthCheckInfo healthCheckInfo = DmaapHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
+ private long healthCheckReadTimeout = 20;
+ private long reconnectInterval = 5;
+ private HealthCheckScheduledTask healthCheckScheduledTask = null ;
+ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
+ private ScheduledFuture<?> scheduledFuture = null;
+ private DmaapConsumerConfiguration configuration = null ;
+
+ private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false);
+ private volatile AtomicBoolean reportedHealthState = null;
+
+ public enum HealthCheckInfoResult {
+ OK(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())),
+ UNAVAILABLE(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())),
+ DOWN(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription()));
+
+ private HealthCheckInfo healthCheckInfo;
+ HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
+ this.healthCheckInfo = healthCheckInfo;
+ }
+ public HealthCheckInfo getHealthCheckInfo() {
+ return healthCheckInfo;
+ }
+ }
+
+ public enum DmaapStatusDescription {
+ OK("OK"), UNAVAILABLE("Dmaap is not available"),DOWN("DOWN"), NOT_CONFIGURED("Dmaap configuration is missing/wrong ");
+
+ private String desc;
+ DmaapStatusDescription(String desc) {
+ this.desc = desc;
+ }
+ public String getDescription() {
+ return desc;
+ }
+
+ }
+
+ @PostConstruct
+ public DmaapHealth init() {
+ log.trace("Enter init method of Dmaap health");
+ synchronized (DmaapHealth.class){
+ this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration();
+
+ Integer pollingInterval = configuration.getPollingInterval();
+ if (pollingInterval != null && pollingInterval!=0) {
+ reconnectInterval = pollingInterval;
+ }
+ Integer healthCheckReadTimeoutConfig = configuration.getTimeoutMs();
+ if (healthCheckReadTimeoutConfig != null) {
+ this.healthCheckReadTimeout = healthCheckReadTimeoutConfig;
+ }
+ this.healthCheckScheduledTask = new HealthCheckScheduledTask( configuration ); //what is the representation? csv? delimiter? json or other
+ startHealthCheckTask(true);
+ }
+ log.trace("Exit init method of DistributionEngineClusterHealth");
+ return this;
+ }
+
+ @PreDestroy
+ protected void destroy() {
+ if (scheduledFuture != null) {
+ scheduledFuture.cancel(true);
+ scheduledFuture = null;
+ }
+ if (scheduler != null) {
+ scheduler.shutdown();
+ }
+ }
+
+ /**
+ * Start health check task.
+ *
+ * @param startTask
+ */
+ public void startHealthCheckTask( boolean startTask ) {
+ synchronized (DmaapHealth.class){
+ if (startTask && this.scheduledFuture == null) {
+ this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS);
+ }
+ }
+ }
+
+ public void report(Boolean isUp){
+ if (reportedHealthState == null)
+ reportedHealthState = new AtomicBoolean(isUp);
+ reportedHealthState.set(isUp);
+ }
+
+ public void logAlarm(boolean lastHealthState) {
+ try{
+ if ( lastHealthState ) {
+ BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR );
+ } else {
+ BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR );
+ }
+ }catch( Exception e ){
+ log.debug("cannot logAlarm -> {}" ,e );
+ }
+ }
+
+ public DmaapConsumerConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ public HealthCheckInfo getHealthCheckInfo() {
+ return healthCheckInfo;
+ }
+
+ /**
+ * Health Check Task Scheduler - infinite check.
+ */
+ public class HealthCheckScheduledTask implements Runnable {
+ private final DmaapConsumerConfiguration config;
+ private static final int timeout = 8192;
+
+ public HealthCheckScheduledTask(final DmaapConsumerConfiguration config){
+ this.config = config;
+ }
+ @Override
+ public void run() {
+ logHealth.trace("Executing Dmaap Health Check Task - Start");
+ boolean prevIsReachable = false;
+ boolean reachable = false;
+ //first try simple ping
+ try{
+ if ( reportedHealthState != null ){
+ reachable = reportedHealthState.get();
+ }
+ else{
+ reachable = false;
+ }
+ prevIsReachable = lastHealthState.getAndSet( reachable );
+ healthCheckInfo = reachable ? HealthCheckInfoResult.OK.healthCheckInfo : HealthCheckInfoResult.DOWN.healthCheckInfo;
+ }
+ catch( Exception e ){
+ log.debug("{} | cannot check connectivity -> {}",DMAAP_HEALTH_CHECK_STR, e );
+ prevIsReachable = lastHealthState.getAndSet(false);
+ healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.healthCheckInfo;
+ }
+ if (prevIsReachable != lastHealthState.get())
+ logAlarm( lastHealthState.get() );
+ }
+
+
+ /**
+ * @deprecated (health is reported outside from EnvironmentEngine consumer fetch)
+ */
+ @Deprecated
+ public boolean isICMPReachable( ) throws IOException{
+ try{
+ String hostname = getUrlHost(config.getHosts());
+ return InetAddress.getByName( hostname ).isReachable(timeout);
+ }catch( URISyntaxException e ){
+ log.debug("{} | malformed host configuration -> ",DMAAP_HEALTH_CHECK_STR , e);
+ }
+ return false;
+ }
+ }
+
+ public static String getUrlHost(String qualifiedHost) throws URISyntaxException{
+ //region - parse complex format ex. <http://URL:PORT>
+ try{
+ UrlValidator validator = new UrlValidator();
+ if (validator.isValid(qualifiedHost)){
+ return URIUtils.extractHost(new URI(qualifiedHost)).getHostName();
+ }else{
+ log.debug("{} | invalid url format, continuing ", DMAAP_HEALTH_CHECK_STR );
+ }
+ }catch(URISyntaxException e){
+ log.debug("{} | invalid url format, continuing {} ", DMAAP_HEALTH_CHECK_STR , e);
+ }
+ //endregion
+
+ //region - try shortcut format <URL> or <URL:PORT>
+ if ( countMatches( qualifiedHost , ":") <= 1){
+ String[] address = qualifiedHost.split(":");
+ if ( address.length>0 && isNotBlank(address[0]) ){
+ return address[0];
+ }
+ }
+ //endregion
+ throw new URISyntaxException( qualifiedHost , "invalid hostname, expecting a single <host:port> , (valid ex. www.google.com:80 | www.google.com | http:\\\\www.google.com:8181)");
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java
new file mode 100644
index 0000000000..3f86fe73de
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.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.be.components.distribution.engine;
+
+/* Example {
+ "operationalEnvironmentId": "28122015552391",
+ "operationalEnvironmentName": "Operational Environment Name",
+ "operationalEnvironmentType": "ECOMP",
+ "tenantContext": "TEST",
+ "workloadContext": "ECOMP_E2E-IST",
+ "action": "Create"
+ }*/
+public class DmaapNotificationDataImpl implements IDmaapNotificationData, IDmaapAuditNotificationData {
+
+ private String operationalEnvironmentId;
+ private String operationalEnvironmentType;
+ private String action;
+ private String operationalEnvironmentName;
+ private String tenantContext;
+
+ @Override
+ public String getOperationalEnvironmentId() {
+ return operationalEnvironmentId;
+ }
+
+ @Override
+ public OperationaEnvironmentTypeEnum getOperationalEnvironmentType() {
+ return OperationaEnvironmentTypeEnum.findByName(operationalEnvironmentType);
+ }
+
+ @Override
+ public DmaapActionEnum getAction() {
+ return DmaapActionEnum.findByName(action);
+ }
+
+ @Override
+ public String getOperationalEnvironmentName() {
+ return operationalEnvironmentName;
+ }
+
+ @Override
+ public String getTenantContext() {
+ return tenantContext;
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java
new file mode 100644
index 0000000000..67977b6361
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java
@@ -0,0 +1,75 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * a pojo which holds all the necessary data to communicate with the message bus
+ * this class is a reflection ot the {@link OperationalEnvironmentEntry} class
+ */
+public class EnvironmentMessageBusData {
+
+ private List<String> dmaaPuebEndpoints;
+
+ private String uebPublicKey;
+
+ private String uebPrivateKey;
+
+ private String envId;
+
+ private String tenant;
+
+ public EnvironmentMessageBusData() {
+ }
+
+ public EnvironmentMessageBusData(OperationalEnvironmentEntry operationalEnvironment) {
+ this.dmaaPuebEndpoints = new ArrayList<>(operationalEnvironment.getDmaapUebAddress());
+ this.uebPublicKey = operationalEnvironment.getUebApikey();
+ this.uebPrivateKey = operationalEnvironment.getUebSecretKey();
+ this.envId = operationalEnvironment.getEnvironmentId();
+ this.tenant = operationalEnvironment.getTenant();
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public void setTenant(String tenant) {
+ this.tenant = tenant;
+ }
+
+ public List<String> getDmaaPuebEndpoints() {
+ return dmaaPuebEndpoints;
+ }
+
+ public void setDmaaPuebEndpoints(List<String> dmaaPuebEndpoints) {
+ this.dmaaPuebEndpoints = dmaaPuebEndpoints;
+ }
+
+ public String getUebPublicKey() {
+ return uebPublicKey;
+ }
+
+ public void setUebPublicKey(String uebPublicKey) {
+ this.uebPublicKey = uebPublicKey;
+ }
+
+ public String getUebPrivateKey() {
+ return uebPrivateKey;
+ }
+
+ public void setUebPrivateKey(String uebPrivateKey) {
+ this.uebPrivateKey = uebPrivateKey;
+ }
+
+ public String getEnvId() {
+ return envId;
+ }
+
+ public void setEnvId(String envId) {
+ this.envId = envId;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java
new file mode 100644
index 0000000000..822464c631
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java
@@ -0,0 +1,526 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.aft.dme2.api.DME2Exception;
+import com.att.aft.dme2.iterator.DME2EndpointIterator;
+import com.att.aft.dme2.iterator.domain.DME2EndpointReference;
+import com.att.aft.dme2.manager.registry.DME2Endpoint;
+import com.att.nsa.apiClient.credentials.ApiCredential;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpStatus;
+import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.DmaapActionEnum;
+import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.OperationaEnvironmentTypeEnum;
+import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
+import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
+import org.openecomp.sdc.be.config.DmeConfiguration;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.info.OperationalEnvInfo;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static org.apache.commons.lang3.StringUtils.isEmpty;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut;
+
+/**
+ * Allows to consume DMAAP topic and handle received notifications
+ */
+@Service
+public class EnvironmentsEngine implements INotificationHandler {
+
+ private static final String MESSAGE_BUS = "MessageBus";
+ private static final String UNKNOWN = "Unknown";
+ private static final Logger log = LoggerFactory.getLogger(EnvironmentsEngine.class);
+ private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
+
+ private Map<String, OperationalEnvironmentEntry> environments;
+ private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
+ private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>();
+ private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>();
+
+ private final DmaapConsumer dmaapConsumer;
+ private final OperationalEnvironmentDao operationalEnvironmentDao;
+ private final DME2EndpointIteratorCreator epIterCreator;
+ private final AaiRequestHandler aaiRequestHandler;
+ private final ComponentsUtils componentUtils;
+ private final CambriaHandler cambriaHandler;
+ private final DistributionEngineClusterHealth distributionEngineClusterHealth;
+ private final DistributionCompleteReporter distributionCompleteReporter;
+
+ public EnvironmentsEngine(DmaapConsumer dmaapConsumer, OperationalEnvironmentDao operationalEnvironmentDao, DME2EndpointIteratorCreator epIterCreator, AaiRequestHandler aaiRequestHandler, ComponentsUtils componentUtils, CambriaHandler cambriaHandler, DistributionEngineClusterHealth distributionEngineClusterHealth, DistributionCompleteReporter distributionCompleteReporter) {
+ this.dmaapConsumer = dmaapConsumer;
+ this.operationalEnvironmentDao = operationalEnvironmentDao;
+ this.epIterCreator = epIterCreator;
+ this.aaiRequestHandler = aaiRequestHandler;
+ this.componentUtils = componentUtils;
+ this.cambriaHandler = cambriaHandler;
+ this.distributionEngineClusterHealth = distributionEngineClusterHealth;
+ this.distributionCompleteReporter = distributionCompleteReporter;
+ }
+
+ @VisibleForTesting
+ @PostConstruct
+ void init() {
+ log.trace("Environments engine has been initialized. ");
+ try {
+ environments = populateEnvironments();
+ createUebTopicsForEnvironments();
+ dmaapConsumer.consumeDmaapTopic(this::handleMessage,
+ (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e));
+ }
+ catch (Exception e) {
+ log.error("An error occurred upon consuming topic by Dmaap consumer client." , e);
+ }
+ }
+ public void connectUebTopicTenantIsolation(OperationalEnvironmentEntry opEnvEntry,
+ AtomicBoolean status,
+ Map<String, DistributionEngineInitTask> envNamePerInitTask, Map<String, DistributionEnginePollingTask> envNamePerPollingTask){
+ connectUebTopic(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask);
+
+ }
+
+ public void connectUebTopicForDistributionConfTopic(String envName,
+ AtomicBoolean status,
+ Map<String, DistributionEngineInitTask> envNamePerInitTask, Map<String, DistributionEnginePollingTask> envNamePerPollingTask){
+ connectUebTopic(environments.get(envName), status, envNamePerInitTask, envNamePerPollingTask);
+
+ }
+ /**
+ * Allows to create and run UEB initializing and polling tasks
+ * @param status
+ * @param envNamePerInitTask
+ * @param envNamePerPollingTask
+ * @param opEnvEntry
+ */
+ private void connectUebTopic(OperationalEnvironmentEntry opEnvEntry, AtomicBoolean status,
+ Map<String, DistributionEngineInitTask> envNamePerInitTask,
+ Map<String, DistributionEnginePollingTask> envNamePerPollingTask) {
+
+ String envId = opEnvEntry.getEnvironmentId();
+
+ DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+ DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask(
+ distributionEngineConfiguration, distributionCompleteReporter, componentUtils, distributionEngineClusterHealth,
+ opEnvEntry);
+ String envName = configurationManager.getDistributionEngineConfiguration().getEnvironments().get(0);
+ DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l,
+ distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask,
+ opEnvEntry);
+ distributionEngineInitTask.startTask();
+ envNamePerInitTask.put(envId, distributionEngineInitTask);
+ envNamePerPollingTask.put(envId, distributionEnginePollingTask);
+
+ log.debug("Environment envId = {} has been connected to the UEB topic", envId);
+ }
+
+ @Override
+ public boolean handleMessage(String notification) {
+ DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager()
+ .getConfiguration().getDmaapConsumerConfiguration();
+ Supplier<Boolean> supplier = () -> handleMessageLogic(notification);
+ Either<Boolean, Boolean> eitherTimeOut = runMethodWithTimeOut(supplier,
+ dmaapConsumerParams.getTimeLimitForNotificationHandleMs());
+
+ boolean result;
+ if (eitherTimeOut.isRight()) {
+ result = false;
+ } else {
+ result = eitherTimeOut.left().value();
+ }
+ return result;
+ }
+
+ public boolean handleMessageLogic(String notification) {
+ Wrapper<Boolean> errorWrapper = new Wrapper<>();
+ Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper = new Wrapper<>();
+ try {
+
+ log.debug("handle message - for operational environment notification received: {}", notification);
+ Gson gsonObj = new GsonBuilder().create();
+
+ IDmaapNotificationData notificationData = gsonObj.fromJson(notification,
+ DmaapNotificationDataImpl.class);
+ IDmaapAuditNotificationData auditNotificationData = gsonObj.fromJson(notification,
+ DmaapNotificationDataImpl.class);
+
+ AuditingActionEnum actionEnum;
+ switch(notificationData.getAction()) {
+ case CREATE:
+ actionEnum = AuditingActionEnum.CREATE_ENVIRONMENT;
+ break;
+ case UPDATE:
+ actionEnum = AuditingActionEnum.UPDATE_ENVIRONMENT;
+ break;
+ case DELETE:
+ actionEnum = AuditingActionEnum.DELETE_ENVIRONMENT;
+ break;
+ default:
+ actionEnum = AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION;
+ break;
+ }
+ componentUtils.auditEnvironmentEngine(actionEnum,
+ notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(),
+ notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(),
+ auditNotificationData.getTenantContext());
+
+ if (errorWrapper.isEmpty()) {
+ validateNotification(errorWrapper, notificationData, auditNotificationData);
+ }
+ // Perform Save In-Progress Dao
+ if (errorWrapper.isEmpty()) {
+ saveEntryWithInProgressStatus(errorWrapper, opEnvEntryWrapper, notificationData);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ buildOpEnv(errorWrapper, opEnvEntryWrapper.getInnerElement());
+ }
+
+ } catch (Exception e) {
+ log.debug("handle message for operational environmet failed for notification: {} with error :{}",
+ notification, e.getMessage(), e);
+ errorWrapper.setInnerElement(false);
+
+ }
+ return errorWrapper.isEmpty();
+ }
+
+ private void validateNotification(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData,
+ IDmaapAuditNotificationData auditNotificationData) {
+ // Check OperationaEnvironmentType
+ if (errorWrapper.isEmpty()) {
+ validateEnvironmentType(errorWrapper, notificationData, auditNotificationData);
+ }
+ // Check Action Type
+ if (errorWrapper.isEmpty()) {
+ validateActionType(errorWrapper, notificationData);
+ }
+ // Check is valid for create/update (not In-Progress state)
+ if (errorWrapper.isEmpty()) {
+ validateState(errorWrapper, notificationData);
+ }
+ }
+
+ public void buildOpEnv(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
+ // Get Env Info From A&AI
+ if (errorWrapper.isEmpty()) {
+ retrieveOpEnvInfoFromAAI(errorWrapper, opEnvEntry);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ // Get List Of UEB Addresses From AFT_DME
+ retrieveUebAddressesFromAftDme(errorWrapper, opEnvEntry);
+ }
+
+ // Create UEB keys and set them on EnvEntry
+ if (errorWrapper.isEmpty()) {
+ createUebKeys(errorWrapper, opEnvEntry);
+ }
+
+ // Create Topics
+ if (errorWrapper.isEmpty()) {
+ log.debug("handle message - Create Topics");
+ createUebTopicsForEnvironment(opEnvEntry);
+ }
+
+ // Save Status Complete and Add to Map
+ if (errorWrapper.isEmpty()) {
+ saveEntryWithCompleteStatus(errorWrapper, opEnvEntry);
+ }
+
+ // Update Environments Map
+ if (errorWrapper.isEmpty()) {
+ environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry);
+ }
+ else{
+ saveEntryWithFailedStatus(errorWrapper, opEnvEntry);
+ }
+ }
+
+ private void saveEntryWithFailedStatus(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
+ log.debug("handle message - save OperationalEnvironment Failed Status");
+ opEnvEntry.setStatus(EnvironmentStatusEnum.FAILED);
+ saveOpEnvEntry(errorWrapper, opEnvEntry);
+ }
+
+ void saveEntryWithCompleteStatus(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
+ log.debug("handle message - save OperationalEnvironment Complete Dao");
+ opEnvEntry.setStatus(EnvironmentStatusEnum.COMPLETED);
+ saveOpEnvEntry(errorWrapper, opEnvEntry);
+
+ }
+
+ void retrieveUebAddressesFromAftDme(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
+ log.debug("handle message - Get List Of UEB Addresses From AFT_DME");
+ try {
+ boolean isKeyFieldsValid = !isEmpty(opEnvEntry.getTenant()) && !isEmpty(opEnvEntry.getEcompWorkloadContext());
+ if( isKeyFieldsValid ){
+ String opEnvKey = map2OpEnvKey(opEnvEntry);
+ String environmentId = opEnvEntry.getEnvironmentId();
+ List<String> uebHosts = discoverUebHosts(opEnvKey, environmentId);
+ opEnvEntry.setDmaapUebAddress(uebHosts.stream().collect(Collectors.toSet()));
+ }
+ else{
+ errorWrapper.setInnerElement(false);
+ log.debug("Can Not Build AFT DME Key from workLoad & Tenant Fields.");
+ }
+
+ } catch (DME2Exception e) {
+ errorWrapper.setInnerElement(false);
+ log.error("Failed to retrieve Ueb Addresses From DME. ", e);
+ }
+ }
+
+ void createUebKeys(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
+ log.debug("handle message - Create UEB keys");
+ List<String> discoverEndPoints = opEnvEntry.getDmaapUebAddress().stream()
+ .collect(Collectors.toList());
+ Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = cambriaHandler
+ .createUebKeys(discoverEndPoints);
+ if (eitherCreateUebKeys.isRight()) {
+ errorWrapper.setInnerElement(false);
+ log.debug("handle message - failed to create UEB Keys");
+ } else {
+ ApiCredential apiCredential = eitherCreateUebKeys.left().value();
+ opEnvEntry.setUebApikey(apiCredential.getApiKey());
+ opEnvEntry.setUebSecretKey(apiCredential.getApiSecret());
+ }
+ }
+
+ void retrieveOpEnvInfoFromAAI(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
+ log.debug("handle message - Get Env Info From A&AI");
+ Either<OperationalEnvInfo, Integer> eitherOperationalEnvInfo = getOperationalEnvById(
+ opEnvEntry.getEnvironmentId());
+ if (eitherOperationalEnvInfo.isRight()) {
+ errorWrapper.setInnerElement(false);
+ log.debug("handle message - failed to retrieve details from A&AI");
+ } else {
+ OperationalEnvInfo operationalEnvInfo = eitherOperationalEnvInfo.left().value();
+ opEnvEntry.setEcompWorkloadContext(operationalEnvInfo.getWorkloadContext());
+ opEnvEntry.setTenant(operationalEnvInfo.getTenantContext());
+ }
+ }
+
+ void saveEntryWithInProgressStatus(Wrapper<Boolean> errorWrapper, Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper, IDmaapNotificationData notificationData) {
+ log.debug("handle message - save OperationalEnvironment In-Progress Dao");
+ OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry();
+ // Entry Environment ID holds actually the environment NAME
+ opEnvEntry.setEnvironmentId(notificationData.getOperationalEnvironmentId());
+ opEnvEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS);
+ opEnvEntry.setIsProduction(false);
+ saveOpEnvEntry(errorWrapper, opEnvEntry);
+ opEnvEntryWrapper.setInnerElement(opEnvEntry);
+
+ }
+
+
+ void validateState(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData) {
+ log.debug("handle message - verify OperationalEnvironment not In-Progress");
+ String opEnvId = notificationData.getOperationalEnvironmentId();
+
+ Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherOpEnv = operationalEnvironmentDao
+ .get(opEnvId);
+ if (eitherOpEnv.isLeft()) {
+ final OperationalEnvironmentEntry opEnvEntry = eitherOpEnv.left().value();
+ if (StringUtils.equals(opEnvEntry.getStatus(), EnvironmentStatusEnum.IN_PROGRESS.getName())) {
+ errorWrapper.setInnerElement(false);
+ log.debug("handle message - validate State Failed Record Found With Status : {} Flow Stopped!", opEnvEntry.getStatus());
+ }
+ } else {
+ CassandraOperationStatus operationStatus = eitherOpEnv.right().value();
+ if (operationStatus != CassandraOperationStatus.NOT_FOUND) {
+ errorWrapper.setInnerElement(false);
+ log.debug("failed to retrieve operationa environment with id:{} cassandra error was :{}", opEnvId,
+ operationStatus);
+ }
+ }
+
+ }
+
+ void validateActionType(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData) {
+ log.debug("handle message - verify Action Type");
+ DmaapActionEnum action = notificationData.getAction();
+ if (action == DmaapActionEnum.DELETE) {
+ errorWrapper.setInnerElement(false);
+ log.debug("handle message - validate Action Type Failed With Action Type: {} Flow Stopped!", action);
+ }
+ }
+
+ void validateEnvironmentType(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData,
+ IDmaapAuditNotificationData auditNotificationData) {
+ log.debug("handle message - verify OperationaEnvironmentType");
+ OperationaEnvironmentTypeEnum envType = notificationData.getOperationalEnvironmentType();
+ if (envType != OperationaEnvironmentTypeEnum.ECOMP) {
+ errorWrapper.setInnerElement(false);
+ log.debug("handle message - validate Environment Type Failed With Environment Type: {} Flow Stopped!", envType);
+ componentUtils.auditEnvironmentEngine(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE,
+ notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(),
+ notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(),
+ auditNotificationData.getTenantContext());
+ }
+ }
+
+
+ private void saveOpEnvEntry(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry entry) {
+ entry.setLastModified(new Date(System.currentTimeMillis()));
+ CassandraOperationStatus saveStaus = operationalEnvironmentDao.save(entry);
+ if (saveStaus != CassandraOperationStatus.OK) {
+ errorWrapper.setInnerElement(false);
+ log.debug("handle message saving operational environmet failed for id :{} with error : {}",
+ entry.getEnvironmentId(), saveStaus);
+ }
+ }
+
+ public List<String> discoverUebHosts(String opEnvKey, String env) throws DME2Exception {
+ DmeConfiguration dmeConfiguration = configurationManager.getConfiguration().getDmeConfiguration();
+ List<String> uebHosts = new LinkedList<>();
+
+ String lookupURI = String.format("http://%s/service=%s/version=1.0.0/envContext=%s/partner=*", dmeConfiguration.getDme2Search(), opEnvKey,
+ env);
+ DME2EndpointIterator iterator = epIterCreator.create(lookupURI);
+
+ // Beginning iteration
+ while (iterator.hasNext()) {
+ DME2EndpointReference ref = iterator.next();
+ DME2Endpoint dmeEndpoint = ref.getEndpoint();
+ log.debug("DME returns EP with UEB host {}, UEB port: {}", dmeEndpoint.getHost(), dmeEndpoint.getPort());
+ uebHosts.add(dmeEndpoint.getHost());
+ }
+
+ return uebHosts;
+ }
+
+ private String map2OpEnvKey(OperationalEnvironmentEntry entry) {
+ return String.format("%s.%s.%s", entry.getTenant(), entry.getEcompWorkloadContext(), MESSAGE_BUS);
+ }
+
+ private Map<String, OperationalEnvironmentEntry> populateEnvironments() {
+ Map<String, OperationalEnvironmentEntry> envs = getEnvironmentsFromDb();
+ OperationalEnvironmentEntry confEntry = readEnvFromConfig();
+ envs.put(confEntry.getEnvironmentId(), confEntry);
+ return envs;
+ }
+
+ private OperationalEnvironmentEntry readEnvFromConfig() {
+ OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
+ DistributionEngineConfiguration distributionEngineConfiguration = configurationManager
+ .getDistributionEngineConfiguration();
+ entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey());
+ entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey());
+
+ Set<String> puebEndpoints = new HashSet<>();
+ puebEndpoints.addAll(distributionEngineConfiguration.getUebServers());
+ entry.setDmaapUebAddress(puebEndpoints);
+
+ String envName = distributionEngineConfiguration.getEnvironments().size() == 1
+ ? distributionEngineConfiguration.getEnvironments().get(0) : UNKNOWN;
+ entry.setEnvironmentId(envName);
+
+ if(log.isDebugEnabled()) {
+ log.debug("Enviroment read from configuration: {}", entry.toString());
+ }
+
+ return entry;
+ }
+
+ private Map<String, OperationalEnvironmentEntry> getEnvironmentsFromDb() {
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> opEnvResult = operationalEnvironmentDao
+ .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED);
+
+ if (opEnvResult.isLeft()) {
+ Map<String, OperationalEnvironmentEntry> resultMap = opEnvResult.left().value().stream()
+ .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity()));
+ resultMap.forEach( (key, value) -> log.debug("Enviroment loaded from DB: {}", value.toString()) );
+ return resultMap;
+ } else {
+ CassandraOperationStatus status = opEnvResult.right().value();
+ log.debug("Failed to populate Operation Envirenments Map from Cassandra, DB status: {}", status);
+ return new HashMap<>();
+ }
+ }
+
+ void createUebTopicsForEnvironments() {
+ environments.values().forEach(this::createUebTopicsForEnvironment);
+ }
+
+ public void createUebTopicsForEnvironment(OperationalEnvironmentEntry opEnvEntry) {
+ String envId = opEnvEntry.getEnvironmentId();
+ log.debug("Create Environment {} on UEB Topic.", envId);
+ AtomicBoolean status = new AtomicBoolean(false);
+ envNamePerStatus.put(envId, status);
+
+ connectUebTopicTenantIsolation(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask);
+ }
+
+ @VisibleForTesting
+ void setConfigurationManager(ConfigurationManager configurationManager) {
+ this.configurationManager = configurationManager;
+ }
+
+ public Map<String, OperationalEnvironmentEntry> getEnvironments() {
+ return environments;
+ }
+
+
+ public Either<OperationalEnvInfo, Integer> getOperationalEnvById(String id) {
+ HttpResponse<String> resp = aaiRequestHandler.getOperationalEnvById(id);
+ if (resp.getStatusCode() == HttpStatus.SC_OK) {
+ try {
+ OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(resp.getResponse());
+
+ log.debug("Get \"{}\" operational environment. {}", id, operationalEnvInfo);
+ return Either.left(operationalEnvInfo);
+ } catch (Exception e) {
+ log.debug("Json convert to OperationalEnvInfo failed with exception ", e);
+ return Either.right(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id,
+ resp.getStatusCode(), resp.getDescription());
+ return Either.right(resp.getStatusCode());
+ }
+ }
+
+ public OperationalEnvironmentEntry getEnvironmentById (String envId) {
+ return environments.get(envId);
+ }
+
+ public boolean isInMap(OperationalEnvironmentEntry env) {
+ return isInMap(env.getEnvironmentId());
+ }
+
+ public boolean isInMap(String envId) {
+ return environments.containsKey(envId);
+ }
+
+ public void addToMap(OperationalEnvironmentEntry opEnvEntry) {
+ environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry);
+
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java
new file mode 100644
index 0000000000..29579c64b7
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java
@@ -0,0 +1,43 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+@Component("executorFactory")
+/**
+ * Allows to create next kinds of single thread executors: SingleThreadExecutor and SingleThreadScheduledExecutor
+ */
+public class ExecutorFactory {
+
+ private static final Logger logger = LoggerFactory.getLogger(EnvironmentsEngine.class);
+
+ public ExecutorService create(String name, UncaughtExceptionHandler exceptionHandler){
+ logger.info("Going to create single thread executor. ");
+ ThreadFactory threadFactory = createThreadFactory(name, exceptionHandler);
+ return Executors.newSingleThreadExecutor(threadFactory);
+ }
+
+ public ScheduledExecutorService createScheduled(String name){
+ logger.info("Going to create single thread scheduled executor. ");
+ ThreadFactory threadFactory = createThreadFactory(name,
+ (t, e) -> LoggerFactory.getLogger(UncaughtExceptionHandler.class).error("An error occurred: ", e));
+ return Executors.newSingleThreadScheduledExecutor(threadFactory);
+ }
+
+ private ThreadFactory createThreadFactory(String name, UncaughtExceptionHandler exceptionHandler) {
+ String nameFormat = name + "-%d";
+ return new ThreadFactoryBuilder()
+ .setThreadFactory(Executors.defaultThreadFactory())
+ .setNameFormat(nameFormat)
+ .setUncaughtExceptionHandler(exceptionHandler)
+ .setDaemon(true)
+ .build();
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java
index 169f4f3efa..4a917710a9 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java
@@ -24,40 +24,40 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum;
public interface IArtifactInfo {
- /** Artifact File name */
- String getArtifactName();
-
- /**
- * Artifact Type.<br>
- * Following are valid values : HEAT , DG_XML. <br>
- * List of values will be extended in post-1510 releases.
- */
- ArtifactTypeEnum getArtifactType();
-
- /**
- * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br>
- * The full artifact URL will be in the following format :<br>
- * https://{serverBaseURL}/{resourcePath}<br>
- * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port <br>
- * resourcePath - "artifactURL" <br>
- * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml
- */
- String getArtifactURL();
-
- /**
- * Base-64 encoded MD5 checksum of the artifact's payload.<br>
- * Should be used for data integrity validation when an artifact's payload is downloaded.<br>
- */
- String getArtifactChecksum();
-
- /**
- * Installation timeout. Used by the orchestrator.
- */
- Integer getArtifactTimeout();
-
- /**
- * Artifact description
- */
- String getArtifactDescription();
+ /** Artifact File name */
+ String getArtifactName();
+
+ /**
+ * Artifact Type.<br>
+ * Following are valid values : HEAT , DG_XML. <br>
+ * List of values will be extended in post-1510 releases.
+ */
+ ArtifactTypeEnum getArtifactType();
+
+ /**
+ * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br>
+ * The full artifact URL will be in the following format :<br>
+ * https://{serverBaseURL}/{resourcePath}<br>
+ * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port <br>
+ * resourcePath - "artifactURL" <br>
+ * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml
+ */
+ String getArtifactURL();
+
+ /**
+ * Base-64 encoded MD5 checksum of the artifact's payload.<br>
+ * Should be used for data integrity validation when an artifact's payload is downloaded.<br>
+ */
+ String getArtifactChecksum();
+
+ /**
+ * Installation timeout. Used by the orchestrator.
+ */
+ Integer getArtifactTimeout();
+
+ /**
+ * Artifact description
+ */
+ String getArtifactDescription();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java
index a27156616b..96abfe087c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,26 +20,35 @@
package org.openecomp.sdc.be.components.distribution.engine;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-
-import fj.data.Either;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
public interface IDistributionEngine {
- public boolean isActive();
+ boolean isActive();
+
+ ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName);
+
+ ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName);
+
+ StorageOperationStatus isEnvironmentAvailable(String envName);
+
+ StorageOperationStatus isEnvironmentAvailable();
- public StorageOperationStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName);
+ /**
+ * Currently, it used for tests. For real implementation we need cancel the initialization task and the polling task.
+ *
+ * @param envName
+ */
+ void disableEnvironment(String envName);
- public StorageOperationStatus isEnvironmentAvailable(String envName);
+ StorageOperationStatus isReadyForDistribution(Service service, String envName);
- /**
- * Currently, it used for tests. For real implementation we need cancel the initialization task and the polling task.
- *
- * @param envName
- */
- public void disableEnvironment(String envName);
+ INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext);
- public Either<INotificationData, StorageOperationStatus> isReadyForDistribution(Service service, String distributionId, String envName);
+ StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service);
+ OperationalEnvironmentEntry getEnvironmentById(String opEnvId);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java
new file mode 100644
index 0000000000..c1b7a313fb
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java
@@ -0,0 +1,6 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+public interface IDmaapAuditNotificationData {
+ String getOperationalEnvironmentName();
+ String getTenantContext();
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java
new file mode 100644
index 0000000000..7b974e8a96
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.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.be.components.distribution.engine;
+
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.getEnumValueByFieldValue;
+
+public interface IDmaapNotificationData {
+ String getOperationalEnvironmentId();
+
+ OperationaEnvironmentTypeEnum getOperationalEnvironmentType();
+
+ DmaapActionEnum getAction();
+
+
+
+
+
+ enum DmaapActionEnum {
+ DELETE("Delete"),
+ CREATE("Create"),
+ UPDATE("Update"),
+ UNKONW("UNKONW")
+
+ ;
+ private String actionName;
+
+ private DmaapActionEnum(String actionName) {
+ this.actionName = actionName;
+ }
+
+ public String getActionName() {
+ return actionName;
+ }
+
+ public static DmaapActionEnum findByName(String actionName){
+ return getEnumValueByFieldValue(actionName, DmaapActionEnum.values(), DmaapActionEnum::getActionName, UNKONW, false);
+ }
+ };
+ enum OperationaEnvironmentTypeEnum {
+ ECOMP("ECOMP"),
+ UNKONW("UNKONW")
+ ;
+ private String eventTypenName;
+
+ private OperationaEnvironmentTypeEnum(String eventTypenName) {
+ this.eventTypenName = eventTypenName;
+ }
+
+ public String getEventTypenName() {
+ return eventTypenName;
+ }
+
+ public static OperationaEnvironmentTypeEnum findByName(String operationalEnvironmentTypeName){
+ return getEnumValueByFieldValue(operationalEnvironmentTypeName, OperationaEnvironmentTypeEnum.values(), OperationaEnvironmentTypeEnum::getEventTypenName, UNKONW, false);
+ }
+ };
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java
index d631724701..d66f8f92f1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java
@@ -23,84 +23,84 @@ package org.openecomp.sdc.be.components.distribution.engine;
import java.util.List;
public interface INotificationData {
- /**
- * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.<br>
- * Generated UUID is compliant with RFC 4122.<br>
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
- * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
- */
- String getDistributionID();
-
- /** Logical Service Name. */
- String getServiceName();
-
- /**
- * Service Version.<br>
- * Two dot (".") separated digit blocks.<br>
- * Ex. : "2.0"
- */
- String getServiceVersion();
-
- /**
- * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
- * Ex. : AA97B177-9383-4934-8543-0F91A7A02836
- */
- String getServiceUUID();
-
- /**
- * Service description
- */
- String getServiceDescription();
-
- /**
- * ServiceInvariant UUID
- */
- String getServiceInvariantUUID();
-
- /** List of the resource instances */
- List<JsonContainerResourceInstance> getResources();
-
- /** List of the artifacts */
- List<ArtifactInfoImpl> getServiceArtifacts();
-
- String getWorkloadContext();
-
- void setDistributionID(String distributionId);
-
- /** Logical Service Name. */
- void setServiceName(String serviceName);
-
- /**
- * Service Version.<br>
- * Two dot (".") separated digit blocks.<br>
- * Ex. : "2.0"
- */
- void setServiceVersion(String serviceVersion);
-
- /**
- * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
- * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
- * Ex. : AA97B177-9383-4934-8543-0F91A7A02836
- */
- void setServiceUUID(String serviceUUID);
-
- /**
- * Service Description
- */
- void setServiceDescription(String serviceDescription);
-
- /**
- * ServiceInvariant UUID
- */
- void setServiceInvariantUUID(String serviceInvariantUuid);
-
- /** List of the Resource Instances */
- void setResources(List<JsonContainerResourceInstance> resource);
-
- /** List of the Resource Instances */
- void setServiceArtifacts(List<ArtifactInfoImpl> artifacts);
-
- void setWorkloadContext(String workloadContext);
+ /**
+ * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.<br>
+ * Generated UUID is compliant with RFC 4122.<br>
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ String getDistributionID();
+
+ /** Logical Service Name. */
+ String getServiceName();
+
+ /**
+ * Service Version.<br>
+ * Two dot (".") separated digit blocks.<br>
+ * Ex. : "2.0"
+ */
+ String getServiceVersion();
+
+ /**
+ * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
+ * Ex. : AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ String getServiceUUID();
+
+ /**
+ * Service description
+ */
+ String getServiceDescription();
+
+ /**
+ * ServiceInvariant UUID
+ */
+ String getServiceInvariantUUID();
+
+ /** List of the resource instances */
+ List<JsonContainerResourceInstance> getResources();
+
+ /** List of the artifacts */
+ List<ArtifactInfoImpl> getServiceArtifacts();
+
+ String getWorkloadContext();
+
+ void setDistributionID(String distributionId);
+
+ /** Logical Service Name. */
+ void setServiceName(String serviceName);
+
+ /**
+ * Service Version.<br>
+ * Two dot (".") separated digit blocks.<br>
+ * Ex. : "2.0"
+ */
+ void setServiceVersion(String serviceVersion);
+
+ /**
+ * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
+ * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
+ * Ex. : AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ void setServiceUUID(String serviceUUID);
+
+ /**
+ * Service Description
+ */
+ void setServiceDescription(String serviceDescription);
+
+ /**
+ * ServiceInvariant UUID
+ */
+ void setServiceInvariantUUID(String serviceInvariantUuid);
+
+ /** List of the Resource Instances */
+ void setResources(List<JsonContainerResourceInstance> resource);
+
+ /** List of the Resource Instances */
+ void setServiceArtifacts(List<ArtifactInfoImpl> artifacts);
+
+ void setWorkloadContext(String workloadContext);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java
new file mode 100644
index 0000000000..a1936c61dd
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+public interface INotificationHandler {
+ /**
+ * Allows to handle received topic message
+ * @param notification
+ * @return true if finished successfully otherwise false
+ */
+ public boolean handleMessage(String notification);
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java
index 9a77b9f94f..deac8751b3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java
@@ -22,18 +22,18 @@ package org.openecomp.sdc.be.components.distribution.engine;
public interface IResourceArtifactInfo extends IArtifactInfo {
- /** resource name */
- String getResourceName();
+ /** resource name */
+ String getResourceName();
- /** resource version */
- String getResourceVersion();
+ /** resource version */
+ String getResourceVersion();
- /**
- * Global UUID of the resource that specific artifact belongs to.<br>
- * It is generated by ASDC per each resource version.<br>
- * Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-"). <br>
- * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
- */
- String getResourceUUID();
+ /**
+ * Global UUID of the resource that specific artifact belongs to.<br>
+ * It is generated by ASDC per each resource version.<br>
+ * Generated UUID is compliant with RFC 4122. It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-"). <br>
+ * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
+ */
+ String getResourceUUID();
}
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 5efcfe7fa8..db0e1e938d 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
@@ -20,109 +20,129 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.List;
-
import org.openecomp.sdc.be.model.ComponentInstance;
+import java.util.List;
+
public class JsonContainerResourceInstance {
- private String resourceInstanceName, resourceName, resourceVersion, resoucreType, resourceUUID, resourceInvariantUUID, resourceCustomizationUUID, category, subcategory;
- private List<ArtifactInfoImpl> artifacts;
-
- public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List<ArtifactInfoImpl> artifacts) {
- super();
- this.resourceInstanceName = resourceInstance.getName();
- this.resourceName = resourceInstance.getComponentName();
- this.resourceVersion = resourceInstance.getComponentVersion();
- this.resoucreType = resourceType;
- this.resourceUUID = resourceInstance.getComponentUid();
- this.artifacts = artifacts;
- this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
- }
-
- 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 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<ArtifactInfoImpl> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<ArtifactInfoImpl> artifacts) {
- this.artifacts = artifacts;
- }
-
- public String getResourceInvariantUUID() {
- return resourceInvariantUUID;
- }
-
- public void setResourceInvariantUUID(String resourceInvariantUUID) {
- this.resourceInvariantUUID = resourceInvariantUUID;
- }
-
- public String getResourceCustomizationUUID() {
- return resourceCustomizationUUID;
- }
-
- public void setResourceCustomizationUUID(String customizationUUID) {
- this.resourceCustomizationUUID = customizationUUID;
- }
-
- 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 "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID
- + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]";
- }
-
+ private String resourceInstanceName;
+ private String resourceName;
+ private String resourceVersion;
+ private String resourceType;
+ private String resourceUUID;
+ private String resourceInvariantUUID;
+ private String resourceCustomizationUUID;
+ private String category;
+ private String subcategory;
+ private List<ArtifactInfoImpl> artifacts;
+
+ public JsonContainerResourceInstance(ComponentInstance resourceInstance, String resourceType, List<ArtifactInfoImpl> artifacts) {
+ super();
+ this.resourceInstanceName = resourceInstance.getName();
+ this.resourceName = resourceInstance.getComponentName();
+ this.resourceVersion = resourceInstance.getComponentVersion();
+ this.resourceType = resourceType;
+ this.resourceUUID = resourceInstance.getComponentUid();
+ this.artifacts = artifacts;
+ this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
+ }
+
+ public JsonContainerResourceInstance(ComponentInstance resourceInstance, List<ArtifactInfoImpl> artifacts) {
+ super();
+ this.resourceInstanceName = resourceInstance.getName();
+ this.resourceName = resourceInstance.getComponentName();
+ this.resourceVersion = resourceInstance.getComponentVersion();
+ if(resourceInstance.getOriginType() != null)
+ this.resourceType = resourceInstance.getOriginType().getValue();
+ this.resourceUUID = resourceInstance.getComponentUid();
+ this.artifacts = artifacts;
+ this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
+ }
+
+ 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 getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ public String getResoucreType() {
+ return resourceType;
+ }
+
+ public void setResoucreType(String resoucreType) {
+ this.resourceType = resoucreType;
+ }
+
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ public List<ArtifactInfoImpl> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<ArtifactInfoImpl> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public String getResourceInvariantUUID() {
+ return resourceInvariantUUID;
+ }
+
+ public void setResourceInvariantUUID(String resourceInvariantUUID) {
+ this.resourceInvariantUUID = resourceInvariantUUID;
+ }
+
+ public String getResourceCustomizationUUID() {
+ return resourceCustomizationUUID;
+ }
+
+ public void setResourceCustomizationUUID(String customizationUUID) {
+ this.resourceCustomizationUUID = customizationUUID;
+ }
+
+ 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 "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resourceType + ", 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 353039647d..1db67a9581 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
@@ -24,111 +24,111 @@ import java.util.List;
public class NotificationDataImpl implements INotificationData {
- private String distributionID;
- private String serviceName;
- private String serviceVersion;
- private String serviceUUID;
- private String serviceDescription;
- private String serviceInvariantUUID;
- private List<JsonContainerResourceInstance> resources;
- private List<ArtifactInfoImpl> serviceArtifacts;
- private String workloadContext;
-
- @Override
- public String getDistributionID() {
- return distributionID;
- }
-
- @Override
- public String getServiceName() {
- return serviceName;
- }
-
- @Override
- public String getServiceVersion() {
- return serviceVersion;
- }
-
- @Override
- public String getServiceUUID() {
- return serviceUUID;
- }
-
- public void setDistributionID(String distributionID) {
- this.distributionID = distributionID;
- }
-
- public void setServiceName(String serviceName) {
- this.serviceName = serviceName;
- }
-
- public void setServiceVersion(String serviceVersion) {
- this.serviceVersion = serviceVersion;
- }
-
- public void setServiceUUID(String serviceUUID) {
- this.serviceUUID = serviceUUID;
- }
-
- public String getServiceDescription() {
- return serviceDescription;
- }
-
- public void setServiceDescription(String serviceDescription) {
- this.serviceDescription = serviceDescription;
- }
- @Override
- public String getWorkloadContext() { return workloadContext; }
-
- @Override
- public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; }
-
- @Override
- public String toString() {
- return "NotificationDataImpl{" +
- "distributionID='" + distributionID + '\'' +
- ", serviceName='" + serviceName + '\'' +
- ", serviceVersion='" + serviceVersion + '\'' +
- ", serviceUUID='" + serviceUUID + '\'' +
- ", serviceDescription='" + serviceDescription + '\'' +
- ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' +
- ", resources=" + resources +
- ", serviceArtifacts=" + serviceArtifacts +
- ", workloadContext='" + workloadContext + '\'' +
- '}';
- }
-
- @Override
- public List<JsonContainerResourceInstance> getResources() {
- return resources;
- }
-
- @Override
- public void setResources(List<JsonContainerResourceInstance> resources) {
- this.resources = resources;
-
- }
-
- @Override
- public List<ArtifactInfoImpl> getServiceArtifacts() {
- // TODO Auto-generated method stub
- return serviceArtifacts;
- }
-
- @Override
- public void setServiceArtifacts(List<ArtifactInfoImpl> serviceArtifacts) {
- this.serviceArtifacts = serviceArtifacts;
-
- }
-
- @Override
- public String getServiceInvariantUUID() {
- return serviceInvariantUUID;
- }
-
- @Override
- public void setServiceInvariantUUID(String serviceInvariantUUID) {
- this.serviceInvariantUUID = serviceInvariantUUID;
- }
+ private String distributionID;
+ private String serviceName;
+ private String serviceVersion;
+ private String serviceUUID;
+ private String serviceDescription;
+ private String serviceInvariantUUID;
+ private List<JsonContainerResourceInstance> resources;
+ private List<ArtifactInfoImpl> serviceArtifacts;
+ private String workloadContext;
+
+ @Override
+ public String getDistributionID() {
+ return distributionID;
+ }
+
+ @Override
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ @Override
+ public String getServiceVersion() {
+ return serviceVersion;
+ }
+
+ @Override
+ public String getServiceUUID() {
+ return serviceUUID;
+ }
+
+ public void setDistributionID(String distributionID) {
+ this.distributionID = distributionID;
+ }
+
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ public void setServiceVersion(String serviceVersion) {
+ this.serviceVersion = serviceVersion;
+ }
+
+ public void setServiceUUID(String serviceUUID) {
+ this.serviceUUID = serviceUUID;
+ }
+
+ public String getServiceDescription() {
+ return serviceDescription;
+ }
+
+ public void setServiceDescription(String serviceDescription) {
+ this.serviceDescription = serviceDescription;
+ }
+ @Override
+ public String getWorkloadContext() { return workloadContext; }
+
+ @Override
+ public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; }
+
+ @Override
+ public String toString() {
+ return "NotificationDataImpl{" +
+ "distributionID='" + distributionID + '\'' +
+ ", serviceName='" + serviceName + '\'' +
+ ", serviceVersion='" + serviceVersion + '\'' +
+ ", serviceUUID='" + serviceUUID + '\'' +
+ ", serviceDescription='" + serviceDescription + '\'' +
+ ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' +
+ ", resources=" + resources +
+ ", serviceArtifacts=" + serviceArtifacts +
+ ", workloadContext='" + workloadContext + '\'' +
+ '}';
+ }
+
+ @Override
+ public List<JsonContainerResourceInstance> getResources() {
+ return resources;
+ }
+
+ @Override
+ public void setResources(List<JsonContainerResourceInstance> resources) {
+ this.resources = resources;
+
+ }
+
+ @Override
+ public List<ArtifactInfoImpl> getServiceArtifacts() {
+ // TODO Auto-generated method stub
+ return serviceArtifacts;
+ }
+
+ @Override
+ public void setServiceArtifacts(List<ArtifactInfoImpl> serviceArtifacts) {
+ this.serviceArtifacts = serviceArtifacts;
+
+ }
+
+ @Override
+ public String getServiceInvariantUUID() {
+ return serviceInvariantUUID;
+ }
+
+ @Override
+ public void setServiceInvariantUUID(String serviceInvariantUUID) {
+ this.serviceInvariantUUID = serviceInvariantUUID;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java
index 74fbb2c660..dc58a24e5f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java
@@ -20,62 +20,57 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.util.concurrent.*;
public class NotificationExecutorService {
- private static Logger logger = LoggerFactory.getLogger(NotificationExecutorService.class.getName());
+ private static final Logger logger = LoggerFactory.getLogger(NotificationExecutorService.class);
- public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) {
+ public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) {
- Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize();
- if (minThreadPoolSize == null) {
- minThreadPoolSize = 0;
- }
+ Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize();
+ if (minThreadPoolSize == null) {
+ minThreadPoolSize = 0;
+ }
- Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize();
- if (maxThreadPoolSize == null) {
- maxThreadPoolSize = 10;
- }
+ Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize();
+ if (maxThreadPoolSize == null) {
+ maxThreadPoolSize = 10;
+ }
- ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
- threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d");
- ThreadFactory threadFactory = threadFactoryBuilder.build();
+ ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
+ threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d");
+ ThreadFactory threadFactory = threadFactoryBuilder.build();
- ExecutorService executorService = new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
+ ExecutorService executorService = new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
- return executorService;
- }
+ return executorService;
+ }
- public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) {
+ public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) {
- logger.debug("shutdown NotificationExecutorService");
- pool.shutdown(); // Disable new tasks from being submitted
- try {
- // Wait a while for existing tasks to terminate
- if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) {
- pool.shutdownNow(); // Cancel currently executing tasks
- // Wait a while for tasks to respond to being cancelled
- if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) {
- logger.debug("Failed to close executor service");
- }
- }
- } catch (InterruptedException ie) {
- // (Re-)Cancel if current thread also interrupted
- pool.shutdownNow();
- // Preserve interrupt status
- Thread.currentThread().interrupt();
- }
- }
+ logger.debug("shutdown NotificationExecutorService");
+ pool.shutdown(); // Disable new tasks from being submitted
+ try {
+ // Wait a while for existing tasks to terminate
+ if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) {
+ pool.shutdownNow(); // Cancel currently executing tasks
+ // Wait a while for tasks to respond to being cancelled
+ if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) {
+ logger.debug("Failed to close executor service");
+ }
+ }
+ } catch (InterruptedException ie) {
+ // (Re-)Cancel if current thread also interrupted
+ pool.shutdownNow();
+ // Preserve interrupt status
+ Thread.currentThread().interrupt();
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java
deleted file mode 100644
index c283ecc92b..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/PublishNotificationRunnable.java
+++ /dev/null
@@ -1,156 +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.components.distribution.engine;
-
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.common.util.ThreadLocalsHolder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PublishNotificationRunnable implements Runnable {
-
- private String envName;
- private String distributionId;
- private Service service;
- private INotificationData data;
- private DistributionEngineConfiguration deConfiguration;
- private String topicName;
- private CambriaHandler cambriaHandler;
- private ComponentsUtils componentUtils;
- private String userId;
- private String modifierName;
- private String requestId;
-
- private static Logger logger = LoggerFactory.getLogger(PublishNotificationRunnable.class.getName());
-
- public PublishNotificationRunnable(String envName, String distributionId, Service service, INotificationData data, DistributionEngineConfiguration deConfiguration, String topicName, String userId, String modifierName,
- CambriaHandler cambriaHandler, ComponentsUtils componentUtils, String requestId) {
- super();
- this.envName = envName;
- this.distributionId = distributionId;
- this.service = service;
- this.data = data;
- this.deConfiguration = deConfiguration;
- this.topicName = topicName;
- this.cambriaHandler = cambriaHandler;
- this.componentUtils = componentUtils;
- this.userId = userId;
- this.modifierName = modifierName;
- this.requestId = requestId;
- }
-
- public INotificationData getData() {
- return data;
- }
-
- public void setData(INotificationData data) {
- this.data = data;
- }
-
- public DistributionEngineConfiguration getDeConfiguration() {
- return deConfiguration;
- }
-
- public void setDeConfiguration(DistributionEngineConfiguration deConfiguration) {
- this.deConfiguration = deConfiguration;
- }
-
- public String getTopicName() {
- return topicName;
- }
-
- public void setTopicName(String topicName) {
- this.topicName = topicName;
- }
-
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getModifierName() {
- return modifierName;
- }
-
- public void setModifierName(String modifierName) {
- this.modifierName = modifierName;
- }
-
- @Override
- public void run() {
-
- long startTime = System.currentTimeMillis();
- ThreadLocalsHolder.setUuid(this.requestId);
-
- CambriaErrorResponse status = cambriaHandler.sendNotificationAndClose(topicName, deConfiguration.getUebPublicKey(), deConfiguration.getUebSecretKey(), deConfiguration.getUebServers(), data,
- deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds());
-
- logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode());
- auditDistributionNotification(topicName, status, service, distributionId, envName, userId, modifierName);
-
- long endTime = System.currentTimeMillis();
- logger.debug("After building and publishing artifacts object. Total took {} milliseconds", (endTime - startTime));
-
- }
-
- private void auditDistributionNotification(String topicName, CambriaErrorResponse status, Service service, String distributionId, String envName, String userId, String modifierName) {
- if (this.componentUtils != null) {
- Integer httpCode = status.getHttpCode();
- String httpCodeStr = String.valueOf(httpCode);
-
- String desc = getDescriptionFromErrorResponse(status);
-
- this.componentUtils.auditDistributionNotification(AuditingActionEnum.DISTRIBUTION_NOTIFY, service.getUUID(), service.getName(), "Service", service.getVersion(), userId, modifierName, envName, service.getLifecycleState().name(), topicName,
- distributionId, desc, httpCodeStr);
- }
- }
-
- private String getDescriptionFromErrorResponse(CambriaErrorResponse status) {
-
- CambriaOperationStatus operationStatus = status.getOperationStatus();
-
- switch (operationStatus) {
- case OK:
- return "OK";
- case AUTHENTICATION_ERROR:
- return "Error: Authentication problem towards U-EB server";
- case INTERNAL_SERVER_ERROR:
- return "Error: Internal U-EB server error";
- case UNKNOWN_HOST_ERROR:
- return "Error: Cannot reach U-EB server host";
- case CONNNECTION_ERROR:
- return "Error: Cannot connect to U-EB server";
- case OBJECT_NOT_FOUND:
- return "Error: object not found in U-EB server";
- default:
- return "Error: Internal Cambria server problem";
-
- }
-
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java
index 31f3cb6fda..19a857a115 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java
@@ -22,37 +22,37 @@ package org.openecomp.sdc.be.components.distribution.engine;
public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResourceArtifactInfo {
- private String resourceName;
- private String resourceVersion;
- private String resourceUUID;
-
- public String getResourceName() {
- return resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- public String getResourceVersion() {
- return resourceVersion;
- }
-
- public void setResourceVersion(String resourceVersion) {
- this.resourceVersion = resourceVersion;
- }
-
- public String getResourceUUID() {
- return resourceUUID;
- }
-
- public void setResourceUUID(String resourceUUID) {
- this.resourceUUID = resourceUUID;
- }
-
- @Override
- public String toString() {
- return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]";
- }
+ private String resourceName;
+ private String resourceVersion;
+ private String resourceUUID;
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]";
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java
index 50d1700f37..1d626805f6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java
@@ -22,9 +22,9 @@ package org.openecomp.sdc.be.components.distribution.engine;
public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServiceArtifactInfo {
- @Override
- public String toString() {
- return "ServiceArtifactInfoImpl [" + super.toString() + "]";
- }
+ @Override
+ public String toString() {
+ return "ServiceArtifactInfoImpl [" + super.toString() + "]";
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
index 0330a756c6..f3d17979ba 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
@@ -20,26 +20,16 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import javax.annotation.PostConstruct;
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.slf4j.Logger;
@@ -47,279 +37,224 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.*;
+import java.util.stream.Collectors;
@Component("serviceDistributionArtifactsBuilder")
public class ServiceDistributionArtifactsBuilder {
- private int defaultArtifactInstallTimeout = 60;
-
- private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName());
-
- final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
- final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
- final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
-
- final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
-
- @javax.annotation.Resource
- InterfaceLifecycleOperation interfaceLifecycleOperation;
-
- @javax.annotation.Resource
- IArtifactOperation artifactOperation;
-
- @Autowired
- ToscaOperationFacade toscaOperationFacade;
-
- /*
- * @javax.annotation.Resource private
- * InformationDeployedArtifactsBusinessLogic
- * informationDeployedArtifactsBusinessLogic;
- */
-
- @PostConstruct
- private void init() {
- defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getDefaultHeatArtifactTimeoutMinutes();
- }
-
- public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
- return interfaceLifecycleOperation;
- }
-
- public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
- this.interfaceLifecycleOperation = interfaceLifecycleOperation;
- }
-
- public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId) {
- INotificationData notificationData = new NotificationDataImpl();
-
- notificationData.setResources(convertRIToJsonContanier(service));
- notificationData.setServiceName(service.getName());
- notificationData.setServiceVersion(service.getVersion());
- notificationData.setDistributionID(distributionId);
- notificationData.setServiceUUID(service.getUUID());
- notificationData.setServiceDescription(service.getDescription());
- notificationData.setServiceInvariantUUID(service.getInvariantUUID());
- String workloadContext= ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
- if(workloadContext!=null){
- notificationData.setWorkloadContext(workloadContext);
- }
- logger.debug("Before returning notification data object {}", notificationData);
-
- return notificationData;
-
- }
-
- public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
-
- notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
-
- logger.debug("Before returning notification data object {}", notificationData);
-
- return notificationData;
-
- }
-
- private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
-
- Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
- List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
- //filters all artifacts with existing EsId
- .filter(artifactDef -> artifactDef.checkEsIdExist())
- //collects all filtered artifacts with existing EsId to List
- .collect(Collectors.toList());
-
- Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
- if(toscaTemplateArtifactOptl.isPresent()){
- extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
- }
-
- Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
- if(toscaCsarArtifactOptl.isPresent()){
- extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
- }
-
- List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
- return artifacts;
- }
-
- private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
- return service.getToscaArtifacts().values().stream()
- //filters TOSCA_TEMPLATE artifact
- .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
- }
-
- private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
- return service.getToscaArtifacts().values().stream()
- //filters TOSCA_CSAR artifact
- .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
- }
-
- private List<JsonContainerResourceInstance> convertRIToJsonContanier(Service service) {
- List<JsonContainerResourceInstance> ret = new ArrayList<JsonContainerResourceInstance>();
- if (service.getComponentInstances() != null) {
- for (ComponentInstance resourceInstance : service.getComponentInstances()) {
- String resoucreType = resourceInstance.getOriginType().getValue();
- List<ArtifactDefinition> artifactsDefList = getArtifactsWithPayload(resourceInstance);
- List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance,
- artifactsDefList);
-
- String resourceInvariantUUID = null;
- String resourceCategory = null;
- String resourceSubcategory = null;
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreCategories(false);
- Either<Resource, StorageOperationStatus> componentResponse = toscaOperationFacade
- .getToscaElement(resourceInstance.getComponentUid(), componentParametersView);
-
- if (componentResponse.isRight()) {
- logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid());
- } else {
- Resource resource = componentResponse.left().value();
- resourceInvariantUUID = resource.getInvariantUUID();
-
- List<CategoryDefinition> categories = resource.getCategories();
-
- if (categories != null) {
- CategoryDefinition categoryDefinition = categories.get(0);
-
- if (categoryDefinition != null) {
- resourceCategory = categoryDefinition.getName();
- List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
- if (null != subcategories) {
- SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
-
- if (subCategoryDefinition != null) {
- resourceSubcategory = subCategoryDefinition.getName();
- }
- }
- }
- }
- }
-
- JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType,
- rebuildArtifactswith120TimeoutInsteadOf60(artifacts)/*TODO used to send artifacts, the function is a fix to the short timeout bug in distribution*/);
- jsonContainer.setResourceInvariantUUID(resourceInvariantUUID);
- jsonContainer.setCategory(resourceCategory);
- jsonContainer.setSubcategory(resourceSubcategory);
- ret.add(jsonContainer);
- }
- }
- return ret;
- }
-
- private List<ArtifactInfoImpl> rebuildArtifactswith120TimeoutInsteadOf60(List<ArtifactInfoImpl> artifacts) {
- for(ArtifactInfoImpl artifact : artifacts){
- if(artifact.getArtifactTimeout().equals(60)){
- artifact.setArtifactTimeout(120);
- }
- }
- return artifacts;
- }
-
- private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
- List<ArtifactDefinition> ret = new ArrayList<ArtifactDefinition>();
-
- // List<ArtifactDefinition> informationDeployedArtifacts =
- // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance);
- List<ArtifactDefinition> deployableArtifacts = new ArrayList<ArtifactDefinition>();
- // deployableArtifacts.addAll(informationDeployedArtifacts);
- if (resourceInstance.getDeploymentArtifacts() != null) {
- deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
- }
-
- for (ArtifactDefinition artifactDef : deployableArtifacts) {
- if (artifactDef.checkEsIdExist()) {
- ret.add(artifactDef);
- }
- }
-
- return ret;
- }
-
- /**
- * build the url for resource intance artifact
- *
- * @param service
- * @param resourceData
- * @param artifactName
- * @return
- */
- public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
- String artifactName) {
-
- String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
- resourceInstance.getNormalizedName(), artifactName);
-
- logger.debug("After building artifact url {}", url);
-
- return url;
- }
-
- /**
- * build the url for resource intance artifact
- *
- * @param service
- * @param resourceData
- * @param artifactName
- * @return
- */
- public static String buildServiceArtifactUrl(Service service, String artifactName) {
-
- String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
-
- logger.debug("After building artifact url {}", url);
-
- return url;
-
- }
-
- /**
- * Retrieve all deployment artifacts of all resources under a given service
- *
- * @param resourceArtifactsResult
- * @param service
- * @param deConfiguration
- * @return
- */
- public Either<Boolean, StorageOperationStatus> isServiceContainsDeploymentArtifacts(Service service) {
-
- Either<Boolean, StorageOperationStatus> result = Either.left(false);
- Map<String, ArtifactDefinition> serviseArtifactsMap = service.getDeploymentArtifacts();
- if (serviseArtifactsMap != null && !serviseArtifactsMap.isEmpty()) {
- result = Either.left(true);
- return result;
- }
-
- List<ComponentInstance> resourceInstances = service.getComponentInstances();
-
- if (resourceInstances != null) {
- for (ComponentInstance resourceInstance : resourceInstances) {
-
- Map<String, ArtifactDefinition> deploymentArtifactsMapper = resourceInstance.getDeploymentArtifacts();
- // List<ArtifactDefinition> informationDeployedArtifacts =
- // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance);
-
- boolean isDeployableArtifactFound = isContainsPayload(deploymentArtifactsMapper.values());// ||
- // isContainsPayload(informationDeployedArtifacts);
- if (isDeployableArtifactFound) {
- result = Either.left(true);
- break;
- }
-
- }
-
- }
-
- return result;
- }
-
- private boolean isContainsPayload(Collection<ArtifactDefinition> collection) {
- boolean payLoadFound = collection != null && collection.stream().anyMatch(p -> p.checkEsIdExist());
- return payLoadFound;
- }
+ private static final Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class);
+
+ static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
+ static final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
+ static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
+ static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
+
+ @javax.annotation.Resource
+ InterfaceLifecycleOperation interfaceLifecycleOperation;
+
+ @javax.annotation.Resource
+ IArtifactOperation artifactOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
+
+ public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
+ return interfaceLifecycleOperation;
+ }
+
+ public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
+ this.interfaceLifecycleOperation = interfaceLifecycleOperation;
+ }
+
+ private String resolveWorkloadContext(String workloadContext) {
+ return workloadContext != null ? workloadContext :
+ ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
+ }
+
+ public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId, String workloadContext) {
+ INotificationData notificationData = new NotificationDataImpl();
+
+ notificationData.setResources(convertRIsToJsonContanier(service));
+ notificationData.setServiceName(service.getName());
+ notificationData.setServiceVersion(service.getVersion());
+ notificationData.setDistributionID(distributionId);
+ notificationData.setServiceUUID(service.getUUID());
+ notificationData.setServiceDescription(service.getDescription());
+ notificationData.setServiceInvariantUUID(service.getInvariantUUID());
+ workloadContext = resolveWorkloadContext(workloadContext);
+ if (workloadContext!=null){
+ notificationData.setWorkloadContext(workloadContext);
+ }
+ logger.debug("Before returning notification data object {}", notificationData);
+
+ return notificationData;
+ }
+
+ public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
+
+ notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
+
+ logger.debug("Before returning notification data object {}", notificationData);
+
+ return notificationData;
+ }
+
+ private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
+
+ Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
+ List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
+ //filters all artifacts with existing EsId
+ .filter(ArtifactDefinition::checkEsIdExist)
+ //collects all filtered artifacts with existing EsId to List
+ .collect(Collectors.toList());
+
+ Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
+ if(toscaTemplateArtifactOptl.isPresent()){
+ extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
+ }
+
+ Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
+ if(toscaCsarArtifactOptl.isPresent()){
+ extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
+ }
+
+ return ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
+ }
+
+ private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
+ return service.getToscaArtifacts().values().stream()
+ //filters TOSCA_TEMPLATE artifact
+ .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
+ }
+
+ private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
+ return service.getToscaArtifacts().values().stream()
+ //filters TOSCA_CSAR artifact
+ .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
+ }
+
+ private List<JsonContainerResourceInstance> convertRIsToJsonContanier(Service service) {
+ List<JsonContainerResourceInstance> ret = new ArrayList<>();
+ if (service.getComponentInstances() != null) {
+ for (ComponentInstance instance : service.getComponentInstances()) {
+ JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance, convertToArtifactsInfoImpl(service, instance));
+ ComponentParametersView filter = new ComponentParametersView();
+ filter.disableAll();
+ filter.setIgnoreCategories(false);
+ toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter)
+ .left()
+ .bind(r->{fillJsonContainer(jsonContainer, (Resource) r); return Either.left(r);})
+ .right()
+ .forEach(r->logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid()));
+ ret.add(jsonContainer);
+ }
+ }
+ return ret;
+ }
+
+ private void fillJsonContainer(JsonContainerResourceInstance jsonContainer, Resource resource) {
+ jsonContainer.setResourceInvariantUUID(resource.getInvariantUUID());
+ setCategories(jsonContainer, resource.getCategories());
+ }
+
+ private List<ArtifactInfoImpl> convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) {
+ List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance));
+ artifacts.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout);
+ return artifacts;
+ }
+
+ private void setCategories(JsonContainerResourceInstance jsonContainer, List<CategoryDefinition> categories) {
+ if (categories != null) {
+ CategoryDefinition categoryDefinition = categories.get(0);
+
+ if (categoryDefinition != null) {
+ jsonContainer.setCategory(categoryDefinition.getName());
+ List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
+ if (null != subcategories) {
+ SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
+
+ if (subCategoryDefinition != null) {
+ jsonContainer.setSubcategory(subCategoryDefinition.getName());
+ }
+ }
+ }
+ }
+ }
+
+ private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
+ List<ArtifactDefinition> ret = new ArrayList<>();
+
+ List<ArtifactDefinition> deployableArtifacts = new ArrayList<>();
+ if (resourceInstance.getDeploymentArtifacts() != null) {
+ deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
+ }
+
+ for (ArtifactDefinition artifactDef : deployableArtifacts) {
+ if (artifactDef.checkEsIdExist()) {
+ ret.add(artifactDef);
+ }
+ }
+
+ return ret;
+ }
+
+ /**
+ * build the URL for resource instance artifact
+ *
+ * @param service
+ * @param resourceInstance
+ * @param artifactName
+ * @return URL string
+ */
+ public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
+ String artifactName) {
+
+ String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
+ resourceInstance.getNormalizedName(), artifactName);
+
+ logger.debug("After building artifact url {}", url);
+
+ return url;
+ }
+
+ /**
+ * build the URL for resource instance artifact
+ *
+ * @param service
+ * @param artifactName
+ * @return URL string
+ */
+ public static String buildServiceArtifactUrl(Service service, String artifactName) {
+
+ String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
+
+ logger.debug("After building artifact url {}", url);
+
+ return url;
+
+ }
+
+ /**
+ * Verifies that the service or at least one of its instance contains deployment artifacts
+ *
+ * @param the service
+ * @return boolean
+ */
+ public boolean verifyServiceContainsDeploymentArtifacts(Service service) {
+ if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) {
+ return true;
+ }
+ boolean contains = false;
+ List<ComponentInstance> resourceInstances = service.getComponentInstances();
+ if (CollectionUtils.isNotEmpty(resourceInstances)) {
+ contains = resourceInstances.stream().anyMatch(i -> isContainsPayload(i.getDeploymentArtifacts()));
+ }
+ return contains;
+ }
+
+ private boolean isContainsPayload(Map<String, ArtifactDefinition> deploymentArtifacts) {
+ return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java
index f8c0e3f593..3477648dbd 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java
@@ -22,5 +22,5 @@ package org.openecomp.sdc.be.components.distribution.engine;
public enum SubscriberTypeEnum {
- CONSUMER, PRODUCER;
+ CONSUMER, PRODUCER;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java
index c522ca91b5..7a25c2ed69 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java
@@ -20,58 +20,58 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.concurrent.Callable;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.concurrent.Callable;
+
public class UebHealthCheckCall implements Callable<Boolean> {
- CambriaHandler cambriaHandler = new CambriaHandler();
+ CambriaHandler cambriaHandler = new CambriaHandler();
- String server;
- String publicApiKey;
+ String server;
+ String publicApiKey;
- private static Logger healthLogger = LoggerFactory.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT);
+ private static final Logger healthLogger = LoggerFactory.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT);
- private static Logger logger = LoggerFactory.getLogger(UebHealthCheckCall.class.getName());
+ private static final Logger logger = LoggerFactory.getLogger(UebHealthCheckCall.class);
- public UebHealthCheckCall(String server, String publicApiKey) {
- super();
- this.server = server;
- this.publicApiKey = publicApiKey;
- }
+ public UebHealthCheckCall(String server, String publicApiKey) {
+ super();
+ this.server = server;
+ this.publicApiKey = publicApiKey;
+ }
- @Override
- public Boolean call() {
+ @Override
+ public Boolean call() {
- healthLogger.trace("Going to run health check towards ueb server {}", server);
+ healthLogger.trace("Going to run health check towards ueb server {}", server);
- boolean result = false;
- CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey);
+ boolean result = false;
+ CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey);
- logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse);
+ logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse);
- if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) {
- logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode);
- result = true;
- }
+ if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) {
+ logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode);
+ result = true;
+ }
- healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result);
+ healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result);
- return result;
- }
+ return result;
+ }
- public String getServer() {
- return server;
- }
+ public String getServer() {
+ return server;
+ }
- public CambriaHandler getCambriaHandler() {
- return cambriaHandler;
- }
+ public CambriaHandler getCambriaHandler() {
+ return cambriaHandler;
+ }
- public void setCambriaHandler(CambriaHandler cambriaHandler) {
- this.cambriaHandler = cambriaHandler;
- }
+ public void setCambriaHandler(CambriaHandler cambriaHandler) {
+ this.cambriaHandler = cambriaHandler;
+ }
}
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 d706e40f5c..8f0865f2ac 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
@@ -20,105 +20,100 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.common.api.Constants;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
public class VfModuleArtifactPayload {
-
- private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription;
- private Boolean isBase;
- private List<String> artifacts;
- private Map< String, Object> properties;
-
- public VfModuleArtifactPayload(GroupDefinition group) {
- vfModuleModelName = group.getName();
- vfModuleModelInvariantUUID = group.getInvariantUUID();
- vfModuleModelVersion = group.getVersion();
- vfModuleModelUUID = group.getGroupUUID();
- vfModuleModelDescription = group.getDescription();
-
- artifacts = group.getArtifactsUuid();
- // Base Value is set from properties
- setBaseValue(group);
-
- }
-
- public VfModuleArtifactPayload(GroupInstance group) {
- vfModuleModelName = group.getGroupName();
- vfModuleModelInvariantUUID = group.getInvariantUUID();
- vfModuleModelVersion = group.getVersion();
- vfModuleModelUUID = group.getGroupUUID();
- vfModuleModelCustomizationUUID = group.getCustomizationUUID();
- vfModuleModelDescription = group.getDescription();
-
- artifacts = group.getArtifactsUuid();
- artifacts.addAll(group.getGroupInstanceArtifactsUuid());
-
- // Base Value is set from properties
- setBaseValue(group);
-
- if(group.convertToGroupInstancesProperties() != null)
- setProperties(group.convertToGroupInstancesProperties());
- //converts List of GroupInstanceProperties to Map propertyName : GroupInstanceProperty ()
- //setProperties(group.getGroupInstancesProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p)));
-
- }
-
- private void setBaseValue(GroupInstance group) {
- if (group.convertToGroupInstancesProperties() != null) {
- Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
- if (findBaseProperty.isPresent()) {
- isBase = Boolean.valueOf(findBaseProperty.get().getValue());
- }
-
- }
- }
- private void setBaseValue(GroupDefinition group) {
- if (group.getProperties() != null) {
- Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
- if (findBaseProperty.isPresent()) {
- isBase = Boolean.valueOf(findBaseProperty.get().getValue());
- }
-
- }
- }
-
-
-
- public List<String> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<String> artifacts) {
- this.artifacts = artifacts;
- }
-
-
-
- public Map<String, Object> getProperties() {
- return properties;
- }
-
- /*public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }*/
-
- public void setProperties(List<GroupInstanceProperty> properties) {
- this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect(
- Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() ));
- }
-
- public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) {
- Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
- Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
- return thisCounter.compareTo(otherCounter);
- }
+
+ private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription;
+ private Boolean isBase;
+ private List<String> artifacts;
+ private Map< String, Object> properties;
+
+ public VfModuleArtifactPayload(GroupDefinition group) {
+ vfModuleModelName = group.getName();
+ vfModuleModelInvariantUUID = group.getInvariantUUID();
+ vfModuleModelVersion = group.getVersion();
+ vfModuleModelUUID = group.getGroupUUID();
+ vfModuleModelDescription = group.getDescription();
+
+ artifacts = group.getArtifactsUuid();
+ // Base Value is set from properties
+ setBaseValue(group);
+
+ }
+
+ public VfModuleArtifactPayload(GroupInstance group) {
+ vfModuleModelName = group.getGroupName();
+ vfModuleModelInvariantUUID = group.getInvariantUUID();
+ vfModuleModelVersion = group.getVersion();
+ vfModuleModelUUID = group.getGroupUUID();
+ vfModuleModelCustomizationUUID = group.getCustomizationUUID();
+ vfModuleModelDescription = group.getDescription();
+
+ artifacts = new ArrayList<>(group.getArtifactsUuid());
+ artifacts.addAll(group.getGroupInstanceArtifactsUuid());
+
+ // Base Value is set from properties
+ setBaseValue(group);
+
+ if(group.convertToGroupInstancesProperties() != null)
+ setProperties(group.convertToGroupInstancesProperties());
+ }
+
+ private void setBaseValue(GroupInstance group) {
+ if (group.convertToGroupInstancesProperties() != null) {
+ Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (findBaseProperty.isPresent()) {
+ isBase = Boolean.valueOf(findBaseProperty.get().getValue());
+ }
+
+ }
+ }
+ private void setBaseValue(GroupDefinition group) {
+ if (group.getProperties() != null) {
+ Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (findBaseProperty.isPresent()) {
+ isBase = Boolean.valueOf(findBaseProperty.get().getValue());
+ }
+
+ }
+ }
+
+
+
+ public List<String> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<String> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+
+
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
+
+
+ public void setProperties(List<GroupInstanceProperty> properties) {
+ this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect(
+ Collectors.toMap(x -> x.getName(), x -> x.getValue() == null? "":x.getValue() ));
+ }
+
+ public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) {
+ Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
+ Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
+ return thisCounter.compareTo(otherCounter);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java
new file mode 100644
index 0000000000..e6f2cc634f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.be.components.distribution.engine.config;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan({"org.openecomp.sdc.be.components.distribution.engine",
+ })
+public class DistributionEngineSpringConfig {
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java
new file mode 100644
index 0000000000..7f9dd45e67
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java
@@ -0,0 +1,9 @@
+package org.openecomp.sdc.be.components.distribution.engine.report;
+
+import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification;
+
+public interface DistributionCompleteReporter {
+
+ void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification);
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java
new file mode 100644
index 0000000000..4e06b0ed0e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.be.components.distribution.engine.report;
+
+import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification;
+import org.openecomp.sdc.be.components.distribution.engine.rest.MSORestClient;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+
+@Component
+public class MsoDistributionCompleteReporter implements DistributionCompleteReporter {
+
+ @Resource
+ private MSORestClient msoClient;
+
+ @Override
+ public void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification) {
+ msoClient.notifyDistributionComplete(distributionStatusNotification.getDistributionID(), distributionStatusNotification.getStatus(), distributionStatusNotification.getErrorReason());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java
new file mode 100644
index 0000000000..45727fb28f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.components.distribution.engine.rest;
+
+/**
+ * a class which represents an MSO distribution status rest request body
+ */
+public class DistributionStatusRequest {
+
+ private String status;
+ private String errorReason;
+
+ public DistributionStatusRequest(String status, String errorReason) {
+ this.status = status;
+ this.errorReason = errorReason;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public String getErrorReason() {
+ return errorReason;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java
new file mode 100644
index 0000000000..76263f942d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java
@@ -0,0 +1,69 @@
+package org.openecomp.sdc.be.components.distribution.engine.rest;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gson.Gson;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.eclipse.jetty.util.URIUtil;
+import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.http.client.api.*;
+import org.openecomp.sdc.common.http.config.BasicAuthorization;
+import org.openecomp.sdc.common.http.config.ExternalServiceConfig;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.util.Properties;
+
+@Component
+public class MSORestClient {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(MSORestClient.class);
+ private static final Gson gson = new Gson();
+ @VisibleForTesting
+ static final String DISTRIBUTIONS_RESOURCE_CONFIG_PARAM = "distributions";
+
+ private ExternalServiceConfig serviceConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig();
+
+ public MSORestClient() {
+ HttpClientConfig httpClientConfig = serviceConfig.getHttpClientConfig();
+ int numOfRetries = httpClientConfig.getNumOfRetries();
+ if ( numOfRetries > 0 ) {
+ httpClientConfig.setRetryHandler(RetryHandlers.getDefault(numOfRetries));
+ }
+ }
+
+ public HttpResponse<String> notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) {
+ try {
+ return doNotifyDistributionComplete(distributionId, distributionStatusEnum, errReason);
+ }
+ catch(HttpExecuteException e) {
+ LOGGER.debug("The request to mso failed with exception ", e);
+ return Responses.INTERNAL_SERVER_ERROR;
+ }
+ }
+
+ private HttpResponse<String> doNotifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) throws HttpExecuteException {
+ StringEntity entity = new StringEntity(gson.toJson(new DistributionStatusRequest(distributionStatusEnum.name(), errReason)), ContentType.APPLICATION_JSON);
+ HttpResponse<String> response = HttpRequest.patch(buildMsoDistributionUrl(distributionId), buildReqHeader(), entity, serviceConfig.getHttpClientConfig());
+ LOGGER.info("response from mso - status code: {}, status description: {}, response: {}, ", response.getStatusCode(), response.getDescription(), response.getResponse());
+ return response;
+ }
+
+ private Properties buildReqHeader() {
+ Properties properties = new Properties();
+ BasicAuthorization basicAuth = serviceConfig.getHttpClientConfig().getBasicAuthorization();
+ RestUtils.addBasicAuthHeader(properties, basicAuth.getUserName(), basicAuth.getPassword());
+ return properties;
+ }
+
+ private String buildMsoDistributionUrl(String distributionId) {
+ String msoBaseUrl = serviceConfig.getHttpRequestConfig().getServerRootUrl();
+ String distributionsPath = serviceConfig.getHttpRequestConfig().getResourceNamespaces().get(DISTRIBUTIONS_RESOURCE_CONFIG_PARAM);
+ String distributionsApiPath = distributionsPath + URIUtil.SLASH + distributionId;
+ return msoBaseUrl + distributionsApiPath;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java
new file mode 100644
index 0000000000..670350a733
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java
@@ -0,0 +1,475 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.components.health;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth;
+import org.openecomp.sdc.be.components.distribution.engine.DmaapHealth;
+import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall;
+import org.openecomp.sdc.be.components.impl.CassandraHealthCheck;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.impl.EsHealthCheckDao;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.openecomp.sdc.common.http.config.Timeouts;
+import org.openecomp.sdc.common.util.HealthCheckUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.stream.Collectors;
+
+import static java.lang.String.format;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
+import static org.apache.http.HttpStatus.SC_OK;
+import static org.openecomp.sdc.common.api.Constants.*;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP;
+import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion;
+
+
+@Component("healthCheckBusinessLogic")
+public class HealthCheckBusinessLogic {
+
+ protected static final String BE_HEALTH_LOG_CONTEXT = "be.healthcheck";
+ private static final String BE_HEALTH_CHECK_STR = "beHealthCheck";
+ private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s";
+ private static final Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT);
+ private static final Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName());
+ private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil();
+ ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task"));
+ HealthCheckScheduledTask healthCheckScheduledTask = null;
+ @Resource
+ private TitanGenericDao titanGenericDao;
+ @Resource
+ private EsHealthCheckDao esHealthCheckDao;
+ @Resource
+ private DistributionEngineClusterHealth distributionEngineClusterHealth;
+ @Resource
+ private DmaapHealth dmaapHealth;
+ @Resource
+ private CassandraHealthCheck cassandraHealthCheck;
+ @Autowired
+ private SwitchoverDetector switchoverDetector;
+ private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
+ private ScheduledFuture<?> scheduledFuture = null;
+
+ @PostConstruct
+ public void init() {
+
+ prevBeHealthCheckInfos = getBeHealthCheckInfos();
+
+ log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
+
+ healthCheckScheduledTask = new HealthCheckScheduledTask();
+
+ if (this.scheduledFuture == null) {
+ this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, SECONDS);
+ }
+
+ }
+
+ public boolean isDistributionEngineUp() {
+
+ HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
+ return !healthCheckInfo.getHealthCheckStatus().equals(DOWN);
+ }
+
+ public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() {
+ Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
+ return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos);
+ }
+
+ private List<HealthCheckInfo> getBeHealthCheckInfos() {
+
+ log.trace("In getBeHealthCheckInfos");
+
+ List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
+
+ //Dmaap
+ getDmaapHealthCheck(healthCheckInfos);
+ // BE
+ getBeHealthCheck(healthCheckInfos);
+
+ // Titan
+ getTitanHealthCheck(healthCheckInfos);
+ // ES
+ getEsHealthCheck(healthCheckInfos);
+
+ // Distribution Engine
+ getDistributionEngineCheck(healthCheckInfos);
+
+ //Cassandra
+ getCassandraHealthCheck(healthCheckInfos);
+
+ // Amdocs
+ getAmdocsHealthCheck(healthCheckInfos);
+
+ //DCAE
+ getDcaeHealthCheck(healthCheckInfos);
+
+ return healthCheckInfos;
+ }
+
+ private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+
+ // ES health check and version
+ String appVersion = getAppVersion();
+ HealthCheckStatus healthCheckStatus;
+ String description;
+
+ try {
+ healthCheckStatus = esHealthCheckDao.getClusterHealthStatus();
+ } catch (Exception e) {
+ healthCheckStatus = DOWN;
+ description = "ES cluster error: " + e.getMessage();
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description));
+ return healthCheckInfos;
+ }
+ if (healthCheckStatus.equals(DOWN)) {
+ description = "ES cluster is down";
+ } else {
+ description = "OK";
+ }
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ES, healthCheckStatus, appVersion, description));
+ return healthCheckInfos;
+ }
+
+ private List<HealthCheckInfo> getBeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ String appVersion = getAppVersion();
+ String description = "OK";
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, UP, appVersion, description));
+ return healthCheckInfos;
+ }
+
+ private List<HealthCheckInfo> getDmaapHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ String appVersion = getAppVersion();
+ dmaapHealth.getHealthCheckInfo().setVersion(appVersion);
+ healthCheckInfos.add(dmaapHealth.getHealthCheckInfo());
+ return healthCheckInfos;
+ }
+
+
+ public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ // Titan health check and version
+ String description;
+ boolean isTitanUp;
+
+ try {
+ isTitanUp = titanGenericDao.isGraphOpen();
+ } catch (Exception e) {
+ description = "Titan error: " + e.getMessage();
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description));
+ return healthCheckInfos;
+ }
+ if (isTitanUp) {
+ description = "OK";
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UP, null, description));
+ } else {
+ description = "Titan graph is down";
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, DOWN, null, description));
+ }
+ return healthCheckInfos;
+ }
+
+ private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+
+ String description;
+ boolean isCassandraUp;
+
+ try {
+ isCassandraUp = cassandraHealthCheck.getCassandraStatus();
+ } catch (Exception e) {
+ isCassandraUp = false;
+ log.debug("Cassandra error: " + e.getMessage());
+ }
+ if (isCassandraUp) {
+ description = "OK";
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UP, null, description));
+ } else {
+ description = "Cassandra is down";
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, description));
+ }
+ return healthCheckInfos;
+
+ }
+
+ private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) {
+
+ HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
+
+ healthCheckInfos.add(healthCheckInfo);
+
+ }
+
+ private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl());
+ healthCheckInfos.add(beHealthCheckInfo);
+ return healthCheckInfos;
+ }
+
+ private List<HealthCheckInfo> getDcaeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl());
+ healthCheckInfos.add(beHealthCheckInfo);
+ return healthCheckInfos;
+ }
+
+ private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) {
+ HealthCheckStatus healthCheckStatus;
+ String description;
+ String version = null;
+ List<HealthCheckInfo> componentsInfo = new ArrayList<>();
+ final int timeout = 3000;
+
+ if (healthCheckUrl != null) {
+ try {
+ HttpResponse<String> httpResponse = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(timeout, timeout)));
+ int statusCode = httpResponse.getStatusCode();
+ String aggDescription = "";
+
+ if (statusCode == SC_OK || statusCode == SC_INTERNAL_SERVER_ERROR) {
+ String response = httpResponse.getResponse();
+ log.trace("{} Health Check response: {}", componentName, response);
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> healthCheckMap = mapper.readValue(response, new TypeReference<Map<String, Object>>() {
+ });
+ version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null;
+ if (healthCheckMap.containsKey("componentsInfo")) {
+ componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {
+ });
+ }
+
+ if (!componentsInfo.isEmpty()) {
+ aggDescription = healthCheckUtil.getAggregateDescription(componentsInfo, null);
+ } else {
+ componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null));
+ }
+ } else {
+ log.trace("{} Health Check Response code: {}", componentName, statusCode);
+ }
+
+ if (statusCode != SC_OK) {
+ healthCheckStatus = DOWN;
+ description = aggDescription.length() > 0
+ ? aggDescription
+ : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN.
+ if (componentsInfo.isEmpty()) {
+ componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
+ }
+ } else {
+ healthCheckStatus = UP;
+ description = "OK";
+ }
+
+ } catch (Exception e) {
+ log.error("{} unexpected response: ", componentName, e);
+ healthCheckStatus = DOWN;
+ description = componentName + " unexpected response: " + e.getMessage();
+ if (componentsInfo != null && componentsInfo.isEmpty()) {
+ componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
+ }
+ }
+ } else {
+ healthCheckStatus = DOWN;
+ description = componentName + " health check Configuration is missing";
+ componentsInfo.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, description));
+ }
+
+ return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo);
+ }
+
+ @PreDestroy
+ protected void destroy() {
+
+ if (scheduledFuture != null) {
+ scheduledFuture.cancel(true);
+ scheduledFuture = null;
+ }
+
+ if (healthCheckScheduler != null) {
+ healthCheckScheduler.shutdown();
+ }
+
+ }
+
+ private void logAlarm(String componentChangedMsg) {
+ BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg);
+ }
+
+ public String getSiteMode() {
+ return switchoverDetector.getSiteMode();
+ }
+
+ public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
+
+ boolean result = false;
+
+ if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
+
+ Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
+ Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
+
+ if (currentValues != null && prevValues != null) {
+ int currentSize = currentValues.size();
+ int prevSize = prevValues.size();
+
+ if (currentSize != prevSize) {
+
+ result = true; //extra/missing component
+
+ Map<String, HealthCheckStatus> notPresent = null;
+ if (currentValues.keySet().containsAll(prevValues.keySet())) {
+ notPresent = new HashMap<>(currentValues);
+ notPresent.keySet().removeAll(prevValues.keySet());
+ } else {
+ notPresent = new HashMap<>(prevValues);
+ notPresent.keySet().removeAll(currentValues.keySet());
+ }
+
+ for (String component : notPresent.keySet()) {
+ logAlarm(format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
+ }
+
+ } else {
+
+ for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) {
+ String key = entry.getKey();
+ HealthCheckStatus value = entry.getValue();
+
+ if (!prevValues.containsKey(key)) {
+ result = true; //component missing
+ logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
+ break;
+ }
+
+ HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
+
+ if (value != prevHealthCheckStatus) {
+ result = true; //component status changed
+ logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
+ break;
+ }
+ }
+ }
+ }
+
+ } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
+ result = false;
+ } else {
+ logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
+ result = true;
+ }
+
+ return result;
+ }
+
+ private String buildOnBoardingHealthCheckUrl() {
+
+ Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
+
+ if (onboardingConfig != null) {
+ String protocol = onboardingConfig.getProtocol();
+ String host = onboardingConfig.getHost();
+ Integer port = onboardingConfig.getPort();
+ String uri = onboardingConfig.getHealthCheckUri();
+
+ return protocol + "://" + host + ":" + port + uri;
+ }
+
+ log.error("onboarding health check configuration is missing.");
+ return null;
+ }
+
+ private String buildDcaeHealthCheckUrl() {
+
+ Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae();
+
+ if (dcaeConfig != null) {
+ String protocol = dcaeConfig.getProtocol();
+ String host = dcaeConfig.getHost();
+ Integer port = dcaeConfig.getPort();
+ String uri = dcaeConfig.getHealthCheckUri();
+
+ return protocol + "://" + host + ":" + port + uri;
+ }
+
+ log.error("dcae health check configuration is missing.");
+ return null;
+ }
+
+ public class HealthCheckScheduledTask implements Runnable {
+
+ List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();
+
+ @Override
+ public void run() {
+ Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
+ healthLogger.trace("Executing BE Health Check Task");
+
+ List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
+ boolean healthStatus = healthCheckUtil.getAggregateStatus(currentBeHealthCheckInfos, config.getHealthStatusExclude());
+
+ boolean prevHealthStatus = healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude());
+
+ boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
+
+ if (prevHealthStatus != healthStatus || anyStatusChanged) {
+ log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
+
+ prevBeHealthCheckInfos = currentBeHealthCheckInfos;
+ logAlarm(healthStatus);
+ }
+
+ }
+
+ private void logAlarm(boolean prevHealthState) {
+ if (prevHealthState) {
+ BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR);
+ } else {
+ BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);
+ }
+ }
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java
new file mode 100644
index 0000000000..e0a8533052
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java
@@ -0,0 +1,42 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.be.model.Service;
+
+/**
+ * Created by chaya on 10/22/2017.
+ */
+public class ActivationRequestInformation {
+ private Service serviceToActivate;
+ private String workloadContext;
+ private String tenant;
+
+ public ActivationRequestInformation(Service serviceToActivate, String workloadContext, String tenant) {
+ this.serviceToActivate = serviceToActivate;
+ this.workloadContext = workloadContext;
+ this.tenant = tenant;
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public void setTenant(String tenant) {
+ this.tenant = tenant;
+ }
+
+ public Service getServiceToActivate() {
+ return serviceToActivate;
+ }
+
+ public void setServiceToActivate(Service serviceToActivate) {
+ this.serviceToActivate = serviceToActivate;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
index 51b5679ffa..50331a71d3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
@@ -20,10 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -52,514 +49,506 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.List;
@Component("additionalInformationBusinessLogic")
public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
- private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation";
-
- private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation";
-
- private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation";
-
- private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation";
-
- private static Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class.getName());
-
- @javax.annotation.Resource
- private IAdditionalInformationOperation additionalInformationOperation = null;
-
- @javax.annotation.Resource
- private IGraphLockOperation graphLockOperation;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
- protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-
- return webApplicationContext.getBean(class1);
- }
-
- /**
- * Create new additional information on resource/service on graph
- *
- * @param resourceId
- * @param propertyName
- * @param newPropertyDefinition
- * @param userId
- * @return Either<PropertyDefinition, ActionStatus>
- */
- public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
- ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
-
- // lock component
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, CREATE_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
- log.info("Failed to lock component {} error - {}", resourceId, lockResult);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
- }
- try {
- responseFormat = validateMaxSizeNotReached(nodeType, resourceId, additionalInfoParameterInfo);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
-
- // validate label
- responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
-
- // validate value
- responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(),
- additionalInfoParameterInfo.getValue(), true);
-
- if (addResult.isRight()) {
- StorageOperationStatus status = addResult.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, CREATE_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label));
- return result;
-
- } else {
- AdditionalInformationDefinition informationDefinition = addResult.left().value();
-
- AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
- result = Either.left(createdAI);
- return result;
- }
-
- } finally {
- commitOrRollback(result);
- // unlock component
- graphLockOperation.unlockComponent(resourceId, nodeType);
- }
-
- }
-
- /**
- * Validate the value format. Format the value.
- *
- * @param additionalInfoParameterInfo
- * @return null in case of success. Otherwise response format.
- */
- private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
- ResponseFormat result = null;
-
- String value = additionalInfoParameterInfo.getValue();
- log.debug("Going to validate additional information value {}", value);
-
- Either<String, ResponseFormat> valueValidRes = validateValue(value);
- if (valueValidRes.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidValueError, context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
- BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
- result = valueValidRes.right().value();
- } else {
- String newValue = valueValidRes.left().value();
- if (log.isTraceEnabled()) {
- if (value != null && false == value.equals(newValue)) {
- log.trace("The additional information value was normalized from {} to {}", value, newValue);
- }
- }
- additionalInfoParameterInfo.setValue(newValue);
- }
- return result;
- }
-
- /**
- * @param additionalInfoParameterInfo
- * @return
- */
- private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
-
- String key = additionalInfoParameterInfo.getKey();
- log.debug("Going to validate additional information key {}", key);
-
- ResponseFormat result = null;
- ResponseFormat responseFormat;
- Either<String, ResponseFormat> validateKeyRes = validateAndNormalizeKey(key);
- if (validateKeyRes.isRight()) {
- responseFormat = validateKeyRes.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidValueError, context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
- BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
- result = responseFormat;
-
- } else {
- String convertedKey = validateKeyRes.left().value();
-
- if (log.isTraceEnabled()) {
- if (key != null && false == key.equals(convertedKey)) {
- log.trace("The additional information key {} was normalized to {}", key, convertedKey);
- }
- }
- additionalInfoParameterInfo.setKey(convertedKey);
- }
- return result;
- }
-
- /**
- * verify that the maximal number of additional information properties has not been reached.
- *
- * @param nodeType
- * @param componentId
- * @param additionalInfoParameterInfo
- * @return response format in case the maximal number has been reached.
- */
- private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) {
-
- ResponseFormat result;
- Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys();
-
- Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true);
- if (checkRes.isRight()) {
- StorageOperationStatus status = checkRes.right().value();
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
- return result;
- }
- Integer currentNumberOfProperties = checkRes.left().value();
- if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) {
- log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties);
- result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
- return result;
- }
-
- return null;
- }
-
- /**
- * validate additional information value
- *
- * @param value
- * @return
- */
- private Either<String, ResponseFormat> validateValue(String value) {
-
- boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value);
- if (false == isNonEmptyString) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED));
- }
-
- boolean valid = StringValidator.getInstance().isValid(value, null);
- if (false == valid) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
- }
-
- String converted = StringConvertor.getInstance().convert(value, null, null);
-
- return Either.left(converted);
- }
-
- private AdditionalInfoParameterInfo findAdditionInformationKey(List<AdditionalInfoParameterInfo> parameters, String key) {
-
- for (AdditionalInfoParameterInfo infoParameterInfo : parameters) {
- if (infoParameterInfo.getKey().equals(key)) {
- return infoParameterInfo;
- }
- }
- return null;
- }
-
- /**
- * validate and normalize the key
- *
- * @param additionalInfoParameterInfo
- * @return
- */
- private Either<String, ResponseFormat> validateAndNormalizeKey(String key) {
-
- AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
- additionalInfoParameterInfo.setKey(key);
-
- key = ValidationUtils.normalizeAdditionalInformation(key);
- boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key);
- if (false == isNonEmptyString) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label));
- }
- boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key);
- if (false == isValidString) {
- if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) {
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
- }
- return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
- }
-
- return Either.left(key);
- }
-
- /**
- * update key and value of a given additional information.
- *
- * @param nodeType
- * @param resourceId
- * @param additionalInfoParameterInfo
- * @param additionalInformationUid
- * - Future use
- * @param userId
- * @return
- */
- public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
- ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
- // lock component
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, UPDATE_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
- log.info("Failed to lock component {} error - {}", resourceId, lockResult);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
- }
- try {
-
- // validate input
- responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
-
- responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
- if (responseFormat != null) {
- result = Either.right(responseFormat);
- return result;
- }
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(),
- additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true);
-
- if (addResult.isRight()) {
- StorageOperationStatus status = addResult.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, UPDATE_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
- return result;
- } else {
- AdditionalInformationDefinition informationDefinition = addResult.left().value();
- AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
- result = Either.left(parameterInfo);
- return result;
- }
-
- } finally {
- commitOrRollback(result);
- // unlock component
- graphLockOperation.unlockComponent(resourceId, nodeType);
- }
-
- }
-
- /**
- * Delete an additional information label
- *
- * @param nodeType
- * @param resourceId
- * @param additionalInfoParameterInfo
- * @param additionalInformationUid
- * - Null. Future use.
- * @param userId
- * @return
- */
- public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
- ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
- if (responseFormat != null) {
- return Either.right(responseFormat);
- }
- // lock component
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, DELETE_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
- log.info("Failed to lock component {} error - {}", resourceId, lockResult);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
- }
-
- try {
-
- Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
- if (findIdRes.isRight()) {
- StorageOperationStatus status = findIdRes.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, GET_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION);
- }
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
- return result;
- }
-
- AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
-
- if (addResult.isRight()) {
- StorageOperationStatus status = addResult.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, DELETE_ADDITIONAL_INFORMATION);
- BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
- return result;
- } else {
- result = Either.left(foundAdditionalInfo);
- return result;
- }
-
- } finally {
- commitOrRollback(result);
- // unlock component
- graphLockOperation.unlockComponent(resourceId, nodeType);
- }
-
- }
-
- /**
- * @param nodeType
- * @param resourceId
- * @param additionalInfoParameterInfo
- * @param additionalInformationUid
- * @param userId
- * @return
- */
- public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
- try {
-
- Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
-
- if (findIdRes.isRight()) {
- StorageOperationStatus status = findIdRes.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
- }
-
- AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
-
- result = Either.left(foundAdditionalInfo);
-
- return result;
-
- } finally {
- commitOrRollback(result);
- }
-
- }
-
- /**
- * Get all additional information properties of a given resource/service
- *
- * @param nodeType
- * @param resourceId
- * @param additionalInformationUid
- * - Future use
- * @param userId
- * @return
- */
- public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Additional Information", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<AdditionalInformationDefinition, ResponseFormat> result = null;
-
- try {
-
- Either<AdditionalInformationDefinition, TitanOperationStatus> findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false);
- if (findIdRes.isRight()) {
- StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value());
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
- result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus));
- } else {
- AdditionalInformationDefinition informationDefinition = findIdRes.left().value();
- result = Either.left(informationDefinition);
- }
-
- return result;
-
- } finally {
- commitOrRollback(result);
- }
-
- }
-
- private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) {
-
- switch (nodeType) {
- case Resource:
-
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
- return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- }
- break;
- case Service:
-
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
- return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- }
- break;
- default:
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName());
- }
-
- return null;
- }
+ private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation";
+
+ private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation";
+
+ private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation";
+
+ private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation";
+
+ private static final Logger log = LoggerFactory.getLogger(AdditionalInformationBusinessLogic.class);
+
+ @javax.annotation.Resource
+ private IAdditionalInformationOperation additionalInformationOperation = null;
+
+ @javax.annotation.Resource
+ private IGraphLockOperation graphLockOperation;
+
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
+
+ protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+
+ return webApplicationContext.getBean(class1);
+ }
+
+ /**
+ * Create new additional information on resource/service on graph
+ *
+ * @param resourceId
+ * @param propertyName
+ * @param newPropertyDefinition
+ * @param userId
+ * @return Either<PropertyDefinition, ActionStatus>
+ */
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
+
+ ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ // lock component
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
+ log.info("Failed to lock component {} error - {}", resourceId, lockResult);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+ try {
+ responseFormat = validateMaxSizeNotReached(nodeType, resourceId, additionalInfoParameterInfo);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ // validate label
+ responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ // validate value
+ responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(),
+ additionalInfoParameterInfo.getValue(), true);
+
+ if (addResult.isRight()) {
+ StorageOperationStatus status = addResult.right().value();
+ BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label));
+ return result;
+
+ } else {
+ AdditionalInformationDefinition informationDefinition = addResult.left().value();
+
+ AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
+ result = Either.left(createdAI);
+ return result;
+ }
+
+ } finally {
+ commitOrRollback(result);
+ // unlock component
+ graphLockOperation.unlockComponent(resourceId, nodeType);
+ }
+
+ }
+
+ /**
+ * Validate the value format. Format the value.
+ *
+ * @param additionalInfoParameterInfo
+ * @return null in case of success. Otherwise response format.
+ */
+ private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
+ ResponseFormat result = null;
+
+ String value = additionalInfoParameterInfo.getValue();
+ log.debug("Going to validate additional information value {}", value);
+
+ Either<String, ResponseFormat> valueValidRes = validateValue(value);
+ if (valueValidRes.isRight()) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
+ result = valueValidRes.right().value();
+ } else {
+ String newValue = valueValidRes.left().value();
+ if (log.isTraceEnabled()) {
+ if (value != null && false == value.equals(newValue)) {
+ log.trace("The additional information value was normalized from {} to {}", value, newValue);
+ }
+ }
+ additionalInfoParameterInfo.setValue(newValue);
+ }
+ return result;
+ }
+
+ /**
+ * @param additionalInfoParameterInfo
+ * @return
+ */
+ private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
+
+ String key = additionalInfoParameterInfo.getKey();
+ log.debug("Going to validate additional information key {}", key);
+
+ ResponseFormat result = null;
+ ResponseFormat responseFormat;
+ Either<String, ResponseFormat> validateKeyRes = validateAndNormalizeKey(key);
+ if (validateKeyRes.isRight()) {
+ responseFormat = validateKeyRes.right().value();
+ BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
+ result = responseFormat;
+
+ } else {
+ String convertedKey = validateKeyRes.left().value();
+
+ if (log.isTraceEnabled()) {
+ if (key != null && false == key.equals(convertedKey)) {
+ log.trace("The additional information key {} was normalized to {}", key, convertedKey);
+ }
+ }
+ additionalInfoParameterInfo.setKey(convertedKey);
+ }
+ return result;
+ }
+
+ /**
+ * verify that the maximal number of additional information properties has not been reached.
+ *
+ * @param nodeType
+ * @param componentId
+ * @param additionalInfoParameterInfo
+ * @return response format in case the maximal number has been reached.
+ */
+ private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) {
+
+ ResponseFormat result;
+ Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys();
+
+ Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true);
+ if (checkRes.isRight()) {
+ StorageOperationStatus status = checkRes.right().value();
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
+ return result;
+ }
+ Integer currentNumberOfProperties = checkRes.left().value();
+ if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) {
+ log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties);
+ result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
+ return result;
+ }
+
+ return null;
+ }
+
+ /**
+ * validate additional information value
+ *
+ * @param value
+ * @return
+ */
+ private Either<String, ResponseFormat> validateValue(String value) {
+
+ boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value);
+ if (false == isNonEmptyString) {
+ return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED));
+ }
+
+ boolean valid = StringValidator.getInstance().isValid(value, null);
+ if (false == valid) {
+ return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
+ }
+
+ String converted = StringConvertor.getInstance().convert(value, null, null);
+
+ return Either.left(converted);
+ }
+
+ private AdditionalInfoParameterInfo findAdditionInformationKey(List<AdditionalInfoParameterInfo> parameters, String key) {
+
+ for (AdditionalInfoParameterInfo infoParameterInfo : parameters) {
+ if (infoParameterInfo.getKey().equals(key)) {
+ return infoParameterInfo;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * validate and normalize the key
+ *
+ * @param additionalInfoParameterInfo
+ * @return
+ */
+ private Either<String, ResponseFormat> validateAndNormalizeKey(String key) {
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
+ additionalInfoParameterInfo.setKey(key);
+
+ key = ValidationUtils.normalizeAdditionalInformation(key);
+ boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(key);
+ if (false == isNonEmptyString) {
+ return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label));
+ }
+ boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(key);
+ if (false == isValidString) {
+ if (false == ValidationUtils.validateLength(key, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) {
+ return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
+ }
+ return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
+ }
+
+ return Either.left(key);
+ }
+
+ /**
+ * update key and value of a given additional information.
+ *
+ * @param nodeType
+ * @param resourceId
+ * @param additionalInfoParameterInfo
+ * @param additionalInformationUid
+ * - Future use
+ * @param userId
+ * @return
+ */
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Additional Information", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
+
+ ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+ // lock component
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
+ log.info("Failed to lock component {} error - {}", resourceId, lockResult);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+ try {
+
+ // validate input
+ responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
+ if (responseFormat != null) {
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(),
+ additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true);
+
+ if (addResult.isRight()) {
+ StorageOperationStatus status = addResult.right().value();
+ BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ return result;
+ } else {
+ AdditionalInformationDefinition informationDefinition = addResult.left().value();
+ AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
+ result = Either.left(parameterInfo);
+ return result;
+ }
+
+ } finally {
+ commitOrRollback(result);
+ // unlock component
+ graphLockOperation.unlockComponent(resourceId, nodeType);
+ }
+
+ }
+
+ /**
+ * Delete an additional information label
+ *
+ * @param nodeType
+ * @param resourceId
+ * @param additionalInfoParameterInfo
+ * @param additionalInformationUid
+ * - Null. Future use.
+ * @param userId
+ * @return
+ */
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Additional Information", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
+
+ ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
+ if (responseFormat != null) {
+ return Either.right(responseFormat);
+ }
+ // lock component
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ADDITIONAL_INFORMATION, nodeType.getName(), resourceId);
+ log.info("Failed to lock component {} error - {}", resourceId, lockResult);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+
+ try {
+
+ Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
+ if (findIdRes.isRight()) {
+ StorageOperationStatus status = findIdRes.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION);
+ }
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ return result;
+ }
+
+ AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
+
+ Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
+
+ if (addResult.isRight()) {
+ StorageOperationStatus status = addResult.right().value();
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ return result;
+ } else {
+ result = Either.left(foundAdditionalInfo);
+ return result;
+ }
+
+ } finally {
+ commitOrRollback(result);
+ // unlock component
+ graphLockOperation.unlockComponent(resourceId, nodeType);
+ }
+
+ }
+
+ /**
+ * @param nodeType
+ * @param resourceId
+ * @param additionalInfoParameterInfo
+ * @param additionalInformationUid
+ * @param userId
+ * @return
+ */
+ public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String additionalInformationUid, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Additional Information", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
+
+ try {
+
+ Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
+
+ if (findIdRes.isRight()) {
+ StorageOperationStatus status = findIdRes.right().value();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+ }
+
+ AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
+
+ result = Either.left(foundAdditionalInfo);
+
+ return result;
+
+ } finally {
+ commitOrRollback(result);
+ }
+
+ }
+
+ /**
+ * Get all additional information properties of a given resource/service
+ *
+ * @param nodeType
+ * @param resourceId
+ * @param additionalInformationUid
+ * - Future use
+ * @param userId
+ * @return
+ */
+ public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String additionalInformationUid, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Additional Information", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<AdditionalInformationDefinition, ResponseFormat> result = null;
+
+ try {
+
+ Either<AdditionalInformationDefinition, TitanOperationStatus> findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false);
+ if (findIdRes.isRight()) {
+ StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(findIdRes.right().value());
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
+ result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus));
+ } else {
+ AdditionalInformationDefinition informationDefinition = findIdRes.left().value();
+ result = Either.left(informationDefinition);
+ }
+
+ return result;
+
+ } finally {
+ commitOrRollback(result);
+ }
+
+ }
+
+ private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) {
+
+ switch (nodeType) {
+ case Resource:
+
+ // verify that resource is checked-out and the user is the last
+ // updater
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
+ return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ }
+ break;
+ case Service:
+
+ // verify that resource is checked-out and the user is the last
+ // updater
+ if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
+ return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ }
+ break;
+ default:
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName());
+ }
+
+ return null;
+ }
}
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
index 1c5a35453b..fcaf5cdfc6 100644
--- 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
@@ -20,12 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
import org.openecomp.sdc.be.components.ArtifactsResolver;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -34,6 +29,7 @@ import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Service;
+import java.util.*;
@org.springframework.stereotype.Component("artifact-resolver")
public class ArtifactResolverImpl implements ArtifactsResolver {
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 bd7f61444d..39ad806cda 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,25 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.EnumMap;
-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.function.Predicate;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import javax.servlet.http.HttpServletRequest;
-
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
@@ -60,25 +45,12 @@ import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
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.info.ArtifactTemplateInfo;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
@@ -92,6 +64,7 @@ import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.ToscaError;
@@ -119,3521 +92,3718 @@ import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.yaml.snakeyaml.Yaml;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
+import javax.servlet.http.HttpServletRequest;
+import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
-
-import fj.data.Either;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.EnumMap;
+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.function.Predicate;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("artifactBusinessLogic")
public class ArtifactsBusinessLogic extends BaseBusinessLogic {
- private static final String ARTIFACT_TYPE_OTHER = "OTHER";
- private static final String ARTIFACT_DESCRIPTION = "artifact description";
- private static final String ARTIFACT_LABEL = "artifact label";
- private static final String ARTIFACT_URL = "artifact url";
- private static final String ARTIFACT_NAME = "artifact name";
- private static final String ARTIFACT_PAYLOAD = "artifact payload";
-
- private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
- private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
- private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
-
- public static final String HEAT_ENV_NAME = "heatEnv";
- public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
- public static final String HEAT_ENV_SUFFIX = "env";
- private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
-
- // private static Integer defaultHeatTimeout;
- // private static final Integer NON_HEAT_TIMEOUT = 0;
- private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
- private Gson gson = new GsonBuilder().setPrettyPrinting().create();
- private static XMLReader parser;
- @javax.annotation.Resource
- private IInterfaceLifecycleOperation interfaceLifecycleOperation;
- @javax.annotation.Resource
- private IUserAdminOperation userOperaton;
-
- @javax.annotation.Resource
- private IElementOperation elementOperation;
-
- @javax.annotation.Resource
- private ResourceBusinessLogic resourceBusinessLogic;
-
- @javax.annotation.Resource
- private ServiceBusinessLogic serviceBusinessLogic;
-
- @javax.annotation.Resource
- private UserBusinessLogic userAdminManager;
-
- @javax.annotation.Resource
- private IHeatParametersOperation heatParametersOperation;
-
- @Autowired
- private ArtifactCassandraDao artifactCassandraDao;
-
- @Autowired
- private ToscaExportHandler toscaExportUtils;
-
- @Autowired
- private CsarUtils csarUtils;
-
- @Autowired
- private LifecycleBusinessLogic lifecycleBusinessLogic;
-
- @Autowired
- private IUserBusinessLogic userBusinessLogic;
- @Autowired
- NodeTemplateOperation nodeTemplateOperation;
-
- @Autowired
- private ArtifactsResolver artifactsResolver;
-
- public ArtifactsBusinessLogic() {
- // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
- // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
- // defaultHeatTimeout = 60;
- // }
- }
-
- public static enum ArtifactOperationEnum {
- Create(), Update(), Delete(), Download(), Link();
-
- public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
- return (operation.equals(Create) || operation.equals(Link));
-
- }
- }
-
- //SAX XML Parser initialization
- static {
- SAXParserFactory spf = SAXParserFactory.newInstance();
- SAXParser newSAXParser = null;
-
- try {
- newSAXParser = spf.newSAXParser();
- parser = newSAXParser.getXMLReader();
- } catch (ParserConfigurationException | SAXException e1) {
- log.debug("SAX XML Parser could not been initialized", e1);
- }
-
- try {
- parser.setFeature("http://apache.org/xml/features/validation/schema", false);
- } catch (SAXNotRecognizedException e) {
- log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
-
- } catch (SAXNotSupportedException e) {
- log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
-
- }
- }
-
- public class ArtifactOperationInfo {
-
- private ArtifactOperationEnum artifactOperationEnum;
- private boolean isExternalApi;
- private boolean ignoreLifecycleState;
-
- public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
- this.artifactOperationEnum = artifactOperationEnum;
- this.isExternalApi = isExternalApi;
- this.ignoreLifecycleState = ignoreLifecycleState;
- }
-
- public boolean isExternalApi() {
- return isExternalApi;
- }
-
- public boolean ignoreLifecycleState() {
- return ignoreLifecycleState;
- }
-
- public ArtifactOperationEnum getArtifactOperationEnum() {
- return artifactOperationEnum;
- }
-
- }
-
- // new flow US556184
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
- String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
- return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
- String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
-
- // step 1 - detect auditing type
- AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
- // step 2 - check header
- if (userId == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
- handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- // step 3 - check user existence
- Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
- if (userResult.isRight()) {
- return Either.right(userResult.right().value());
- }
-
- // step 4 - check user's role
- User user = userResult.left().value();
- Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
- if (validateUserRole.isRight()) {
- return Either.right(validateUserRole.right().value());
- }
-
- // steps 5 - 6 - 7
- // 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;
- // ComponentInstance resourceInstance = null;
- String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
- if (validateComponent.isRight()) {
- return Either.right(validateComponent.right().value());
- }
- component = validateComponent.left().value();
- Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
- if (validateWorkOnResource.isRight()) {
- return Either.right(validateWorkOnResource.right().value());
- }
- // step 8
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
- shouldLock, inTransaction, true);
-
- return result;
- }
-
- /**
- * This Method validates only the Artifact and does not validate user / role / component ect...<br>
- * For regular usage use <br>
- * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
- *
- * @return
- */
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
- ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
- Component parent = component;
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-
- AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
- artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
- if (errorWrapper.isEmpty()) {
- // step 10
- result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
- } else {
- result = Either.right(errorWrapper.getInnerElement());
- }
- return result;
- }
-
- private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
- org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
- if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
- Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
- if (validateArtifact.isRight()) {
- ResponseFormat responseFormat = validateArtifact.right().value();
- handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- errorWrapper.setInnerElement(validateArtifact.right().value());
- } else {
- if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
- artifactInfo = validateArtifact.left().value();
- handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
- }
- }
- }
- return artifactInfo;
- }
-
- private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
- Wrapper<ResponseFormat> errorWrapper) {
- ArtifactDefinition validatedArtifact = validateArtifact.left().value();
-
- if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
- if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
- ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
- Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
-
- ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
- Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
- if (eitherGenerated.isRight()) {
- errorWrapper.setInnerElement(eitherGenerated.right().value());
- }
- }
- }
- }
-
- private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
- boolean needGenerate;
- needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
- return needGenerate;
- }
-
- private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
- return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
- boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
- if (generated.isRight()) {
- return generated;
- }
- byte[] decodedPayload = artifactDefinition.getPayloadData();
- artifactDefinition.setEsId(artifactDefinition.getUniqueId());
- artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
- return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
- shouldLock, inTransaction);
-
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
- log.debug("tosca artifact generation");
- if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
- Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
-
- if (generated.isRight()) {
- log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
-
- return Either.right(generated.right().value());
- }
- byte[] value = generated.left().value();
- artifactInfo.setPayload(value);
-
- } else {
- Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
- if (exportComponent.isRight()) {
- log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
- ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
- return Either.right(responseFormat);
- }
- log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
- String payload = exportComponent.left().value().getMainYaml();
- artifactInfo.setPayloadData(payload);
- }
- return Either.left(Either.left(artifactInfo));
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
- String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
- if (interfaceName != null && operationName != null) {
- interfaceName = interfaceName.toLowerCase();
- operationName = operationName.toLowerCase();
- }
- switch (operation.getArtifactOperationEnum()) {
- case Download:
- if (artifactGenerationRequired(parent, artifactInfo)) {
- return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
- }
- return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
- case Delete:
- return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
- case Update:
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
- if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
- && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
- result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
- if (needUpdateGroup && result.isLeft()) {
- Either<ArtifactDefinition, Operation> updateResult = result.left().value();
- ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
- if (error != ActionStatus.OK) {
- result = Either.right(componentsUtils.getResponseFormat(error));
- }
- }
- } else {
- if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
- result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
- }
- }
- if (result == null) {
- result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
- if (needUpdateGroup && result.isLeft()) {
- Either<ArtifactDefinition, Operation> updateResult = result.left().value();
-
- ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
- if (error != ActionStatus.OK) {
- result = Either.right(componentsUtils.getResponseFormat(error));
- }
- }
- }
- return result;
- case Create:
- return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
- case Link:
- return handleLink(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
- }
- return null;
- }
-
- private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
- List<GroupDefinition> groups = parent.getGroups();
- if (groups != null && !groups.isEmpty()) {
- List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
- if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
- groupToUpdate.forEach(g -> {
- g.getArtifacts().remove(artifactInfo.getUniqueId());
- g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
- g.getArtifacts().add(artAfterUpdate.getUniqueId());
- g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
- });
- Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
- if (status.isRight()) {
- log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
- return componentsUtils.convertFromStorageResponse(status.right().value());
- }
- }
- }
- return ActionStatus.OK;
- }
-
- private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
- List<GroupDefinition> groups = parent.getGroups();
- if (groups != null && !groups.isEmpty()) {
- List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
- if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
- groupToUpdate.forEach(g -> {
- g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
- g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
- g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
- g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
- g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
- g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
- });
- Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
- if (status.isRight()) {
- log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
- return componentsUtils.convertFromStorageResponse(status.right().value());
- }
- }
- }
- return ActionStatus.OK;
- }
-
- private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
- List<GroupInstance> updatedGroupInstances = new ArrayList<>();
- List<GroupInstance> groupInstances = null;
- Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
- if (componentInstOp.isPresent()) {
- groupInstances = componentInstOp.get().getGroupInstances();
- }
- if (CollectionUtils.isNotEmpty(groupInstances)) {
- boolean isUpdated = false;
- for (GroupInstance groupInstance : groupInstances) {
- isUpdated = false;
- if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
- groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
- groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
- isUpdated = true;
- }
- if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
- groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
- groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
- isUpdated = true;
- }
- if (isUpdated) {
- updatedGroupInstances.add(groupInstance);
- }
- }
- }
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
- if (status.isRight()) {
- log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
- return componentsUtils.convertFromStorageResponse(status.right().value());
- }
- return ActionStatus.OK;
- }
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
- if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
- result = generateToscaArtifact(parent, artifactInfo, false, false);
- } else {
- String heatArtifactId = artifactInfo.getGeneratedFromId();
- Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
- if (heatRes.isRight()) {
- log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
- return Either.right(responseFormat);
- }
- String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
- artifactInfo.setPayloadData(generatedPayload);
- result = Either.left(Either.left(artifactInfo));
- }
- return result;
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
- ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
- convertParentType(componentType);
- String parentId = parent.getUniqueId();
- Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
- ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
-
- if (origMd5 != null) {
- Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
- if (validateMd5.isRight()) {
- ResponseFormat responseFormat = validateMd5.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
-
- if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
-
- Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
- if (payloadEither.isRight()) {
- ResponseFormat responseFormat = payloadEither.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- } else { // duplicate
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- }
-
- // lock resource
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
- return Either.right(lockComponent.right().value());
- }
- }
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- try {
- resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
- return resultOp;
-
- } finally {
- // unlock resource
- if (resultOp == null || resultOp.isRight()) {
- log.debug("all changes rollback");
- if (false == inTransaction)
- titanDao.rollback();
- } else {
- log.debug("all changes committed");
- if (false == inTransaction)
- titanDao.commit();
- }
- if (shouldLock)
- componentType = parent.getComponentType();
- NodeTypeEnum nodeType = componentType.getNodeType();
- graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
- // graphLockOperation.unlockComponent(parentId, parentType);
- }
- }
-
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
- if (artifactGenerationRequired(component, csarArtifact)) {
- Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
-
- if (generated.isRight()) {
- log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
-
- return Either.right(generated.right().value());
- }
- return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
- }
- return downloadArtifact(csarArtifact, component);
- }
-
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
- // perform all validation in common flow
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
- null, parentId, containerComponentType);
- if (result.isRight()) {
- return Either.right(result.right().value());
- }
- ArtifactDefinition artifactDefinition;
- Either<ArtifactDefinition, Operation> insideValue = result.left().value();
- if (insideValue.isLeft()) {
- artifactDefinition = insideValue.left().value();
- } else {
- artifactDefinition = insideValue.right().value().getImplementationArtifact();
- }
- // for tosca artifacts and heat env on VF level generated on download without saving
- if (artifactDefinition.getPayloadData() != null) {
- return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
- }
- return downloadArtifact(artifactDefinition, null);
- }
-
- public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
- // step 1
- // detect auditing type
- Map<String, ArtifactDefinition> resMap = null;
- Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
-
- new Wrapper<>();
- // step 2
- // check header
- if (userId == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
-
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- // step 3
- // check user existence
- // step 4
- // check user's role
-
- Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
- if (userResult.isRight()) {
-
- resultOp = Either.right(userResult.right().value());
- return resultOp;
- }
-
- userResult.left().value();
-
- // steps 5 - 6 - 7
- // 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;
- // ComponentInstance resourceInstance = null;
- String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
- ComponentParametersView componentFilter = new ComponentParametersView();
- componentFilter.disableAll();
- componentFilter.setIgnoreArtifacts(false);
- if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
- componentFilter.setIgnoreComponentInstances(false);
-
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
-
- if (validateComponent.isRight()) {
- resultOp = Either.right(validateComponent.right().value());
- return resultOp;
- }
- component = validateComponent.left().value();
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
- if (lockComponent.isRight()) {
-
- resultOp = Either.right(lockComponent.right().value());
- return resultOp;
- }
-
- try {
- ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
-
- if (groupType == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
-
- resultOp = Either.right(responseFormat);
- return resultOp;
-
- }
- if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
- List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
- if (list != null && !list.isEmpty()) {
- resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
- } else {
- resMap = new HashMap<>();
- }
- resultOp = Either.left(resMap);
- return resultOp;
- } else {
-
- Either<Map<String, ArtifactDefinition>, 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 {
- resMap = new HashMap<>();
- resultOp = Either.left(resMap);
- }
- } else {
- resMap = artifactsMapStatus.left().value();
- resultOp = Either.left(resMap);
- }
- return resultOp;
- }
- } finally {
- // unlock resource
- if (resultOp == null || resultOp.isRight()) {
- log.debug("all changes rollback");
- titanDao.rollback();
- } else {
- log.debug("all changes committed");
-
- titanDao.commit();
- }
-
- componentType = component.getComponentType();
- NodeTypeEnum nodeType = componentType.getNodeType();
- graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
- // graphLockOperation.unlockComponent(parentId, parentType);
- }
-
- }
-
- private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
- boolean inTransaction) {
- // step 9
- // check artifact existence
- Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
- if (artifactResult.isRight()) {
- if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
- log.debug("addArtifact - artifact {} not found", artifactId);
- return Either.right(responseFormat);
-
- } else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
- log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
- return Either.right(responseFormat);
- }
- }
- // step 9.1
- // check artifact belong to component
- boolean found = false;
- switch (componentType) {
- case RESOURCE:
- case SERVICE:
- found = checkArtifactInComponent(component, artifactId);
- break;
- case RESOURCE_INSTANCE:
- found = checkArtifactInResourceInstance(component, componentId, artifactId);
- break;
- default:
-
- }
- if (!found) {
- // String component =
- // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
- // "service";
- String componentName = componentType.name().toLowerCase();
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
- log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
- return Either.right(responseFormat);
- }
- return Either.left(artifactResult.left().value());
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
- org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
-
- String artifactId = null;
-
- // step 11
- Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
- if (payloadEither.isRight()) {
- return Either.right(payloadEither.right().value());
- }
- byte[] decodedPayload = payloadEither.left().value();
- convertParentType(componentType);
-
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
- return Either.right(lockComponent.right().value());
- }
- }
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
-
- try {
- resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
- return resultOp;
- } finally {
- if (shouldLock) {
- unlockComponent(resultOp, parent, inTransaction);
- }
-
- }
-
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
- org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
-
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
- return Either.right(lockComponent.right().value());
- }
- }
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
-
- try {
- resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
- return resultOp;
- } finally {
- if (shouldLock) {
- unlockComponent(resultOp, parent, inTransaction);
- }
-
- }
-
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
- ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
-
- convertParentType(componentType);
-
- // lock resource
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
-
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
- return Either.right(lockComponent.right().value());
- }
- }
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- try {
- resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
- return resultOp;
-
- } finally {
- if (shouldLock) {
- unlockComponent(resultOp, parent, inTransaction);
- }
- }
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
- ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
-
- Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
-
- if (payloadEither.isRight()) {
- return Either.right(payloadEither.right().value());
- }
- byte[] decodedPayload = payloadEither.left().value();
-
- return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
- }
-
- private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
- org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
- // Md5 validations
- Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
- if (validateMd5.isRight()) {
- ResponseFormat responseFormat = validateMd5.right().value();
- handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
-
- // step 11
- Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
- if (validateResult.isRight()) {
- ResponseFormat responseFormat = validateResult.right().value();
- handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(validateResult.right().value());
- }
-
- Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
- if (payloadEither.isRight()) {
- ResponseFormat responseFormat = payloadEither.right().value();
- handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- log.debug("Error during handle payload");
- return Either.right(responseFormat);
- }
-
- // validate heat parameters. this part must be after the parameters are
- // extracted in "handlePayload"
- Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
- if (validateAndConvertHeatParamers.isRight()) {
- ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
- handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
- log.debug("Error during handle payload");
- return Either.right(responseFormat);
- }
- return payloadEither;
- }
-
- public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
- ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
-
- if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
- return;
- }
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
-
- if (user == null) {
- user = new User();
- user.setUserId("UNKNOWN");
- }
- switch (componentTypeEnum) {
-
- case RESOURCE:
- Resource resource = (Resource) component;
- if (resource == null) {
- // In that case, component ID should be instead of name
- resource = new Resource();
- resource.setName(componentId);
- }
- componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
- break;
-
- case SERVICE:
- Service service = (Service) component;
- if (service == null) {
- // In that case, component ID should be instead of name
- service = new Service();
- service.setName(componentId);
- }
- componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
- break;
-
- case RESOURCE_INSTANCE:
- if (resourceInstanceName == null) {
- resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
-
- break;
- default:
- break;
- }
- }
-
- private String getResourceInstanceNameFromComponent(Component component, String componentId) {
- ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
- String resourceInstanceName = null;
- if (resourceInstance != null) {
- resourceInstanceName = resourceInstance.getName();
- }
- return resourceInstanceName;
- }
-
- public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- // Putting together artifact info
- String artifactData = buildAuditingArtifactData(artifactDefinition);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
- return auditingFields;
- }
-
- // -----
-
- private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
- StringBuilder sb = new StringBuilder();
- if (artifactDefinition != null) {
- sb.append(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();
- }
-
- private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
-
- if (origMd5 != null) {
- String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
-
- if (false == encodeBase64Str.equals(origMd5)) {
- log.debug("The calculated md5 is different then the received one");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
- }
- } else {
- if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
- if (payload!=null && payload.length != 0) {
- log.debug("Missing md5 header during artifact create");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
- }
- }
- // Update metadata
- if (payload != null && payload.length != 0) {
- log.debug("Cannot have payload while md5 header is missing");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- }
- return Either.left(true);
- }
-
- private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
- ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
-
- Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
- if (artifactById.isRight()) {
- return Either.right(artifactById.right().value());
- }
- ArtifactDefinition currentArtifactInfo = artifactById.left().value();
-
- ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
- Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
- if (validateInformationalArtifactRes.isRight()) {
- return Either.right(validateInformationalArtifactRes.right().value());
- }
- Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
- if (validateAndSetArtifactname.isRight()) {
- return Either.right(validateAndSetArtifactname.right().value());
- }
- if (operationName != null && interfaceName != null) {
- operationName = operationName.toLowerCase();
- interfaceName = interfaceName.toLowerCase();
- }
- Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
- if (logicalNameStatus.isRight()) {
- return Either.right(logicalNameStatus.right().value());
- }
- // This is a patch to block possibility of updating service api fields
- // through other artifacts flow
-
- if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
- checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
- } else {
- checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
- }
-
- composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
- if (currentArtifactInfo != null) {
- artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
- }
-
- // artifactGroupType is not allowed to be updated
- if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
- Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
- if (validateGroupType.isRight()) {
- return Either.right(validateGroupType.right().value());
- }
- }
- // TODO TEMP !!!
- NodeTypeEnum parentType = convertParentType(componentType);
-
- // TODO TEMP !!!
- boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
-
- if (isDeploymentArtifact(artifactInfo)) {
- Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
- if (deploymentValidationResult.isRight()) {
- return Either.right(deploymentValidationResult.right().value());
- }
- } else {
- artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
-
- /*
- * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
- * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
- */
- }
-
- Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
- if (descriptionResult.isRight()) {
- return Either.right(descriptionResult.right().value());
- }
-
- if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
- Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
- if (validateServiceApiType.isRight()) {
- return Either.right(validateServiceApiType.right().value());
- }
- // Change of type is not allowed and should be ignored
-
- artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
-
- Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
- if (validateUrl.isRight()) {
- return Either.right(validateUrl.right().value());
- }
-
- Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
- if (validateUpdate.isRight()) {
- log.debug("serviceApi first update cnnot be without payload.");
- return Either.right(validateUpdate.right().value());
- }
- } else {
- Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
- if (validateArtifactType.isRight()) {
- return Either.right(validateArtifactType.right().value());
- }
- if (artifactInfo.getApiUrl() != null) {
- artifactInfo.setApiUrl(null);
- log.error("Artifact URL cannot be set through this API - ignoring");
- }
-
- if (artifactInfo.getServiceApi() != null) {
- if (artifactInfo.getServiceApi()) {
- artifactInfo.setServiceApi(false);
- log.error("Artifact service API flag cannot be changed - ignoring");
- }
- }
- }
-
- return Either.left(artifactInfo);
- }
-
- private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
- if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
- artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
- artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
- artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
- }
- }
-
- private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
-
- Either<ArtifactDefinition, ResponseFormat> result = null;
- ArtifactDefinition foundArtifact = null;
- if (StringUtils.isNotEmpty(artifactId)) {
- foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
- }
- if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
- log.debug("Artifact {} already exist", artifactId);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
- }
- if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
- log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
- }
- if (result == null) {
- result = Either.left(foundArtifact);
- }
- 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<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
- ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
- ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
- Either<Boolean, ResponseFormat> validationResult = Either.left(true);
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
- if (artifactType == null) {
- validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
- } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
- String artifactTypeName = artifactType.getType();
- ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
- Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
- Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
- if (!validArtifactTypes.contains(artifactTypeName)) {
- validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
- } else {
- List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
- if (!validResourceType.contains(parentResourceType.name())) {
- validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
- }
- }
- }
- return validationResult;
- }
-
- private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
- if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- return NodeTypeEnum.Resource;
- } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
- return NodeTypeEnum.ResourceInstance;
- } else {
- return NodeTypeEnum.Service;
- }
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
- String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
-
- NodeTypeEnum parentType = convertParentType(componentType);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
- ArtifactDefinition foundArtifact = null;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
- org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
- boolean isDuplicated = false;
- String esId = null;
- Either<Boolean, StorageOperationStatus> needCloneRes = null;
- try {
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
- resultOp = Either.right(lockComponent.right().value());
- }
- }
- if (resultOp == null) {
- log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
- getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
- if (getContainerRes.isRight()) {
- log.debug("Failed to fetch the container component {}. ", parentId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- }
- if (resultOp == null) {
- fetchedContainerComponent = getContainerRes.left().value();
- log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
- getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
- if (getArtifactRes.isRight()) {
- log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
- responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- } else {
- foundArtifact = getArtifactRes.left().value().getLeft();
- esId = foundArtifact.getEsId();
- }
- }
- if (resultOp == null && StringUtils.isNotEmpty(esId)) {
- needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
- if (needCloneRes.isRight()) {
- log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- }
- boolean isNeedToDeleteArtifactFromDB = true;
- if (resultOp == null) {
-
- if(componentType == ComponentTypeEnum.RESOURCE_INSTANCE){
- String instanceId = parentId;
- Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
-
- if (isOnlyResourceInstanceArtifact.isRight()) {
- log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right().value(), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
- }
-
- Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
- if (updatedArtifactRes.isRight()) {
- log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- } else {
- isDuplicated = updatedArtifactRes.left().value().getDuplicated();
- }
- }
-
- if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
-
- if(isNeedToDeleteArtifactFromDB){
- log.debug("Going to delete the artifact {} from the database. ", artifactId);
- CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
- if (cassandraStatus != CassandraOperationStatus.OK) {
- log.debug("Failed to delete the artifact {} from the database. ", artifactId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- }
- }
- if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
-
- List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
- if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
- Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
- if (status.isRight()) {
- log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- }
- }
- if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
- StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
- if (status != StorageOperationStatus.OK) {
- log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- }
- if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
- List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
- if (CollectionUtils.isNotEmpty(updatedGroups)) {
- Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
- if (status.isRight()) {
- log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
- responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- }
- }
- }
- if (resultOp == null) {
- resultOp = Either.left(Either.left(foundArtifact));
- handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
- }
- return resultOp;
- } finally {
- if (shouldLock) {
- unlockComponent(resultOp, parent, inTransaction);
- }
- }
- }
-
- private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact( ArtifactDefinition foundArtifact, Component parent, String instanceId) {
- Either<Boolean, ActionStatus> result = Either.left(true);
- ComponentInstance foundInstance = null;
- Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
- if (!componentInstanceOpt.isPresent()) {
- result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
- } else {
- foundInstance = componentInstanceOpt.get();
- String componentUid = foundInstance.getComponentUid();
- Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
- if (getContainerRes.isRight()) {
- log.debug("Failed to fetch the container component {}. ", componentUid);
- result = Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
- }
- Component origComponent = getContainerRes.left().value();
- Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
- if( deploymentArtifacts!= null && !deploymentArtifacts.isEmpty()){
- Optional<String> op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
- if(op.isPresent()){
- return Either.left(false);
- }
- }
- Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
- if( artifacts!= null && !artifacts.isEmpty()){
- Optional<String> op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
- if(op.isPresent()){
- return Either.left(false);
- }
- }
-
- }
- return result;
- }
-
- private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
- List<GroupDataDefinition> updatedGroups = new ArrayList<>();
- boolean isUpdated = false;
- if (groups != null) {
- for (GroupDefinition group : groups) {
- isUpdated = false;
- if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
- group.getArtifacts().remove(artifactId);
- isUpdated = true;
- }
- if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
- group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
- isUpdated = true;
- }
- if (isUpdated) {
- updatedGroups.add(group);
- }
- }
- }
- return updatedGroups;
- }
-
- private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
- List<GroupInstance> updatedGroupInstances = new ArrayList<>();
- if (CollectionUtils.isNotEmpty(groupInstances)) {
- boolean isUpdated = false;
- for (GroupInstance groupInstance : groupInstances) {
- isUpdated = false;
- if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
- groupInstance.getGroupInstanceArtifacts().remove(artifactId);
- isUpdated = true;
- }
- if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
- groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
- isUpdated = true;
- }
- if (isUpdated) {
- updatedGroupInstances.add(groupInstance);
- }
- }
- }
- return updatedGroupInstances;
- }
-
- private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
-
- Either<ArtifactDataDefinition, StorageOperationStatus> result;
- boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
- String componentId = component.getUniqueId();
- String instanceId = componentId.equals(parentId) ? null : parentId;
- if (isMandatory) {
- log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
- resetMandatoryArtifactFields(foundArtifact);
- result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, 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);
- } else {
- log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
- result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
- }
- return result;
- }
-
- private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
-
- Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
- Map<String, ArtifactDefinition> artifacts = new HashMap<>();
- ComponentInstance foundInstance = null;
- if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
- Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
- if (!componentInstanceOpt.isPresent()) {
- result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
- } else {
- foundInstance = componentInstanceOpt.get();
- fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
- }
- } else {
- fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
- }
- if (result == null) {
- if (artifacts.containsKey(artifactId)) {
- result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
- } else {
- result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
- }
- }
- return result;
- }
-
- private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
- Map<String, ArtifactDefinition> currArtifacts;
- if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
- currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
- if (MapUtils.isNotEmpty(currArtifacts)) {
- artifacts.putAll(currArtifacts);
- }
- }
- if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
- currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
- if (MapUtils.isNotEmpty(currArtifacts)) {
- artifacts.putAll(currArtifacts);
- }
- }
- if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
- currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
- if (MapUtils.isNotEmpty(currArtifacts)) {
- artifacts.putAll(currArtifacts);
- }
- }
- }
-
- private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
- Map<String, ArtifactDefinition> currArtifacts;
- if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
- currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
- if (MapUtils.isNotEmpty(currArtifacts)) {
- artifacts.putAll(currArtifacts);
- }
- }
- if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
- currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
- if (MapUtils.isNotEmpty(currArtifacts)) {
- artifacts.putAll(currArtifacts);
- }
- }
- }
-
- private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
- StorageOperationStatus result;
- switch (cassandraStatus) {
- case OK:
- result = StorageOperationStatus.OK;
- break;
- case NOT_FOUND:
- result = StorageOperationStatus.NOT_FOUND;
- break;
- case CLUSTER_NOT_CONNECTED:
- case KEYSPACE_NOT_CONNECTED:
- result = StorageOperationStatus.CONNECTION_FAILURE;
- break;
- default:
- result = StorageOperationStatus.GENERAL_ERROR;
- break;
- }
- return result;
- }
-
- private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
- if (fetchedArtifact != null) {
- log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
- fetchedArtifact.setEsId(null);
- fetchedArtifact.setArtifactName(null);
- fetchedArtifact.setDescription(null);
- fetchedArtifact.setApiUrl(null);
- fetchedArtifact.setArtifactChecksum(null);
- nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
- fetchedArtifact.setArtifactUUID(null);
- long time = System.currentTimeMillis();
- fetchedArtifact.setPayloadUpdateDate(time);
- fetchedArtifact.setHeatParameters(null);
- fetchedArtifact.setHeatParamsUpdateDate(null);
- }
- }
-
- private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
- StorageOperationStatus error = StorageOperationStatus.OK;
- if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
- log.debug("Need to re-generate customization UUID for instance {}", instanceId);
- error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
- }
- return error;
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
- org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
- if (artifactById.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
- log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
- handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- ArtifactDefinition artifactDefinition = artifactById.left().value();
- if (artifactDefinition == null) {
- log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
- handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
-
- Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
- return Either.left(insideEither);
- }
-
- private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
- if (!(ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) && artifactById.isRight()) {
- // in case of update artifact must be
- BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
- log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
- }
- if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && artifactById.isLeft()) {
- log.debug("Artifact {} already exist", artifactId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
- }
- ArtifactDefinition currentArtifactInfo = null;
- if (artifactById.isLeft()) {
- // get previous value
- currentArtifactInfo = artifactById.left().value();
- }
- return Either.left(currentArtifactInfo);
- }
-
- private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
- ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
-
- String artifactLabel = artifactInfo.getArtifactLabel();
- if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
- BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
- log.debug("missing artifact logical name for component {}", componentId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
- }
- if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
-
- if (operationName != null) {
- if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
- log.debug("artifact label cannot be set {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
- } else {
- artifactLabel = operationName;
- }
- }
- String displayName = artifactInfo.getArtifactDisplayName();
- if (displayName == null || displayName.isEmpty())
- displayName = artifactLabel;
- displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
- // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
- // log.debug("Invalid format form Artifact displayName : {}", displayName);
- // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- // }
- artifactInfo.setArtifactDisplayName(displayName);
-
- if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
- log.debug("Invalid format form Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
-
- if (artifactLabel.isEmpty()) {
- log.debug("missing normalized artifact logical name for component {}", componentId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
- }
-
- if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
- log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
- }
- if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
- log.debug("Non unique Artifact label : {}", artifactLabel);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
- }
- }
- artifactInfo.setArtifactLabel(artifactLabel);
-
- return Either.left(ActionStatus.OK);
- }
-
- private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
- boolean isUnique = true;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
- if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
- artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
- } else {
- artifacts = artifactToscaOperation.getArtifacts(componentId);
- }
-
- if (artifacts.isLeft()) {
- for (String label : artifacts.left().value().keySet()) {
- if (label.equals(artifactLabel)) {
- isUnique = false;
- break;
- }
- }
- }
- if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
- if (allInterfacesOfResource.isLeft()) {
- for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
- for (Operation operation : interace.getOperationsMap().values()) {
- if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
- isUnique = false;
- break;
- }
- }
- }
- }
- }
- return isUnique;
- }
-
- // ***************************************************************
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
- ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
- ComponentInstance foundInstance = findComponentInstance(parentId, parent);
- String instanceId = null;
- String instanceName = null;
- if (foundInstance != null) {
- instanceId = foundInstance.getUniqueId();
- instanceName = foundInstance.getName();
- }
- boolean isLeft = false;
- String artifactUniqueId = null;
- StorageOperationStatus error = null;
- // information/deployment/api aritfacts
- log.trace("Try to create entry on graph");
- NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
-
- isLeft = result.isLeft();
- if (isLeft) {
- artifactUniqueId = result.left().value().getUniqueId();
- result.left().value();
-
- insideEither = Either.left(result.left().value());
- resultOp = Either.left(insideEither);
-
- error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
- if (error != StorageOperationStatus.OK) {
- isLeft = false;
- }
-
- } if (isLeft) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
- return resultOp;
- } else{
- log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
- resultOp = Either.right(responseFormat);
- return resultOp;
-
- }
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
- ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
-
- ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
- ComponentInstance foundInstance = findComponentInstance(parentId, parent);
- String instanceId = null;
- String instanceName = null;
- if (foundInstance != null) {
- instanceId = foundInstance.getUniqueId();
- instanceName = foundInstance.getName();
- }
- if (artifactData == null) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
- log.debug("Failed to create artifact object for ES.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
-
- }
- // set on graph object id of artifact in ES!
- artifactInfo.setEsId(artifactData.getId());
-
- boolean isLeft = false;
- String artifactUniqueId = null;
- StorageOperationStatus error = null;
- if (interfaceType != null && operationName != null) {
- // lifecycle artifact
- Operation operation = convertToOperation(artifactInfo, operationName);
-
- Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
-
- isLeft = result.isLeft();
- if (isLeft) {
- artifactUniqueId = result.left().value().getImplementation().getUniqueId();
- result.left().value().getImplementation();
-
- insideEither = Either.right(result.left().value());
- resultOp = Either.left(insideEither);
- } else {
- error = result.right().value();
- }
- } else {
- // information/deployment/api aritfacts
- log.trace("Try to create entry on graph");
- NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
-
- isLeft = result.isLeft();
- if (isLeft) {
- artifactUniqueId = result.left().value().getUniqueId();
- result.left().value();
-
- insideEither = Either.left(result.left().value());
- resultOp = Either.left(insideEither);
-
- error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
- if (error != StorageOperationStatus.OK) {
- isLeft = false;
- }
-
- } else {
- error = result.right().value();
- }
- }
- if (isLeft) {
- boolean res = saveArtifacts(artifactData, parentId, false);
- // String uniqueId = artifactDefinition.getUniqueId();
-
- if (res) {
- log.debug("Artifact saved into ES - {}", artifactUniqueId);
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
- return resultOp;
- } else {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
- log.debug("Failed to save the artifact.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
-
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- } else {
- log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
- handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
-
- }
-
- private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
- ComponentInstance foundInstance = null;
- if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
- foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
- }
- return foundInstance;
- }
-
- private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
-
- Either<Boolean, ResponseFormat> result = Either.left(true);
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
-
- validateArtifactTypeExists(responseWrapper, artifactInfo);
-
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
-
- Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
-
- if (responseWrapper.isEmpty()) {
- validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
- }
-
- if (responseWrapper.isEmpty()) {
- // Common code for all types
- // not allowed to change artifactType
- if (!isCreate) {
- Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
- if (validateServiceApiType.isRight()) {
- responseWrapper.setInnerElement(validateServiceApiType.right().value());
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- if (parentType.equals(NodeTypeEnum.Resource)) {
- // if (parentComponent instanceof Resource) {
- Resource resource = (Resource) parentComponent;
- ResourceTypeEnum resourceType = resource.getResourceType();
- ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
- if (config == null) {
- responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
- } else {
- List<String> myList = config.getValidForResourceTypes();
- Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
- if (either.isRight()) {
- responseWrapper.setInnerElement(either.right().value());
- }
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
- }
-
- if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
- String artifactName = artifactInfo.getArtifactName();
- if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
- validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
- }
- }
-
- if (responseWrapper.isEmpty()) {
- switch (artifactType) {
- case HEAT:
- case HEAT_VOL:
- case HEAT_NET: {
- result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
- break;
- }
- case HEAT_ENV: {
- result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
- artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
- break;
- }
- case DCAE_INVENTORY_TOSCA:
- case DCAE_INVENTORY_JSON:
- case DCAE_INVENTORY_POLICY:
- // Validation is done in handle payload.
- case DCAE_INVENTORY_DOC:
- case DCAE_INVENTORY_BLUEPRINT:
- case DCAE_INVENTORY_EVENT:
- // No specific validation
- default: {
- artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
- }
- }
-
- }
-
- if (!responseWrapper.isEmpty()) {
- result = Either.right(responseWrapper.getInnerElement());
- }
- return result;
- }
-
- private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
- if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
- responseWrapper.setInnerElement(responseFormat);
- log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
- }
- }
-
- private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
- Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
- if (parentType.equals(NodeTypeEnum.Resource)) {
- resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
- } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
- resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
- } else {
- resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
- }
- return resourceDeploymentArtifacts;
- }
-
- public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
- if (artifactType == null) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
- responseWrapper.setInnerElement(responseFormat);
- log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
- }
- }
-
- private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
- ArtifactTypeConfig retConfig = null;
- String fileType = artifactType.getType();
- if (parentType.equals(NodeTypeEnum.Resource)) {
- retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
- } else if (parentType.equals(NodeTypeEnum.Service)) {
- retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
- } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
- retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
- }
- return retConfig;
- }
-
- private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
- // extract heat parameters
- if (artifactInfo.getPayloadData() != null) {
- String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
- Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
- if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
- log.info("failed to parse heat parameters ");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
- return Either.right(responseFormat);
- } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
- artifactInfo.setListHeatParameters(heatParameters.left().value());
- }
- }
- return Either.left(true);
-
- }
-
- // Valid extension
- public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
- String fileType = artifactType.getType();
- List<String> acceptedTypes = null;
- ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
- if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
- log.debug("parent type of artifact can be either resource or service");
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return;
- }
-
- if (deploymentAcceptedTypes == null) {
- log.debug("parent type of artifact can be either resource or service");
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
- return;
- } else {
- acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
- }
- /*
- * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
- *
- * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
- * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
- * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
- * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
- */
-
- String artifactName = artifactInfo.getArtifactName();
- String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
- // Pavel - File extension validation is case-insensitive - Ella,
- // 21/02/2016
- if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
- log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
- return;
- }
- }
-
- private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
-
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
- Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
- Wrapper<byte[]> payloadWrapper = new Wrapper<>();
-
- if (errorWrapper.isEmpty()) {
- validateValidYaml(errorWrapper, artifactInfo);
- }
-
- if (errorWrapper.isEmpty()) {
- // Validate Heat Exist
- validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
- }
-
- // if (errorWrapper.isEmpty() && isCreate) {
- // // Validate Only Single HeatEnv Artifact
- // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
- // }
-
- if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
- fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
- }
-
- if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
- validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
- }
-
- // Init Response
- Either<Boolean, ResponseFormat> eitherResponse;
- if (errorWrapper.isEmpty()) {
- eitherResponse = Either.left(true);
- } else {
- eitherResponse = Either.right(errorWrapper.getInnerElement());
- }
- return eitherResponse;
- }
-
- public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
- if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
- Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
- if (fillArtifactPayload.isRight()) {
- errorWrapper.setInnerElement(fillArtifactPayload.right().value());
- log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
- }
- } else {
- payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
- }
- }
-
- public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
- Either<Boolean, ResponseFormat> result = Either.left(true);
- Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
- if (eitherArtifactData.isLeft()) {
- byte[] data = eitherArtifactData.left().value().getDataAsArray();
- data = Base64.encodeBase64(data);
- payloadWrapper.setInnerElement(data);
- } else {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
- result = Either.right(responseFormat);
- }
- return result;
-
- }
-
- @SuppressWarnings("unchecked")
- private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
- String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
- Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
- String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
- Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
-
- Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
- Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
- if (eitherHeatEnvProperties.isRight()) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
- } else if (eitherHeatProperties.isRight()) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
- } else {
- Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
- Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
- heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
- if (heatEnvPropertiesKeys.size() > 0) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
- errorWrapper.setInnerElement(responseFormat);
- }
- }
- }
-
- private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
- YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
- boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
- if (!isYamlValid) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
- }
- }
-
- public boolean isValidXml(byte[] xmlToParse) {
- if(parser == null) {
- log.debug("SAX XML Parser have not been initialized");
- return false;
- }
- boolean isXmlValid = true;
-
- try {
- parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
- } catch (IOException | SAXException e) {
- log.debug("Xml is invalid : {}", e.getMessage(), e);
- isXmlValid = false;
- }
-
- return isXmlValid;
- }
-
- public boolean isValidJson(byte[] jsonToParse) {
- String parsed = new String(jsonToParse);
- try {
- gson.fromJson(parsed, Object.class);
- } catch (Exception e) {
- log.debug("Json is invalid : {}", e.getMessage(), e);
- return false;
- }
- return true;
- }
-
- public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
- boolean typeArtifactFound = false;
- // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
- // (parentType == NodeTypeEnum.Resource) ?
- // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
- // parentComponent).iterator()
- // : getDeploymentArtifacts(parentComponent, parentType).iterator();
-
- Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
-
- while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
- ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
- typeArtifactFound = (foundArtifactType == allowedArtifactType);
- }
- if (typeArtifactFound) {
- String parentName = parentComponent.getName();
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
-
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
-
- }
- }
-
- public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
- boolean artifactNameFound = false;
- // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
- // (parentType == NodeTypeEnum.Resource) ?
- // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
- // parentComponent).iterator()
- // : getDeploymentArtifacts(parentComponent, parentType).iterator();
-
- Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
-
- while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
- artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
- }
- if (artifactNameFound) {
- String parentName = parentComponent.getName();
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
-
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
-
- }
- }
-
- private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
- ComponentTypeEnum componentType) {
- Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
- if (res.isRight()) {
- ResponseFormat responseFormat;
- if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
- responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
- } else {
- responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
- }
- errorWrapper.setInnerElement(responseFormat);
-
- return;
- }
- ArtifactDefinition heatArtifact = res.left().value();
- heatArtifactMDWrapper.setInnerElement(heatArtifact);
- // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
- // while (!heatFound && parentArtifactsItr.hasNext()) {
- // ArtifactDefinition currArtifact = parentArtifactsItr.next();
- // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
- // heatFound = true;
- // heatArtifactMDWrapper.setInnerElement(currArtifact);
- // log.trace("In validateHeatExist found artifact {}", currArtifact);
- // /*
- // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
- // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
- // */
- // }
- // }
- // if (!heatFound) {
- // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
- // errorWrapper.setInnerElement(responseFormat);
- // log.debug("Can't create heat env artifact because No heat Artifact exist.");
- // }
-
- }
-
- private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
- log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
- // timeout > 0 for HEAT artifacts
- Integer timeout = artifactInfo.getTimeout();
- Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
- if (timeout == null) {
- artifactInfo.setTimeout(defaultTimeout);
- // HEAT artifact but timeout is invalid
- } else if (timeout < 1) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
- }
-
- // US649856 - Allow several HEAT files on Resource
- /*
- * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
- * Either.right(errorWrapper.getInnerElement()); } }
- */
-
- log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
- String listToString = (typeList != null) ? typeList.toString() : "";
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
- Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
- String resourceTypeName = resourceType.name();
- if (typeList != null && typeList.contains(resourceTypeName)) {
- either = Either.left(true);
- }
- return either;
- }
-
- private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
- if (artifactInfo.getHeatParameters() != null) {
- for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
- String parameterType = heatParam.getType();
- HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
- String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
- if (heatParameterType == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
- return Either.right(responseFormat);
- }
-
- StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
- if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
- ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
- return Either.right(responseFormat);
- }
- }
- }
- return Either.left(artifactInfo);
- }
-
- public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
- List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
- if (parentComponent.getDeploymentArtifacts() != null) {
- if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
- Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
- if (getRI.isRight()) {
- return deploymentArtifacts;
- }
- ComponentInstance ri = getRI.left().value();
- if (ri.getDeploymentArtifacts() != null) {
- deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
- }
- } else if (parentComponent.getDeploymentArtifacts() != null) {
- deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
- }
- }
- return deploymentArtifacts;
- }
-
- private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
- // on create if null add informational to current
- if (artifactInfo.getArtifactGroupType() == null) {
- artifactInfo.setArtifactGroupType(type);
- }
- if (artifactInfo.getUniqueId() != null) {
- log.error("artifact uniqid cannot be set ignoring");
- }
- artifactInfo.setUniqueId(null);
-
- if (artifactInfo.getArtifactRef() != null) {
- log.error("artifact ref cannot be set ignoring");
- }
- artifactInfo.setArtifactRef(null);
-
- if (artifactInfo.getArtifactRepository() != null) {
- log.error("artifact repository cannot be set ignoring");
- }
- artifactInfo.setArtifactRepository(null);
-
- if (artifactInfo.getUserIdCreator() != null) {
- log.error("creator uuid cannot be set ignoring");
- }
- artifactInfo.setArtifactCreator(user.getUserId());
-
- if (artifactInfo.getUserIdLastUpdater() != null) {
- log.error("userId of last updater cannot be set ignoring");
- }
- artifactInfo.setUserIdLastUpdater(user.getUserId());
-
- if (artifactInfo.getCreatorFullName() != null) {
- log.error("creator Full name cannot be set ignoring");
- }
- String fullName = user.getFirstName() + " " + user.getLastName();
- artifactInfo.setUpdaterFullName(fullName);
-
- if (artifactInfo.getUpdaterFullName() != null) {
- log.error("updater Full name cannot be set ignoring");
- }
- artifactInfo.setUpdaterFullName(fullName);
-
- if (artifactInfo.getCreationDate() != null) {
- log.error("Creation Date cannot be set ignoring");
- }
- long time = System.currentTimeMillis();
- artifactInfo.setCreationDate(time);
-
- if (artifactInfo.getLastUpdateDate() != null) {
- log.error("Last Update Date cannot be set ignoring");
- }
- artifactInfo.setLastUpdateDate(time);
-
- if (artifactInfo.getEsId() != null) {
- log.error("es id cannot be set ignoring");
- }
- artifactInfo.setEsId(null);
-
- }
-
- /*
- * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
- * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
- * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
- * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
- * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
- * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
- */
-
- private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
- String id = artifactId;
- if (artifactId == null || artifactId.isEmpty()) {
- String uniqueId = null;
- if (interfaceName != null && operationName != null) {
- uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
- } else {
- uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
- }
- artifactInfo.setUniqueId(uniqueId);
- artifactInfo.setEsId(uniqueId);
- id = uniqueId;
- } else {
- artifactInfo.setUniqueId(artifactId);
- artifactInfo.setEsId(artifactId);
- }
- return id;
- }
-
- private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
- if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
- BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
- log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
- }
-
- boolean artifactTypeExist = false;
- Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
- ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
-
- if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
- allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
- } else {
-
- allArtifactTypes = elementOperation.getAllArtifactTypes();
- }
- if (allArtifactTypes.isRight()) {
- BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
- log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
- return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
- }
-
- for (ArtifactType type : allArtifactTypes.left().value()) {
- if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
- artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
- artifactTypeExist = true;
- break;
- }
- }
-
- if (!artifactTypeExist) {
- BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
- log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
- }
-
- return Either.left(ActionStatus.OK);
- }
-
- private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
-
- Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
- List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
-
- if (parentType.equals(NodeTypeEnum.Service)) {
- deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
- } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
- deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
- } else {
- deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
- }
- if (deploymentArtifacts != null) {
- for (String artifactType : deploymentArtifacts.keySet()) {
- ArtifactType artifactT = new ArtifactType();
- artifactT.setName(artifactType);
- artifactTypes.add(artifactT);
- }
- return Either.left(artifactTypes);
- } else {
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
-
- }
-
- private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
- if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
- }
- return Either.left(true);
-
- }
-
- private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
- if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
- }
-
- String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
- if (normalizeFileName == null || normalizeFileName.isEmpty()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
- }
- artifactInfo.setArtifactName(normalizeFileName);
-
- if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
- }
-
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
- if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
- log.info("artifact type is missing operation ignored");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
- }
-
- if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
- log.info("artifact type cannot be changed operation ignored");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- return Either.left(true);
- }
-
- private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
- if (artifactInfo.getArtifactGroupType() == null) {
- artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
- }
-
- else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
- log.info("artifact group type cannot be changed. operation failed");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- return Either.left(artifactInfo);
- }
-
- private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
-
- // on update if null add informational to current
- if (currentArtifact.getArtifactGroupType() == null && type != null) {
- currentArtifact.setArtifactGroupType(type);
- }
-
- if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
- log.error("artifact uniqid cannot be set ignoring");
- }
- artifactInfo.setUniqueId(currentArtifact.getUniqueId());
-
- if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
- log.error("artifact ref cannot be set ignoring");
- }
- artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
-
- if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
- log.error("artifact repository cannot be set ignoring");
- }
- artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
-
- if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
- log.error("creator uuid cannot be set ignoring");
- }
- artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
-
- if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
- log.error("artifact creator cannot be set ignoring");
- }
- artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
-
- if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
- log.error("userId of last updater cannot be set ignoring");
- }
- artifactInfo.setUserIdLastUpdater(user.getUserId());
-
- if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
- log.error("creator Full name cannot be set ignoring");
- }
- artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
-
- if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
- log.error("updater Full name cannot be set ignoring");
- }
- String fullName = user.getFirstName() + " " + user.getLastName();
- artifactInfo.setUpdaterFullName(fullName);
-
- if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
- log.error("Creation Date cannot be set ignoring");
- }
- artifactInfo.setCreationDate(currentArtifact.getCreationDate());
-
- if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
- log.error("Last Update Date cannot be set ignoring");
- }
- long time = System.currentTimeMillis();
- artifactInfo.setLastUpdateDate(time);
-
- if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
- log.error("es id cannot be set ignoring");
- }
- artifactInfo.setEsId(currentArtifact.getUniqueId());
-
- if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
- log.error(" Artifact Display Name cannot be set ignoring");
- }
- artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
-
- if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
- log.debug("serviceApi cannot be set. ignoring.");
- }
- artifactInfo.setServiceApi(currentArtifact.getServiceApi());
-
- if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
- log.debug("artifact group cannot be set. ignoring.");
- }
- artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
-
- artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
-
- if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
- log.debug("artifact UUID cannot be set. ignoring.");
- }
- artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
-
- if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
- checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
- }
- }
-
- private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
-
- Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
- for (HeatParameterDefinition parameter : heatParameters) {
- HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
-
- if (currentParam != null) {
-
- if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
- log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
- parameter.setName(currentParam.getName());
- }
- if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
- log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
- parameter.setDefaultValue(currentParam.getDefaultValue());
- }
- if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
- log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
- parameter.setType(currentParam.getType());
- }
- if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
- log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
- parameter.setDescription(currentParam.getDescription());
- }
-
- // check and set current value
- if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
- log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
- parameter.setCurrentValue(currentParam.getDefaultValue());
- }
- }
- }
- }
-
- private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
-
- Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
- for (HeatParameterDefinition param : currentParameters) {
- currentParamsMap.put(param.getUniqueId(), param);
- }
- return currentParamsMap;
- }
-
- private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
- if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
- log.debug("Artifact url cannot be empty.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
- }
- artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
-
- if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
- }
- if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
- }
-
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
- if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
- log.debug("Artifact description cannot be empty.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
- }
- String description = artifactInfo.getDescription();
- description = ValidationUtils.removeNoneUtf8Chars(description);
- description = ValidationUtils.normaliseWhitespace(description);
- description = ValidationUtils.stripOctets(description);
- description = ValidationUtils.removeHtmlTagsOnly(description);
- if (!ValidationUtils.validateIsEnglish(description)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
- }
- artifactInfo.setDescription(description);
- return Either.left(true);
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
- ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
- ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
- String prevArtifactId = null;
- String currArtifactId = artifactId;
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
-
- if (artifactData == null) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
- log.debug("Failed to create artifact object for ES.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- log.trace("Try to update entry on graph");
- String artifactUniqueId = null;
- ArtifactDefinition artifactDefinition = artifactInfo;
- StorageOperationStatus error = null;
-
- boolean isLeft = false;
- if (interfaceType != null && operationName != null) {
- // lifecycle artifact
- /*
- * Operation operation = convertToOperation(artifactInfo, operationName);
- *
- * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
- *
- * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
- *
- * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
- */
- } else {
- log.debug("Enty on graph is updated. Update artifact in ES");
- boolean res = true;
- // Changing previous and current artifactId for auditing
- prevArtifactId = currArtifactId;
- currArtifactId = artifactDefinition.getUniqueId();
-
- NodeTypeEnum convertParentType = convertParentType(componentType);
-
- if (decodedPayload == null) {
- if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
- Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
- // Either<ESArtifactData, ResourceUploadStatus>
- // artifactfromES = daoUploader.getArtifact(artifactId);
- if (artifactFromCassandra.isRight()) {
- log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
- error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- return resultOp;
- }
- // clone data to new artifact
- artifactData.setData(artifactFromCassandra.left().value().getData());
- artifactData.setId(artifactFromCassandra.left().value().getId());
- }
- } else {
- if (artifactDefinition.getEsId() == null) {
- artifactDefinition.setEsId(artifactDefinition.getUniqueId());
- artifactData.setId(artifactDefinition.getUniqueId());
- }
- }
-
- Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
- isLeft = result.isLeft();
- if (isLeft) {
- artifactUniqueId = result.left().value().getUniqueId();
- artifactDefinition = result.left().value();
- String artifactType = artifactInfo.getArtifactType();
- if (NodeTypeEnum.Resource == convertParentType
- && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
-
- if (!artifactUniqueId.equals(artifactId)) {
- // need to update the generated id in heat env
- Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
- Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
- if (findFirst.isPresent()) {
- ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
- artifactEnvInfo.setArtifactChecksum(null);
- artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
- }
- }
-
- /*
- * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
- *
- * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
- * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
- *
- * } } }
- */
- }
- error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
-
- insideEither = Either.left(result.left().value());
- resultOp = Either.left(insideEither);
- if (error != StorageOperationStatus.OK) {
- isLeft = false;
- }
-
- } else {
- error = result.right().value();
- }
- if (isLeft) {
-
- // create new entry in ES
- res = true;
- if (artifactData.getData() != null) {
- if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
- artifactData.setId(artifactDefinition.getEsId());
- res = saveArtifacts(artifactData, parentId, false);
-
- }
- }
-
- if (res) {
- log.debug("Artifact saved into ES - {}", artifactUniqueId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- // resultOp = Either.left(result.left().value());
- // return resultOp;
- } else {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
- log.debug("Failed to save the artifact.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- // return resultOp;
- }
- }
-
- return resultOp;
- }
-
- private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
- log.trace("Starting payload handling");
- byte[] payload = artifactInfo.getPayloadData();
- byte[] decodedPayload = null;
-
- if (payload != null && payload.length != 0) {
- // the generated artifacts were already decoded by the handler
- decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
- if (decodedPayload.length == 0) {
- log.debug("Failed to decode the payload.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
- }
-
- String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
- artifactInfo.setArtifactChecksum(checkSum);
- log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
-
- // Specific payload validations of different types
- Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
- if (isDeploymentArtifact(artifactInfo)) {
- log.trace("Starting deployment artifacts payload validation");
- String artifactType = artifactInfo.getArtifactType();
- if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
- || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
- isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
- if (isValidPayload.isLeft()) {
- isValidPayload = extractHeatParameters(artifactInfo);
- }
- } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
- || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
- || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
- isValidPayload = validateXmlPayload(decodedPayload, artifactType);
- // else
- // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
- // || ){
- } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
- || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
- String artifactFileName = artifactInfo.getArtifactName();
- String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
- switch (fileExtension) {
- case "xml":
- isValidPayload = validateXmlPayload(decodedPayload, artifactType);
- break;
- case "json":
- isValidPayload = validateJsonPayload(decodedPayload, artifactType);
- break;
- case "yml":
- case "yaml":
- isValidPayload = validateYmlPayload(decodedPayload, artifactType);
- break;
- }
- }
- }
- if (isValidPayload.isRight()) {
- ResponseFormat responseFormat = isValidPayload.right().value();
- return Either.right(responseFormat);
- }
-
- } // null/empty payload is normal if called from metadata update ONLY.
- // The validation of whether this is metadata/payload update case is
- // currently done separately
- else {
- if (!isArtifactMetadataUpdate) {
- log.debug("Payload is missing.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
- return Either.right(responseFormat);
- }
- }
- log.trace("Ended payload handling");
- return Either.left(decodedPayload);
- }
-
- private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
- // Basic YAML validation
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
- if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
- log.debug("Invalid YAML format");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
- return Either.right(responseFormat);
- }
- if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
- // HEAT specific YAML validation
- DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
- if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
- log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
- return Either.right(responseFormat);
- }
- }
-
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
- Either<Boolean, ResponseFormat> res = Either.left(true);
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
- if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
- log.debug("Invalid YAML format");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
- res = Either.right(responseFormat);
- }
-
- return res;
- }
-
- private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
- boolean isXmlValid = isValidXml(payload);
- if (!isXmlValid) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
- log.debug("Invalid XML content");
- return Either.right(responseFormat);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
- boolean isJsonValid = isValidJson(payload);
- if (!isJsonValid) {
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
- log.debug("Invalid JSON content");
- return Either.right(responseFormat);
- }
- return Either.left(true);
- }
-
- public void handleTransaction(Either<Operation, ResponseFormat> opState) {
- if (opState == null || opState.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- }
-
- public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
- boolean inTransaction) {
- User user = new User();
- user.setUserId(userUserId);
- Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
- if (parent.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
- return Either.right(responseFormat);
- }
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
- false, inTransaction);
- if (handleDelete.isRight()) {
- return Either.right(handleDelete.right().value());
- }
- Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
- return Either.left(result.right().value());
-
- }
-
- private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
- Operation op = new Operation();
- long time = System.currentTimeMillis();
- op.setCreationDate(time);
-
- String artifactName = artifactInfo.getArtifactName();
- artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
-
- op.setImplementation(artifactInfo);
- op.setLastUpdateDate(time);
- return op;
- }
-
- private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
- String newArtifactName = operationName + "_" + artifactName;
- log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
- return newArtifactName;
- }
-
- // download by MSO
- public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
-
- // General validation
- if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
- log.debug("One of the function parameteres is null");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- // Normalizing artifact name
- artifactName = ValidationUtils.normalizeFileName(artifactName);
-
- // Resource validation
- Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
- if (validateResourceNameAndVersion.isRight()) {
- return Either.right(validateResourceNameAndVersion.right().value());
- }
-
- Resource resource = validateResourceNameAndVersion.left().value();
- String resourceId = resource.getUniqueId();
-
- // Service validation
- Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
- if (validateServiceNameAndVersion.isRight()) {
- return Either.right(validateServiceNameAndVersion.right().value());
- }
-
- Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
- if (artifacts == null || artifacts.isEmpty()) {
- log.debug("Deployment artifacts of resource {} are not found", resourceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
- }
-
- ArtifactDefinition deploymentArtifact = null;
-
- for (ArtifactDefinition artifactDefinition : artifacts.values()) {
- if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
- log.debug("Found deployment artifact {}", artifactName);
- deploymentArtifact = artifactDefinition;
- break;
- }
- }
-
- if (deploymentArtifact == null) {
- log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
- }
-
- // Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
- if (downloadArtifactEither.isRight()) {
- log.debug("Download artifact {} failed", artifactName);
- return Either.right(downloadArtifactEither.right().value());
- }
- log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
- return Either.left(downloadArtifactEither.left().value().getRight());
- }
-
- // download by MSO
- public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
-
- // General validation
- if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
- log.debug("One of the function parameteres is null");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- // Normalizing artifact name
- artifactName = ValidationUtils.normalizeFileName(artifactName);
-
- // Resource validation
- /*
- * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
- * Either.right(validateResourceNameAndVersion.right().value()); }
- *
- * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
- */
-
- // Service validation
- Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
- if (validateServiceNameAndVersion.isRight()) {
- return Either.right(validateServiceNameAndVersion.right().value());
- }
-
- Service service = validateServiceNameAndVersion.left().value();
-
- // ResourceInstance validation
- Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
- if (validateResourceInstance.isRight()) {
- return Either.right(validateResourceInstance.right().value());
- }
-
- ComponentInstance resourceInstance = validateResourceInstance.left().value();
-
- Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
-
- final String finalArtifactName = artifactName;
- Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
-
- boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
- ArtifactDefinition deployableArtifact;
-
- if (!hasDeploymentArtifacts) {
- log.debug("Deployment artifact with name {} not found", artifactName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
- }
-
- log.debug("Found deployment artifact {}", artifactName);
- deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
- // Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service );
-
- if (downloadArtifactEither.isRight()) {
- log.debug("Download artifact {} failed", artifactName);
- return Either.right(downloadArtifactEither.right().value());
- }
- log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
- return Either.left(downloadArtifactEither.left().value().getRight());
- }
-
- private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
-
- List<ComponentInstance> riList = service.getComponentInstances();
- for (ComponentInstance ri : riList) {
- if (ri.getNormalizedName().equals(resourceInstanceName))
- return Either.left(ri);
- }
-
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
- }
-
- private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
-
- Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
- if (serviceListBySystemName.isRight()) {
- log.debug("Couldn't fetch any service with name {}", serviceName);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
- }
- List<Service> serviceList = serviceListBySystemName.left().value();
- if (serviceList == null || serviceList.isEmpty()) {
- log.debug("Couldn't fetch any service with name {}", serviceName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
- }
-
- Service foundService = null;
- for (Service service : serviceList) {
- if (service.getVersion().equals(serviceVersion)) {
- log.trace("Found service with version {}", serviceVersion);
- foundService = service;
- break;
- }
- }
-
- if (foundService == null) {
- log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
- }
- return Either.left(foundService);
- }
-
- private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
-
- Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
- if (resourceListBySystemName.isRight()) {
- log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
- }
- return Either.left(resourceListBySystemName.left().value());
- }
-
- public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
- // Validation
- log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
- if (serviceName == null || serviceVersion == null || artifactName == null) {
- log.debug("One of the function parameteres is null");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- // Normalizing artifact name
- final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
-
- // Service validation
- Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
- if (validateServiceNameAndVersion.isRight()) {
- return Either.right(validateServiceNameAndVersion.right().value());
- }
-
- String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
-
- // Looking for deployment or tosca artifacts
- Service service = validateServiceNameAndVersion.left().value();
-
- if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
- log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
- }
-
- Optional<ArtifactDefinition> foundArtifactOptl = null;
-
- if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
- foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
- // filters artifact by name
- .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
- }
- if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
- foundArtifactOptl = service.getToscaArtifacts().values().stream()
- // filters TOSCA artifact by name
- .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
- }
- if (!foundArtifactOptl.isPresent()) {
- log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
- }
- log.debug("Found deployment artifact {}", normalizedArtifactName);
- // Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service);
- if (downloadArtifactEither.isRight()) {
- log.debug("Download artifact {} failed", normalizedArtifactName);
- return Either.right(downloadArtifactEither.right().value());
- }
- log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
- return Either.left(downloadArtifactEither.left().value().getRight());
- }
-
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
- log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
- Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
- if (artifactById.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
- log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
- }
- ArtifactDefinition artifactDefinition = artifactById.left().value();
- if (artifactDefinition == null) {
- log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
- }
-
- return downloadArtifact(artifactDefinition, null);
- }
-
- private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
- boolean found = false;
- Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
- if (artifactsS != null) {
- for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
- if (entry.getValue().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
- if (!found && deploymentArtifactsS != null) {
- for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
- if (entry.getValue().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
- if (!found && toscaArtifactsS != null) {
- for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
- if (entry.getValue().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- switch (component.getComponentType()) {
- case RESOURCE:
- Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
- if (!found && interfaces != null) {
- for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
- Map<String, Operation> operations = entry.getValue().getOperationsMap();
- for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
- if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- }
- break;
- case SERVICE:
- Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
- if (!found && apiArtifacts != null) {
- for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
- if (entry.getValue().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- break;
- default:
-
- }
-
- return found;
- }
-
- private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
-
- boolean found = false;
- List<ComponentInstance> resourceInstances = component.getComponentInstances();
- ComponentInstance resourceInstance = null;
- for (ComponentInstance ri : resourceInstances) {
- if (ri.getUniqueId().equals(resourceInstanceId)) {
- resourceInstance = ri;
- break;
- }
- }
- if (resourceInstance != null) {
- Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
- if (artifacts != null) {
- for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- if (entry.getValue().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- if (!found) {
- artifacts = resourceInstance.getArtifacts();
- if (artifacts != null) {
- for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- if (entry.getValue().getUniqueId().equals(artifactId)) {
- found = true;
- break;
- }
- }
- }
- }
- }
- return found;
- }
-
- private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
- String containerComponentType, boolean inTransaction) {
-
- ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
- componentForAudit.getNodeType();
-
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
-
- if (componentResult.isRight()) {
- ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
- log.debug("Service not found, serviceId {}", componentId);
- handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
- return Either.right(responseFormat);
- }
- return Either.left(componentResult.left().value());
- }
-
- private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
- ComponentTypeEnum componentType) {
- if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
- Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
- if (canWork.isRight()) {
- String uniqueId = component.getUniqueId();
- log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
- handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
- return Either.right(canWork.right().value());
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
-
- if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
- String role = user.getRole();
- if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
- handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- }
- return Either.left(true);
- }
-
- private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
-
- if (validateUserExists.isRight()) {
- User user = new User();
- user.setUserId(userId);
- handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
- return Either.right(validateUserExists.right().value());
- }
- return Either.left(validateUserExists.left().value());
- }
-
- protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
- AuditingActionEnum auditingAction = null;
- switch (operation.getArtifactOperationEnum()) {
- case Create:
- auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
- break;
- case Update:
- auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
- break;
- case Delete:
- auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
- break;
- case Download:
- auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
- break;
- default:
- break;
- }
- return auditingAction;
- }
-
- private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) {
- String esArtifactId = artifactDefinition.getEsId();
- Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
- if (artifactfromES.isRight()) {
- CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
- StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
- log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName());
- handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null);
-
- return Either.right(responseFormat);
- }
-
- ESArtifactData esArtifactData = artifactfromES.left().value();
- byte[] data = esArtifactData.getDataAsArray();
- if (data == null) {
- log.debug("Artifact data from ES is null");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
- }
- String artifactName = artifactDefinition.getArtifactName();
- log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
- return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
- }
-
- public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
- ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
- return artifactData;
- }
-
- private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
-
- CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
-
- if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
- log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
- } else {
- log.info("Failed to save artifact {}.", artifactData.getId());
- return false;
- }
- return true;
- }
-
- private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
- return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
- }
-
- private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
- return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
- }
-
- public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
- Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
- if (user.isRight()) {
- ResponseFormat responseFormat;
- if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
- log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- } else {
- log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
- responseFormat = componentsUtils.getResponseFormat(user.right().value());
- }
- return Either.right(responseFormat);
- }
-
- ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
- return Either.left(artifactDefinition);
- }
-
- public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
- ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
- String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
- String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
- String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
-
- artifactInfo.setArtifactDisplayName(artifactName);
- artifactInfo.setArtifactLabel(logicalName.toLowerCase());
- artifactInfo.setArtifactType(artifactType);
- artifactInfo.setDescription(artifactDescription);
- artifactInfo.setArtifactGroupType(groupType);
- nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
-
- setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
-
- return artifactInfo;
- }
-
- private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
- String uniqueId = null;
-
- if (resourceId != null) {
- uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
- artifactInfo.setUniqueId(uniqueId);
- }
- artifactInfo.setUserIdCreator(user.getUserId());
- String fullName = user.getFullName();
- artifactInfo.setUpdaterFullName(fullName);
-
- long time = System.currentTimeMillis();
-
- artifactInfo.setCreatorFullName(fullName);
- artifactInfo.setCreationDate(time);
-
- artifactInfo.setLastUpdateDate(time);
- artifactInfo.setUserIdLastUpdater(user.getUserId());
-
- artifactInfo.setMandatory(true);
- }
-
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
- return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
- }
-
- public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
- return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
- }
-
- private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
-
- byte[] payload = payloadStr.getBytes();
-
- ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
- return Either.left(artifactData);
- }
-
- /**
- *
- * @param artifactDefinition
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
- boolean shouldLock, String instanceId) {
- String payload = generateHeatEnvPayload(artifactDefinition);
- String prevUUID = artifactDefinition.getArtifactUUID();
- ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
- return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId)
- .left()
- .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
- }
-
- public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
- boolean shouldLock, String instanceId) {
- String payload = generateHeatEnvPayload(artifactDefinition);
- String prevUUID = artifactDefinition.getArtifactUUID();
- ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
- return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId)
- .left()
- .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
- }
-
- private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
- if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
+ private static final String ARTIFACT_TYPE_OTHER = "OTHER";
+ private static final String ARTIFACT_DESCRIPTION = "artifact description";
+ private static final String ARTIFACT_LABEL = "artifact label";
+ private static final String ARTIFACT_URL = "artifact url";
+ private static final String ARTIFACT_NAME = "artifact name";
+ private static final String ARTIFACT_PAYLOAD = "artifact payload";
+
+ private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
+ private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
+ private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
+
+ public static final String HEAT_ENV_NAME = "heatEnv";
+ public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
+ public static final String HEAT_ENV_SUFFIX = "env";
+ private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
+
+ private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
+ private Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ @javax.annotation.Resource
+ private IInterfaceLifecycleOperation interfaceLifecycleOperation;
+ @javax.annotation.Resource
+ private IUserAdminOperation userOperaton;
+
+ @javax.annotation.Resource
+ private IElementOperation elementOperation;
+
+ @javax.annotation.Resource
+ private ResourceBusinessLogic resourceBusinessLogic;
+
+ @javax.annotation.Resource
+ private ServiceBusinessLogic serviceBusinessLogic;
+
+ @javax.annotation.Resource
+ private UserBusinessLogic userAdminManager;
+
+ @javax.annotation.Resource
+ private IHeatParametersOperation heatParametersOperation;
+
+ @Autowired
+ private ArtifactCassandraDao artifactCassandraDao;
+
+ @Autowired
+ private ToscaExportHandler toscaExportUtils;
+
+ @Autowired
+ private CsarUtils csarUtils;
+
+ @Autowired
+ private LifecycleBusinessLogic lifecycleBusinessLogic;
+
+ @Autowired
+ private IUserBusinessLogic userBusinessLogic;
+
+ @Autowired
+ private NodeTemplateOperation nodeTemplateOperation;
+
+ @Autowired
+ private ArtifactsResolver artifactsResolver;
+
+ public enum ArtifactOperationEnum {
+ CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
+
+ public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
+ return operation == CREATE || operation == LINK;
+ }
+ }
+
+ public class ArtifactOperationInfo {
+
+ private ArtifactOperationEnum artifactOperationEnum;
+ private boolean isExternalApi;
+ private boolean ignoreLifecycleState;
+
+ public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
+ this.artifactOperationEnum = artifactOperationEnum;
+ this.isExternalApi = isExternalApi;
+ this.ignoreLifecycleState = ignoreLifecycleState;
+ }
+
+ public boolean isExternalApi() {
+ return isExternalApi;
+ }
+
+ public boolean ignoreLifecycleState() {
+ return ignoreLifecycleState;
+ }
+
+ public ArtifactOperationEnum getArtifactOperationEnum() {
+ return artifactOperationEnum;
+ }
+
+ }
+
+ // new flow US556184
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
+ String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
+ return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
+ String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
+
+ // step 1 - detect auditing type
+ AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
+ // step 2 - check header
+ if (userId == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
+ handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ // step 3 - check user existence
+ Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
+ if (userResult.isRight()) {
+ return Either.right(userResult.right().value());
+ }
+
+ // step 4 - check user's role
+ User user = userResult.left().value();
+ Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
+ if (validateUserRole.isRight()) {
+ return Either.right(validateUserRole.right().value());
+ }
+
+ // steps 5 - 6 - 7
+ // 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;
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
+ if (validateComponent.isRight()) {
+ return Either.right(validateComponent.right().value());
+ }
+ component = validateComponent.left().value();
+ Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
+ if (validateWorkOnResource.isRight()) {
+ return Either.right(validateWorkOnResource.right().value());
+ }
+ // step 8
+
+ return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, user, component,
+ shouldLock, inTransaction, true);
+ }
+
+ /**
+ * This Method validates only the Artifact and does not validate user / role / component ect...<br>
+ * For regular usage use <br>
+ * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
+ *
+ * @return
+ */
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
+ ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
+ Component parent = component;
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+
+ AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
+ artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
+ if (errorWrapper.isEmpty()) {
+ // step 10
+ result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
+ }
+ else {
+ result = Either.right(errorWrapper.getInnerElement());
+ }
+ return result;
+ }
+
+ private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
+ Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
+ ArtifactDefinition validatedArtifactInfo = artifactInfo;
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
+ .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
+ Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
+ if (validateArtifact.isRight()) {
+ ResponseFormat responseFormat = validateArtifact.right().value();
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ errorWrapper.setInnerElement(validateArtifact.right().value());
+ }
+ else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
+ validatedArtifactInfo = validateArtifact.left().value();
+ handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
+ }
+ }
+ return validatedArtifactInfo;
+ }
+
+ private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
+ ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
+ ArtifactDefinition validatedArtifact = validateArtifact.left().value();
+
+ if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
+ && ComponentTypeEnum.SERVICE == component.getComponentType()) {
+ ComponentInstance componentInstance = component.getComponentInstances()
+ .stream()
+ .filter(p -> p.getUniqueId().equals(componentId))
+ .findAny()
+ .get();
+ Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
+
+ ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
+ .stream()
+ .filter(p -> p.getUniqueId()
+ .equals(validatedArtifact.getUniqueId()))
+ .findAny()
+ .get();
+ Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
+ .getName(), user, componentId, shouldLock, inTransaction);
+ if (eitherGenerated.isRight()) {
+ errorWrapper.setInnerElement(eitherGenerated.right().value());
+ }
+ }
+ }
+
+ private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
+ boolean needGenerate;
+ needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
+ .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
+ .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
+ .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
+ return needGenerate;
+ }
+
+ private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
+ return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
+ .getArtifactType()
+ .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
+ boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
+ if (generated.isRight()) {
+ return generated;
+ }
+ byte[] decodedPayload = artifactDefinition.getPayloadData();
+ artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+ artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
+ return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
+ .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
+ shouldLock, inTransaction);
+
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
+ log.debug("tosca artifact generation");
+ if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
+ Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
+
+ if (generated.isRight()) {
+ log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
+ .value());
+
+ return Either.right(generated.right().value());
+ }
+ byte[] value = generated.left().value();
+ artifactInfo.setPayload(value);
+
+ }
+ else {
+ Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
+ if (exportComponent.isRight()) {
+ log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
+ .value());
+ ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
+ return Either.right(responseFormat);
+ }
+ log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
+ String payload = exportComponent.left().value().getMainYaml();
+ artifactInfo.setPayloadData(payload);
+ }
+ return Either.left(Either.left(artifactInfo));
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
+ String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
+ if (interfaceName != null && operationName != null) {
+ interfaceName = interfaceName.toLowerCase();
+ operationName = operationName.toLowerCase();
+ }
+ switch (operation.getArtifactOperationEnum()) {
+ case DOWNLOAD:
+ if (artifactGenerationRequired(parent, artifactInfo)) {
+ return generateNotSavedArtifact(parent, artifactInfo);
+ }
+ return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
+ case DELETE:
+ return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
+ case UPDATE:
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
+ if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
+ && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
+ result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
+ if (needUpdateGroup && result.isLeft()) {
+ Either<ArtifactDefinition, Operation> updateResult = result.left().value();
+ ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
+ .value(), parent, componentType, componentId);
+ if (error != ActionStatus.OK) {
+ result = Either.right(componentsUtils.getResponseFormat(error));
+ }
+ }
+ }
+ else {
+ if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
+ result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
+ }
+ }
+ if (result == null) {
+ result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
+ if (needUpdateGroup && result.isLeft()) {
+ Either<ArtifactDefinition, Operation> updateResult = result.left().value();
+
+ ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
+ .value(), parent, componentType);
+ if (error != ActionStatus.OK) {
+ result = Either.right(componentsUtils.getResponseFormat(error));
+ }
+ }
+ }
+ return result;
+ case CREATE:
+ return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
+ case LINK:
+ return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
+ }
+ return null;
+ }
+
+ private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
+ List<GroupDefinition> groups = parent.getGroups();
+ if (groups != null && !groups.isEmpty()) {
+ List<GroupDataDefinition> groupToUpdate = groups.stream()
+ .filter(g -> g.getArtifacts() != null && g.getArtifacts()
+ .contains(artifactInfo
+ .getUniqueId()))
+ .collect(Collectors.toList());
+ if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
+ groupToUpdate.forEach(g -> {
+ g.getArtifacts().remove(artifactInfo.getUniqueId());
+ g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
+ g.getArtifacts().add(artAfterUpdate.getUniqueId());
+ g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
+ });
+ Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
+ return componentsUtils.convertFromStorageResponse(status.right().value());
+ }
+ }
+ }
+ return ActionStatus.OK;
+ }
+
+ private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
+ List<GroupDefinition> groups = parent.getGroups();
+ if (groups != null && !groups.isEmpty()) {
+ List<GroupDataDefinition> groupToUpdate = groups.stream()
+ .filter(g -> g.getArtifacts() != null && g.getArtifacts()
+ .contains(artifactInfoHeat
+ .getUniqueId()))
+ .collect(Collectors.toList());
+ if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
+ groupToUpdate.forEach(g -> {
+ g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
+ g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
+ g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
+ g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
+ g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
+ g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
+ });
+ Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
+ return componentsUtils.convertFromStorageResponse(status.right().value());
+ }
+ }
+ }
+ return ActionStatus.OK;
+ }
+
+ private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
+ List<GroupInstance> updatedGroupInstances = new ArrayList<>();
+ List<GroupInstance> groupInstances = null;
+ Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
+ .stream()
+ .filter(ci -> ci.getUniqueId().equals(parentId))
+ .findFirst();
+ if (componentInstOp.isPresent()) {
+ groupInstances = componentInstOp.get().getGroupInstances();
+ }
+ if (CollectionUtils.isNotEmpty(groupInstances)) {
+ boolean isUpdated = false;
+ for (GroupInstance groupInstance : groupInstances) {
+ isUpdated = false;
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
+ .contains(artifactInfo
+ .getUniqueId())) {
+ groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
+ groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
+ isUpdated = true;
+ }
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
+ .contains(artifactInfo
+ .getArtifactUUID())) {
+ groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
+ groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
+ isUpdated = true;
+ }
+ if (isUpdated) {
+ updatedGroupInstances.add(groupInstance);
+ }
+ }
+ }
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
+ return componentsUtils.convertFromStorageResponse(status.right().value());
+ }
+ return ActionStatus.OK;
+ }
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
+ if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
+ result = generateToscaArtifact(parent, artifactInfo, false, false);
+ }
+ else {
+ String heatArtifactId = artifactInfo.getGeneratedFromId();
+ Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
+ if (heatRes.isRight()) {
+ log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
+ .getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
+ .right()
+ .value()), "");
+ return Either.right(responseFormat);
+ }
+ String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
+ artifactInfo.setPayloadData(generatedPayload);
+ result = Either.left(Either.left(artifactInfo));
+ }
+ return result;
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
+ ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
+ convertParentType(componentType);
+ String parentId = parent.getUniqueId();
+ Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
+ .getGeneratedFromId());
+ ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
+
+ if (origMd5 != null) {
+ Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
+ if (validateMd5.isRight()) {
+ ResponseFormat responseFormat = validateMd5.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+
+ if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
+
+ Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
+ if (payloadEither.isRight()) {
+ ResponseFormat responseFormat = payloadEither.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ }
+ else { // duplicate
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ }
+
+ // lock resource
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
+ .value(), componentType, null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ try {
+ resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
+ return resultOp;
+
+ }
+ finally {
+ // unlock resource
+ if (resultOp == null || resultOp.isRight()) {
+ log.debug("all changes rollback");
+ if (!inTransaction) {
+ titanDao.rollback();
+ }
+ }
+ else {
+ log.debug("all changes committed");
+ if (!inTransaction) {
+ titanDao.commit();
+ }
+ }
+ if (shouldLock) {
+ graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
+ }
+ }
+ }
+
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
+ if (artifactGenerationRequired(component, csarArtifact)) {
+ Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
+
+ if (generated.isRight()) {
+ log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
+ .value());
+
+ return Either.right(generated.right().value());
+ }
+ return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
+ .value()));
+ }
+ return downloadArtifact(csarArtifact);
+ }
+
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
+ // perform all validation in common flow
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
+ null, parentId, containerComponentType);
+ if (result.isRight()) {
+ return Either.right(result.right().value());
+ }
+ ArtifactDefinition artifactDefinition;
+ Either<ArtifactDefinition, Operation> insideValue = result.left().value();
+ if (insideValue.isLeft()) {
+ artifactDefinition = insideValue.left().value();
+ }
+ else {
+ artifactDefinition = insideValue.right().value().getImplementationArtifact();
+ }
+ // for tosca artifacts and heat env on VF level generated on download without saving
+ if (artifactDefinition.getPayloadData() != null) {
+ return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
+ .getPayloadData()));
+ }
+ return downloadArtifact(artifactDefinition);
+ }
+
+ public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
+ // step 1
+ // detect auditing type
+ Map<String, ArtifactDefinition> resMap = null;
+ Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
+
+ new Wrapper<>();
+ // step 2
+ // check header
+ if (userId == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
+
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+ // step 3
+ // check user existence
+ // step 4
+ // check user's role
+
+ Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
+ if (userResult.isRight()) {
+
+ resultOp = Either.right(userResult.right().value());
+ return resultOp;
+ }
+
+ userResult.left().value();
+
+ // steps 5 - 6 - 7
+ // 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;
+ ComponentParametersView componentFilter = new ComponentParametersView();
+ componentFilter.disableAll();
+ componentFilter.setIgnoreArtifacts(false);
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ componentFilter.setIgnoreComponentInstances(false);
+ }
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
+ .findByParamName(containerComponentType), componentFilter);
+
+ if (validateComponent.isRight()) {
+ resultOp = Either.right(validateComponent.right().value());
+ return resultOp;
+ }
+ component = validateComponent.left().value();
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
+ if (lockComponent.isRight()) {
+
+ resultOp = Either.right(lockComponent.right().value());
+ return resultOp;
+ }
+
+ try {
+ ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
+
+ if (groupType == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
+
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+
+ }
+ if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
+ List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
+ if (list != null && !list.isEmpty()) {
+ resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
+ }
+ else {
+ resMap = new HashMap<>();
+ }
+ resultOp = Either.left(resMap);
+ return resultOp;
+ }
+ else {
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
+ .getNodeType(), 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 {
+ resMap = new HashMap<>();
+ resultOp = Either.left(resMap);
+ }
+ }
+ else {
+ resMap = artifactsMapStatus.left().value();
+ resultOp = Either.left(resMap);
+ }
+ return resultOp;
+ }
+ }
+ finally {
+ // unlock resource
+ if (resultOp == null || resultOp.isRight()) {
+ log.debug("all changes rollback");
+ titanDao.rollback();
+ }
+ else {
+ log.debug("all changes committed");
+ titanDao.commit();
+ }
+
+ componentType = component.getComponentType();
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
+ }
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
+ // step 9
+ // check artifact existence
+ Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
+ .getUniqueId());
+ if (artifactResult.isRight()) {
+ if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
+ log.debug("addArtifact - artifact {} not found", artifactId);
+ return Either.right(responseFormat);
+
+ }
+ else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
+ .right()
+ .value()));
+ log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
+ .value());
+ return Either.right(responseFormat);
+ }
+ }
+ // step 9.1
+ // check artifact belong to component
+ boolean found = false;
+ switch (componentType) {
+ case RESOURCE:
+ case SERVICE:
+ found = checkArtifactInComponent(component, artifactId);
+ break;
+ case RESOURCE_INSTANCE:
+ found = checkArtifactInResourceInstance(component, componentId, artifactId);
+ break;
+ default:
+
+ }
+ if (!found) {
+ String componentName = componentType.name().toLowerCase();
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
+ log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
+ return Either.right(responseFormat);
+ }
+ return Either.left(artifactResult.left().value());
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+ org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
+
+ String artifactId = null;
+
+ // step 11
+ Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
+ if (payloadEither.isRight()) {
+ return Either.right(payloadEither.right().value());
+ }
+ byte[] decodedPayload = payloadEither.left().value();
+ convertParentType(componentType);
+
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
+ .value(), componentType, null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+
+ try {
+ resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
+ return resultOp;
+ }
+ finally {
+ if (shouldLock) {
+ unlockComponent(resultOp, parent, inTransaction);
+ }
+
+ }
+
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+ Component parent, boolean shouldLock, boolean inTransaction) {
+
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
+ .value(), componentType, null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+
+ try {
+ resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
+ return resultOp;
+ }
+ finally {
+ if (shouldLock) {
+ unlockComponent(resultOp, parent, inTransaction);
+ }
+
+ }
+
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
+ ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
+
+ convertParentType(componentType);
+
+ // lock resource
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
+
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
+ .value(), componentType, null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ try {
+ resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
+ return resultOp;
+
+ }
+ finally {
+ if (shouldLock) {
+ unlockComponent(resultOp, parent, inTransaction);
+ }
+ }
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
+ ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
+
+ Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
+
+ if (payloadEither.isRight()) {
+ return Either.right(payloadEither.right().value());
+ }
+ byte[] decodedPayload = payloadEither.left().value();
+
+ return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
+ }
+
+ private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
+ Component parent, String origMd5, String originData, String interfaceType, String operationName) {
+ // Md5 validations
+ Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
+ if (validateMd5.isRight()) {
+ ResponseFormat responseFormat = validateMd5.right().value();
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+
+ // step 11
+ Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
+ if (validateResult.isRight()) {
+ ResponseFormat responseFormat = validateResult.right().value();
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(validateResult.right().value());
+ }
+
+ Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
+ if (payloadEither.isRight()) {
+ ResponseFormat responseFormat = payloadEither.right().value();
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ log.debug("Error during handle payload");
+ return Either.right(responseFormat);
+ }
+
+ // validate heat parameters. this part must be after the parameters are
+ // extracted in "handlePayload"
+ Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
+ .getArtifactType());
+ if (validateAndConvertHeatParamers.isRight()) {
+ ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
+ handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
+ log.debug("Error during handle payload");
+ return Either.right(responseFormat);
+ }
+ return payloadEither;
+ }
+
+ public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
+ ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
+
+ if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType()
+ .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
+ return;
+ }
+ String artifactData = buildAuditingArtifactData(artifactDefinition);
+
+ if (user == null) {
+ user = new User();
+ user.setUserId("UNKNOWN");
+ }
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ Resource resource = (Resource) component;
+ if (resource == null) {
+ // In that case, component ID should be instead of name
+ resource = new Resource();
+ resource.setName(componentId);
+ }
+ componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(prevArtifactUuid)
+ .build(), currentArtifactUuid, artifactData);
+ break;
+
+ case SERVICE:
+ Service service = (Service) component;
+ if (service == null) {
+ // In that case, component ID should be instead of name
+ service = new Service();
+ service.setName(componentId);
+ }
+ componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE,
+ ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
+ ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
+ null, null, artifactData, null);
+ break;
+
+ case RESOURCE_INSTANCE:
+ if (resourceInstanceName == null) {
+ resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
+ }
+ componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE,
+ ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
+ ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
+ resourceInstanceName, null, artifactData, null);
+ break;
+ default:
+ break;
+ }
+ }
+
+ private String getResourceInstanceNameFromComponent(Component component, String componentId) {
+ ComponentInstance resourceInstance = component.getComponentInstances()
+ .stream()
+ .filter(p -> p.getUniqueId().equals(componentId))
+ .findFirst()
+ .orElse(null);
+ String resourceInstanceName = null;
+ if (resourceInstance != null) {
+ resourceInstanceName = resourceInstance.getName();
+ }
+ return resourceInstanceName;
+ }
+
+ public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
+ Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ // Putting together artifact info
+ String artifactData = buildAuditingArtifactData(artifactDefinition);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
+ return auditingFields;
+ }
+
+ // -----
+
+ private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
+ StringBuilder sb = new StringBuilder();
+ if (artifactDefinition != null) {
+ sb.append(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();
+ }
+
+ private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
+
+ if (origMd5 != null) {
+ String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
+ if (!encodeBase64Str.equals(origMd5)) {
+ log.debug("The calculated md5 is different then the received one");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
+ }
+ }
+ else {
+ if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
+ log.debug("Missing md5 header during artifact create");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
+ }
+ // Update metadata
+ if (payload != null && payload.length != 0) {
+ log.debug("Cannot have payload while md5 header is missing");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
+ ComponentTypeEnum componentType, Component parentComponent) {
+
+ Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
+ if (artifactById.isRight()) {
+ return Either.right(artifactById.right().value());
+ }
+ ArtifactDefinition currentArtifactInfo = artifactById.left().value();
+
+ ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
+ Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
+ if (validateInformationalArtifactRes.isRight()) {
+ return Either.right(validateInformationalArtifactRes.right().value());
+ }
+ Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
+ if (validateAndSetArtifactname.isRight()) {
+ return Either.right(validateAndSetArtifactname.right().value());
+ }
+ if (operationName != null && interfaceName != null) {
+ operationName = operationName.toLowerCase();
+ interfaceName = interfaceName.toLowerCase();
+ }
+ Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
+ if (logicalNameStatus.isRight()) {
+ return Either.right(logicalNameStatus.right().value());
+ }
+ // This is a patch to block possibility of updating service api fields
+ // through other artifacts flow
+
+ ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
+ if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
+ checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
+ }
+ else {
+ checkCreateFields(user, artifactInfo, artifactGroupType);
+ }
+
+ composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
+ if (currentArtifactInfo != null) {
+ artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
+ }
+
+ // artifactGroupType is not allowed to be updated
+ if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
+ Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
+ if (validateGroupType.isRight()) {
+ return Either.right(validateGroupType.right().value());
+ }
+ }
+ // TODO TEMP !!!
+ NodeTypeEnum parentType = convertParentType(componentType);
+
+ // TODO TEMP !!!
+ boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
+
+ if (isDeploymentArtifact(artifactInfo)) {
+ Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
+ if (deploymentValidationResult.isRight()) {
+ return Either.right(deploymentValidationResult.right().value());
+ }
+ }
+ else {
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
+ }
+
+ Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
+ if (descriptionResult.isRight()) {
+ return Either.right(descriptionResult.right().value());
+ }
+
+ if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
+ .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
+ Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
+ if (validateServiceApiType.isRight()) {
+ return Either.right(validateServiceApiType.right().value());
+ }
+ // Change of type is not allowed and should be ignored
+
+ artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
+
+ Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
+ if (validateUrl.isRight()) {
+ return Either.right(validateUrl.right().value());
+ }
+
+ Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
+ if (validateUpdate.isRight()) {
+ log.debug("serviceApi first update cnnot be without payload.");
+ return Either.right(validateUpdate.right().value());
+ }
+ }
+ else {
+ Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
+ if (validateArtifactType.isRight()) {
+ return Either.right(validateArtifactType.right().value());
+ }
+ if (artifactInfo.getApiUrl() != null) {
+ artifactInfo.setApiUrl(null);
+ log.error("Artifact URL cannot be set through this API - ignoring");
+ }
+
+ if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
+ artifactInfo.setServiceApi(false);
+ log.error("Artifact service API flag cannot be changed - ignoring");
+ }
+ }
+
+ return Either.left(artifactInfo);
+ }
+
+ private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
+ if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
+ artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
+ artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
+ artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
+ }
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
+
+ Either<ArtifactDefinition, ResponseFormat> result = null;
+ ArtifactDefinition foundArtifact = null;
+ if (StringUtils.isNotEmpty(artifactId)) {
+ foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
+ }
+ if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
+ log.debug("Artifact {} already exist", artifactId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
+ }
+ if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
+ log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
+ }
+ if (result == null) {
+ result = Either.left(foundArtifact);
+ }
+ 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<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
+ ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
+ ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
+ Either<Boolean, ResponseFormat> validationResult = Either.left(true);
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
+ if (artifactType == null) {
+ validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
+ .getArtifactType()));
+ }
+ else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
+ String artifactTypeName = artifactType.getType();
+ ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
+ Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceInformationalArtifacts();
+ Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
+ if (!validArtifactTypes.contains(artifactTypeName)) {
+ validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
+ }
+ else {
+ List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
+ .getValidForResourceTypes();
+ if (!validResourceType.contains(parentResourceType.name())) {
+ validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
+ }
+ }
+ }
+ return validationResult;
+ }
+
+ private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
+ if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
+ return NodeTypeEnum.Resource;
+ }
+ else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
+ return NodeTypeEnum.ResourceInstance;
+ }
+ else {
+ return NodeTypeEnum.Service;
+ }
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
+ boolean shouldLock, boolean inTransaction) {
+
+ NodeTypeEnum parentType = convertParentType(componentType);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
+ ArtifactDefinition foundArtifact = null;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
+ org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
+ boolean isDuplicated = false;
+ String esId = null;
+ Either<Boolean, StorageOperationStatus> needCloneRes = null;
+ try {
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
+ .value(), componentType, null);
+ resultOp = Either.right(lockComponent.right().value());
+ }
+ }
+ if (resultOp == null) {
+ log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
+ getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
+ if (getContainerRes.isRight()) {
+ log.debug("Failed to fetch the container component {}. ", parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
+ .right()
+ .value()), artifactId);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ if (resultOp == null) {
+ fetchedContainerComponent = getContainerRes.left().value();
+ log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
+ getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
+ if (getArtifactRes.isRight()) {
+ log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
+ .getUniqueId());
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
+ .value(), artifactId);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ else {
+ foundArtifact = getArtifactRes.left().value().getLeft();
+ esId = foundArtifact.getEsId();
+ }
+ }
+ if (resultOp == null && StringUtils.isNotEmpty(esId)) {
+ needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
+ .getComponentType()));
+ if (needCloneRes.isRight()) {
+ log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
+ .right()
+ .value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ boolean isNeedToDeleteArtifactFromDB = true;
+ if (resultOp == null) {
+
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ String instanceId = parentId;
+ Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
+
+ if (isOnlyResourceInstanceArtifact.isRight()) {
+ log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
+ .value(), foundArtifact
+ .getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
+ }
+
+ Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
+ .left()
+ .value());
+ if (updatedArtifactRes.isRight()) {
+ log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
+ .right()
+ .value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ else {
+ isDuplicated = updatedArtifactRes.left().value().getDuplicated();
+ }
+ }
+
+ if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
+ log.debug("Going to delete the artifact {} from the database. ", artifactId);
+ CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
+ if (cassandraStatus != CassandraOperationStatus.OK) {
+ log.debug("Failed to delete the artifact {} from the database. ", artifactId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact
+ .getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+
+ List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
+ .left()
+ .value()
+ .getRight()
+ .getGroupInstances());
+ if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
+ Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
+ .right()
+ .value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ }
+ if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
+ if (status != StorageOperationStatus.OK) {
+ log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
+ .getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
+ List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
+ .getGroups());
+ if (CollectionUtils.isNotEmpty(updatedGroups)) {
+ Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
+ if (status.isRight()) {
+ log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
+ responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
+ .right()
+ .value()), foundArtifact.getArtifactDisplayName());
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ }
+ if (resultOp == null) {
+ resultOp = Either.left(Either.left(foundArtifact));
+ handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
+ }
+ return resultOp;
+ }
+ finally {
+ if (shouldLock) {
+ unlockComponent(resultOp, parent, inTransaction);
+ }
+ }
+ }
+
+ private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
+ Either<Boolean, ActionStatus> result = Either.left(true);
+ ComponentInstance foundInstance = null;
+ Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
+ .stream()
+ .filter(i -> i.getUniqueId().equals(instanceId))
+ .findFirst();
+ if (!componentInstanceOpt.isPresent()) {
+ result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
+ }
+ else {
+ foundInstance = componentInstanceOpt.get();
+ String componentUid = foundInstance.getComponentUid();
+ Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
+ if (getContainerRes.isRight()) {
+ log.debug("Failed to fetch the container component {}. ", componentUid);
+ return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
+ }
+ Component origComponent = getContainerRes.left().value();
+ Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
+ if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
+ Optional<String> op = deploymentArtifacts.keySet()
+ .stream()
+ .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
+ .findAny();
+ if (op.isPresent()) {
+ return Either.left(false);
+ }
+ }
+ Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
+ if (artifacts != null && !artifacts.isEmpty()) {
+ Optional<String> op = artifacts.keySet()
+ .stream()
+ .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
+ .findAny();
+ if (op.isPresent()) {
+ return Either.left(false);
+ }
+ }
+
+ }
+ return result;
+ }
+
+ private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
+ List<GroupDataDefinition> updatedGroups = new ArrayList<>();
+ boolean isUpdated = false;
+ if (groups != null) {
+ for (GroupDefinition group : groups) {
+ isUpdated = false;
+ if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
+ group.getArtifacts().remove(artifactId);
+ isUpdated = true;
+ }
+ if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
+ .contains(foundArtifact.getArtifactUUID())) {
+ group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
+ isUpdated = true;
+ }
+ if (isUpdated) {
+ updatedGroups.add(group);
+ }
+ }
+ }
+ return updatedGroups;
+ }
+
+ private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
+ List<GroupInstance> updatedGroupInstances = new ArrayList<>();
+ if (CollectionUtils.isNotEmpty(groupInstances)) {
+ boolean isUpdated = false;
+ for (GroupInstance groupInstance : groupInstances) {
+ isUpdated = false;
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
+ .contains(artifactId)) {
+ groupInstance.getGroupInstanceArtifacts().remove(artifactId);
+ isUpdated = true;
+ }
+ if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
+ .contains(foundArtifact
+ .getArtifactUUID())) {
+ groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
+ isUpdated = true;
+ }
+ if (isUpdated) {
+ updatedGroupInstances.add(groupInstance);
+ }
+ }
+ }
+ return updatedGroupInstances;
+ }
+
+ private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
+
+ Either<ArtifactDataDefinition, StorageOperationStatus> result;
+ boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
+ String componentId = component.getUniqueId();
+ String instanceId = componentId.equals(parentId) ? null : parentId;
+ if (isMandatory) {
+ log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
+ resetMandatoryArtifactFields(foundArtifact);
+ result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, 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);
+ }
+ else {
+ log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
+ result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
+ }
+ return result;
+ }
+
+ private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
+
+ Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
+ Map<String, ArtifactDefinition> artifacts = new HashMap<>();
+ ComponentInstance foundInstance = null;
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
+ Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
+ .stream()
+ .filter(i -> i.getUniqueId()
+ .equals(parentId))
+ .findFirst();
+ if (!componentInstanceOpt.isPresent()) {
+ result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
+ }
+ else {
+ foundInstance = componentInstanceOpt.get();
+ fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
+ }
+ }
+ else {
+ fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
+ }
+ if (result == null) {
+ if (artifacts.containsKey(artifactId)) {
+ result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
+ }
+ else {
+ result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
+ Map<String, ArtifactDefinition> currArtifacts;
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
+ currArtifacts = component.getDeploymentArtifacts()
+ .values()
+ .stream()
+ .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
+ currArtifacts = component.getArtifacts()
+ .values()
+ .stream()
+ .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
+ currArtifacts = component.getToscaArtifacts()
+ .values()
+ .stream()
+ .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ }
+
+ private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
+ Map<String, ArtifactDefinition> currArtifacts;
+ if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
+ currArtifacts = instance.getDeploymentArtifacts()
+ .values()
+ .stream()
+ .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
+ currArtifacts = instance.getArtifacts()
+ .values()
+ .stream()
+ .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
+ if (MapUtils.isNotEmpty(currArtifacts)) {
+ artifacts.putAll(currArtifacts);
+ }
+ }
+ }
+
+ private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
+ StorageOperationStatus result;
+ switch (cassandraStatus) {
+ case OK:
+ result = StorageOperationStatus.OK;
+ break;
+ case NOT_FOUND:
+ result = StorageOperationStatus.NOT_FOUND;
+ break;
+ case CLUSTER_NOT_CONNECTED:
+ case KEYSPACE_NOT_CONNECTED:
+ result = StorageOperationStatus.CONNECTION_FAILURE;
+ break;
+ default:
+ result = StorageOperationStatus.GENERAL_ERROR;
+ break;
+ }
+ return result;
+ }
+
+ private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
+ if (fetchedArtifact != null) {
+ log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
+ fetchedArtifact.setEsId(null);
+ fetchedArtifact.setArtifactName(null);
+ fetchedArtifact.setDescription(null);
+ fetchedArtifact.setApiUrl(null);
+ fetchedArtifact.setArtifactChecksum(null);
+ nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
+ fetchedArtifact.setArtifactUUID(null);
+ long time = System.currentTimeMillis();
+ fetchedArtifact.setPayloadUpdateDate(time);
+ fetchedArtifact.setHeatParameters(null);
+ fetchedArtifact.setHeatParamsUpdateDate(null);
+ }
+ }
+
+ private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
+ StorageOperationStatus error = StorageOperationStatus.OK;
+ if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+ log.debug("Need to re-generate customization UUID for instance {}", instanceId);
+ error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
+ }
+ return error;
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
+ Component parent) {
+ Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
+ .getUniqueId());
+ if (artifactById.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
+ log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ ArtifactDefinition artifactDefinition = artifactById.left().value();
+ if (artifactDefinition == null) {
+ log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+
+ Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
+ return Either.left(insideEither);
+ }
+
+ private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
+ ComponentTypeEnum componentType) {
+
+ String artifactLabel = artifactInfo.getArtifactLabel();
+ if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
+ .isEmpty())) {
+ BeEcompErrorManager.getInstance()
+ .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
+ log.debug("missing artifact logical name for component {}", componentId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
+ }
+ if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
+
+ if (operationName != null) {
+ if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
+ log.debug("artifact label cannot be set {}", artifactLabel);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
+ }
+ else {
+ artifactLabel = operationName;
+ }
+ }
+ String displayName = artifactInfo.getArtifactDisplayName();
+ if (displayName == null || displayName.isEmpty()) {
+ displayName = artifactLabel;
+ }
+ displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
+ artifactInfo.setArtifactDisplayName(displayName);
+
+ if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
+ log.debug("Invalid format form Artifact label : {}", artifactLabel);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
+
+ if (artifactLabel.isEmpty()) {
+ log.debug("missing normalized artifact logical name for component {}", componentId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
+ }
+
+ if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
+ log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
+ .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
+ }
+ if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
+ log.debug("Non unique Artifact label : {}", artifactLabel);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
+ }
+ }
+ artifactInfo.setArtifactLabel(artifactLabel);
+
+ return Either.left(ActionStatus.OK);
+ }
+
+ private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
+ boolean isUnique = true;
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
+ if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
+ artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
+ }
+ else {
+ artifacts = artifactToscaOperation.getArtifacts(componentId);
+ }
+
+ if (artifacts.isLeft()) {
+ for (String label : artifacts.left().value().keySet()) {
+ if (label.equals(artifactLabel)) {
+ isUnique = false;
+ break;
+ }
+ }
+ }
+ if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
+ .getAllInterfacesOfResource(componentId, true, true);
+ if (allInterfacesOfResource.isLeft()) {
+ for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
+ for (Operation operation : interace.getOperationsMap().values()) {
+ if (operation.getImplementation() != null && operation.getImplementation()
+ .getArtifactLabel()
+ .equals(artifactLabel)) {
+ isUnique = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+ return isUnique;
+ }
+
+ // ***************************************************************
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
+ ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ Either<ArtifactDefinition, Operation> insideEither = null;
+ ComponentInstance foundInstance = findComponentInstance(parentId, parent);
+ String instanceId = null;
+ String instanceName = null;
+ if (foundInstance != null) {
+ instanceId = foundInstance.getUniqueId();
+ instanceName = foundInstance.getName();
+ }
+ boolean isLeft = false;
+ String artifactUniqueId = null;
+ StorageOperationStatus error = null;
+ // information/deployment/api aritfacts
+ log.trace("Try to create entry on graph");
+ NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
+ .getUniqueId(), nodeType, true, instanceId);
+
+ isLeft = result.isLeft();
+ if (isLeft) {
+ artifactUniqueId = result.left().value().getUniqueId();
+ result.left().value();
+
+ insideEither = Either.left(result.left().value());
+ resultOp = Either.left(insideEither);
+
+ error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
+ if (error != StorageOperationStatus.OK) {
+ isLeft = false;
+ }
+
+ }
+ if (isLeft) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
+ return resultOp;
+ }
+ else {
+ log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
+ .getArtifactDisplayName());
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+
+ }
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
+ ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
+
+ ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ Either<ArtifactDefinition, Operation> insideEither = null;
+ ComponentInstance foundInstance = findComponentInstance(parentId, parent);
+ String instanceId = null;
+ String instanceName = null;
+ if (foundInstance != null) {
+ if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
+ log.debug("Failed to create artifact, already exists");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
+ .getArtifactLabel());
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
+ .getName());
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+
+ instanceId = foundInstance.getUniqueId();
+ instanceName = foundInstance.getName();
+ }
+ if (artifactData == null) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
+ log.debug("Failed to create artifact object for ES.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+
+ }
+ // set on graph object id of artifact in ES!
+ artifactInfo.setEsId(artifactData.getId());
+
+ boolean isLeft = false;
+ String artifactUniqueId = null;
+ StorageOperationStatus error = null;
+ if (interfaceType != null && operationName != null) {
+ // lifecycle artifact
+ Operation operation = convertToOperation(artifactInfo, operationName);
+
+ Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
+
+ isLeft = result.isLeft();
+ if (isLeft) {
+ artifactUniqueId = result.left().value().getImplementation().getUniqueId();
+ result.left().value().getImplementation();
+
+ insideEither = Either.right(result.left().value());
+ resultOp = Either.left(insideEither);
+ }
+ else {
+ error = result.right().value();
+ }
+ }
+ else {
+ // information/deployment/api aritfacts
+ log.trace("Try to create entry on graph");
+ NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
+ .getUniqueId(), nodeType, true, instanceId);
+
+ isLeft = result.isLeft();
+ if (isLeft) {
+ artifactUniqueId = result.left().value().getUniqueId();
+ artifactData.setId(result.left().value().getEsId());
+ insideEither = Either.left(result.left().value());
+ resultOp = Either.left(insideEither);
+
+ error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
+ if (error != StorageOperationStatus.OK) {
+ isLeft = false;
+ }
+
+ }
+ else {
+ error = result.right().value();
+ }
+ }
+ if (isLeft) {
+ boolean res = saveArtifacts(artifactData, parentId);
+
+ if (res) {
+ log.debug("Artifact saved into ES - {}", artifactUniqueId);
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
+ return resultOp;
+ }
+ else {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
+ log.debug("Failed to save the artifact.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
+
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+ }
+ else {
+ log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
+ .getArtifactDisplayName());
+ handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+
+ }
+
+ private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
+ ComponentInstance foundInstance = null;
+ if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
+ foundInstance = containerComponent.getComponentInstances()
+ .stream()
+ .filter(i -> i.getUniqueId().equals(componentInstanceId))
+ .findFirst()
+ .orElse(null);
+ }
+ return foundInstance;
+ }
+
+ private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
+
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
+
+ validateArtifactTypeExists(responseWrapper, artifactInfo);
+
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
+
+ Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
+
+ if (responseWrapper.isEmpty()) {
+ validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
+ }
+
+ // Common code for all types
+ // not allowed to change artifactType
+ if (responseWrapper.isEmpty() && !isCreate) {
+ Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
+ if (validateServiceApiType.isRight()) {
+ responseWrapper.setInnerElement(validateServiceApiType.right().value());
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ if (parentType.equals(NodeTypeEnum.Resource)) {
+ Resource resource = (Resource) parentComponent;
+ ResourceTypeEnum resourceType = resource.getResourceType();
+ ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
+ if (config == null) {
+ responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
+ .getArtifactType()));
+ }
+ else {
+ List<String> myList = config.getValidForResourceTypes();
+ Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
+ if (either.isRight()) {
+ responseWrapper.setInnerElement(either.right().value());
+ }
+ }
+ }
+
+ validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
+ }
+
+ if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
+ String artifactName = artifactInfo.getArtifactName();
+ if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
+ validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
+ }
+ }
+
+ if (responseWrapper.isEmpty()) {
+ switch (artifactType) {
+ case HEAT:
+ case HEAT_VOL:
+ case HEAT_NET:
+ result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
+ break;
+ case HEAT_ENV:
+ result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
+ break;
+ case DCAE_INVENTORY_TOSCA:
+ case DCAE_INVENTORY_JSON:
+ case DCAE_INVENTORY_POLICY:
+ // Validation is done in handle payload.
+ case DCAE_INVENTORY_DOC:
+ case DCAE_INVENTORY_BLUEPRINT:
+ case DCAE_INVENTORY_EVENT:
+ // No specific validation
+ default:
+ artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
+ break;
+ }
+
+ }
+
+ if (!responseWrapper.isEmpty()) {
+ result = Either.right(responseWrapper.getInnerElement());
+ }
+ return result;
+ }
+
+ private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
+ if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
+ .getArtifactType());
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
+ }
+ }
+
+ private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
+ Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
+ if (parentType.equals(NodeTypeEnum.Resource)) {
+ resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceDeploymentArtifacts();
+ }
+ else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
+ resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceInstanceDeploymentArtifacts();
+ }
+ else {
+ resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getServiceDeploymentArtifacts();
+ }
+ return resourceDeploymentArtifacts;
+ }
+
+ public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
+ if (artifactType == null) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
+ .getArtifactType());
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
+ }
+ }
+
+ private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
+ ArtifactTypeConfig retConfig = null;
+ String fileType = artifactType.getType();
+ if (parentType.equals(NodeTypeEnum.Resource)) {
+ retConfig = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceDeploymentArtifacts()
+ .get(fileType);
+ }
+ else if (parentType.equals(NodeTypeEnum.Service)) {
+ retConfig = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getServiceDeploymentArtifacts()
+ .get(fileType);
+ }
+ else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
+ retConfig = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceInstanceDeploymentArtifacts()
+ .get(fileType);
+ }
+ return retConfig;
+ }
+
+ private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
+ // extract heat parameters
+ if (artifactInfo.getPayloadData() != null) {
+ String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
+ .getArtifactType());
+ if (heatParameters.isRight() && (!heatParameters.right()
+ .value()
+ .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
+ log.info("failed to parse heat parameters ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
+ .getArtifactType());
+ return Either.right(responseFormat);
+ }
+ else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
+ artifactInfo.setListHeatParameters(heatParameters.left().value());
+ }
+ }
+ return Either.left(true);
+
+ }
+
+ // Valid extension
+ public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
+ String fileType = artifactType.getType();
+ List<String> acceptedTypes = null;
+ ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
+ if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
+ log.debug("parent type of artifact can be either resource or service");
+ responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return;
+ }
+
+ if (deploymentAcceptedTypes == null) {
+ log.debug("parent type of artifact can be either resource or service");
+ responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
+ .getArtifactType()));
+ return;
+ }
+ else {
+ acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
+ }
+ /*
+ * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
+ */
+
+ String artifactName = artifactInfo.getArtifactName();
+ String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
+ // Pavel - File extension validation is case-insensitive - Ella,
+ // 21/02/2016
+ if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
+ log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
+ responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
+ return;
+ }
+ }
+
+ private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
+
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
+ Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
+ Wrapper<byte[]> payloadWrapper = new Wrapper<>();
+
+ if (errorWrapper.isEmpty()) {
+ validateValidYaml(errorWrapper, artifactInfo);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ // Validate Heat Exist
+ validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
+ .getComponentType());
+ }
+
+ if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
+ fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
+ }
+
+ if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
+ validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
+ }
+
+ // init Response
+ Either<Boolean, ResponseFormat> eitherResponse;
+ if (errorWrapper.isEmpty()) {
+ eitherResponse = Either.left(true);
+ }
+ else {
+ eitherResponse = Either.right(errorWrapper.getInnerElement());
+ }
+ return eitherResponse;
+ }
+
+ public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
+ if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
+ Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
+ if (fillArtifactPayload.isRight()) {
+ errorWrapper.setInnerElement(fillArtifactPayload.right().value());
+ log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
+ }
+ }
+ else {
+ payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
+ }
+ }
+
+ public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
+ .getEsId());
+ if (eitherArtifactData.isLeft()) {
+ byte[] data = eitherArtifactData.left().value().getDataAsArray();
+ data = Base64.encodeBase64(data);
+ payloadWrapper.setInnerElement(data);
+ }
+ else {
+ StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
+ .right()
+ .value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
+ result = Either.right(responseFormat);
+ }
+ return result;
+
+ }
+
+ @SuppressWarnings("unchecked")
+ private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
+ String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
+ Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
+ String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
+ Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+
+ Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
+ Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
+ if (eitherHeatEnvProperties.isRight()) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
+ errorWrapper.setInnerElement(responseFormat);
+ log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
+ }
+ else if (eitherHeatProperties.isRight()) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
+ .getArtifactName(), heatArtifact.getArtifactName());
+ errorWrapper.setInnerElement(responseFormat);
+ log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
+ .getArtifactName());
+ }
+ else {
+ Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
+ Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
+ heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
+ if (!heatEnvPropertiesKeys.isEmpty()) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
+ .getArtifactName(), heatArtifact.getArtifactName());
+ errorWrapper.setInnerElement(responseFormat);
+ }
+ }
+ }
+
+ private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
+ YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
+ boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
+ if (!isYamlValid) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
+ .getArtifactType());
+ errorWrapper.setInnerElement(responseFormat);
+ log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
+ }
+ }
+
+ private boolean isValidXml(byte[] xmlToParse) {
+ boolean isXmlValid = true;
+ try {
+ XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
+ setFeatures(reader);
+ reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
+ }
+ catch (ParserConfigurationException | IOException | SAXException e) {
+ log.debug("Xml is invalid : {}", e.getMessage(), e);
+ isXmlValid = false;
+ }
+ return isXmlValid;
+ }
+
+ private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
+ try {
+ reader.setFeature("http://apache.org/xml/features/validation/schema", false);
+ reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ }
+ catch (SAXNotRecognizedException e) {
+ log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
+ }
+ }
+
+ private boolean isValidJson(byte[] jsonToParse) {
+ String parsed = new String(jsonToParse);
+ try {
+ gson.fromJson(parsed, Object.class);
+ }
+ catch (Exception e) {
+ log.debug("Json is invalid : {}", e.getMessage(), e);
+ return false;
+ }
+ return true;
+ }
+
+ private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
+ boolean artifactNameFound = false;
+ Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
+ .iterator();
+
+ while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
+ artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
+ }
+ if (artifactNameFound) {
+ String parentName = parentComponent.getName();
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
+ .name(), parentName, artifactName);
+
+ errorWrapper.setInnerElement(responseFormat);
+ log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
+
+ }
+ }
+
+ private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
+ ComponentTypeEnum componentType) {
+ Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
+ if (res.isRight()) {
+ ResponseFormat responseFormat;
+ if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
+ responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
+ }
+ else {
+ responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
+ }
+ errorWrapper.setInnerElement(responseFormat);
+ return;
+ }
+ ArtifactDefinition heatArtifact = res.left().value();
+ heatArtifactMDWrapper.setInnerElement(heatArtifact);
+ }
+
+ private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
+ log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
+ // timeout > 0 for HEAT artifacts
+ Integer timeout = artifactInfo.getTimeout();
+ if (timeout == null) {
+ Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
+ artifactInfo.setTimeout(defaultTimeout);
+ // HEAT artifact but timeout is invalid
+ }
+ else if (timeout < 1) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
+ }
+
+ // US649856 - Allow several HEAT files on Resource
+ log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
+ String listToString = (typeList != null) ? typeList.toString() : "";
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
+ .getArtifactName(), listToString, resourceType.getValue());
+ Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
+ String resourceTypeName = resourceType.name();
+ if (typeList != null && typeList.contains(resourceTypeName)) {
+ either = Either.left(true);
+ }
+ return either;
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
+ if (artifactInfo.getHeatParameters() != null) {
+ for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
+ String parameterType = heatParam.getType();
+ HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
+ String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
+ if (heatParameterType == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
+ .getType());
+ return Either.right(responseFormat);
+ }
+
+ StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
+ if (validateAndUpdateProperty != StorageOperationStatus.OK) {
+ log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
+ ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
+ .getType(), heatParam.getName());
+ return Either.right(responseFormat);
+ }
+ }
+ }
+ return Either.left(artifactInfo);
+ }
+
+ public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
+ List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
+ if (parentComponent.getDeploymentArtifacts() != null) {
+ if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
+ Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
+ if (getRI.isRight()) {
+ return deploymentArtifacts;
+ }
+ ComponentInstance ri = getRI.left().value();
+ if (ri.getDeploymentArtifacts() != null) {
+ deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
+ }
+ }
+ else if (parentComponent.getDeploymentArtifacts() != null) {
+ deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
+ }
+ }
+ return deploymentArtifacts;
+ }
+
+ private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
+ // on create if null add informational to current
+ if (artifactInfo.getArtifactGroupType() == null) {
+ artifactInfo.setArtifactGroupType(type);
+ }
+ if (artifactInfo.getUniqueId() != null) {
+ log.error("artifact uniqid cannot be set ignoring");
+ }
+ artifactInfo.setUniqueId(null);
+
+ if (artifactInfo.getArtifactRef() != null) {
+ log.error("artifact ref cannot be set ignoring");
+ }
+ artifactInfo.setArtifactRef(null);
+
+ if (artifactInfo.getArtifactRepository() != null) {
+ log.error("artifact repository cannot be set ignoring");
+ }
+ artifactInfo.setArtifactRepository(null);
+
+ if (artifactInfo.getUserIdCreator() != null) {
+ log.error("creator uuid cannot be set ignoring");
+ }
+ artifactInfo.setArtifactCreator(user.getUserId());
+
+ if (artifactInfo.getUserIdLastUpdater() != null) {
+ log.error("userId of last updater cannot be set ignoring");
+ }
+ artifactInfo.setUserIdLastUpdater(user.getUserId());
+
+ if (artifactInfo.getCreatorFullName() != null) {
+ log.error("creator Full name cannot be set ignoring");
+ }
+ String fullName = user.getFirstName() + " " + user.getLastName();
+ artifactInfo.setUpdaterFullName(fullName);
+
+ if (artifactInfo.getUpdaterFullName() != null) {
+ log.error("updater Full name cannot be set ignoring");
+ }
+ artifactInfo.setUpdaterFullName(fullName);
+
+ if (artifactInfo.getCreationDate() != null) {
+ log.error("Creation Date cannot be set ignoring");
+ }
+ long time = System.currentTimeMillis();
+ artifactInfo.setCreationDate(time);
+
+ if (artifactInfo.getLastUpdateDate() != null) {
+ log.error("Last Update Date cannot be set ignoring");
+ }
+ artifactInfo.setLastUpdateDate(time);
+
+ if (artifactInfo.getEsId() != null) {
+ log.error("es id cannot be set ignoring");
+ }
+ artifactInfo.setEsId(null);
+
+ }
+
+
+ private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
+ String id = artifactId;
+ if (artifactId == null || artifactId.isEmpty()) {
+ String uniqueId = null;
+ if (interfaceName != null && operationName != null) {
+ uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
+ .getArtifactLabel());
+ }
+ else {
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
+ }
+ artifactInfo.setUniqueId(uniqueId);
+ artifactInfo.setEsId(uniqueId);
+ id = uniqueId;
+ }
+ else {
+ artifactInfo.setUniqueId(artifactId);
+ artifactInfo.setEsId(artifactId);
+ }
+ return id;
+ }
+
+ private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
+ if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
+ BeEcompErrorManager.getInstance()
+ .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
+ log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
+ }
+
+ boolean artifactTypeExist = false;
+ Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
+ ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
+
+ if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
+ allArtifactTypes = getDeploymentArtifactTypes(parentType);
+ }
+ else {
+
+ allArtifactTypes = elementOperation.getAllArtifactTypes();
+ }
+ if (allArtifactTypes.isRight()) {
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
+ .right()
+ .value()
+ .name());
+ log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
+ .value());
+ return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
+ }
+
+ for (ArtifactType type : allArtifactTypes.left().value()) {
+ if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
+ artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
+ artifactTypeExist = true;
+ break;
+ }
+ }
+
+ if (!artifactTypeExist) {
+ BeEcompErrorManager.getInstance()
+ .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
+ .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
+ log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
+ .getArtifactType()));
+ }
+
+ return Either.left(ActionStatus.OK);
+ }
+
+ private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
+
+ Map<String, ArtifactTypeConfig> deploymentArtifacts ;
+ List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
+
+ if (parentType.equals(NodeTypeEnum.Service)) {
+ deploymentArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getServiceDeploymentArtifacts();
+ }
+ else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
+ deploymentArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceInstanceDeploymentArtifacts();
+ }
+ else {
+ deploymentArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getResourceDeploymentArtifacts();
+ }
+ if (deploymentArtifacts != null) {
+ for (String artifactType : deploymentArtifacts.keySet()) {
+ ArtifactType artifactT = new ArtifactType();
+ artifactT.setName(artifactType);
+ artifactTypes.add(artifactT);
+ }
+ return Either.left(artifactTypes);
+ }
+ else {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
+ if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
+ }
+ return Either.left(true);
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
+ if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
+ }
+
+ String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
+ if (normalizeFileName == null || normalizeFileName.isEmpty()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
+ }
+ artifactInfo.setArtifactName(normalizeFileName);
+
+ if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
+ }
+
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
+ if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
+ log.info("artifact type is missing operation ignored");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
+ }
+
+ if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
+ log.info("artifact type cannot be changed operation ignored");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ return Either.left(true);
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
+ if (artifactInfo.getArtifactGroupType() == null) {
+ artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
+ }
+
+ else if (!currentArtifact.getArtifactGroupType()
+ .getType()
+ .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
+ log.info("artifact group type cannot be changed. operation failed");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ return Either.left(artifactInfo);
+ }
+
+ private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
+
+ // on update if null add informational to current
+ if (currentArtifact.getArtifactGroupType() == null && type != null) {
+ currentArtifact.setArtifactGroupType(type);
+ }
+
+ if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
+ log.error("artifact uniqid cannot be set ignoring");
+ }
+ artifactInfo.setUniqueId(currentArtifact.getUniqueId());
+
+ if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
+ .equals(artifactInfo.getArtifactRef())) {
+ log.error("artifact ref cannot be set ignoring");
+ }
+ artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
+
+ if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
+ .equals(artifactInfo.getArtifactRepository())) {
+ log.error("artifact repository cannot be set ignoring");
+ }
+ artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
+
+ if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
+ .equals(artifactInfo.getUserIdCreator())) {
+ log.error("creator uuid cannot be set ignoring");
+ }
+ artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
+
+ if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
+ .equals(artifactInfo.getArtifactCreator())) {
+ log.error("artifact creator cannot be set ignoring");
+ }
+ artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
+
+ if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
+ .equals(artifactInfo.getUserIdLastUpdater())) {
+ log.error("userId of last updater cannot be set ignoring");
+ }
+ artifactInfo.setUserIdLastUpdater(user.getUserId());
+
+ if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
+ .equals(artifactInfo.getCreatorFullName())) {
+ log.error("creator Full name cannot be set ignoring");
+ }
+ artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
+
+ if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
+ .equals(artifactInfo.getUpdaterFullName())) {
+ log.error("updater Full name cannot be set ignoring");
+ }
+ String fullName = user.getFirstName() + " " + user.getLastName();
+ artifactInfo.setUpdaterFullName(fullName);
+
+ if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
+ .equals(artifactInfo.getCreationDate())) {
+ log.error("Creation Date cannot be set ignoring");
+ }
+ artifactInfo.setCreationDate(currentArtifact.getCreationDate());
+
+ if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
+ .equals(artifactInfo.getLastUpdateDate())) {
+ log.error("Last Update Date cannot be set ignoring");
+ }
+ long time = System.currentTimeMillis();
+ artifactInfo.setLastUpdateDate(time);
+
+ if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
+ log.error("es id cannot be set ignoring");
+ }
+ artifactInfo.setEsId(currentArtifact.getUniqueId());
+
+ if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
+ .equals(artifactInfo.getArtifactDisplayName())) {
+ log.error(" Artifact Display Name cannot be set ignoring");
+ }
+ artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
+
+ if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
+ .equals(artifactInfo.getServiceApi())) {
+ log.debug("serviceApi cannot be set. ignoring.");
+ }
+ artifactInfo.setServiceApi(currentArtifact.getServiceApi());
+
+ if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
+ .equals(artifactInfo.getArtifactGroupType())) {
+ log.debug("artifact group cannot be set. ignoring.");
+ }
+ artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
+
+ artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
+
+ if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
+ .isEmpty() && !currentArtifact.getArtifactUUID()
+ .equals(artifactInfo.getArtifactUUID())) {
+ log.debug("artifact UUID cannot be set. ignoring.");
+ }
+ artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
+
+ if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
+ .getHeatParameters()
+ .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
+ checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
+ }
+ }
+
+ private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
+
+ Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
+ for (HeatParameterDefinition parameter : heatParameters) {
+ HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
+
+ if (currentParam != null) {
+
+ if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
+ log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
+ parameter.setName(currentParam.getName());
+ }
+ if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
+ .equalsIgnoreCase(currentParam.getDefaultValue())) {
+ log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
+ parameter.setDefaultValue(currentParam.getDefaultValue());
+ }
+ if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
+ log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
+ parameter.setType(currentParam.getType());
+ }
+ if (parameter.getDescription() != null && !parameter.getDescription()
+ .equalsIgnoreCase(currentParam.getDescription())) {
+ log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
+ parameter.setDescription(currentParam.getDescription());
+ }
+
+ // check and set current value
+ if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
+ log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
+ parameter.setCurrentValue(currentParam.getDefaultValue());
+ }
+ }
+ }
+ }
+
+ private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
+
+ Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
+ for (HeatParameterDefinition param : currentParameters) {
+ currentParamsMap.put(param.getUniqueId(), param);
+ }
+ return currentParamsMap;
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
+ if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
+ log.debug("Artifact url cannot be empty.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
+ }
+ artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
+
+ if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
+ }
+ if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
+ }
+
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
+ if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
+ log.debug("Artifact description cannot be empty.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
+ }
+ String description = artifactInfo.getDescription();
+ description = ValidationUtils.removeNoneUtf8Chars(description);
+ description = ValidationUtils.normaliseWhitespace(description);
+ description = ValidationUtils.stripOctets(description);
+ description = ValidationUtils.removeHtmlTagsOnly(description);
+ if (!ValidationUtils.validateIsEnglish(description)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
+ .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
+ }
+ artifactInfo.setDescription(description);
+ return Either.left(true);
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
+ ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
+ ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
+ String prevArtifactId = null;
+ String currArtifactId = artifactId;
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ Either<ArtifactDefinition, Operation> insideEither = null;
+
+ if (artifactData == null) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
+ log.debug("Failed to create artifact object for ES.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+ log.trace("Try to update entry on graph");
+ String artifactUniqueId = null;
+ ArtifactDefinition artifactDefinition = artifactInfo;
+ StorageOperationStatus error;
+
+ boolean isLeft;
+ if (!(interfaceType != null && operationName != null)) {
+ log.debug("Enty on graph is updated. Update artifact in ES");
+ boolean res = true;
+ // Changing previous and current artifactId for auditing
+ prevArtifactId = currArtifactId;
+ currArtifactId = artifactDefinition.getUniqueId();
+
+ NodeTypeEnum convertParentType = convertParentType(componentType);
+
+ if (decodedPayload == null) {
+ if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
+ Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
+ .getEsId());
+ if (artifactFromCassandra.isRight()) {
+ log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
+ error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
+ .value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
+ handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ return resultOp;
+ }
+ // clone data to new artifact
+ artifactData.setData(artifactFromCassandra.left().value().getData());
+ artifactData.setId(artifactFromCassandra.left().value().getId());
+ }
+ }
+ else {
+ if (artifactDefinition.getEsId() == null) {
+ artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+ artifactData.setId(artifactDefinition.getUniqueId());
+ }
+ }
+
+ Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent
+ .getUniqueId(), artifactId, convertParentType, parentId);
+ isLeft = result.isLeft();
+ if (isLeft) {
+ artifactUniqueId = result.left().value().getUniqueId();
+ artifactDefinition = result.left().value();
+ String artifactType = artifactInfo.getArtifactType();
+ if (NodeTypeEnum.Resource == convertParentType
+ && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
+ && !artifactUniqueId.equals(artifactId)) {
+ // need to update the generated id in heat env
+ Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
+ Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
+ .stream()
+ .filter(a -> a.getValue()
+ .getGeneratedFromId() != null && a
+ .getValue()
+ .getGeneratedFromId()
+ .equals(artifactId))
+ .findFirst();
+ if (findFirst.isPresent()) {
+ ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
+ artifactEnvInfo.setArtifactChecksum(null);
+ artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
+ }
+ }
+ error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
+
+ insideEither = Either.left(result.left().value());
+ resultOp = Either.left(insideEither);
+ if (error != StorageOperationStatus.OK) {
+ isLeft = false;
+ }
+
+ }
+ else {
+ error = result.right().value();
+ }
+ if (isLeft) {
+
+ // create new entry in ES
+ res = true;
+ if (artifactData.getData() != null) {
+ if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
+ artifactData.setId(artifactDefinition.getEsId());
+ }
+ res = saveArtifacts(artifactData, parentId);
+
+ }
+ }
+
+ if (res) {
+ log.debug("Artifact saved into ES - {}", artifactUniqueId);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
+ }
+ else {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
+ log.debug("Failed to save the artifact.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+
+ return resultOp;
+ }
+
+ private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
+ log.trace("Starting payload handling");
+ byte[] payload = artifactInfo.getPayloadData();
+ byte[] decodedPayload = null;
+
+ if (payload != null && payload.length != 0) {
+ // the generated artifacts were already decoded by the handler
+ decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
+ if (decodedPayload.length == 0) {
+ log.debug("Failed to decode the payload.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(responseFormat);
+ }
+
+ String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
+ artifactInfo.setArtifactChecksum(checkSum);
+ log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
+
+ // Specific payload validations of different types
+ Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
+ if (isDeploymentArtifact(artifactInfo)) {
+ log.trace("Starting deployment artifacts payload validation");
+ String artifactType = artifactInfo.getArtifactType();
+ if (ArtifactTypeEnum.HEAT.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
+ .getType()
+ .equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
+ isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
+ if (isValidPayload.isLeft()) {
+ isValidPayload = extractHeatParameters(artifactInfo);
+ }
+ }
+ else if (ArtifactTypeEnum.YANG_XML.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
+ .getType()
+ .equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.VENDOR_LICENSE.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
+ .getType()
+ .equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
+ .getType()
+ .equalsIgnoreCase(artifactType)) {
+ isValidPayload = validateXmlPayload(decodedPayload, artifactType);
+ }
+ else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
+ .getType()
+ .equalsIgnoreCase(artifactType)
+ || ArtifactTypeEnum.VES_EVENTS.getType()
+ .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
+ .getType()
+ .equalsIgnoreCase(artifactType)) {
+ String artifactFileName = artifactInfo.getArtifactName();
+ String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
+ switch (fileExtension) {
+ case "xml":
+ isValidPayload = validateXmlPayload(decodedPayload, artifactType);
+ break;
+ case "json":
+ isValidPayload = validateJsonPayload(decodedPayload, artifactType);
+ break;
+ case "yml":
+ case "yaml":
+ isValidPayload = validateYmlPayload(decodedPayload, artifactType);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ if (isValidPayload.isRight()) {
+ ResponseFormat responseFormat = isValidPayload.right().value();
+ return Either.right(responseFormat);
+ }
+
+ } // null/empty payload is normal if called from metadata update ONLY.
+ // The validation of whether this is metadata/payload update case is
+ // currently done separately
+ else {
+ if (!isArtifactMetadataUpdate) {
+ log.debug("Payload is missing.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
+ return Either.right(responseFormat);
+ }
+ }
+ log.trace("Ended payload handling");
+ return Either.left(decodedPayload);
+ }
+
+ private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
+ // Basic YAML validation
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+ if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
+ log.debug("Invalid YAML format");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
+ return Either.right(responseFormat);
+ }
+ if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
+ // HEAT specific YAML validation
+ DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
+ if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
+ log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
+ return Either.right(responseFormat);
+ }
+ }
+
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
+ Either<Boolean, ResponseFormat> res = Either.left(true);
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+ if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
+ log.debug("Invalid YAML format");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
+ res = Either.right(responseFormat);
+ }
+
+ return res;
+ }
+
+ private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
+ boolean isXmlValid = isValidXml(payload);
+ if (!isXmlValid) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
+ log.debug("Invalid XML content");
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
+ boolean isJsonValid = isValidJson(payload);
+ if (!isJsonValid) {
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+ .getResponseFormat(ActionStatus.INVALID_JSON, type);
+ log.debug("Invalid JSON content");
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ }
+
+ public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
+ boolean inTransaction) {
+ User user = new User();
+ user.setUserId(userUserId);
+ Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
+ if (parent.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
+ .right()
+ .value()));
+ return Either.right(responseFormat);
+ }
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
+ .left()
+ .value(),
+ false, inTransaction);
+ if (handleDelete.isRight()) {
+ return Either.right(handleDelete.right().value());
+ }
+ Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
+ return Either.left(result.right().value());
+
+ }
+
+ private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
+ Operation op = new Operation();
+ long time = System.currentTimeMillis();
+ op.setCreationDate(time);
+
+ String artifactName = artifactInfo.getArtifactName();
+ artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
+
+ op.setImplementation(artifactInfo);
+ op.setLastUpdateDate(time);
+ return op;
+ }
+
+ private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
+ String newArtifactName = operationName + "_" + artifactName;
+ log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
+ return newArtifactName;
+ }
+
+ // download by MSO
+ public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
+
+ // General validation
+ if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
+ log.debug("One of the function parameteres is null");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ // Normalizing artifact name
+ artifactName = ValidationUtils.normalizeFileName(artifactName);
+
+ // Resource validation
+ Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
+ if (validateResourceNameAndVersion.isRight()) {
+ return Either.right(validateResourceNameAndVersion.right().value());
+ }
+
+ Resource resource = validateResourceNameAndVersion.left().value();
+ String resourceId = resource.getUniqueId();
+
+ // Service validation
+ Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
+ if (validateServiceNameAndVersion.isRight()) {
+ return Either.right(validateServiceNameAndVersion.right().value());
+ }
+
+ Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
+ if (artifacts == null || artifacts.isEmpty()) {
+ log.debug("Deployment artifacts of resource {} are not found", resourceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+ }
+
+ ArtifactDefinition deploymentArtifact = null;
+
+ for (ArtifactDefinition artifactDefinition : artifacts.values()) {
+ if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
+ .equals(artifactName)) {
+ log.debug("Found deployment artifact {}", artifactName);
+ deploymentArtifact = artifactDefinition;
+ break;
+ }
+ }
+
+ if (deploymentArtifact == null) {
+ log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+ }
+
+ // Downloading the artifact
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
+ if (downloadArtifactEither.isRight()) {
+ log.debug("Download artifact {} failed", artifactName);
+ return Either.right(downloadArtifactEither.right().value());
+ }
+ log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
+ return Either.left(downloadArtifactEither.left().value().getRight());
+ }
+
+ // download by MSO
+ public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
+
+ // General validation
+ if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
+ log.debug("One of the function parameteres is null");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ // Normalizing artifact name
+ artifactName = ValidationUtils.normalizeFileName(artifactName);
+
+ // Service validation
+ Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
+ if (validateServiceNameAndVersion.isRight()) {
+ return Either.right(validateServiceNameAndVersion.right().value());
+ }
+
+ Service service = validateServiceNameAndVersion.left().value();
+
+ // ResourceInstance validation
+ Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
+ if (validateResourceInstance.isRight()) {
+ return Either.right(validateResourceInstance.right().value());
+ }
+
+ ComponentInstance resourceInstance = validateResourceInstance.left().value();
+
+ Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
+
+ final String finalArtifactName = artifactName;
+ Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
+
+ boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
+ .stream()
+ .anyMatch(filterArtifactByName);
+ ArtifactDefinition deployableArtifact;
+
+ if (!hasDeploymentArtifacts) {
+ log.debug("Deployment artifact with name {} not found", artifactName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
+ }
+
+ log.debug("Found deployment artifact {}", artifactName);
+ deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
+ // Downloading the artifact
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
+
+ if (downloadArtifactEither.isRight()) {
+ log.debug("Download artifact {} failed", artifactName);
+ return Either.right(downloadArtifactEither.right().value());
+ }
+ log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
+ return Either.left(downloadArtifactEither.left().value().getRight());
+ }
+
+ private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
+
+ List<ComponentInstance> riList = service.getComponentInstances();
+ for (ComponentInstance ri : riList) {
+ if (ri.getNormalizedName().equals(resourceInstanceName)) {
+ return Either.left(ri);
+ }
+ }
+
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
+ }
+
+ private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
+
+ Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
+ if (serviceListBySystemName.isRight()) {
+ log.debug("Couldn't fetch any service with name {}", serviceName);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
+ .right()
+ .value(), ComponentTypeEnum.SERVICE), serviceName));
+ }
+ List<Service> serviceList = serviceListBySystemName.left().value();
+ if (serviceList == null || serviceList.isEmpty()) {
+ log.debug("Couldn't fetch any service with name {}", serviceName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
+ }
+
+ Service foundService = null;
+ for (Service service : serviceList) {
+ if (service.getVersion().equals(serviceVersion)) {
+ log.trace("Found service with version {}", serviceVersion);
+ foundService = service;
+ break;
+ }
+ }
+
+ if (foundService == null) {
+ log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
+ .getValue(), serviceVersion));
+ }
+ return Either.left(foundService);
+ }
+
+ private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
+
+ Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
+ if (resourceListBySystemName.isRight()) {
+ log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
+ .right()
+ .value()), resourceName));
+ }
+ return Either.left(resourceListBySystemName.left().value());
+ }
+
+ public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
+ // Validation
+ log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
+ if (serviceName == null || serviceVersion == null || artifactName == null) {
+ log.debug("One of the function parameteres is null");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ // Normalizing artifact name
+ final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
+
+ // Service validation
+ Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
+ if (validateServiceNameAndVersion.isRight()) {
+ return Either.right(validateServiceNameAndVersion.right().value());
+ }
+
+ String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
+
+ // Looking for deployment or tosca artifacts
+ Service service = validateServiceNameAndVersion.left().value();
+
+ if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
+ log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
+ }
+
+ Optional<ArtifactDefinition> foundArtifactOptl = null;
+
+ if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
+ foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
+ // filters artifact by name
+ .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
+ }
+ if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
+ foundArtifactOptl = service.getToscaArtifacts().values().stream()
+ // filters TOSCA artifact by name
+ .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
+ }
+ if (!foundArtifactOptl.isPresent()) {
+ log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
+ }
+ log.debug("Found deployment artifact {}", normalizedArtifactName);
+ // Downloading the artifact
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
+ .get());
+ if (downloadArtifactEither.isRight()) {
+ log.debug("Download artifact {} failed", normalizedArtifactName);
+ return Either.right(downloadArtifactEither.right().value());
+ }
+ log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
+ return Either.left(downloadArtifactEither.left().value().getRight());
+ }
+
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
+ log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
+ Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
+ if (artifactById.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
+ log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
+ }
+ ArtifactDefinition artifactDefinition = artifactById.left().value();
+ if (artifactDefinition == null) {
+ log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
+ }
+
+ return downloadArtifact(artifactDefinition);
+ }
+
+ private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
+ boolean found = false;
+ Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
+ if (artifactsS != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
+ if (!found && deploymentArtifactsS != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
+ if (!found && toscaArtifactsS != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ switch (component.getComponentType()) {
+ case RESOURCE:
+ Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
+ if (!found && interfaces != null) {
+ for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
+ Map<String, Operation> operations = entry.getValue().getOperationsMap();
+ for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
+ if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
+ .getImplementation()
+ .getUniqueId()
+ .equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ }
+ break;
+ case SERVICE:
+ Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
+ if (!found && apiArtifacts != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ break;
+ default:
+
+ }
+
+ return found;
+ }
+
+ private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
+
+ boolean found = false;
+ List<ComponentInstance> resourceInstances = component.getComponentInstances();
+ ComponentInstance resourceInstance = null;
+ for (ComponentInstance ri : resourceInstances) {
+ if (ri.getUniqueId().equals(resourceInstanceId)) {
+ resourceInstance = ri;
+ break;
+ }
+ }
+ if (resourceInstance != null) {
+ Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
+ if (artifacts != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ if (!found) {
+ artifacts = resourceInstance.getArtifacts();
+ if (artifacts != null) {
+ for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
+ if (entry.getValue().getUniqueId().equals(artifactId)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ return found;
+ }
+
+ private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
+ String containerComponentType) {
+
+ ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
+ componentForAudit.getNodeType();
+
+ Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
+ .getToscaFullElement(componentId);
+
+ if (componentResult.isRight()) {
+ ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
+ log.debug("Service not found, serviceId {}", componentId);
+ handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
+ return Either.right(responseFormat);
+ }
+ return Either.left(componentResult.left().value());
+ }
+
+ private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
+ if (canWork.isRight()) {
+ String uniqueId = component.getUniqueId();
+ log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
+ handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
+ .value(), component
+ .getComponentType(), null);
+ return Either.right(canWork.right().value());
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
+
+ if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
+ String role = user.getRole();
+ if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
+ handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
+
+ if (validateUserExists.isRight()) {
+ User user = new User();
+ user.setUserId(userId);
+ handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right()
+ .value(), componentType, null);
+ return Either.right(validateUserExists.right().value());
+ }
+ return Either.left(validateUserExists.left().value());
+ }
+
+ protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
+ AuditingActionEnum auditingAction = null;
+ switch (operation.getArtifactOperationEnum()) {
+ case CREATE:
+ auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
+ break;
+ case UPDATE:
+ auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
+ break;
+ case DELETE:
+ auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
+ break;
+ case DOWNLOAD:
+ auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
+ break;
+ default:
+ break;
+ }
+ return auditingAction;
+ }
+
+ private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
+ String esArtifactId = artifactDefinition.getEsId();
+ Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
+ if (artifactfromES.isRight()) {
+ CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
+ StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
+ log.debug("Error when getting artifact from ES, error: {}", actionStatus);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
+ .getArtifactDisplayName());
+
+ return Either.right(responseFormat);
+ }
+
+ ESArtifactData esArtifactData = artifactfromES.left().value();
+ byte[] data = esArtifactData.getDataAsArray();
+ if (data == null) {
+ log.debug("Artifact data from ES is null");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
+ }
+ String artifactName = artifactDefinition.getArtifactName();
+ log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
+ return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
+ }
+
+ public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
+ return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
+ }
+
+ private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
+ CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
+
+ if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
+ log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
+ }
+ else {
+ log.info("Failed to save artifact {}.", artifactData.getId());
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
+ return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
+ }
+
+ private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
+ return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
+ }
+
+ public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
+ Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
+ if (user.isRight()) {
+ ResponseFormat responseFormat;
+ if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
+ log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ }
+ else {
+ log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
+ responseFormat = componentsUtils.getResponseFormat(user.right().value());
+ }
+ return Either.right(responseFormat);
+ }
+
+ ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
+ .left()
+ .value(), groupType);
+ return Either.left(artifactDefinition);
+ }
+
+ public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
+ ArtifactDefinition artifactInfo = new ArtifactDefinition();
+
+ String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
+ String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
+ String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
+
+ artifactInfo.setArtifactDisplayName(artifactName);
+ artifactInfo.setArtifactLabel(logicalName.toLowerCase());
+ artifactInfo.setArtifactType(artifactType);
+ artifactInfo.setDescription(artifactDescription);
+ artifactInfo.setArtifactGroupType(groupType);
+ nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
+
+ setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
+
+ return artifactInfo;
+ }
+
+ private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
+ String uniqueId = null;
+
+ if (resourceId != null) {
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
+ .toLowerCase());
+ artifactInfo.setUniqueId(uniqueId);
+ }
+ artifactInfo.setUserIdCreator(user.getUserId());
+ String fullName = user.getFullName();
+ artifactInfo.setUpdaterFullName(fullName);
+
+ long time = System.currentTimeMillis();
+
+ artifactInfo.setCreatorFullName(fullName);
+ artifactInfo.setCreationDate(time);
+
+ artifactInfo.setLastUpdateDate(time);
+ artifactInfo.setUserIdLastUpdater(user.getUserId());
+
+ artifactInfo.setMandatory(true);
+ }
+
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
+ return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
+ }
+
+ public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
+ return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
+ }
+
+ private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
+
+ byte[] payload = payloadStr.getBytes();
+
+ ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
+ return Either.left(artifactData);
+ }
+
+ /**
+ * @param artifactDefinition
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
+ String instanceId, boolean shouldLock, boolean inTransaction) {
+ String payload = generateHeatEnvPayload(artifactDefinition);
+ String prevUUID = artifactDefinition.getArtifactUUID();
+ ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
+ return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
+ .left()
+ .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
+ }
+
+ public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
+ boolean shouldLock, boolean inTransaction, String instanceId) {
+ String payload = generateHeatEnvPayload(artifactDefinition);
+ String prevUUID = artifactDefinition.getArtifactUUID();
+ ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
+ return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
+ .left()
+ .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
+ if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
List<ComponentInstance> componentInstances = component.getComponentInstances();
if (componentInstances != null) {
- Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
+ Optional<ComponentInstance> findFirst = componentInstances.stream()
+ .filter(ci -> ci.getUniqueId()
+ .equals(instanceId))
+ .findFirst();
if (findFirst.isPresent()) {
ComponentInstance relevantInst = findFirst.get();
- List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
+ List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
+ .getGroupInstances());
if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
updatedGroupInstances.forEach(gi -> {
@@ -3643,426 +3813,496 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Either<List<GroupInstance>, 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());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
+ .convertFromStorageResponse(status.right()
+ .value()), clonedBeforeGenerate.getArtifactDisplayName());
return Either.right(responseFormat);
}
}
}
}
}
- return Either.left(updatedArtDef);
- }
-
- private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
- List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
- StringBuilder sb = new StringBuilder();
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
- sb.append("parameters:\n");
- if (heatParameters != null) {
- heatParameters.sort(Comparator.comparing(e -> e.getName()));
-
- List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
-
- for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
-
- String heatValue = heatParameterDefinition.getCurrentValue();
- if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
- heatValue = heatParameterDefinition.getDefaultValue();
- if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
- empltyHeatValues.add(heatParameterDefinition);
- continue;
- }
- }
- HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
- if (type != null) {
- switch (type) {
- case BOOLEAN:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
- break;
- case NUMBER:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
- break;
- case COMMA_DELIMITED_LIST:
- case JSON:
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
- break;
- default:
- String value = heatValue;
- boolean starts = value.startsWith("\"");
- boolean ends = value.endsWith("\"");
- if (!(starts && ends)) {
- starts = value.startsWith("'");
- ends = value.endsWith("'");
- if (!(starts && ends)) {
- value = "\"" + value + "\"";
- }
- }
- sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
- sb.append("\n");
- break;
-
- }
- }
- }
- if (!empltyHeatValues.isEmpty()) {
- empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
- empltyHeatValues.forEach(hv -> {
- sb.append(" ").append(hv.getName()).append(":");
- HeatParameterType type = HeatParameterType.isValidType(hv.getType());
- if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
- sb.append(" \"\"").append("\n");
- } else {
- sb.append(" ").append("\n");
- }
- });
- }
- }
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
-
- // DE265919 fix
- String result = sb.toString().replaceAll("\\\\n", "\n");
-
- return result;
- }
-
- /**
- *
- * @param artifactDefinition
- * @param payload
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
- User modifier, boolean shouldLock, String instanceId) {
- return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
- () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
-
- }
-
- public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
- User modifier, boolean shouldLock, String instanceId) {
- return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, System::currentTimeMillis,
- () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
-
- }
-
- protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
- boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
-
- log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
- if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
-
- log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
- Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
- ESArtifactData artifactData = null;
-
- if (artifactDataRes.isLeft()) {
- artifactData = artifactDataRes.left().value();
- } else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
- return Either.right(artifactDataRes.right().value());
- }
- String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
- String oldCheckSum;
- String esArtifactId = artifactDefinition.getEsId();
- Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
- ESArtifactData esArtifactData;
- if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
- log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
- artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
- if (artifactfromES.isRight()) {
- CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
- StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
- log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus.name(), esArtifactId);
- return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
- }
- esArtifactData = artifactfromES.left().value();
- oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
- } else {
- oldCheckSum = artifactDefinition.getArtifactChecksum();
-
- }
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
-
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
- if (lockComponent.isRight()) {
- handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
- return Either.right(lockComponent.right().value());
- }
- }
- try {
- if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
-
- artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
- updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
- log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
- if (updateArifactDefinitionStatus.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
- return Either.right(responseFormat);
- }
- } else {
-
- oldCheckSum = artifactDefinition.getArtifactChecksum();
- artifactDefinition.setArtifactChecksum(newCheckSum);
- // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
- artifactDefinition.setEsId(artifactDefinition.getUniqueId());
- log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
- updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
-
- log.trace("Update Payload ", artifactDefinition.getEsId());
- }
- if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
-
- artifactDefinition = updateArifactDefinitionStatus.left().value();
- artifactData.setId(artifactDefinition.getUniqueId());
- CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
-
- if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
- titanDao.commit();
- log.debug("Artifact Saved In ES {}", artifactData.getId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
- } else {
- titanDao.rollback();
- log.info("Failed to save artifact {}.", artifactData.getId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
- return Either.right(responseFormat);
- }
- } else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
- log.debug("Failed To update artifact {}", artifactData.getId());
- handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
- ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
- return Either.right(responseFormat);
-
- }
- } finally {
- if (shouldLock) {
- graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
- }
- }
- }
-
- return Either.left(artifactDefinition);
- }
-
-
- public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
- return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(),
- artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
-
- }
-
- public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
- List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
-
- Map<String, Object> json = new HashMap<String, Object>();
- if (artifactId != null && !artifactId.isEmpty())
- json.put(Constants.ARTIFACT_ID, artifactId);
-
- json.put(Constants.ARTIFACT_NAME, artifactName);
- json.put(Constants.ARTIFACT_TYPE, artifactType);
- json.put(Constants.ARTIFACT_DESCRIPTION, description);
-
- if (artifactContent != null) {
- String encodedPayload = new String(artifactContent);
-
- // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
- // if (!isEncoded) {
- log.debug("payload is encoded. perform decode");
- encodedPayload = Base64.encodeBase64String(artifactContent);
- json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
- }
- // }
- json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
- json.put(Constants.ARTIFACT_LABEL, label);
- json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
- json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
- : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
- json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
- : heatParameters);
- return json;
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
-
- String jsonStr = gson.toJson(json);
- ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
- String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
- artifactDefinitionFromJson, null, jsonStr, null, null, null, user, containerComponent, false, false, true);
- if (uploadArtifactToService.isRight())
- return Either.right(uploadArtifactToService.right().value());
-
- return Either.left(uploadArtifactToService.left().value());
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
- org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
- convertParentType(componentType);
- String parentId = parent.getUniqueId();
- // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
- ArtifactDefinition currArtifact = artifactInfo;
-
- if (origMd5 != null) {
- Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
- if (validateMd5.isRight()) {
- ResponseFormat responseFormat = validateMd5.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
-
- if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
- Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
- if (deploymentValidationResult.isRight()) {
- ResponseFormat responseFormat = deploymentValidationResult.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
-
- Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
- if (payloadEither.isRight()) {
- ResponseFormat responseFormat = payloadEither.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- } else { // duplicate
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
- return Either.right(responseFormat);
- }
- }
-
- // lock resource
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
- if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
- return Either.right(lockComponent.right().value());
- }
- }
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- try {
- resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
- return resultOp;
-
- } finally {
- // unlock resource
- if (resultOp == null || resultOp.isRight()) {
- log.debug("all changes rollback");
- if (false == inTransaction)
- titanDao.rollback();
- } else {
- log.debug("all changes committed");
- if (false == inTransaction)
- titanDao.commit();
- }
- if (shouldLock)
- componentType = parent.getComponentType();
- NodeTypeEnum nodeType = componentType.getNodeType();
- graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
- // graphLockOperation.unlockComponent(parentId, parentType);
- }
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
- ComponentTypeEnum componentType, String origMd5) {
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
- /*
- * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
- */
- Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
- if (getRI.isRight()) {
- return Either.right(getRI.right().value());
- }
- ComponentInstance ri = getRI.left().value();
- Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
- if (getArtifactRes.isRight()) {
- return Either.right(getArtifactRes.right().value());
- }
- ArtifactDefinition currArtifact = getArtifactRes.left().value();
-
- if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
- List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
- List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
- new ArrayList<HeatParameterDefinition>();
-
- // upload
- if (origMd5 != null) {
- Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
- updatedHeatEnvParams, currArtifact.getArtifactName());
- if (uploadParamsValidationResult.isRight()) {
- ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
- artifactInfo.setListHeatParameters(updatedHeatEnvParams);
- }
-
- Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
- if (validateAndConvertHeatParamers.isRight()) {
- ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
-
- if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
- // fill reduced heat env parameters List for updating
- replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
- currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
- currArtifact.setListHeatParameters(currentHeatEnvParams);
-
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
- if (updateArifactRes.isRight()) {
- log.debug("Failed to update artifact on graph - {}", artifactId);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
- StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
- if (error != StorageOperationStatus.OK) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
-
- error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
- if (error != StorageOperationStatus.OK) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
- return Either.right(responseFormat);
- }
-
- }
- insideEither = Either.left(currArtifact);
- resultOp = Either.left(insideEither);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
- return resultOp;
- }
-
- private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
- for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
+ return Either.left(updatedArtDef);
+ }
+
+ private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
+ List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
+ StringBuilder sb = new StringBuilder();
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
+ sb.append("parameters:\n");
+ if (heatParameters != null) {
+ heatParameters.sort(Comparator.comparing(e -> e.getName()));
+
+ List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
+
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+
+ String heatValue = heatParameterDefinition.getCurrentValue();
+ if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
+ heatValue = heatParameterDefinition.getDefaultValue();
+ if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
+ empltyHeatValues.add(heatParameterDefinition);
+ continue;
+ }
+ }
+ HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
+ if (type != null) {
+ switch (type) {
+ case BOOLEAN:
+ sb.append(" ")
+ .append(heatParameterDefinition.getName())
+ .append(":")
+ .append(" ")
+ .append(Boolean.parseBoolean(heatValue))
+ .append("\n");
+ break;
+ case NUMBER:
+ sb.append(" ")
+ .append(heatParameterDefinition.getName())
+ .append(":")
+ .append(" ")
+ .append(new BigDecimal(heatValue).toPlainString())
+ .append("\n");
+ break;
+ case COMMA_DELIMITED_LIST:
+ case JSON:
+ sb.append(" ")
+ .append(heatParameterDefinition.getName())
+ .append(":")
+ .append(" ")
+ .append(heatValue)
+ .append("\n");
+ break;
+ default:
+ String value = heatValue;
+ boolean starts = value.startsWith("\"");
+ boolean ends = value.endsWith("\"");
+ if (!(starts && ends)) {
+ starts = value.startsWith("'");
+ ends = value.endsWith("'");
+ if (!(starts && ends)) {
+ value = "\"" + value + "\"";
+ }
+ }
+ sb.append(" ")
+ .append(heatParameterDefinition.getName())
+ .append(":")
+ .append(" ")
+ .append(value);
+ sb.append("\n");
+ break;
+
+ }
+ }
+ }
+ if (!empltyHeatValues.isEmpty()) {
+ empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
+ empltyHeatValues.forEach(hv -> {
+ sb.append(" ").append(hv.getName()).append(":");
+ HeatParameterType type = HeatParameterType.isValidType(hv.getType());
+ if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
+ .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
+ sb.append(" \"\"").append("\n");
+ }
+ else {
+ sb.append(" ").append("\n");
+ }
+ });
+ }
+ }
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
+
+ // DE265919 fix
+ return sb.toString().replaceAll("\\\\n", "\n");
+ }
+
+ /**
+ * @param artifactDefinition
+ * @param payload
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
+ User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
+ return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
+ .getHeatParamsUpdateDate(),
+ () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
+
+ }
+
+ public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
+ User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
+ return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
+ () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
+
+ }
+
+ protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
+ boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
+
+ log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
+ .getEsId());
+ if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
+ .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
+
+ log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
+ Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
+ ESArtifactData artifactData = null;
+
+ if (artifactDataRes.isLeft()) {
+ artifactData = artifactDataRes.left().value();
+ }
+ else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
+ .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+
+ return Either.right(artifactDataRes.right().value());
+ }
+ String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
+ String oldCheckSum;
+ String esArtifactId = artifactDefinition.getEsId();
+ Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
+ ESArtifactData esArtifactData;
+ if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
+ log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
+ artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
+ if (artifactfromES.isRight()) {
+ CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
+ StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
+ log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
+ return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
+ }
+ esArtifactData = artifactfromES.left().value();
+ oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
+ }
+ else {
+ oldCheckSum = artifactDefinition.getArtifactChecksum();
+
+ }
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
+
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
+ if (lockComponent.isRight()) {
+ handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
+ .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ try {
+ if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
+
+ artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
+ updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component
+ .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
+ log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
+ .getArtifactType(), artifactDefinition.getEsId());
+ if (updateArifactDefinitionStatus.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
+ .right()
+ .value()), artifactDefinition.getArtifactDisplayName());
+ log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
+ .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+
+ return Either.right(responseFormat);
+ }
+ }
+ else {
+
+ oldCheckSum = artifactDefinition.getArtifactChecksum();
+ artifactDefinition.setArtifactChecksum(newCheckSum);
+ artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+ log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
+ .getArtifactType(), artifactDefinition.getEsId());
+ updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component
+ .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
+
+ log.trace("Update Payload ", artifactDefinition.getEsId());
+ }
+ if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
+
+ artifactDefinition = updateArifactDefinitionStatus.left().value();
+ artifactData.setId(artifactDefinition.getUniqueId());
+ CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
+
+ if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
+ if (!inTransaction) {
+ titanDao.commit();
+ }
+ log.debug("Artifact Saved In ES {}", artifactData.getId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
+ .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+
+ }
+ else {
+ if (!inTransaction) {
+ titanDao.rollback();
+ }
+ log.info("Failed to save artifact {}.", artifactData.getId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
+ .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+
+ return Either.right(responseFormat);
+ }
+ }
+ else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
+ .right()
+ .value()), artifactDefinition.getArtifactDisplayName());
+ log.debug("Failed To update artifact {}", artifactData.getId());
+ handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
+ .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
+ ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
+
+ return Either.right(responseFormat);
+
+ }
+ }
+ finally {
+ if (shouldLock) {
+ graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
+ .getNodeType());
+ }
+ }
+ }
+
+ return Either.left(artifactDefinition);
+ }
+
+
+ public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
+ return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
+ .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
+ artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
+
+ }
+
+ public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
+ List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
+
+ Map<String, Object> json = new HashMap<String, Object>();
+ if (artifactId != null && !artifactId.isEmpty()) {
+ json.put(Constants.ARTIFACT_ID, artifactId);
+ }
+
+ json.put(Constants.ARTIFACT_NAME, artifactName);
+ json.put(Constants.ARTIFACT_TYPE, artifactType);
+ json.put(Constants.ARTIFACT_DESCRIPTION, description);
+
+ if (artifactContent != null) {
+ log.debug("payload is encoded. perform decode");
+ String encodedPayload = Base64.encodeBase64String(artifactContent);
+ json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
+ }
+ json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
+ json.put(Constants.ARTIFACT_LABEL, label);
+ json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
+ json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
+ : updatedRequiredArtifacts.stream()
+ .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
+ .getType()
+ .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
+ .map(e -> e.getFileName())
+ .collect(Collectors.toList()));
+ json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
+ : heatParameters);
+ return json;
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
+
+ String jsonStr = gson.toJson(json);
+ ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
+ String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
+ artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
+ if (uploadArtifactToService.isRight()) {
+ return Either.right(uploadArtifactToService.right().value());
+ }
+
+ return Either.left(uploadArtifactToService.left().value());
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
+ org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
+ convertParentType(componentType);
+ String parentId = parent.getUniqueId();
+ ArtifactDefinition currArtifact = artifactInfo;
+
+ if (origMd5 != null) {
+ Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
+ if (validateMd5.isRight()) {
+ ResponseFormat responseFormat = validateMd5.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+
+ if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
+ Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
+ if (deploymentValidationResult.isRight()) {
+ ResponseFormat responseFormat = deploymentValidationResult.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+
+ Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
+ if (payloadEither.isRight()) {
+ ResponseFormat responseFormat = payloadEither.right().value();
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ }
+ else { // duplicate
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ return Either.right(responseFormat);
+ }
+ }
+
+ // lock resource
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
+ if (lockComponent.isRight()) {
+ handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
+ .value(), componentType, null);
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ try {
+ resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
+ return resultOp;
+
+ }
+ finally {
+ // unlock resource
+ if (resultOp == null || resultOp.isRight()) {
+ log.debug("all changes rollback");
+ if (!inTransaction) {
+ titanDao.rollback();
+ }
+ }
+ else {
+ log.debug("all changes committed");
+ if (!inTransaction) {
+ titanDao.commit();
+ }
+ }
+ if (shouldLock) {
+ componentType = parent.getComponentType();
+ }
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
+ }
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
+ ComponentTypeEnum componentType, String origMd5) {
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
+ Either<ArtifactDefinition, Operation> insideEither = null;
+ Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
+ if (getRI.isRight()) {
+ return Either.right(getRI.right().value());
+ }
+ ComponentInstance ri = getRI.left().value();
+ Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
+ if (getArtifactRes.isRight()) {
+ return Either.right(getArtifactRes.right().value());
+ }
+ ArtifactDefinition currArtifact = getArtifactRes.left().value();
+
+ if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
+ .equals(ArtifactTypeEnum.HEAT_VOL
+ .getType()) || currArtifact
+ .getArtifactType()
+ .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+ List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
+ List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
+ new ArrayList<HeatParameterDefinition>();
+
+ // upload
+ if (origMd5 != null) {
+ Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
+ .getName(), currentHeatEnvParams,
+ updatedHeatEnvParams, currArtifact.getArtifactName());
+ if (uploadParamsValidationResult.isRight()) {
+ ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+ artifactInfo.setListHeatParameters(updatedHeatEnvParams);
+ }
+
+ Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
+ .getType());
+ if (validateAndConvertHeatParamers.isRight()) {
+ ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+
+ if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
+ // fill reduced heat env parameters List for updating
+ replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
+ currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
+ currArtifact.setListHeatParameters(currentHeatEnvParams);
+
+ Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent
+ .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
+ if (updateArifactRes.isRight()) {
+ log.debug("Failed to update artifact on graph - {}", artifactId);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
+ .right()
+ .value()));
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+ StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
+ if (error != StorageOperationStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+
+ error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
+ .value()
+ .getUniqueId(), parent.getUniqueId());
+ if (error != StorageOperationStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+
+ }
+ insideEither = Either.left(currArtifact);
+ resultOp = Either.left(insideEither);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
+ .getName());
+ return resultOp;
+ }
+
+ private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
+ for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
String paramName = heatEnvParam.getName();
for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
@@ -4071,1001 +4311,1144 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
}
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
- ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
- Either<ArtifactDefinition, Operation> insideEither = null;
- /*
- * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
- */
- String currentHeatId = currHeatArtifact.getUniqueId();
-
- String esArtifactId = currHeatArtifact.getEsId();
- Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
- if (artifactfromES.isRight()) {
- CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
- StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
- log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
- return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
- }
-
- ESArtifactData esArtifactData = artifactfromES.left().value();
- ArtifactDefinition updatedHeatArt = currHeatArtifact;
-
- List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
- List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
- List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
-
- if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
-
- String paramName;
- for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
-
- paramName = heatEnvParam.getName();
- for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
- if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
- String updatedParamValue = heatEnvParam.getCurrentValue();
- if (updatedParamValue == null)
- updatedParamValue = heatEnvParam.getDefaultValue();
- HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
- if (!paramType.getValidator().isValid(updatedParamValue, null)) {
- ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
- return Either.right(responseFormat);
-
- }
- currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
- newHeatEnvParams.add(currHeatParam);
- break;
- }
- }
- }
- if (!newHeatEnvParams.isEmpty()) {
- currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
- Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
-
- if (operationStatus.isRight()) {
- log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
- return Either.right(responseFormat);
-
- }
- updatedHeatArt = operationStatus.left().value();
- boolean res = true;
- if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
- esArtifactData.setId(updatedHeatArt.getEsId());
- res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
-
- if (res) {
- log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
- // resultOp = Either.left(result.left().value());
- // return resultOp;
- } else {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
- log.debug("Failed to save the artifact.");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
- resultOp = Either.right(responseFormat);
- // return resultOp;
- }
-
- insideEither = Either.left(updatedHeatArt);
- }
- }
- Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
- if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
- artifactEnvInfo.setArtifactChecksum(null);
- updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
- } else {
- updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
-
- }
- if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
- ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
- if (result != ActionStatus.OK) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
- return Either.right(responseFormat);
- }
- }
-
- if (updatedHeatEnvParams.isEmpty()) {
- return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
- }
- resultOp = Either.left(insideEither);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
- return resultOp;
-
- }
-
- private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
- return Either.right(responseFormat);
- }
-
-
- private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
- StorageOperationStatus error = StorageOperationStatus.OK;
- log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
- List<GroupInstance> groupsInstances = ri.getGroupInstances();
- // List<GroupInstance> associatedGroups = null;
- List<String> groupInstancesId = null;
- if (groupsInstances != null && !groupsInstances.isEmpty()) {
- groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
- }
- if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
- // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
- toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
- }
- return error;
-
- }
-
- public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
- String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
-
- if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
- return Either.right(responseFormat);
- }
-
- for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
- String paramName = uploadedHeatParam.getName();
- boolean isExistsInHeat = false;
- for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
- if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
- isExistsInHeat = true;
- uploadedHeatParam.setType(currHeatParam.getType());
- uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
- uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
- uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
- break;
- }
- }
- if (!isExistsInHeat) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
- handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
- return Either.right(responseFormat);
- }
- }
- return Either.left(updatedHeatEnvParams);
- }
-
- private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
- ResponseFormat responseFormat = null;
- List<ComponentInstance> ris = component.getComponentInstances();
- for (ComponentInstance ri : ris) {
- if (riID.equals(ri.getUniqueId())) {
- return Either.left(ri);
- }
- }
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
- log.debug("Resource Instance not found, resourceInstanceId {}", riID);
- handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
- return Either.right(responseFormat);
- }
-
- private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
- ResponseFormat responseFormat = null;
- Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
- for (ArtifactDefinition artifact : rtifactsMap.values()) {
- if (artifactId.equals(artifact.getUniqueId())) {
- return Either.left(artifact);
- }
- }
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
- handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
- return Either.right(responseFormat);
- }
-
- public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
- ArtifactDefinition ret;
- if (eitherArtifact.isLeft()) {
- ret = eitherArtifact.left().value();
- } else {
- ret = eitherArtifact.right().value().getImplementationArtifact();
- }
- return ret;
- }
-
- /**
- * downloads artifact of component by UUIDs
- *
- * @param componentType
- * @param componentUuid
- * @param artifactUUID
- * @param auditAdditionalParam
- * @return
- */
- public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<byte[], ResponseFormat> result;
- byte[] downloadedArtifact = null;
- Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
- if (errorWrapper.isEmpty()) {
- auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
- }
- if (errorWrapper.isEmpty()) {
- result = Either.left(downloadedArtifact);
- } else {
- result = Either.right(errorWrapper.getInnerElement());
- }
- return result;
- }
-
- /**
- * downloads an artifact of resource instance of component by UUIDs
- *
- * @param componentType
- * @param componentUuid
- * @param resourceInstanceName
- * @param artifactUUID
- * @param auditAdditionalParam
- * @return
- */
- public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<byte[], ResponseFormat> result;
- byte[] downloadedArtifact = null;
- ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
- if (errorWrapper.isEmpty()) {
- downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
- }
- if (errorWrapper.isEmpty()) {
- result = Either.left(downloadedArtifact);
- } else {
- result = Either.right(errorWrapper.getInnerElement());
- }
- return result;
- }
-
- /**
- * uploads an artifact to a component by UUID
- *
- * @param data
- * @param request
- * @param componentType
- * @param componentUuid
- * @param additionalParams
- * @param operation
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
- ArtifactOperationInfo operation) {
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
- ArtifactDefinition uploadArtifact = null;
- Component component = null;
- String componentId = null;
- ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- Either<ComponentMetadataData, StorageOperationStatus> 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);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
- }
- if (errorWrapper.isEmpty()) {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
- String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
-
- if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
- if (component != null) {
- componentId = component.getUniqueId();
- componentName = component.getName();
- }
- }
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
- }
- if (errorWrapper.isEmpty()) {
- actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- uploadArtifact = actionResult.left().value().left().value();
- uploadArtifactResult = Either.left(uploadArtifact);
- } else {
- uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
- }
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
- return uploadArtifactResult;
- }
-
- /**
- * upload an artifact to a resource instance by UUID
- *
- * @param data
- * @param request
- * @param componentType
- * @param componentUuid
- * @param resourceInstanceName
- * @param additionalParams
- * @param operation
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition uploadArtifact = null;
- Component component = null;
- String componentInstanceId;
- String componentId;
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> 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);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
- }
- if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- if (component == null) {
- componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
- } else {
- componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
- }
- }
- if (errorWrapper.isEmpty()) {
- componentInstanceId = componentRiPair.getRight().getUniqueId();
- componentId = componentRiPair.getLeft().getUniqueId();
- ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
-
- actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- uploadArtifact = actionResult.left().value().left().value();
- uploadArtifactResult = Either.left(uploadArtifact);
- } else {
- uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
- }
- updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
- return uploadArtifactResult;
- }
-
- /**
- * updates an artifact on a component by UUID
- *
- * @param data
- * @param request
- * @param componentType
- * @param componentUuid
- * @param artifactUUID
- * @param additionalParams
- * @param operation
- * TODO
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition updateArtifact = null;
- Component component = null;
- String componentId = null;
- String artifactId = null;
- ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- Either<ComponentMetadataData, StorageOperationStatus> 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);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- if (errorWrapper.isEmpty()) {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
- String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
-
- if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
- if (component != null) {
- componentId = component.getUniqueId();
- componentName = component.getName();
- }
- }
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
- }
- if (errorWrapper.isEmpty()) {
- artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
- }
- if (errorWrapper.isEmpty()) {
- actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- updateArtifact = actionResult.left().value().left().value();
- updateArtifactResult = Either.left(updateArtifact);
-
- } else {
- updateArtifactResult = Either.right(errorWrapper.getInnerElement());
- }
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
- return updateArtifactResult;
- }
-
- /**
- * updates an artifact on a resource instance by UUID
- *
- * @param data
- * @param request
- * @param componentType
- * @param componentUuid
- * @param resourceInstanceName
- * @param artifactUUID
- * @param additionalParams
- * @param operation
- * TODO
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
-
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition updateArtifact = null;
- Component component = null;
- String componentInstanceId = null;
- String componentId = null;
- String artifactId = null;
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> 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);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- if (component == null) {
- componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
- } else {
- componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
- }
- }
- if (errorWrapper.isEmpty()) {
- componentInstanceId = componentRiPair.getRight().getUniqueId();
- componentId = componentRiPair.getLeft().getUniqueId();
- artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
-
- actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- updateArtifact = actionResult.left().value().left().value();
- updateArtifactResult = Either.left(updateArtifact);
- } else {
- updateArtifactResult = Either.right(errorWrapper.getInnerElement());
- }
- updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
- return updateArtifactResult;
- }
-
- /**
- * deletes an artifact on a component by UUID
- *
- * @param request
- * @param componentType
- * @param componentUuid
- * @param artifactUUID
- * @param additionalParams
- * @param operation
- * TODO
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
- ArtifactOperationInfo operation) {
-
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition deleteArtifact = null;
- Component component = null;
- String componentId = null;
- String artifactId = null;
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- Either<ComponentMetadataData, StorageOperationStatus> 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);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
- }
- if (errorWrapper.isEmpty()) {
- componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
- String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
- if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
- if (component != null) {
- componentId = component.getUniqueId();
- componentName = component.getName();
- }
- }
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
- }
- if (errorWrapper.isEmpty()) {
- artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
- }
- if (errorWrapper.isEmpty()) {
- actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- deleteArtifact = actionResult.left().value().left().value();
- deleteArtifactResult = Either.left(deleteArtifact);
- } else {
- deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
- }
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
- return deleteArtifactResult;
- }
-
- /**
- * deletes an artifact from a resource instance by UUID
- *
- * @param request
- * @param componentType
- * @param componentUuid
- * @param resourceInstanceName
- * @param artifactUUID
- * @param additionalParams
- * @param operation
- * TODO
- * @return
- */
- public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
- Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
-
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
- ArtifactDefinition deleteArtifact = null;
- Component component = null;
- String componentInstanceId = null;
- String componentId = null;
- String artifactId = null;
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- ImmutablePair<Component, ComponentInstance> componentRiPair = null;
- Either<ComponentMetadataData, StorageOperationStatus> 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);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- }
- if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- if (component == null) {
- componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
- } else {
- componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
- }
- }
- if (errorWrapper.isEmpty()) {
- componentInstanceId = componentRiPair.getRight().getUniqueId();
- componentId = componentRiPair.getLeft().getUniqueId();
- artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
-
- actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
-
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- deleteArtifact = actionResult.left().value().left().value();
- deleteArtifactResult = Either.left(deleteArtifact);
- } else {
- deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
- }
- updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
- return deleteArtifactResult;
- }
-
- private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
- String artifactId = null;
- ArtifactDefinition foundArtifact = null;
- if (instance.getDeploymentArtifacts() != null) {
- foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
- }
- if (foundArtifact == null && instance.getArtifacts() != null) {
- foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
- }
- if (foundArtifact == null) {
- log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
- } else {
- artifactId = foundArtifact.getUniqueId();
- }
- return artifactId;
- }
-
- @SuppressWarnings("unchecked")
- public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
- Map<String, String> existingEnvVersions) {
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
- if (deploymentResourceArtifacts == null) {
- log.debug("no deployment artifacts are configured for generated artifacts");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
- if (placeHolderData == null) {
- log.debug("no env type {} are configured for generated artifacts", envType);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
- Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
- if (createArtifactPlaceHolder.isRight()) {
- return Either.right(createArtifactPlaceHolder.right().value());
- }
- ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
- artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
- artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
- artifactHeatEnv.setTimeout(0);
- buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
- // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
- handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
- ArtifactDefinition heatEnvPlaceholder;
- // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
- if (parentType != NodeTypeEnum.ResourceInstance) {
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component.getUniqueId(), parentType, parentId);
- if (addHeatEnvArtifact.isRight()) {
- log.debug("failed to create heat env artifact on resource instance");
- return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
- }
- heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
- } else {
- heatEnvPlaceholder = artifactHeatEnv;
- artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
- setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
- }
- // audit
- EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(heatEnvPlaceholder, "", heatEnvPlaceholder.getUniqueId());
- artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
- ComponentTypeEnum componentType = component.getComponentType();
- if (parentType == NodeTypeEnum.ResourceInstance) {
- componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
- }
- componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
- return Either.left(heatEnvPlaceholder);
- }
-
- private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
- if (artifact.getListHeatParameters() == null) {
- return;
- }
- List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
- for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
+ ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
+ Either<ArtifactDefinition, Operation> insideEither = null;
+ String currentHeatId = currHeatArtifact.getUniqueId();
+
+ String esArtifactId = currHeatArtifact.getEsId();
+ Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
+ if (artifactFromES.isRight()) {
+ CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
+ StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
+ log.debug("Error when getting artifact from ES, error: {}", actionStatus);
+ return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
+ }
+
+ ESArtifactData esArtifactData = artifactFromES.left().value();
+
+ ArtifactDefinition updatedHeatArt = currHeatArtifact;
+
+ List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
+ List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
+ List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
+
+ if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
+ .isEmpty()) {
+
+ String paramName;
+ for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
+
+ paramName = heatEnvParam.getName();
+ for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
+ if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
+
+ String updatedParamValue = heatEnvParam.getCurrentValue();
+ if (updatedParamValue == null) {
+ updatedParamValue = heatEnvParam.getDefaultValue();
+ }
+ HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
+ if (!paramType.getValidator().isValid(updatedParamValue, null)) {
+ ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
+ .getType(), paramType.getType(), paramName);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
+ return Either.right(responseFormat);
+
+ }
+ currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
+ newHeatEnvParams.add(currHeatParam);
+ break;
+ }
+ }
+ }
+ if (!newHeatEnvParams.isEmpty()) {
+ currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
+ Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent
+ .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
+
+ if (operationStatus.isRight()) {
+ log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
+ .right()
+ .value()));
+ return Either.right(responseFormat);
+
+ }
+ updatedHeatArt = operationStatus.left().value();
+ boolean res = true;
+ if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
+ esArtifactData.setId(updatedHeatArt.getEsId());
+ }
+ res = saveArtifacts(esArtifactData, parent.getUniqueId());
+
+ if (res) {
+ log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
+ .getUniqueId(), responseFormat, componentType, null);
+ }
+ else {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
+ log.debug("Failed to save the artifact.");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
+ .getUniqueId(), responseFormat, componentType, null);
+ resultOp = Either.right(responseFormat);
+ }
+
+ insideEither = Either.left(updatedHeatArt);
+ }
+ }
+ Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
+ if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
+ artifactEnvInfo.setArtifactChecksum(null);
+ updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
+ .getUniqueId(), componentType.getNodeType(), componentId);
+ }
+ else {
+ updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
+ .getNodeType());
+
+ }
+ if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
+ ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
+ .left()
+ .value(), parent, componentType);
+ if (result != ActionStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
+ return Either.right(responseFormat);
+ }
+ }
+
+ if (updatedHeatEnvParams.isEmpty()) {
+ return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
+ }
+ resultOp = Either.left(insideEither);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
+ return resultOp;
+
+ }
+
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
+ return Either.right(responseFormat);
+ }
+
+
+ private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
+ StorageOperationStatus error = StorageOperationStatus.OK;
+ log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
+ List<GroupInstance> groupsInstances = ri.getGroupInstances();
+ List<String> groupInstancesId = null;
+ if (groupsInstances != null && !groupsInstances.isEmpty()) {
+ groupInstancesId = groupsInstances.stream()
+ .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
+ .contains(artifactId))
+ .map(GroupInstanceDataDefinition::getUniqueId)
+ .collect(Collectors.toList());
+ }
+ if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
+ toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
+ }
+ return error;
+
+ }
+
+ public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
+ String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
+
+ if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
+ .getArtifactName(), currArtifactName);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
+ return Either.right(responseFormat);
+ }
+
+ for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
+ String paramName = uploadedHeatParam.getName();
+ boolean isExistsInHeat = false;
+ for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
+ if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
+
+ isExistsInHeat = true;
+ uploadedHeatParam.setType(currHeatParam.getType());
+ uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
+ uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
+ uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
+ break;
+ }
+ }
+ if (!isExistsInHeat) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
+ return Either.right(responseFormat);
+ }
+ }
+ return Either.left(updatedHeatEnvParams);
+ }
+
+ private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
+ ResponseFormat responseFormat = null;
+ List<ComponentInstance> ris = component.getComponentInstances();
+ for (ComponentInstance ri : ris) {
+ if (riID.equals(ri.getUniqueId())) {
+ return Either.left(ri);
+ }
+ }
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
+ log.debug("Resource Instance not found, resourceInstanceId {}", riID);
+ handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
+ return Either.right(responseFormat);
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
+ ResponseFormat responseFormat = null;
+ Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
+ for (ArtifactDefinition artifact : rtifactsMap.values()) {
+ if (artifactId.equals(artifact.getUniqueId())) {
+ return Either.left(artifact);
+ }
+ }
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
+ handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
+ .getName());
+ return Either.right(responseFormat);
+ }
+
+ public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
+ ArtifactDefinition ret;
+ if (eitherArtifact.isLeft()) {
+ ret = eitherArtifact.left().value();
+ }
+ else {
+ ret = eitherArtifact.right().value().getImplementationArtifact();
+ }
+ return ret;
+ }
+
+ /**
+ * downloads artifact of component by UUIDs
+ *
+ * @param componentType
+ * @param componentUuid
+ * @param artifactUUID
+ * @param auditAdditionalParam
+ * @return
+ */
+ public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<byte[], ResponseFormat> result;
+ byte[] downloadedArtifact = null;
+ Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
+ downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
+ }
+ if (errorWrapper.isEmpty()) {
+ result = Either.left(downloadedArtifact);
+ }
+ else {
+ result = Either.right(errorWrapper.getInnerElement());
+ }
+ return result;
+ }
+
+ /**
+ * downloads an artifact of resource instance of component by UUIDs
+ *
+ * @param componentType
+ * @param componentUuid
+ * @param resourceInstanceName
+ * @param artifactUUID
+ * @param auditAdditionalParam
+ * @return
+ */
+ public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<byte[], ResponseFormat> result;
+ byte[] downloadedArtifact = null;
+ ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
+ .getName());
+ }
+ if (errorWrapper.isEmpty()) {
+ result = Either.left(downloadedArtifact);
+ }
+ else {
+ result = Either.right(errorWrapper.getInnerElement());
+ }
+ return result;
+ }
+
+ /**
+ * uploads an artifact to a component by UUID
+ *
+ * @param data
+ * @param request
+ * @param componentType
+ * @param componentUuid
+ * @param additionalParams
+ * @param operation
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
+ ArtifactOperationInfo operation) {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
+ ArtifactDefinition uploadArtifact = null;
+ Component component = null;
+ String componentId = null;
+ ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ Either<ComponentMetadataData, StorageOperationStatus> 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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
+ }
+ if (errorWrapper.isEmpty()) {
+ componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
+
+ if (!getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
+ if (component != null) {
+ componentId = component.getUniqueId();
+ componentName = component.getName();
+ }
+ }
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+ }
+ if (errorWrapper.isEmpty()) {
+ actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
+ .right()
+ .value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ uploadArtifact = actionResult.left().value().left().value();
+ uploadArtifactResult = Either.left(uploadArtifact);
+ }
+ else {
+ uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
+ }
+ updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
+ return uploadArtifactResult;
+ }
+
+ /**
+ * upload an artifact to a resource instance by UUID
+ *
+ * @param data
+ * @param request
+ * @param componentType
+ * @param componentUuid
+ * @param resourceInstanceName
+ * @param additionalParams
+ * @param operation
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
+ ArtifactDefinition uploadArtifact = null;
+ Component component = null;
+ String componentInstanceId;
+ String componentId;
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ ImmutablePair<Component, ComponentInstance> componentRiPair = null;
+ Either<ComponentMetadataData, StorageOperationStatus> 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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
+ }
+ if (errorWrapper.isEmpty() && !getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getUniqueId(), userId, errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ if (component == null) {
+ componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
+ }
+ else {
+ componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ componentInstanceId = componentRiPair.getRight().getUniqueId();
+ componentId = componentRiPair.getLeft().getUniqueId();
+ ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
+
+ actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
+ .findParamByType(componentType));
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
+ .right()
+ .value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ uploadArtifact = actionResult.left().value().left().value();
+ uploadArtifactResult = Either.left(uploadArtifact);
+ }
+ else {
+ uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
+ }
+ updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
+ return uploadArtifactResult;
+ }
+
+ /**
+ * updates an artifact on a component by UUID
+ *
+ * @param data
+ * @param request
+ * @param componentType
+ * @param componentUuid
+ * @param artifactUUID
+ * @param additionalParams
+ * @param operation TODO
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
+ ArtifactDefinition updateArtifact = null;
+ Component component = null;
+ String componentId = null;
+ String artifactId = null;
+ ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ Either<ComponentMetadataData, StorageOperationStatus> 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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ }
+ if (errorWrapper.isEmpty()) {
+ componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
+
+ if (!getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
+ if (component != null) {
+ componentId = component.getUniqueId();
+ componentName = component.getName();
+ }
+ }
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+ }
+ if (errorWrapper.isEmpty()) {
+ artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
+ }
+ if (errorWrapper.isEmpty()) {
+ actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
+ .right()
+ .value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ updateArtifact = actionResult.left().value().left().value();
+ updateArtifactResult = Either.left(updateArtifact);
+
+ }
+ else {
+ updateArtifactResult = Either.right(errorWrapper.getInnerElement());
+ }
+ updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
+ return updateArtifactResult;
+ }
+
+ /**
+ * updates an artifact on a resource instance by UUID
+ *
+ * @param data
+ * @param request
+ * @param componentType
+ * @param componentUuid
+ * @param resourceInstanceName
+ * @param artifactUUID
+ * @param additionalParams
+ * @param operation TODO
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
+ ArtifactDefinition updateArtifact = null;
+ Component component = null;
+ String componentInstanceId = null;
+ String componentId = null;
+ String artifactId = null;
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ ImmutablePair<Component, ComponentInstance> componentRiPair = null;
+ Either<ComponentMetadataData, StorageOperationStatus> 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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ }
+ if (errorWrapper.isEmpty() && !getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getUniqueId(), userId, errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ if (component == null) {
+ componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
+ }
+ else {
+ componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ componentInstanceId = componentRiPair.getRight().getUniqueId();
+ componentId = componentRiPair.getLeft().getUniqueId();
+ artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
+
+ actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
+ .findParamByType(componentType));
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
+ .right()
+ .value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ updateArtifact = actionResult.left().value().left().value();
+ updateArtifactResult = Either.left(updateArtifact);
+ }
+ else {
+ updateArtifactResult = Either.right(errorWrapper.getInnerElement());
+ }
+ updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
+ return updateArtifactResult;
+ }
+
+ /**
+ * deletes an artifact on a component by UUID
+ *
+ * @param request
+ * @param componentType
+ * @param componentUuid
+ * @param artifactUUID
+ * @param additionalParams
+ * @param operation TODO
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
+ ArtifactOperationInfo operation) {
+
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
+ ArtifactDefinition deleteArtifact = null;
+ Component component = null;
+ String componentId = null;
+ String artifactId = null;
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ Either<ComponentMetadataData, StorageOperationStatus> 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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
+ }
+ if (errorWrapper.isEmpty()) {
+ componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
+ String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
+ if (!getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
+ if (component != null) {
+ componentId = component.getUniqueId();
+ componentName = component.getName();
+ }
+ }
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
+ }
+ if (errorWrapper.isEmpty()) {
+ artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
+ }
+ if (errorWrapper.isEmpty()) {
+ actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
+ .right()
+ .value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ deleteArtifact = actionResult.left().value().left().value();
+ deleteArtifactResult = Either.left(deleteArtifact);
+ }
+ else {
+ deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
+ }
+ updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
+ return deleteArtifactResult;
+ }
+
+ /**
+ * deletes an artifact from a resource instance by UUID
+ *
+ * @param request
+ * @param componentType
+ * @param componentUuid
+ * @param resourceInstanceName
+ * @param artifactUUID
+ * @param additionalParams
+ * @param operation TODO
+ * @return
+ */
+ public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
+ Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
+
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
+ ArtifactDefinition deleteArtifact = null;
+ Component component = null;
+ String componentInstanceId = null;
+ String componentId = null;
+ String artifactId = null;
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ ImmutablePair<Component, ComponentInstance> componentRiPair = null;
+ Either<ComponentMetadataData, StorageOperationStatus> 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);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ }
+ if (errorWrapper.isEmpty() && !getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ component = checkoutParentComponent(componentType, getComponentRes.left()
+ .value()
+ .getMetadataDataDefinition()
+ .getUniqueId(), userId, errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ if (component == null) {
+ componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
+ }
+ else {
+ componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ componentInstanceId = componentRiPair.getRight().getUniqueId();
+ componentId = componentRiPair.getLeft().getUniqueId();
+ artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+
+ actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
+ .findParamByType(componentType));
+
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
+ .right()
+ .value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ deleteArtifact = actionResult.left().value().left().value();
+ deleteArtifactResult = Either.left(deleteArtifact);
+ }
+ else {
+ deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
+ }
+ updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
+ return deleteArtifactResult;
+ }
+
+ private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
+ String artifactId = null;
+ ArtifactDefinition foundArtifact = null;
+ if (instance.getDeploymentArtifacts() != null) {
+ foundArtifact = instance.getDeploymentArtifacts()
+ .values()
+ .stream()
+ .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
+ .equals(artifactUUID))
+ .findFirst()
+ .orElse(null);
+ }
+ if (foundArtifact == null && instance.getArtifacts() != null) {
+ foundArtifact = instance.getArtifacts()
+ .values()
+ .stream()
+ .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
+ .equals(artifactUUID))
+ .findFirst()
+ .orElse(null);
+ }
+ if (foundArtifact == null) {
+ log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
+ }
+ else {
+ artifactId = foundArtifact.getUniqueId();
+ }
+ return artifactId;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
+ Map<String, String> existingEnvVersions) {
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getDeploymentResourceInstanceArtifacts();
+ if (deploymentResourceArtifacts == null) {
+ log.debug("no deployment artifacts are configured for generated artifacts");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
+ if (placeHolderData == null) {
+ log.debug("no env type {} are configured for generated artifacts", envType);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
+ Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
+ .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
+ if (createArtifactPlaceHolder.isRight()) {
+ return Either.right(createArtifactPlaceHolder.right().value());
+ }
+ ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
+ artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
+ artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
+ artifactHeatEnv.setTimeout(0);
+ buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
+ // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
+ handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
+ ArtifactDefinition heatEnvPlaceholder;
+ // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
+ if (parentType != NodeTypeEnum.ResourceInstance) {
+ Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
+ .getUniqueId(), parentType, parentId);
+ if (addHeatEnvArtifact.isRight()) {
+ log.debug("failed to create heat env artifact on resource instance");
+ return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
+ .right()
+ .value(), false), "", null));
+ }
+ heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
+ }
+ else {
+ heatEnvPlaceholder = artifactHeatEnv;
+ artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
+ setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
+ }
+ String artifactData = buildAuditingArtifactData(heatEnvPlaceholder);
+ ComponentTypeEnum componentType = component.getComponentType();
+ if (parentType == NodeTypeEnum.ResourceInstance) {
+ componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
+ }
+ componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType,
+ ResourceAuditData.newBuilder().build(),
+ ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
+ parentName, null, artifactData, null);
+ return Either.left(heatEnvPlaceholder);
+ }
+
+ private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
+ if (artifact.getListHeatParameters() == null) {
+ return;
+ }
+ List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
+ for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
heatEnvParameter.setCurrentValue(null);
heatEnvParameters.add(heatEnvParameter);
}
- artifactDefinition.setListHeatParameters(heatEnvParameters);
- }
-
- private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
- String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
- String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
- String name = heatArtifact.getArtifactName();
- String fileName;
- if (name == null) {
- name = heatArtifact.getArtifactLabel();
- fileName = name + "." + envExtension;
- } else {
- fileName = name.replaceAll("." + heatExtension, "." + envExtension);
- }
- heatEnvArtifact.setArtifactName(fileName);
- }
-
- private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
- if (null != existingEnvVersions) {
- String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
- if (null != prevVersion) {
- heatEnvArtifact.setArtifactVersion(prevVersion);
- }
- }
- }
-
- /**
- * Handles Artifacts Request For Inner Component
- *
- * @param artifactsToHandle
- * @param component
- * @param user
- * @param vfcsNewCreatedArtifacts
- * @param operation
- * @param shouldLock
- * @param inTransaction
- * @return
- */
- public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
- ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
-
- Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
- ComponentTypeEnum componentType = component.getComponentType();
- List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
- String originData;
- String origMd5;
- try {
- for (ArtifactDefinition artifact : artifactsToHandle) {
- originData = buildJsonStringForCsarVfcArtifact(artifact);
- origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
- actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
- if (actionResult.isRight()) {
- log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
- errorWrapper.setInnerElement(actionResult.right().value());
- if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
- vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
- }
- break;
- }
- uploadedArtifacts.add(actionResult.left().value().left().value());
- }
- if (errorWrapper.isEmpty()) {
- handleArtifactsResult = Either.left(uploadedArtifacts);
- } else {
- handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleArtifactsResult = Either.right(responseFormat);
- log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
- }
- return handleArtifactsResult;
- }
-
- private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
- ComponentInstance componentInstance = null;
- String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
- Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
- if (errorWrapper.isEmpty()) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
- if (componentInstance == null) {
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
- log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
- }
- }
- return componentInstance;
- }
-
- private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
-
- ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
- String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
- ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
- if (componentInstance == null) {
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
- log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
- } else {
- relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
- }
- return relatedComponentComponentInstancePair;
- }
-
- private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
- ComponentInstance componentInstance;
- ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
- Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
- if (errorWrapper.isEmpty()) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
- if (componentInstance == null) {
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
- log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
- } else {
- relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
- }
- }
- return relatedComponentComponentInstancePair;
- }
-
- private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
-
- byte[] downloadedArtifact = null;
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
- List<ArtifactDefinition> artifactsList = null;
- ArtifactDefinition deploymentArtifact = null;
- if (artifacts != null && !artifacts.isEmpty()) {
- artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
- }
- if (artifactsList == null || artifactsList.isEmpty()) {
- log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
- }
- if (errorWrapper.isEmpty()) {
- deploymentArtifact = artifactsList.get(0);
- downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
- if (downloadArtifactEither.isRight()) {
- log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
- errorWrapper.setInnerElement(downloadArtifactEither.right().value());
- }
- }
- if (errorWrapper.isEmpty()) {
- log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
- downloadedArtifact = downloadArtifactEither.left().value().getRight();
- }
- return downloadedArtifact;
- }
-
- private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
- Component component = null;
- Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
- if (getComponentRes.isRight()) {
- StorageOperationStatus status = getComponentRes.right().value();
- log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- } else {
- component = getComponentRes.left().value();
- }
- return component;
- }
-
- private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
- Component component = null;
- Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
- if (getComponentRes.isRight()) {
- StorageOperationStatus status = getComponentRes.right().value();
- log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
- } else {
- List<Component> value = getComponentRes.left().value();
- if (value.isEmpty()){
- log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
- ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
- } else {
- component = value.get(0);
- }
- }
- return component;
- }
-
- private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
- String artifactId = null;
- ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
- StorageOperationStatus storageStatus;
- ArtifactDefinition latestArtifact = null;
- List<ArtifactDefinition> artifacts = null;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
- if (getArtifactsRes.isRight()) {
- storageStatus = getArtifactsRes.right().value();
- log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
- if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
- actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
- }
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
- }
- if (errorWrapper.isEmpty()) {
- artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
- if (artifacts == null || artifacts.isEmpty()) {
- log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
- }
- }
- if (errorWrapper.isEmpty()) {
- latestArtifact = artifacts.stream().max((a1, a2) -> {
- int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
- if (compareRes == 0) {
- compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
- }
- return compareRes;
- }).get();
- if (latestArtifact == null) {
- log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
- }
- }
- if (errorWrapper.isEmpty()) {
- artifactId = latestArtifact.getUniqueId();
- }
- return artifactId;
- }
-
- private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
-
- Component component = null;
- Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
- if (getUserRes.isRight()) {
- log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
- }
- if (errorWrapper.isEmpty()) {
- User modifier = getUserRes.left().value();
- LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
- Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
- if (checkoutRes.isRight()) {
- log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
- errorWrapper.setInnerElement(checkoutRes.right().value());
- } else {
- component = checkoutRes.left().value();
- }
- }
- return component;
- }
-
- private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
- if (artifact == null) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
- if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
- }
- } else {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
- }
- }
-
- private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
- Map<String, Object> json = new HashMap<>();
- String artifactName = artifact.getArtifactName();
- json.put(Constants.ARTIFACT_NAME, artifactName);
- json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
- json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
- json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
- json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
- json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
- json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
- return gson.toJson(json);
- }
+ artifactDefinition.setListHeatParameters(heatEnvParameters);
+ }
+
+ private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
+ String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
+ String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
+ String name = heatArtifact.getArtifactName();
+ String fileName;
+ if (name == null) {
+ name = heatArtifact.getArtifactLabel();
+ fileName = name + "." + envExtension;
+ }
+ else {
+ fileName = name.replaceAll("." + heatExtension, "." + envExtension);
+ }
+ heatEnvArtifact.setArtifactName(fileName);
+ }
+
+ private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
+ if (null != existingEnvVersions) {
+ String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
+ if (null != prevVersion) {
+ heatEnvArtifact.setArtifactVersion(prevVersion);
+ }
+ }
+ }
+
+ /**
+ * Handles Artifacts Request For Inner Component
+ *
+ * @param artifactsToHandle
+ * @param component
+ * @param user
+ * @param vfcsNewCreatedArtifacts
+ * @param operation
+ * @param shouldLock
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
+ ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
+
+ Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
+ ComponentTypeEnum componentType = component.getComponentType();
+ List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
+ String originData;
+ String origMd5;
+ try {
+ for (ArtifactDefinition artifact : artifactsToHandle) {
+ originData = buildJsonStringForCsarVfcArtifact(artifact);
+ origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
+ actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
+ .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
+ if (actionResult.isRight()) {
+ log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
+ .getName(), actionResult.right().value());
+ errorWrapper.setInnerElement(actionResult.right().value());
+ if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
+ vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
+ }
+ break;
+ }
+ uploadedArtifacts.add(actionResult.left().value().left().value());
+ }
+ if (errorWrapper.isEmpty()) {
+ handleArtifactsResult = Either.left(uploadedArtifacts);
+ }
+ else {
+ handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
+ }
+ }
+ catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleArtifactsResult = Either.right(responseFormat);
+ log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
+ }
+ return handleArtifactsResult;
+ }
+
+ private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
+ ComponentInstance componentInstance = null;
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
+ Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ componentInstance = component.getComponentInstances()
+ .stream()
+ .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
+ .equals(normalizedName))
+ .findFirst()
+ .orElse(null);
+ if (componentInstance == null) {
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
+ .getComponentType()
+ .getValue(), component.getName()));
+ log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
+ }
+ }
+ return componentInstance;
+ }
+
+ private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
+
+ ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
+ ComponentInstance componentInstance = component.getComponentInstances()
+ .stream()
+ .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
+ .equals(normalizedName))
+ .findFirst()
+ .orElse(null);
+ if (componentInstance == null) {
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
+ .getComponentType()
+ .getValue(), component.getName()));
+ log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
+ }
+ else {
+ relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
+ }
+ return relatedComponentComponentInstancePair;
+ }
+
+ private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
+ ComponentInstance componentInstance;
+ ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
+ Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ componentInstance = component.getComponentInstances()
+ .stream()
+ .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
+ .findFirst()
+ .orElse(null);
+ if (componentInstance == null) {
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
+ .getComponentType()
+ .getValue(), component.getName()));
+ log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
+ }
+ else {
+ relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
+ }
+ }
+ return relatedComponentComponentInstancePair;
+ }
+
+ private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
+
+ byte[] downloadedArtifact = null;
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
+ List<ArtifactDefinition> artifactsList = null;
+ ArtifactDefinition deploymentArtifact = null;
+ if (artifacts != null && !artifacts.isEmpty()) {
+ artifactsList = artifacts.values()
+ .stream()
+ .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
+ .equals(artifactUUID))
+ .collect(Collectors.toList());
+ }
+ if (artifactsList == null || artifactsList.isEmpty()) {
+ log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
+ }
+ if (errorWrapper.isEmpty()) {
+ deploymentArtifact = artifactsList.get(0);
+ downloadArtifactEither = downloadArtifact(deploymentArtifact);
+ if (downloadArtifactEither.isRight()) {
+ log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
+ errorWrapper.setInnerElement(downloadArtifactEither.right().value());
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
+ downloadedArtifact = downloadArtifactEither.left().value().getRight();
+ }
+ return downloadedArtifact;
+ }
+
+ private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
+ Component component = null;
+ Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
+ if (getComponentRes.isRight()) {
+ StorageOperationStatus status = getComponentRes.right().value();
+ log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ }
+ else {
+ component = getComponentRes.left().value();
+ }
+ return component;
+ }
+
+ private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
+ Component component = null;
+ Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
+ if (getComponentRes.isRight()) {
+ StorageOperationStatus status = getComponentRes.right().value();
+ log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
+ }
+ else {
+ List<Component> value = getComponentRes.left().value();
+ if (value.isEmpty()) {
+ log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
+ ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
+ }
+ else {
+ component = value.get(0);
+ }
+ }
+ return component;
+ }
+
+ private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
+ String artifactId = null;
+ ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
+ StorageOperationStatus storageStatus;
+ ArtifactDefinition latestArtifact = null;
+ List<ArtifactDefinition> artifacts = null;
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
+ if (getArtifactsRes.isRight()) {
+ storageStatus = getArtifactsRes.right().value();
+ log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
+ if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
+ actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
+ }
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
+ }
+ if (errorWrapper.isEmpty()) {
+ artifacts = getArtifactsRes.left()
+ .value()
+ .values()
+ .stream()
+ .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
+ .equals(artifactUUID))
+ .collect(Collectors.toList());
+ if (artifacts == null || artifacts.isEmpty()) {
+ log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ latestArtifact = artifacts.stream().max((a1, a2) -> {
+ int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
+ if (compareRes == 0) {
+ compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
+ .getLastUpdateDate());
+ }
+ return compareRes;
+ }).get();
+ if (latestArtifact == null) {
+ log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
+ }
+ }
+ if (errorWrapper.isEmpty()) {
+ artifactId = latestArtifact.getUniqueId();
+ }
+ return artifactId;
+ }
+
+ private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
+
+ Component component = null;
+ Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
+ if (getUserRes.isRight()) {
+ log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
+ .right()
+ .value());
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
+ }
+ if (errorWrapper.isEmpty()) {
+ User modifier = getUserRes.left().value();
+ LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
+ Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
+ if (checkoutRes.isRight()) {
+ log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
+ .getNodeType(), parentId, checkoutRes.right().value().getStatus());
+ errorWrapper.setInnerElement(checkoutRes.right().value());
+ }
+ else {
+ component = checkoutRes.left().value();
+ }
+ }
+ return component;
+ }
+
+ private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
+ if (artifact == null) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
+ if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
+ }
+ }
+ else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
+ }
+ }
+
+ private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
+ Map<String, Object> json = new HashMap<>();
+ String artifactName = artifact.getArtifactName();
+ json.put(Constants.ARTIFACT_NAME, artifactName);
+ json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
+ json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
+ json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
+ json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
+ json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
+ json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
+ return gson.toJson(json);
+ }
+
+ @VisibleForTesting
+ void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
+ this.nodeTemplateOperation = nodeTemplateOperation;
+ }
}
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 2e14028338..6756108387 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
@@ -20,11 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -39,7 +35,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
/**
* This class holds the business logic relevant for attributes manipulation.
@@ -50,256 +49,256 @@ import fj.data.Either;
@Component("attributeBusinessLogic")
public class AttributeBusinessLogic extends BaseBusinessLogic {
- private static final String CREATE_ATTRIBUTE = "CreateAttribute";
- private static final String UPDATE_ATTRIBUTE = "UpdateAttribute";
- private static final String DELETE_ATTRIBUTE = "DeleteAttribute";
-
- private static Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class.getName());
-
- /**
- * Created attribute on the resource with resourceId
- *
- * @param resourceId
- * @param newAttributeDef
- * @param userId
- * @return AttributeDefinition if created successfully Or ResponseFormat
- */
- public Either<PropertyDefinition, ResponseFormat> createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) {
- Either<PropertyDefinition, ResponseFormat> result = null;
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Attribute", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
- if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- try {
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
- if (status.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
- Resource resource = status.left().value();
-
- // verify that resource is checked-out and the user is the last updater
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- // verify attribute does not exist in resource
- if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
- }
- Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (eitherAllDataTypes.isRight()) {
- return Either.right(eitherAllDataTypes.right().value());
- }
- // validate property default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value());
- if (defaultValuesValidation.isRight()) {
- return Either.right(defaultValuesValidation.right().value());
- }
-
- handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value());
-
- // add the new attribute to resource on graph
- // need to get StorageOpaerationStatus and convert to ActionStatus from
- // componentsUtils
- Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef);
- if (either.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
- return result;
- }
- result = Either.left(either.left().value());
-
- return result;
- } finally {
- commitOrRollback(result);
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
-
- }
-
- private boolean isAttributeExist(List<PropertyDefinition> 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();
- }
- return isExist;
-
- }
-
- /**
- * @param resourceId
- * @param attributeId
- * @param userId
- * @return
- */
- public Either<PropertyDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Attribute", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
- if (status.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
- Resource resource = status.left().value();
-
- List<PropertyDefinition> attributes = resource.getAttributes();
- if (attributes == null) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
- } else {
- Either<PropertyDefinition, ResponseFormat> result;
- // verify attribute exist in resource
- Optional<PropertyDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny();
-
- if (optionalAtt.isPresent()) {
- result = Either.left(optionalAtt.get());
- } else {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
- }
- return result;
- }
-
- }
-
- /**
- * Updates Attribute on resource
- *
- * @param resourceId
- * @param attributeId
- * @param newAttDef
- * @param userId
- * @return
- */
- public Either<PropertyDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) {
- Either<PropertyDefinition, ResponseFormat> result = null;
-
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
- if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- try {
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
- if (eitherResource.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
- Resource resource = eitherResource.left().value();
-
- // verify that resource is checked-out and the user is the last updater
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- // verify attribute exist in resource
- Either<PropertyDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
- if (eitherAttribute.isRight()) {
- return Either.right(eitherAttribute.right().value());
- }
- Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (eitherAllDataTypes.isRight()) {
- return Either.right(eitherAllDataTypes.right().value());
- }
-
- // validate attribute default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value());
- if (defaultValuesValidation.isRight()) {
- return Either.right(defaultValuesValidation.right().value());
- }
- // add the new property to resource on graph
-
- StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value());
- if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
- log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute);
- result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName()));
- }
-
-
- Either<PropertyDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);
-
- if (eitherAttUpdate.isRight()) {
- log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
- result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
- return result;
- }
-
- result = Either.left(eitherAttUpdate.left().value());
- return result;
- } finally {
- commitOrRollback(result);
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
-
- }
-
- /**
- * Deletes Attribute on resource
- *
- * @param resourceId
- * @param attributeId
- * @param userId
- * @return
- */
- public Either<PropertyDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {
-
- Either<PropertyDefinition, ResponseFormat> result = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
- if (lockResult != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- try {
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
- if (eitherResource.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
- Resource resource = eitherResource.left().value();
-
- // verify that resource is checked-out and the user is the last updater
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- // verify attribute exist in resource
- Either<PropertyDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId);
- if (eitherAttributeExist.isRight()) {
- return Either.right(eitherAttributeExist.right().value());
- }
- String attributeName = eitherAttributeExist.left().value().getName();
-
- // delete attribute of resource from graph
- StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName);
- if (eitherAttributeDelete != StorageOperationStatus.OK) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName()));
- return result;
- }
-
- result = Either.left(eitherAttributeExist.left().value());
- return result;
- } finally {
- commitOrRollback(result);
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
- }
+ private static final String CREATE_ATTRIBUTE = "CreateAttribute";
+ private static final String UPDATE_ATTRIBUTE = "UpdateAttribute";
+ private static final String DELETE_ATTRIBUTE = "DeleteAttribute";
+
+ private static final Logger log = LoggerFactory.getLogger(AttributeBusinessLogic.class);
+
+ /**
+ * Created attribute on the resource with resourceId
+ *
+ * @param resourceId
+ * @param newAttributeDef
+ * @param userId
+ * @return AttributeDefinition if created successfully Or ResponseFormat
+ */
+ public Either<PropertyDefinition, ResponseFormat> createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) {
+ Either<PropertyDefinition, ResponseFormat> result = null;
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Attribute", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
+ if (lockResult != StorageOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ try {
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
+ if (status.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ }
+ Resource resource = status.left().value();
+
+ // verify that resource is checked-out and the user is the last updater
+ if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ // verify attribute does not exist in resource
+ if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
+ }
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (eitherAllDataTypes.isRight()) {
+ return Either.right(eitherAllDataTypes.right().value());
+ }
+ // validate property default values
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes.left().value());
+ if (defaultValuesValidation.isRight()) {
+ return Either.right(defaultValuesValidation.right().value());
+ }
+
+ handleDefaultValue(newAttributeDef, eitherAllDataTypes.left().value());
+
+ // add the new attribute to resource on graph
+ // need to get StorageOpaerationStatus and convert to ActionStatus from
+ // componentsUtils
+ Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef);
+ if (either.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ return result;
+ }
+ result = Either.left(either.left().value());
+
+ return result;
+ } finally {
+ commitOrRollback(result);
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+
+ }
+
+ private boolean isAttributeExist(List<PropertyDefinition> 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();
+ }
+ return isExist;
+
+ }
+
+ /**
+ * @param resourceId
+ * @param attributeId
+ * @param userId
+ * @return
+ */
+ public Either<PropertyDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Attribute", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
+ if (status.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ }
+ Resource resource = status.left().value();
+
+ List<PropertyDefinition> attributes = resource.getAttributes();
+ if (attributes == null) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
+ } else {
+ Either<PropertyDefinition, ResponseFormat> result;
+ // verify attribute exist in resource
+ Optional<PropertyDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny();
+
+ if (optionalAtt.isPresent()) {
+ result = Either.left(optionalAtt.get());
+ } else {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
+ }
+ return result;
+ }
+
+ }
+
+ /**
+ * Updates Attribute on resource
+ *
+ * @param resourceId
+ * @param attributeId
+ * @param newAttDef
+ * @param userId
+ * @return
+ */
+ public Either<PropertyDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) {
+ Either<PropertyDefinition, ResponseFormat> result = null;
+
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
+ if (lockResult != StorageOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ try {
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
+ if (eitherResource.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ }
+ Resource resource = eitherResource.left().value();
+
+ // verify that resource is checked-out and the user is the last updater
+ if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ // verify attribute exist in resource
+ Either<PropertyDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
+ if (eitherAttribute.isRight()) {
+ return Either.right(eitherAttribute.right().value());
+ }
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (eitherAllDataTypes.isRight()) {
+ return Either.right(eitherAllDataTypes.right().value());
+ }
+
+ // validate attribute default values
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes.left().value());
+ if (defaultValuesValidation.isRight()) {
+ return Either.right(defaultValuesValidation.right().value());
+ }
+ // add the new property to resource on graph
+
+ StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes.left().value());
+ if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
+ log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute);
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName()));
+ }
+
+
+ Either<PropertyDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);
+
+ if (eitherAttUpdate.isRight()) {
+ log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
+ return result;
+ }
+
+ result = Either.left(eitherAttUpdate.left().value());
+ return result;
+ } finally {
+ commitOrRollback(result);
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+
+ }
+
+ /**
+ * Deletes Attribute on resource
+ *
+ * @param resourceId
+ * @param attributeId
+ * @param userId
+ * @return
+ */
+ public Either<PropertyDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {
+
+ Either<PropertyDefinition, ResponseFormat> result = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Attribute", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
+ if (lockResult != StorageOperationStatus.OK) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ try {
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
+ if (eitherResource.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ }
+ Resource resource = eitherResource.left().value();
+
+ // verify that resource is checked-out and the user is the last updater
+ if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ // verify attribute exist in resource
+ Either<PropertyDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId);
+ if (eitherAttributeExist.isRight()) {
+ return Either.right(eitherAttributeExist.right().value());
+ }
+ String attributeName = eitherAttributeExist.left().value().getName();
+
+ // delete attribute of resource from graph
+ StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName);
+ if (eitherAttributeDelete != StorageOperationStatus.OK) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName()));
+ return result;
+ }
+
+ result = Either.left(eitherAttributeExist.left().value());
+ return result;
+ } finally {
+ commitOrRollback(result);
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
index 14c451a3b0..e401cb14f5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,14 +20,11 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -40,18 +37,10 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.IComplexDefaultValue;
-import org.openecomp.sdc.be.model.IPropertyInputCommon;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
+import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
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.IGraphLockOperation;
@@ -60,6 +49,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -78,696 +68,716 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.JsonElement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
-import fj.data.Either;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
public abstract class BaseBusinessLogic {
- @Autowired
- protected ComponentsUtils componentsUtils;
-
- @Autowired
- protected IUserBusinessLogic userAdmin;
-
- @Autowired
- protected IGraphLockOperation graphLockOperation;
-
- @Autowired
- protected TitanDao titanDao;
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
-
- @Autowired
- protected IElementOperation elementDao;
-
- @Autowired
- protected IGroupOperation groupOperation;
-
- @Autowired
- protected IGroupInstanceOperation groupInstanceOperation;
-
- @Autowired
- protected IGroupTypeOperation groupTypeOperation;
-
- /*@Autowired
- protected IArtifactOperation artifactOperation;*/
- @javax.annotation.Resource
- protected ArtifactsOperations artifactToscaOperation;
-
-// @Autowired
-// protected IAttributeOperation attributeOperation;
-
- @Autowired
- protected PropertyOperation propertyOperation;
-
- @Autowired
- protected ApplicationDataTypeCache applicationDataTypeCache;
-
- @Autowired
- protected ToscaOperationFacade toscaOperationFacade;
-
- protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
-
- public void setUserAdmin(UserBusinessLogic userAdmin) {
- this.userAdmin = userAdmin;
- }
-
- public void setComponentsUtils(ComponentsUtils componentsUtils) {
- this.componentsUtils = componentsUtils;
- }
-
- public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
- this.graphLockOperation = graphLockOperation;
- }
-
- public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
- this.toscaOperationFacade = toscaOperationFacade;
- }
-
-
- private static Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class.getName());
-
- public static final String EMPTY_VALUE = null;
-
- protected Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) {
- String userId = user.getUserId();
-
- if (StringUtils.isEmpty(userId)) {
- log.debug("User header is missing ");
- BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- return Either.right(responseFormat);
- }
- return Either.left(user);
- }
-
- protected Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) {
- return validateUserExists(user.getUserId(), ecompErrorContext, inTransaction);
- }
-
- protected void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, ecompErrorContext, false);
- if (resp.isRight()) {
- errorWrapper.setInnerElement(resp.right().value());
- }
- }
-
- public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) {
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, false);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
- log.debug("validateUserExists - not authorized user, userId {}", userId);
- Either.right(ActionStatus.RESTRICTED_OPERATION);
- } else {
- log.debug("validateUserExists - failed to authorize user, userId {}", userId);
- }
- log.debug("User is not listed. userId {}", userId);
- BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
- return Either.right(eitherCreator.right().value());
- }
- return Either.left(eitherCreator.left().value());
- }
-
- public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) {
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, inTransaction);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- ResponseFormat responseFormat;
- if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
- if (log.isDebugEnabled())
- log.debug("validateUserExists - not authorized user, userId {}", userId);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- } else {
- if (log.isDebugEnabled())
- log.debug("validateUserExists - failed to authorize user, userId {}", userId);
- responseFormat = componentsUtils.getResponseFormat(eitherCreator.right().value());
- }
- if (log.isDebugEnabled())
- log.debug("User is not listed. userId {}", userId);
- BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
- return Either.right(responseFormat);
- }
- return Either.left(eitherCreator.left().value());
- }
-
- protected Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) {
- Role userRole = Role.valueOf(user.getRole());
- if (roles != null) {
- if (!roles.contains(userRole)) {
- if (log.isDebugEnabled())
- log.debug("user is not in appropriate role to perform action");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- return Either.right(responseFormat);
- }
- return Either.left(Boolean.TRUE);
- }
- return Either.left(Boolean.FALSE);
- }
-
- protected Either<Boolean, ResponseFormat> lockComponent(Component component, String ecompErrorContext) {
- return lockComponent(component.getUniqueId(), component, ecompErrorContext);
- }
-
- protected Either<Boolean, ResponseFormat> lockComponent(String componentId, Component component, String ecompErrorContext) {
- ComponentTypeEnum componentType = component.getComponentType();
- NodeTypeEnum nodeType = componentType.getNodeType();
- StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
-
- if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
- return Either.left(true);
- } else {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
- log.debug("Failed to lock component {} error - {}" ,componentId, actionStatus);
- return Either.right(responseFormat);
- }
- }
-
- protected void unlockComponent(Either<?, ?> either, Component component, boolean inTransaction) {
- ComponentTypeEnum componentType = component.getComponentType();
- NodeTypeEnum nodeType = componentType.getNodeType();
- if (false == inTransaction) {
- if (either == null || either.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- }
- // unlock resource
- graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
- }
-
- protected void unlockComponent(Either<?, ?> either, Component component) {
- unlockComponent(either, component, false);
- }
-
- protected <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) {
- if (bodyObject == null) {
- log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- } else {
- return Either.left(true);
- }
- }
-
- protected Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- if (componentTypeEnum == null) {
- log.debug("Invalid component type {}", componentType);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
- } else {
- return Either.left(componentTypeEnum);
- }
- }
-
- protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
-
- if(filter == null){
- filter = new ComponentParametersView();
- }
- Either<Component, StorageOperationStatus> componentFound = toscaOperationFacade.getToscaElement(componentId, filter);
- if (componentFound.isRight()) {
- StorageOperationStatus storageOperationStatus = componentFound.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
- log.debug("Component with id {} was not found", componentId);
- return Either.right(responseFormat);
- }
- return Either.left(componentFound.left().value());
- }
-
- public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) {
- Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
- log.debug("Component {} is not checked-out", component.getName());
- return canWork;
- }
-
- // verify userId is not null
- if (userId == null) {
- log.debug("Current user userId is null");
- return canWork;
- }
-
- // verify component last update user is the current user
- String lastUpdaterUserId = component.getLastUpdaterUserId();
- if (!userId.equals(lastUpdaterUserId)) {
- log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
- return canWork;
- }
-
- // verify resource is not deleted
- if ((component.getIsDeleted() != null) && (component.getIsDeleted() == true)) {
- log.debug("Component {} is marked as deleted", component.getUniqueId());
- return canWork;
- }
-
- return Either.left(true);
- }
-
- public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
- switch (parentComponentType) {
- case SERVICE:
- return ComponentTypeEnum.RESOURCE;
- case RESOURCE:
- return ComponentTypeEnum.RESOURCE;
- case PRODUCT:
- return ComponentTypeEnum.SERVICE;
- default:
- break;
- }
- return null;
- }
-
- // For UT
- public void setTitanGenericDao(TitanDao titanDao) {
- this.titanDao = titanDao;
- }
-
- protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) {
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus operationStatus = allDataTypes.right().value();
- if (operationStatus == TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
- } else {
- BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
- return Either.left(allDataTypes.left().value());
- }
-
- protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
- String type = null;
- String innerType = null;
- if (!propertyOperation.isPropertyTypeValid(property)) {
- log.info("Invalid type for property {} type {}", property.getName(), property.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
- return Either.right(responseFormat);
- }
- type = property.getType();
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
- innerType = propertyInnerTypeValid.getLeft();
- if (!propertyInnerTypeValid.getRight().booleanValue()) {
- log.info("Invalid inner type for property {} type {}", property.getName(), property.getType() );
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
- return Either.right(responseFormat);
- }
- }
- if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
- log.info("Invalid default value for property {} type {}", property.getName(), property.getType() );
- ResponseFormat responseFormat;
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
- } else {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
- }
- return Either.right(responseFormat);
-
- }
- return Either.left(true);
- }
-
-// protected Either<Resource, StorageOperationStatus> getResource(final String resourceId) {
-//
-// log.debug("Get resource with id {}", resourceId);
-// Either<Resource, StorageOperationStatus> status = resourceOperation.getResource(resourceId);
-// if (status.isRight()) {
-// log.debug("Resource with id {} was not found", resourceId);
-// return Either.right(status.right().value());
-// }
-//
-// Resource resource = status.left().value();
-// if (resource == null) {
-// BeEcompErrorManager.getInstance().logBeComponentMissingError("Property Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId);
-// log.debug("General Error while get resource with id {}", resourceId);
-// return Either.right(StorageOperationStatus.GENERAL_ERROR);
-// }
-// return Either.left(resource);
-// }
-
- protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) {
- // convert property
- ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType());
- PropertyValueConverter converter = type.getConverter();
- // get inner type
- String innerType = null;
-
- if (newAttributeDef != null) {
- SchemaDefinition schema = newAttributeDef.getSchema();
- if (schema != null) {
- PropertyDataDefinition prop = schema.getProperty();
- if (schema.getProperty() != null) {
- innerType = prop.getType();
- }
- }
- String convertedValue = null;
- if (newAttributeDef.getDefaultValue() != null) {
- convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes);
- newAttributeDef.setDefaultValue(convertedValue);
- }
- }
- }
-
- protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- }
-
- }
-
- protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
- log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- }
-
- protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- }
-
- }
-
- protected ToscaPropertyType getType(String propertyType) {
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- return type;
-
- }
-
- protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) {
- if (result == null || result.isRight()) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
-
- protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) {
- ComponentTypeEnum componentType = component.getComponentType();
- NodeTypeEnum nodeType = componentType.getNodeType();
- StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
-
- if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
- return Either.left(true);
- } else {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name);
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
- log.debug("Failed to lock component {} error - {}", name, actionStatus);
- return Either.right(responseFormat);
- }
- }
-
- protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView, boolean inTransaction) {
-
- Either<Component, StorageOperationStatus> componentFound = null;
- componentFound = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
-
- if (componentFound.isRight()) {
- StorageOperationStatus storageOperationStatus = componentFound.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
- log.debug("Component with id {} was not found", componentId);
- return Either.right(responseFormat);
- }
- return Either.left(componentFound.left().value());
- }
-
- protected Either<GroupProperty, ResponseFormat> validateFreeText(GroupProperty groupPropertyToUpdate) {
-
- Either<GroupProperty, ResponseFormat> ret;
- final String groupTypeValue = groupPropertyToUpdate.getValue();
- if (!StringUtils.isEmpty(groupTypeValue)) {
- if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
- NodeTypeEnum.Property.getName(),
- String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)));
- }
-
- else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
- NodeTypeEnum.Property.getName()));
- } else {
- ret = Either.left(groupPropertyToUpdate);
- }
-
- } else {
- ret = Either.left(groupPropertyToUpdate);
- }
- return ret;
- }
-
- @SuppressWarnings("unchecked")
- protected <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
- T enumFound = enumGetter.apply(name);
- return Arrays.asList(enumValues).contains(enumFound);
- }
-
- protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
- String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
-
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- innerType = propDef.getType();
- }
-
- Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
- log.trace("After validateAndUpdateRules. pair = {}", pair);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
-
- return Either.left(newValue);
- }
-
- protected Either<String, StorageOperationStatus> validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
- String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
-
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- innerType = propDef.getType();
- }
-
- Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
- }
-
- return Either.left(newValue);
- }
-
- public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
- ToscaPropertyType type = getType(propertyType);
-
- if (isValidate) {
-
- if (type == null) {
- DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
- if (validateResult.right.booleanValue() == false) {
- log.debug("The value {} of property from type {} is invalid", value, propertyType);
- return Either.right(false);
- }
- JsonElement jsonElement = validateResult.left;
- String valueFromJsonElement = getValueFromJsonElement(jsonElement);
- return Either.left(valueFromJsonElement);
- }
- log.trace("before validating property type {}", propertyType);
- boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
- if (false == isValidProperty) {
- log.debug("The value {} of property from type {} is invalid", value, type);
- return Either.right(false);
- }
- }
- Object convertedValue = value;
- if (false == isEmptyValue(value) && isValidate) {
- PropertyValueConverter converter = type.getConverter();
- convertedValue = converter.convert(value, innerType, dataTypes);
- }
- return Either.left(convertedValue);
- }
-
- public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
-
- if (rules == null || rules.isEmpty() == true) {
- return new ImmutablePair<String, Boolean>(null, true);
- }
-
- for (PropertyRule rule : rules) {
- String value = rule.getValue();
- Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
- if (updateResult.isRight()) {
- Boolean status = updateResult.right().value();
- if (status == false) {
- return new ImmutablePair<String, Boolean>(value, status);
- }
- } else {
- String newValue = null;
- Object object = updateResult.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- rule.setValue(newValue);
- }
- }
-
- return new ImmutablePair<String, Boolean>(null, true);
- }
-
- protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- if (isEmptyValue(value)) {
- return true;
- }
-
- PropertyTypeValidator validator = type.getValidator();
-
- boolean isValid = validator.isValid(value, innerType, dataTypes);
- if (true == isValid) {
- return true;
- } else {
- return false;
- }
-
- }
-
- public boolean isEmptyValue(String value) {
- if (value == null) {
- return true;
- }
- return false;
- }
-
- public boolean isNullParam(String value) {
- if (value == null) {
- return true;
- }
- return false;
- }
-
- public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
-
- List<PropertyRule> rules = resourceInstanceProperty.getRules();
- if (rules == null) {
- PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
- rules = new ArrayList<>();
- rules.add(propertyRule);
- } else {
- rules = sortRules(rules);
- }
-
- propertyValueData.setRules(rules);
- }
-
- private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
- List<String> path = resourceInstanceProperty.getPath();
- // FOR BC. Since old Property values on VFC/VF does not have rules on
- // graph.
- // Update could be done on one level only, thus we can use this
- // operation to avoid migration.
- if (path == null || path.isEmpty() == true) {
- path = new ArrayList<>();
- path.add(resourceInstanceId);
- }
- PropertyRule propertyRule = new PropertyRule();
- propertyRule.setRule(path);
- propertyRule.setValue(propertyValueData.getValue());
- return propertyRule;
- }
-
- private List<PropertyRule> sortRules(List<PropertyRule> rules) {
-
- // TODO: sort the rules by size and binary representation.
- // (x, y, .+) --> 110 6 priority 1
- // (x, .+, z) --> 101 5 priority 2
-
- return rules;
- }
-
- protected String getValueFromJsonElement(JsonElement jsonElement) {
- String value = null;
-
- if (jsonElement == null || jsonElement.isJsonNull()) {
- value = EMPTY_VALUE;
- } else {
- if (jsonElement.toString().isEmpty()) {
- value = "";
- } else {
- value = jsonElement.toString();
- }
- }
-
- return value;
- }
+ private static final Logger log = LoggerFactory.getLogger(BaseBusinessLogic.class);
+
+ private static final String EMPTY_VALUE = null;
+ @Autowired
+ protected ComponentsUtils componentsUtils;
+
+ @Autowired
+ protected IUserBusinessLogic userAdmin;
+
+ @Autowired
+ protected IGraphLockOperation graphLockOperation;
+
+ @Autowired
+ protected TitanDao titanDao;
+
+ @Autowired
+ protected TitanGenericDao titanGenericDao;
+
+ @Autowired
+ protected IElementOperation elementDao;
+
+ @Autowired
+ protected IGroupOperation groupOperation;
+
+ @Autowired
+ protected IGroupInstanceOperation groupInstanceOperation;
+
+ @Autowired
+ protected IGroupTypeOperation groupTypeOperation;
+
+ @Autowired
+ protected GroupBusinessLogic groupBusinessLogic;
+
+ @Autowired
+ protected PolicyTypeOperation policyTypeOperation;
+
+ @javax.annotation.Resource
+ protected ArtifactsOperations artifactToscaOperation;
+
+ @Autowired
+ protected PropertyOperation propertyOperation;
+
+ @Autowired
+ protected ApplicationDataTypeCache applicationDataTypeCache;
+
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+ @Autowired
+ protected ApplicationDataTypeCache dataTypeCache;
+
+ @Autowired
+ protected ForwardingPathOperation forwardingPathOperation;
+
+ @javax.annotation.Resource
+ private UserValidations userValidations;
+
+ protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+
+
+ public void setUserAdmin(UserBusinessLogic userAdmin) {
+ this.userAdmin = userAdmin;
+ }
+
+ public void setUserValidations(UserValidations userValidations) {
+ this.userValidations = userValidations;
+ }
+
+ public void setComponentsUtils(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
+
+ public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
+ this.graphLockOperation = graphLockOperation;
+ }
+
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }
+
+ public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation){
+ this.forwardingPathOperation = forwardingPathOperation;
+ }
+
+ public void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) {
+ this.policyTypeOperation = policyTypeOperation;
+ }
+
+
+ public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) {
+ this.dataTypeCache = dataTypeCache;
+ }
+
+ public void setPropertyOperation(PropertyOperation propertyOperation) {
+ this.propertyOperation = propertyOperation;
+ }
+
+ protected Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) {
+ return userValidations.validateUserNotEmpty(user, ecompErrorContext);
+ }
+
+ protected Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) {
+ return userValidations.validateUserExists(user.getUserId(), ecompErrorContext, inTransaction);
+ }
+
+ protected void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) {
+ userValidations.validateUserExist(userId, ecompErrorContext, errorWrapper);
+ }
+
+ public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) {
+ return userValidations.validateUserExistsActionStatus(userId, ecompErrorContext);
+ }
+
+ public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) {
+ return userValidations.validateUserExists(userId, ecompErrorContext, inTransaction);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) {
+ return userValidations.validateUserRole(user, roles);
+ }
+
+ protected Either<Boolean, ResponseFormat> lockComponent(Component component, String ecompErrorContext) {
+ return lockComponent(component.getUniqueId(), component, ecompErrorContext);
+ }
+
+ protected Either<Component, ResponseFormat> lockComponent(Component component, boolean shoulLock, String ecompErrorContext) {
+ return shoulLock ? lockComponent(component.getUniqueId(), component, ecompErrorContext)
+ .either(l -> Either.left(component), Either::right) : Either.left(component);
+ }
+
+ protected Either<Boolean, ResponseFormat> lockComponent(String componentId, Component component, String ecompErrorContext) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
+
+ if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
+ return Either.left(true);
+ } else {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), componentId);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
+ log.debug("Failed to lock component {} error - {}", componentId, actionStatus);
+ return Either.right(responseFormat);
+ }
+ }
+
+ protected void unlockComponent(Either<?, ?> either, Component component, boolean inTransaction) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ if (!inTransaction) {
+ if (either == null || either.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
+ }
+
+ protected void unlockComponent(Either<?, ?> either, Component component) {
+ unlockComponent(either, component, false);
+ }
+ protected void unlockComponentById(Either<?, ?> either, String componentId) {
+ Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
+ if(component.isLeft() && component != null) {
+ unlockComponent(either, component.left().value(), false);
+ }
+ }
+
+ protected <T> Either<Boolean, ResponseFormat> validateJsonBody(T bodyObject, Class<T> clazz) {
+ if (bodyObject == null) {
+ log.debug("Invalid JSON received for object of type {}", clazz.getSimpleName());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ } else {
+ return Either.left(true);
+ }
+ }
+
+ protected Either<ComponentTypeEnum, ResponseFormat> validateComponentType(String componentType) {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ if (componentTypeEnum == null) {
+ log.debug("Invalid component type {}", componentType);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
+ } else {
+ return Either.left(componentTypeEnum);
+ }
+ }
+
+ protected Either<Component, ResponseFormat> validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
+ if (filter == null) {
+ filter = new ComponentParametersView();
+ }
+ return toscaOperationFacade.getToscaElement(componentId, filter)
+ .right()
+ .map(err -> handleGetComponentError(componentId, componentType, err))
+ .left()
+ .bind(cmpt -> validateComponentType(cmpt, componentType));
+ }
+
+ private Either<Component, ResponseFormat> validateComponentType(Component cmpt, ComponentTypeEnum componentType) {
+ if (componentType != cmpt.getComponentType()) {
+ log.debug("component {} is not of requested type {}", cmpt.getUniqueId(), componentType);
+ ActionStatus cmptNotFoundError = componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType);
+ return Either.right(componentsUtils.getResponseFormat(cmptNotFoundError));
+ }
+ return Either.left(cmpt);
+ }
+
+ protected <T extends PropertyDataDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
+ if (allDataTypesEither.isRight()) {
+ TitanOperationStatus status = allDataTypesEither.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+ }
+ Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
+ String innerType = null;
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ innerType = propDef.getType();
+ }
+ // Specific Update Logic
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
+ String newValue = property.getValue();
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (Boolean.FALSE.equals(res)) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+ if (!isInput) {
+ ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
+ if (Boolean.FALSE.equals(pair.getRight())) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ }
+ return Either.left(newValue);
+ }
+
+ public Either<Boolean, ResponseFormat> validateCanWorkOnComponent(Component component, String userId) {
+ Either<Boolean, ResponseFormat> canWork = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
+ log.debug("Component {} is not checked-out", component.getName());
+ return canWork;
+ }
+
+ // verify userId is not null
+ if (userId == null) {
+ log.debug("Current user userId is null");
+ return canWork;
+ }
+
+ // verify component last update user is the current user
+ String lastUpdaterUserId = component.getLastUpdaterUserId();
+ if (!userId.equals(lastUpdaterUserId)) {
+ log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
+ return canWork;
+ }
+
+ // verify resource is not deleted
+ if (Boolean.TRUE.equals(component.getIsDeleted())) {
+ log.debug("Component {} is marked as deleted", component.getUniqueId());
+ return canWork;
+ }
+
+ return Either.left(true);
+ }
+
+ public ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
+ switch (parentComponentType) {
+ case SERVICE:
+ return ComponentTypeEnum.RESOURCE;
+ case RESOURCE:
+ return ComponentTypeEnum.RESOURCE;
+ case PRODUCT:
+ return ComponentTypeEnum.SERVICE;
+ default:
+ break;
+ }
+ return null;
+ }
+
+ // For UT
+ public void setTitanGenericDao(TitanDao titanDao) {
+ this.titanDao = titanDao;
+ }
+
+ protected Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes(ApplicationDataTypeCache applicationDataTypeCache) {
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus operationStatus = allDataTypes.right().value();
+ if (operationStatus == TitanOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
+ } else {
+ BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ return Either.left(allDataTypes.left().value());
+ }
+
+ protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
+ String type = null;
+ String innerType = null;
+ if (!propertyOperation.isPropertyTypeValid(property)) {
+ log.info("Invalid type for property {} type {}", property.getName(), property.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+ return Either.right(responseFormat);
+ }
+ type = property.getType();
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
+ innerType = propertyInnerTypeValid.getLeft();
+ if (!propertyInnerTypeValid.getRight().booleanValue()) {
+ log.info("Invalid inner type for property {} type {}", property.getName(), property.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+ return Either.right(responseFormat);
+ }
+ }
+ if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
+ log.info("Invalid default value for property {} type {}", property.getName(), property.getType());
+ ResponseFormat responseFormat;
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
+ }
+ return Either.right(responseFormat);
+
+ }
+ return Either.left(true);
+ }
+
+
+ protected void handleDefaultValue(IComplexDefaultValue newAttributeDef, Map<String, DataTypeDefinition> dataTypes) {
+ // convert property
+ ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDef.getType());
+ PropertyValueConverter converter = type.getConverter();
+ // get inner type
+ String innerType = null;
+
+ if (newAttributeDef != null) {
+ SchemaDefinition schema = newAttributeDef.getSchema();
+ if (schema != null) {
+ PropertyDataDefinition prop = schema.getProperty();
+ if (schema.getProperty() != null) {
+ innerType = prop.getType();
+ }
+ }
+ String convertedValue = null;
+ if (newAttributeDef.getDefaultValue() != null) {
+ convertedValue = converter.convert(newAttributeDef.getDefaultValue(), innerType, dataTypes);
+ newAttributeDef.setDefaultValue(convertedValue);
+ }
+ }
+ }
+
+ protected void validateComponentTypeEnum(ComponentTypeEnum componentTypeEnum, String errorContext, Wrapper<ResponseFormat> errorWrapper) {
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+
+ }
+
+ protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
+ log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ }
+
+ protected void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ }
+
+ }
+
+ protected ToscaPropertyType getType(String propertyType) {
+ return ToscaPropertyType.isValidType(propertyType);
+ }
+
+ protected void commitOrRollback(Either<? extends Object, ResponseFormat> result) {
+ if (result == null || result.isRight()) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+
+ protected Either<Boolean, ResponseFormat> lockComponentByName(String name, Component component, String ecompErrorContext) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
+
+ if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
+ return Either.left(true);
+ } else {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(ecompErrorContext, nodeType.getName(), name);
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(lockResourceStatus, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, component.getName());
+ log.debug("Failed to lock component {} error - {}", name, actionStatus);
+ return Either.right(responseFormat);
+ }
+ }
+
+ protected Either<Component, ResponseFormat> validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) {
+ return toscaOperationFacade.getToscaElement(componentId, componentParametersView)
+ .right()
+ .map(err -> handleGetComponentError(componentId, componentType, err));
+
+ }
+
+ private ResponseFormat handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentError, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
+ log.debug("error fetching component with id {}. error status: {}", componentId, getComponentError);
+ return responseFormat;
+ }
+
+ protected Either<GroupProperty, ResponseFormat> validateFreeText(GroupProperty groupPropertyToUpdate) {
+
+ Either<GroupProperty, ResponseFormat> ret;
+ final String groupTypeValue = groupPropertyToUpdate.getValue();
+ if (!StringUtils.isEmpty(groupTypeValue)) {
+ if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ NodeTypeEnum.Property.getName(),
+ String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)));
+ } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
+ NodeTypeEnum.Property.getName()));
+ } else {
+ ret = Either.left(groupPropertyToUpdate);
+ }
+
+ } else {
+ ret = Either.left(groupPropertyToUpdate);
+ }
+ return ret;
+ }
+
+
+ @SafeVarargs
+ static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
+ T enumFound = enumGetter.apply(name);
+ return Arrays.asList(enumValues).contains(enumFound);
+ }
+
+ Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ innerType = propDef.getType();
+ }
+
+ Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (Boolean.FALSE.equals(res)) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
+ log.trace("After validateAndUpdateRules. pair = {}", pair);
+ if (Boolean.FALSE.equals(pair.getRight())) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+
+ return Either.left(newValue);
+ }
+
+ protected Either<String, StorageOperationStatus> validateInputValueBeforeCreate(ComponentInstanceInput property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ innerType = propDef.getType();
+ }
+
+ Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (Boolean.FALSE.equals(res)) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
+ log.debug("After validateAndUpdateRules. pair = {}", pair);
+ if (Boolean.FALSE.equals(pair.getRight())) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
+ }
+
+ return Either.left(newValue);
+ }
+
+ public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
+ ToscaPropertyType type = getType(propertyType);
+
+ if (isValidate) {
+
+ if (type == null) {
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
+ if (Boolean.FALSE.equals(validateResult.right)) {
+ log.debug("The value {} of property from type {} is invalid", value, propertyType);
+ return Either.right(false);
+ }
+ JsonElement jsonElement = validateResult.left;
+ String valueFromJsonElement = getValueFromJsonElement(jsonElement);
+ return Either.left(valueFromJsonElement);
+ }
+ log.trace("before validating property type {}", propertyType);
+ boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
+ if (!isValidProperty) {
+ log.debug("The value {} of property from type {} is invalid", value, type);
+ return Either.right(false);
+ }
+ }
+ Object convertedValue = value;
+ if (!isEmptyValue(value) && isValidate) {
+ PropertyValueConverter converter = type.getConverter();
+ convertedValue = converter.convert(value, innerType, dataTypes);
+ }
+ return Either.left(convertedValue);
+ }
+
+ public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
+
+ if (rules == null || rules.isEmpty()) {
+ return ImmutablePair.of(null, true);
+ }
+
+ for (PropertyRule rule : rules) {
+ String value = rule.getValue();
+ Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
+ if (updateResult.isRight()) {
+ Boolean status = updateResult.right().value();
+ if (Boolean.FALSE.equals(status)) {
+ return ImmutablePair.of(value, status);
+ }
+ } else {
+ String newValue = null;
+ Object object = updateResult.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ rule.setValue(newValue);
+ }
+ }
+
+ return ImmutablePair.of(null, true);
+ }
+
+ protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ if (isEmptyValue(value)) {
+ return true;
+ }
+
+ PropertyTypeValidator validator = type.getValidator();
+
+ return validator.isValid(value, innerType, dataTypes);
+ }
+
+ public boolean isEmptyValue(String value) {
+ if (value == null) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isNullParam(String value) {
+ if (value == null) {
+ return true;
+ }
+ return false;
+ }
+
+ public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
+
+ List<PropertyRule> rules = resourceInstanceProperty.getRules();
+ if (rules == null) {
+ PropertyRule propertyRule = buildRuleFromPath(propertyValueData, resourceInstanceProperty, resourceInstanceId);
+ rules = new ArrayList<>();
+ rules.add(propertyRule);
+ } else {
+ rules = sortRules(rules);
+ }
+
+ propertyValueData.setRules(rules);
+ }
+
+ private PropertyRule buildRuleFromPath(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) {
+ List<String> path = resourceInstanceProperty.getPath();
+ // FOR BC. Since old Property values on VFC/VF does not have rules on
+ // graph.
+ // Update could be done on one level only, thus we can use this
+ // operation to avoid migration.
+ if (isEmpty(path)) {
+ path = new ArrayList<>();
+ path.add(resourceInstanceId);
+ }
+ PropertyRule propertyRule = new PropertyRule();
+ propertyRule.setRule(path);
+ propertyRule.setValue(propertyValueData.getValue());
+ return propertyRule;
+ }
+
+ private List<PropertyRule> sortRules(List<PropertyRule> rules) {
+
+ // TODO: sort the rules by size and binary representation.
+ // (x, y, .+) --> 110 6 priority 1
+ // (x, .+, z) --> 101 5 priority 2
+
+ return rules;
+ }
+
+ protected String getValueFromJsonElement(JsonElement jsonElement) {
+ String value = null;
+
+ if (jsonElement == null || jsonElement.isJsonNull()) {
+ value = EMPTY_VALUE;
+ } else {
+ if (jsonElement.toString().isEmpty()) {
+ value = "";
+ } else {
+ value = jsonElement.toString();
+ }
+ }
+
+ return value;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
index 5cf42cedd6..caf051ec81 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -41,83 +34,87 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
@Component("capabilityTypeImportManager")
public class CapabilityTypeImportManager {
- private static Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class.getName());
- @Resource
- private CapabilityTypeOperation capabilityTypeOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private CommonImportManager commonImportManager;
-
- public Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes(String capabilityYml) {
- Either<List<CapabilityTypeDefinition>, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml);
- if (capabilityTypes.isRight()) {
- ActionStatus status = capabilityTypes.right().value();
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null);
- return Either.right(responseFormat);
- }
- return createCapabilityTypesByDao(capabilityTypes.left().value());
-
- }
-
- private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) {
- return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData));
-
- }
-
- private Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) {
- List<CapabilityTypeDefinition> createdCapabilities = new ArrayList<>();
- Either<List<CapabilityTypeDefinition>, ResponseFormat> eitherResult = Either.left(createdCapabilities);
- Iterator<CapabilityTypeDefinition> capTypeItr = capabilityTypesToCreate.iterator();
- boolean stopDao = false;
- while (capTypeItr.hasNext() && !stopDao) {
- CapabilityTypeDefinition capabilityType = capTypeItr.next();
-
- log.info("send capabilityType {} to dao for create", capabilityType.getType());
- Either<CapabilityTypeDefinition, StorageOperationStatus> dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType);
- if (dataModelResponse.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingCapabilityTypeError, "Create CapabilityTypes");
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type");
- log.debug("failed to create capabilityType: {}", capabilityType.getType());
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType);
- eitherResult = Either.right(responseFormat);
- stopDao = true;
- }
-
- } else {
- createdCapabilities.add(capabilityType);
- }
- if (!capTypeItr.hasNext()) {
- log.info("capabilityTypes were created successfully!!!");
- }
-
- }
-
- return eitherResult;
-
- }
-
- private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
- CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
-
- capabilityType.setType(capabilityTypeName);
-
- // Description
- final Consumer<String> descriptionSetter = description -> capabilityType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
- // Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
- // Properties
- commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values));
-
- return capabilityType;
- }
+ private static final Logger log = LoggerFactory.getLogger(CapabilityTypeImportManager.class);
+ @Resource
+ private CapabilityTypeOperation capabilityTypeOperation;
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Resource
+ private CommonImportManager commonImportManager;
+
+ public Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes(String capabilityYml) {
+ Either<List<CapabilityTypeDefinition>, ActionStatus> capabilityTypes = createCapabilityTypesFromYml(capabilityYml);
+ if (capabilityTypes.isRight()) {
+ ActionStatus status = capabilityTypes.right().value();
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(status, null);
+ return Either.right(responseFormat);
+ }
+ return createCapabilityTypesByDao(capabilityTypes.left().value());
+
+ }
+
+ private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityYml) {
+ return commonImportManager.createElementTypesFromYml(capabilityYml, (capTypeName, capTypeJsonData) -> createCapabilityType(capTypeName, capTypeJsonData));
+
+ }
+
+ private Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) {
+ List<CapabilityTypeDefinition> createdCapabilities = new ArrayList<>();
+ Either<List<CapabilityTypeDefinition>, ResponseFormat> eitherResult = Either.left(createdCapabilities);
+ Iterator<CapabilityTypeDefinition> capTypeItr = capabilityTypesToCreate.iterator();
+ boolean stopDao = false;
+ while (capTypeItr.hasNext() && !stopDao) {
+ CapabilityTypeDefinition capabilityType = capTypeItr.next();
+
+ log.info("send capabilityType {} to dao for create", capabilityType.getType());
+ Either<CapabilityTypeDefinition, StorageOperationStatus> dataModelResponse = capabilityTypeOperation.addCapabilityType(capabilityType);
+ if (dataModelResponse.isRight()) {
+ BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create CapabilityTypes", "capability type");
+ log.debug("failed to create capabilityType: {}", capabilityType.getType());
+ if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByCapabilityType(componentsUtils.convertFromStorageResponseForCapabilityType(dataModelResponse.right().value()), capabilityType);
+ eitherResult = Either.right(responseFormat);
+ stopDao = true;
+ }
+
+ } else {
+ createdCapabilities.add(capabilityType);
+ }
+ if (!capTypeItr.hasNext()) {
+ log.info("capabilityTypes were created successfully!!!");
+ }
+
+ }
+
+ return eitherResult;
+
+ }
+
+ private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
+ CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
+
+ capabilityType.setType(capabilityTypeName);
+
+ // Description
+ final Consumer<String> descriptionSetter = description -> capabilityType.setDescription(description);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
+ // Derived From
+ final Consumer<String> derivedFromSetter = derivedFrom -> capabilityType.setDerivedFrom(derivedFrom);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
+ // Properties
+ commonImportManager.setPropertiesMap(toscaJson, (values) -> capabilityType.setProperties(values));
+
+ return capabilityType;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
index 1f5770856b..31db9651c6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
@@ -1,5 +1,18 @@
package org.openecomp.sdc.be.components.impl;
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.Session;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
@@ -10,178 +23,163 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
-import javax.annotation.PostConstruct;
+@Component("cassandra-health-check")
+public class CassandraHealthCheck {
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
-import org.openecomp.sdc.be.dao.cassandra.schema.Table;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
-import com.datastax.driver.core.Session;
+ private static final Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class);
-@Component("cassandra-health-check")
-public class CassandraHealthCheck {
-
-
- private static Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class.getName());
-
- private String localDataCenterName = null;
-
- private Set<String> sdcKeyspaces = new HashSet<String>();
-
- private int HC_FormulaNumber;
-
- @PostConstruct
- private void init() {
-
- //Initialize local data center name - this field must be filled by DevOps
- localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
-
- if (GeneralUtility.isEmptyString(localDataCenterName)) {
- log.error("localDataCenter Name in configuration.yaml is missing.");
- return;
- }
-
- //Collect all SDC keyspaces
- for (Table table : Table.values()) {
- sdcKeyspaces.add(table.getTableDescription().getKeyspace());
- }
-
- String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
- Properties prop = new Properties();
- InputStream titanProp = null;
- try {
- //load a properties file
- titanProp = new FileInputStream(titanCfgFile);
- prop.load(titanProp);
- //Add titan keyspace
- String titanKeyspace = prop.getProperty("storage.cassandra.keyspace");
- if (!GeneralUtility.isEmptyString(titanKeyspace)) {
- sdcKeyspaces.add(titanKeyspace);
- }
- } catch (Exception e) {
- log.error("Failed to open titen.properties file , url is : {}", titanCfgFile);
- }
-
- log.info("All sdc keyspaces are : {}", sdcKeyspaces);
-
- //Calculate the Formula of Health Check
- Cluster cluster = null;
- try {
-
- log.info("creating cluster for Cassandra Health Check.");
- //Create cluster from nodes in cassandra configuration
- cluster = SdcSchemaUtils.createCluster();
- if (cluster == null) {
- log.error("Failure create cassandra cluster.");
- return;
- }
-
- Metadata metadata = cluster.getMetadata();
-
- if (metadata == null) {
- log.error("Failure get cassandra metadata.");
- return;
- }
-
- log.info("Cluster Metadata: {}", metadata.toString());
- List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
- List<Integer> replactionFactorList = new ArrayList<Integer>();
-
- //Collect the keyspaces Replication Factor of current localDataCenter
- for (KeyspaceMetadata keyspace : keyspaces) {
-
- if (sdcKeyspaces.contains(keyspace.getName())) {
-
- log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
- Map<String, String> replicationOptions = keyspace.getReplication();
-
- //In 1 site with one data center
- if (replicationOptions.containsKey("replication_factor")) {
- replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
- }
- //In multiple sites with some data center
- else if (replicationOptions.containsKey(localDataCenterName)) {
- replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
- }
- }
- }
-
- if (replactionFactorList.size() == 0) {
- log.error("Replication factor NOT found in all keyspaces");
- return;
- }
-
- int maxReplicationFactor = Collections.max(replactionFactorList);
- log.info("maxReplication Factor is: {}", maxReplicationFactor);
-
- int localQuorum = maxReplicationFactor/2 + 1;
- log.info("localQuorum is: {}", localQuorum);
-
- HC_FormulaNumber = maxReplicationFactor - localQuorum;
-
- log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
-
-
- } catch (Exception e) {
- log.error("create cassandra cluster failed with exception.", e);
- } finally {
- if (cluster != null) {
- cluster.close();
- }
- }
-
- }
-
- public boolean getCassandraStatus() {
-
- if (GeneralUtility.isEmptyString(localDataCenterName)) {
- log.error("localDataCenter Name in configuration.yaml is missing.");
- return false;
- }
-
- Cluster cluster = null;
- Session session = null;
- try {
- log.info("creating cluster for Cassandra for monitoring.");
- cluster = SdcSchemaUtils.createCluster();
- if (cluster == null) {
- log.error("Failure create cassandra cluster.");
- return false;
- }
- session = cluster.connect();
- Metadata metadata = cluster.getMetadata();
-
- if (metadata == null) {
- log.error("Failure get cassandra metadata.");
- return false;
- }
-
- log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
-
- //Count the number of data center nodes that are down
- Long downHostsNumber = metadata.getAllHosts().stream()
- .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
-
- log.info("The cassandra down nodes number is {}", downHostsNumber.toString());
- return (HC_FormulaNumber >= downHostsNumber);
-
- } catch (Exception e) {
- log.error("create cassandra cluster failed with exception.", e);
- return false;
- } finally {
- if (session != null) {
+ private String localDataCenterName = null;
+
+ private Set<String> sdcKeyspaces = new HashSet<String>();
+
+ private int HC_FormulaNumber;
+
+ @PostConstruct
+ private void init() {
+
+ //Initialize local data center name - this field must be filled by DevOps
+ localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
+
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ log.error("localDataCenter Name in configuration.yaml is missing.");
+ return;
+ }
+
+ //Collect all SDC keyspaces
+ for (Table table : Table.values()) {
+ sdcKeyspaces.add(table.getTableDescription().getKeyspace());
+ }
+
+ String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
+ Properties prop = new Properties();
+ InputStream titanProp = null;
+ try {
+ //load a properties file
+ titanProp = new FileInputStream(titanCfgFile);
+ prop.load(titanProp);
+ //Add titan keyspace
+ String titanKeyspace = prop.getProperty("storage.cassandra.keyspace");
+ if (!GeneralUtility.isEmptyString(titanKeyspace)) {
+ sdcKeyspaces.add(titanKeyspace);
+ }
+ } catch (Exception e) {
+ log.error("Failed to open titen.properties file , url is : {}", titanCfgFile, e);
+ }
+
+ log.info("All sdc keyspaces are : {}", sdcKeyspaces);
+
+ //Calculate the Formula of Health Check
+ Cluster cluster = null;
+ try {
+
+ log.info("creating cluster for Cassandra Health Check.");
+ //Create cluster from nodes in cassandra configuration
+ cluster = SdcSchemaUtils.createCluster();
+ if (cluster == null) {
+ log.error("Failure create cassandra cluster.");
+ return;
+ }
+
+ Metadata metadata = cluster.getMetadata();
+
+ if (metadata == null) {
+ log.error("Failure get cassandra metadata.");
+ return;
+ }
+
+ log.info("Cluster Metadata: {}", metadata);
+ List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
+ List<Integer> replactionFactorList = new ArrayList<Integer>();
+
+ //Collect the keyspaces Replication Factor of current localDataCenter
+ for (KeyspaceMetadata keyspace : keyspaces) {
+
+ if (sdcKeyspaces.contains(keyspace.getName())) {
+
+ log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
+ Map<String, String> replicationOptions = keyspace.getReplication();
+
+ //In 1 site with one data center
+ if (replicationOptions.containsKey("replication_factor")) {
+ replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
+ }
+ //In multiple sites with some data center
+ else if (replicationOptions.containsKey(localDataCenterName)) {
+ replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
+ }
+ }
+ }
+
+ if (replactionFactorList.size() == 0) {
+ log.error("Replication factor NOT found in all keyspaces");
+ return;
+ }
+
+ int maxReplicationFactor = Collections.max(replactionFactorList);
+ log.info("maxReplication Factor is: {}", maxReplicationFactor);
+
+ int localQuorum = maxReplicationFactor/2 + 1;
+ log.info("localQuorum is: {}", localQuorum);
+
+ HC_FormulaNumber = maxReplicationFactor - localQuorum;
+
+ log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
+
+
+ } catch (Exception e) {
+ log.error("create cassandra cluster failed with exception.", e);
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+
+ }
+
+ public boolean getCassandraStatus() {
+
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ log.error("localDataCenter Name in configuration.yaml is missing.");
+ return false;
+ }
+
+ Cluster cluster = null;
+ Session session = null;
+ try {
+ log.info("creating cluster for Cassandra for monitoring.");
+ cluster = SdcSchemaUtils.createCluster();
+ if (cluster == null) {
+ log.error("Failure create cassandra cluster.");
+ return false;
+ }
+ session = cluster.connect();
+ Metadata metadata = cluster.getMetadata();
+
+ if (metadata == null) {
+ log.error("Failure get cassandra metadata.");
+ return false;
+ }
+
+ log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
+
+ //Count the number of data center nodes that are down
+ Long downHostsNumber = metadata.getAllHosts().stream()
+ .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
+
+ log.info("The cassandra down nodes number is {}", downHostsNumber);
+ return HC_FormulaNumber >= downHostsNumber;
+
+ } catch (Exception e) {
+ log.error("create cassandra cluster failed with exception.", e);
+ return false;
+ } finally {
+ if (session != null) {
session.close();
}
- if (cluster != null) {
- cluster.close();
- }
- }
- }
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
index 57ab46346a..fa662898d8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-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 fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
@@ -45,230 +39,229 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
-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;
@Component("categoriesImportManager")
public class CategoriesImportManager {
- @javax.annotation.Resource
- private IElementOperation elementOperation;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
+ @javax.annotation.Resource
+ private IElementOperation elementOperation;
- private static Logger log = LoggerFactory.getLogger(CategoriesImportManager.class.getName());
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
- public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) {
+ private static final Logger log = LoggerFactory.getLogger(CategoriesImportManager.class);
- Map<String, List<CategoryDefinition>> allCategories = createCategoriesFromYml(categoriesTypesYml);
- return createCategoriesByDao(allCategories);
- }
+ public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) {
- private Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategoriesByDao(Map<String, List<CategoryDefinition>> allCategories) {
- Map<String, List<CategoryDefinition>> result = new HashMap<>();
- log.debug("createCategoriesByDao: starting to create Categories.");
- for (Map.Entry<String, List<CategoryDefinition>> entry : allCategories.entrySet()) {
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey());
- NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY);
- NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY);
- NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING);
- log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
- List<CategoryDefinition> newCategoriesvalue = new ArrayList<>();
- for (CategoryDefinition category : entry.getValue()) {
+ Map<String, List<CategoryDefinition>> allCategories = createCategoriesFromYml(categoriesTypesYml);
+ return createCategoriesByDao(allCategories);
+ }
- Either<CategoryDefinition, ResponseFormat> createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory);
- if (createdCategoryRes.isRight()) {
- return Either.right(createdCategoryRes.right().value());
- }
+ private Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategoriesByDao(Map<String, List<CategoryDefinition>> allCategories) {
+ Map<String, List<CategoryDefinition>> result = new HashMap<>();
+ log.debug("createCategoriesByDao: starting to create Categories.");
+ for (Map.Entry<String, List<CategoryDefinition>> entry : allCategories.entrySet()) {
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey());
+ NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY);
+ NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY);
+ NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING);
+ log.debug("createCategoriesByDao: creating componentType:{} nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
+ List<CategoryDefinition> newCategoriesvalue = new ArrayList<>();
+ for (CategoryDefinition category : entry.getValue()) {
- CategoryDefinition newcategory = createdCategoryRes.left().value();
- String categoryId = newcategory.getUniqueId();
- log.debug("createCategoriesByDao: create category was successful {}", newcategory);
- List<SubCategoryDefinition> newsubcategories = new ArrayList<>();
- List<SubCategoryDefinition> subcategories = category.getSubcategories();
- if (subcategories != null) {
- for (SubCategoryDefinition subcategory : subcategories) {
- Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory);
- if (createdSubCategory.isRight()) {
- return Either.right(createdCategoryRes.right().value());
- }
- SubCategoryDefinition newsubcategory = createdSubCategory.left().value();
- List<GroupingDefinition> groupings = subcategory.getGroupings();
- if (groupings != null) {
- List<GroupingDefinition> newgroupings = new ArrayList<>();
- for (GroupingDefinition grouping : groupings) {
- Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup);
- if (createdGrouping.isRight()) {
- return Either.right(createdCategoryRes.right().value());
- }
- newgroupings.add(createdGrouping.left().value());
- }
- newsubcategory.setGroupings(newgroupings);
- }
- newsubcategories.add(newsubcategory);
- }
- newcategory.setSubcategories(newsubcategories);
- }
- newCategoriesvalue.add(newcategory);
- }
- result.put(entry.getKey(), newCategoriesvalue);
- }
- return Either.left(result);
- }
+ Either<CategoryDefinition, ResponseFormat> createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory);
+ if (createdCategoryRes.isRight()) {
+ return Either.right(createdCategoryRes.right().value());
+ }
- private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) {
+ CategoryDefinition newcategory = createdCategoryRes.left().value();
+ log.debug("createCategoriesByDao: create category was successful {}", newcategory);
+ List<SubCategoryDefinition> newsubcategories = new ArrayList<>();
+ List<SubCategoryDefinition> subcategories = category.getSubcategories();
+ if (subcategories != null) {
+ for (SubCategoryDefinition subcategory : subcategories) {
+ Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory);
+ if (createdSubCategory.isRight()) {
+ return Either.right(createdCategoryRes.right().value());
+ }
+ SubCategoryDefinition newsubcategory = createdSubCategory.left().value();
+ List<GroupingDefinition> groupings = subcategory.getGroupings();
+ if (groupings != null) {
+ List<GroupingDefinition> newgroupings = new ArrayList<>();
+ for (GroupingDefinition grouping : groupings) {
+ Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup);
+ if (createdGrouping.isRight()) {
+ return Either.right(createdCategoryRes.right().value());
+ }
+ newgroupings.add(createdGrouping.left().value());
+ }
+ newsubcategory.setGroupings(newgroupings);
+ }
+ newsubcategories.add(newsubcategory);
+ }
+ newcategory.setSubcategories(newsubcategories);
+ }
+ newCategoriesvalue.add(newcategory);
+ }
+ result.put(entry.getKey(), newCategoriesvalue);
+ }
+ return Either.left(result);
+ }
- log.debug("createGroupingDeo: creating grouping {}", grouping);
- Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
- if (createdGrouping.isRight()) {
- if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) {
- log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName());
- String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName());
- createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId);
- if (createdGrouping.isRight()) {
- log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup);
- return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
- }
- }
- log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(),
- category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null,
- createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
-
- return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
- } else {
- log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value());
- }
- return Either.left(createdGrouping.left().value());
+ private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) {
- }
+ log.debug("createGroupingDeo: creating grouping {}", grouping);
+ Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
+ if (createdGrouping.isRight()) {
+ if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY.equals(createdGrouping.right().value())) {
+ log.debug(" create grouping for {} group {} already exists ", entry.getKey(), grouping.getName());
+ String groupingId = UniqueIdBuilder.buildGroupingUid(grouping.getUniqueId(), grouping.getNormalizedName());
+ createdGrouping = elementOperation.getGroupingUniqueForType(nodeTypeGroup, groupingId);
+ if (createdGrouping.isRight()) {
+ log.debug("failed to get grouping that exists groupingId: {} type: {}", groupingId, nodeTypeGroup);
+ return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
+ }
+ }
+ log.debug("Failed to create groupingcategory for {} category {} subcategory {} grouping {} error {}", entry.getKey(),
+ category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null,
+ createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
- private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) {
- log.debug("createSubCategorieDeo: creating subcategory {}", subcategory);
- Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
- if (createdSubCategory.isRight()) {
- if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) {
- log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName());
- String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName());
- createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId);
- if (createdSubCategory.isRight()) {
- log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory);
- return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
- }
- } else {
- log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
- return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
- }
- } else {
- log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value());
- }
- return Either.left(createdSubCategory.left().value());
- }
+ return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
+ } else {
+ log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value());
+ }
+ return Either.left(createdGrouping.left().value());
- private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) {
- log.debug("createCategorieDeo: creating category {}", category);
- Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory);
- if (createdCategory.isRight()) {
- log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value());
- if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) {
- return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
- } else {
- log.debug("createCategorieDeo: category exists {} retriving.", category);
- String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory);
- createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId);
- if (createdCategory.isRight()) {
- log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory);
- return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
- }
- }
- } else {
- log.debug("createCategorieDeo: create category was successful {}", createdCategory.left().value());
- }
- return Either.left(createdCategory.left().value());
- }
+ }
- private Map<String, List<CategoryDefinition>> createCategoriesFromYml(String categoriesTypesYml) {
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(categoriesTypesYml);
- Map<String, List<CategoryDefinition>> allCategories = new HashMap<>();
+ private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) {
+ log.debug("createSubCategorieDeo: creating subcategory {}", subcategory);
+ Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
+ if (createdSubCategory.isRight()) {
+ if (ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.equals(createdSubCategory.right().value())) {
+ log.debug(" create subcategory for {} category {} subcategory {} already exists retrieving", entry.getKey(), newcategory.getName(), subcategory.getName());
+ String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName());
+ createdSubCategory = elementOperation.getSubCategory(nodeTypeSubCategory, subCategoryId);
+ if (createdSubCategory.isRight()) {
+ log.debug("failed to get sub category that exists subCategoryId: {} type: {}", subCategoryId, nodeTypeSubCategory);
+ return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
+ }
+ } else {
+ log.debug("Failed to create subcategory for {} category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
+ return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
+ }
+ } else {
+ log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value());
+ }
+ return Either.left(createdSubCategory.left().value());
+ }
- Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator();
- while (categoryEntryItr.hasNext()) {
- Entry<String, Object> categoryTypeEntry = categoryEntryItr.next();
- String categoryType = categoryTypeEntry.getKey();
- List<CategoryDefinition> categoriesPerType = null;
- Map<String, Object> categoryPerType = null;
- switch (categoryType) {
- case ComponentTypeEnum.SERVICE_PARAM_NAME:
- categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
- categoriesPerType = createServiceCategories(categoryPerType);
- break;
- case ComponentTypeEnum.RESOURCE_PARAM_NAME:
- categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
- categoriesPerType = createResourceCategories(categoryPerType);
- break;
- case ComponentTypeEnum.PRODUCT_PARAM_NAME:
- // TODO
- break;
- default:
- log.debug("Not supported category type - {}", categoryType);
- break;
- }
- if (categoriesPerType != null) {
- allCategories.put(categoryType, categoriesPerType);
- }
- }
- return allCategories;
- }
+ private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) {
+ log.debug("createCategorieDeo: creating category {}", category);
+ Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory);
+ if (createdCategory.isRight()) {
+ log.debug("Failed to create category for {} {} error {}", entry.getKey(), category.getName(), createdCategory.right().value());
+ if (!ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.equals(createdCategory.right().value())) {
+ return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
+ } else {
+ log.debug("createCategorieDeo: category exists {} retriving.", category);
+ String categoryId = UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeTypeCategory);
+ createdCategory = elementOperation.getCategory(nodeTypeCategory, categoryId);
+ if (createdCategory.isRight()) {
+ log.debug("failed to get category that exists categoryId: {} type: {}", categoryId, nodeTypeCategory);
+ return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
+ }
+ }
+ } else {
+ log.debug("createCategorieDeo: create category was successful {}", createdCategory.left().value());
+ }
+ return Either.left(createdCategory.left().value());
+ }
- private List<CategoryDefinition> createServiceCategories(Map<String, Object> categories) {
- List<CategoryDefinition> categroiesDef = new ArrayList<>();
- String catName = null;
- List<String> icons = null;
- for (Entry<String, Object> entry : categories.entrySet()) {
- CategoryDefinition catDef = new CategoryDefinition();
- Map<String, Object> category = (Map<String, Object>) entry.getValue();
- catName = (String) category.get("name");
- catDef.setName(catName);
- icons = (List<String>) category.get("icons");
- catDef.setIcons(icons);
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
- catDef.setNormalizedName(normalizedName);
- categroiesDef.add(catDef);
- }
+ private Map<String, List<CategoryDefinition>> createCategoriesFromYml(String categoriesTypesYml) {
+ Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(categoriesTypesYml);
+ Map<String, List<CategoryDefinition>> allCategories = new HashMap<>();
- return categroiesDef;
- }
+ Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator();
+ while (categoryEntryItr.hasNext()) {
+ Entry<String, Object> categoryTypeEntry = categoryEntryItr.next();
+ String categoryType = categoryTypeEntry.getKey();
+ List<CategoryDefinition> categoriesPerType = null;
+ Map<String, Object> categoryPerType = null;
+ switch (categoryType) {
+ case ComponentTypeEnum.SERVICE_PARAM_NAME:
+ categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
+ categoriesPerType = createServiceCategories(categoryPerType);
+ break;
+ case ComponentTypeEnum.RESOURCE_PARAM_NAME:
+ categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
+ categoriesPerType = createResourceCategories(categoryPerType);
+ break;
+ case ComponentTypeEnum.PRODUCT_PARAM_NAME:
+ // TODO
+ break;
+ default:
+ log.debug("Not supported category type - {}", categoryType);
+ break;
+ }
+ if (categoriesPerType != null) {
+ allCategories.put(categoryType, categoriesPerType);
+ }
+ }
+ return allCategories;
+ }
- private List<CategoryDefinition> createResourceCategories(Map<String, Object> categoryPerType) {
- List<CategoryDefinition> categroiesDef = new ArrayList<>();
- for (Map.Entry<String, Object> entry : categoryPerType.entrySet()) {
- Map<String, Object> category = (Map<String, Object>) entry.getValue();
- CategoryDefinition catDef = new CategoryDefinition();
- String catName = (String) category.get("name");
- catDef.setName(catName);
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
- catDef.setNormalizedName(normalizedName);
- Map<String, Object> subcategories = (Map<String, Object>) category.get("subcategories");
- List<SubCategoryDefinition> subcateDef = new ArrayList<>();
- for (Entry<String, Object> subcategory : subcategories.entrySet()) {
- Map<String, Object> subcategoryInfo = (Map<String, Object>) subcategory.getValue();
- SubCategoryDefinition subDef = new SubCategoryDefinition();
- String subcategoryName = (String) subcategoryInfo.get("name");
- subDef.setName(subcategoryName);
- List<String> subcategoryIcons = (List<String>) subcategoryInfo.get("icons");
- subDef.setIcons(subcategoryIcons);
- normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName);
- subDef.setNormalizedName(normalizedName);
- subcateDef.add(subDef);
- }
+ private List<CategoryDefinition> createServiceCategories(Map<String, Object> categories) {
+ List<CategoryDefinition> categroiesDef = new ArrayList<>();
+ String catName = null;
+ List<String> icons = null;
+ for (Entry<String, Object> entry : categories.entrySet()) {
+ CategoryDefinition catDef = new CategoryDefinition();
+ Map<String, Object> category = (Map<String, Object>) entry.getValue();
+ catName = (String) category.get("name");
+ catDef.setName(catName);
+ icons = (List<String>) category.get("icons");
+ catDef.setIcons(icons);
+ String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
+ catDef.setNormalizedName(normalizedName);
+ categroiesDef.add(catDef);
+ }
- catDef.setSubcategories(subcateDef);
- categroiesDef.add(catDef);
- }
- return categroiesDef;
- }
+ return categroiesDef;
+ }
- public static void setLog(Logger log) {
- CategoriesImportManager.log = log;
- }
+ private List<CategoryDefinition> createResourceCategories(Map<String, Object> categoryPerType) {
+ List<CategoryDefinition> categroiesDef = new ArrayList<>();
+ for (Map.Entry<String, Object> entry : categoryPerType.entrySet()) {
+ Map<String, Object> category = (Map<String, Object>) entry.getValue();
+ CategoryDefinition catDef = new CategoryDefinition();
+ String catName = (String) category.get("name");
+ catDef.setName(catName);
+ String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
+ catDef.setNormalizedName(normalizedName);
+ Map<String, Object> subcategories = (Map<String, Object>) category.get("subcategories");
+ List<SubCategoryDefinition> subcateDef = new ArrayList<>();
+ for (Entry<String, Object> subcategory : subcategories.entrySet()) {
+ Map<String, Object> subcategoryInfo = (Map<String, Object>) subcategory.getValue();
+ SubCategoryDefinition subDef = new SubCategoryDefinition();
+ String subcategoryName = (String) subcategoryInfo.get("name");
+ subDef.setName(subcategoryName);
+ List<String> subcategoryIcons = (List<String>) subcategoryInfo.get("icons");
+ subDef.setIcons(subcategoryIcons);
+ normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName);
+ subDef.setNormalizedName(normalizedName);
+ subcateDef.add(subDef);
+ }
+ catDef.setSubcategories(subcateDef);
+ categroiesDef.add(catDef);
+ }
+ return categroiesDef;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
index 31c665686e..055e479d0d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
@@ -20,27 +20,13 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -49,260 +35,279 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
-import jersey.repackaged.com.google.common.base.Function;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
@Component("commonImportManager")
public class CommonImportManager {
- private static Logger log = LoggerFactory.getLogger(CommonImportManager.class.getName());
-
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private PropertyOperation propertyOperation;
-
- protected void setProperties(Map<String, Object> toscaJson, Consumer<List<PropertyDefinition>> consumer) {
- consumer.accept(getProperties(toscaJson));
- }
-
- private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
- List<PropertyDefinition> values = null;
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
-
- if (properties.isLeft()) {
- values = new ArrayList<>();
- Map<String, PropertyDefinition> propertiesMap = properties.left().value();
- if (propertiesMap != null && propertiesMap.isEmpty() == false) {
-
- for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
- String propName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
- newPropertyDefinition.setName(propName);
- values.add(newPropertyDefinition);
- }
- }
- }
-
- return values;
- }
-
- protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) {
- final List<PropertyDefinition> properties = getProperties(toscaJson);
- if (properties != null) {
- Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
- consumer.accept(collect);
- }
-
- }
-
- interface ICreateElementType<T1, T2, ElementType> {
- ElementType createElement(T1 firstArg, T2 secondArg);
- }
-
- protected <ElementDefinition> Either<List<ElementDefinition>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi) {
-
- List<ElementDefinition> elementTypes = new ArrayList<>();
- try {
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(elementTypesYml);
-
- Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
- while (elementTypesEntryItr.hasNext()) {
- Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
- String elementTypeName = elementTypeNameDataEntry.getKey();
- Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
- ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData);
- elementTypes.add(elementDefinition);
-
- }
-
- } catch (Exception e) {
- log.debug("Failed to yaml file {}", elementTypesYml, e);
- return Either.right(ActionStatus.INVALID_YAML_FILE);
- }
- return Either.left(elementTypes);
- }
-
- protected <FieldType> void setField(Map<String, Object> toscaJson, String fieldName, Consumer<FieldType> setter) {
- if (toscaJson.containsKey(fieldName)) {
- FieldType fieldValue = (FieldType) toscaJson.get(fieldName);
- setter.accept(fieldValue);
- }
-
- }
-
- public enum ElementTypeEnum {
- PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType
- };
-
- private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) {
- ActionStatus ret;
- switch (elementTypeEnum) {
- case GroupType:
- ret = componentsUtils.convertFromStorageResponseForGroupType(status);
- break;
- case DataType:
- ret = componentsUtils.convertFromStorageResponseForDataType(status);
- break;
- case CapabilityType:
- ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
- break;
- case InterfaceLifecycleType:
- ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
- break;
- default:
- ret = componentsUtils.convertFromStorageResponse(status);
- break;
- }
- return ret;
- }
-
- private <ElementTypeDefinition> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) {
- ResponseFormat ret;
- switch (elementTypeEnum) {
- case GroupType:
- ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
- break;
- case PolicyType:
- ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
- break;
- case DataType:
- ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
- break;
- case CapabilityType:
- ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
- break;
-
- default:
- ret = componentsUtils.getResponseFormat(actionStatus);
- break;
- }
- return ret;
- }
-
- protected <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypesByDao(List<ElementTypeDefinition> elementTypesToCreate,
- Function<ElementTypeDefinition, Either<ActionStatus, ResponseFormat>> validator, Function<ElementTypeDefinition, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
- Function<String, Either<ElementTypeDefinition, StorageOperationStatus>> elementFetcher, Function<ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementAdder,
- BiFunction<ElementTypeDefinition, ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementUpgrader) {
-
- List<ImmutablePair<ElementTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
-
- Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = Either.left(createdElementTypes);
-
- Iterator<ElementTypeDefinition> elementTypeItr = elementTypesToCreate.iterator();
-
- try {
-
- while (elementTypeItr.hasNext()) {
- ElementTypeDefinition elementType = elementTypeItr.next();
- final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType);
- ElementTypeEnum elementTypeEnum = elementInfo.left;
- String elementName = elementInfo.right;
-
- Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
- if (validateElementType.isRight()) {
- ResponseFormat responseFormat = validateElementType.right().value();
- log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage());
- eitherResult = Either.right(responseFormat);
- break;
- }
-
- log.info("send {} : {} to dao for create", elementTypeEnum.name(), elementName);
-
- Either<ElementTypeDefinition, StorageOperationStatus> findElementType = elementFetcher.apply(elementName);
- if (findElementType.isRight()) {
- StorageOperationStatus status = findElementType.right().value();
- log.debug("searched {} finished with result:{}", elementTypeEnum.name(), status.name());
- if (status != StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType);
- eitherResult = Either.right(responseFormat);
- break;
- } else {
- Either<ElementTypeDefinition, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType);
-
- if (dataModelResponse.isRight()) {
- try {
- BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name());
- log.debug("failed to create {}: {}", elementTypeEnum.name(), elementName);
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
-
- eitherResult = Either.right(responseFormat);
- break;
- } else {
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
- }
- } finally {
- propertyOperation.getTitanGenericDao().rollback();
- }
- } else {
- propertyOperation.getTitanGenericDao().commit();
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true));
- log.debug("{} : {} was created successfully.", elementTypeEnum.name(), elementName);
- }
- if (!elementTypeItr.hasNext()) {
- log.info("all {} were created successfully!!!", elementTypeEnum.name());
- }
-
- }
- } else {
-
- if (elementUpgrader != null) {
- Either<ElementTypeDefinition, StorageOperationStatus> upgradeResponse = null;
- try {
- upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value());
- if (upgradeResponse.isRight()) {
- StorageOperationStatus status = upgradeResponse.right().value();
- if (status == StorageOperationStatus.OK) {
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
- } else {
- ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
- eitherResult = Either.right(responseFormat);
- break;
- }
- } else {
- log.debug("{} : {} was upgraded successfully.", elementTypeEnum.name(), elementName);
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true));
- }
- } finally {
- if (upgradeResponse == null || upgradeResponse.isRight()) {
- propertyOperation.getTitanGenericDao().rollback();
- } else {
- propertyOperation.getTitanGenericDao().commit();
- }
- }
-
- } else {
- // mshitrit Once GroupType Versions are supported add
- // code here
- createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
- log.debug("{} : {} already exists.", elementTypeEnum.name(), elementName);
- }
-
- }
-
- }
- } finally {
- if (eitherResult.isRight()) {
- propertyOperation.getTitanGenericDao().rollback();
- }
- }
-
- return eitherResult;
-
- }
-
- public <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<ElementTypeDefinition>, ActionStatus>> elementTypeFromYmlCreater,
- Function<List<ElementTypeDefinition>, Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) {
-
- Either<List<ElementTypeDefinition>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml);
- if (elementTypes.isRight()) {
- ActionStatus status = elementTypes.right().value();
- ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null);
- return Either.right(responseFormat);
- }
- return elementTypeDaoCreater.apply(elementTypes.left().value());
-
- }
+ private static final Logger log = LoggerFactory.getLogger(CommonImportManager.class);
+
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Resource
+ private PropertyOperation propertyOperation;
+
+ protected void setProperties(Map<String, Object> toscaJson, Consumer<List<PropertyDefinition>> consumer) {
+ consumer.accept(getProperties(toscaJson));
+ }
+
+ private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
+ List<PropertyDefinition> values = null;
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
+
+ if (properties.isLeft()) {
+ values = new ArrayList<>();
+ Map<String, PropertyDefinition> propertiesMap = properties.left().value();
+ if (propertiesMap != null && propertiesMap.isEmpty() == false) {
+
+ for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
+ String propName = entry.getKey();
+ PropertyDefinition propertyDefinition = entry.getValue();
+ PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
+ newPropertyDefinition.setName(propName);
+ values.add(newPropertyDefinition);
+ }
+ }
+ }
+
+ return values;
+ }
+
+ protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) {
+ final List<PropertyDefinition> properties = getProperties(toscaJson);
+ if (properties != null) {
+ Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
+ consumer.accept(collect);
+ }
+
+ }
+
+ interface ICreateElementType<T1, T2, ElementType> {
+ ElementType createElement(T1 firstArg, T2 secondArg);
+ }
+
+ protected <ElementDefinition> Either<List<ElementDefinition>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi) {
+
+ List<ElementDefinition> elementTypes = new ArrayList<>();
+ try {
+ Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(elementTypesYml);
+
+ elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson);
+ } catch (Exception e) {
+ log.debug("Failed to yaml file {}", elementTypesYml, e);
+ return Either.right(ActionStatus.INVALID_YAML_FILE);
+ }
+ return Either.left(elementTypes);
+ }
+
+ /**
+ * @param createApi * @param createApi
+ * @param elementTypes
+ * @param toscaJson
+ */
+ protected <ElementDefinition> List<ElementDefinition> createElementTypesFromToscaJsonMap(
+ ICreateElementType<String, Map<String, Object>, ElementDefinition> createApi, Map<String, Object> toscaJson) {
+ List<ElementDefinition> elementTypes = new ArrayList<>();
+
+ Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
+ while (elementTypesEntryItr.hasNext()) {
+ Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
+ String elementTypeName = elementTypeNameDataEntry.getKey();
+ Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
+ ElementDefinition elementDefinition = createApi.createElement(elementTypeName, elementTypeJsonData);
+ elementTypes.add(elementDefinition);
+ }
+ return elementTypes;
+ }
+
+ protected <FieldType> void setField(Map<String, Object> toscaJson, String fieldName, Consumer<FieldType> setter) {
+ if (toscaJson.containsKey(fieldName)) {
+ FieldType fieldValue = (FieldType) toscaJson.get(fieldName);
+ setter.accept(fieldValue);
+ }
+
+ }
+
+ public enum ElementTypeEnum {
+ PolicyType, GroupType, DataType, CapabilityType, InterfaceLifecycleType
+ };
+
+ private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) {
+ ActionStatus ret;
+ switch (elementTypeEnum) {
+ case GroupType:
+ ret = componentsUtils.convertFromStorageResponseForGroupType(status);
+ break;
+ case DataType:
+ ret = componentsUtils.convertFromStorageResponseForDataType(status);
+ break;
+ case CapabilityType:
+ ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
+ break;
+ case InterfaceLifecycleType:
+ ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
+ break;
+ default:
+ ret = componentsUtils.convertFromStorageResponse(status);
+ break;
+ }
+ return ret;
+ }
+
+ private <ElementTypeDefinition> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, ElementTypeDefinition elementTypeDefinition) {
+ ResponseFormat ret;
+ switch (elementTypeEnum) {
+ case GroupType:
+ ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
+ break;
+ case PolicyType:
+ ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
+ break;
+ case DataType:
+ ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
+ break;
+ case CapabilityType:
+ ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
+ break;
+
+ default:
+ ret = componentsUtils.getResponseFormat(actionStatus);
+ break;
+ }
+ return ret;
+ }
+
+ protected <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypesByDao(List<ElementTypeDefinition> elementTypesToCreate,
+ Function<ElementTypeDefinition, Either<ActionStatus, ResponseFormat>> validator, Function<ElementTypeDefinition, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+ Function<String, Either<ElementTypeDefinition, StorageOperationStatus>> elementFetcher, Function<ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementAdder,
+ BiFunction<ElementTypeDefinition, ElementTypeDefinition, Either<ElementTypeDefinition, StorageOperationStatus>> elementUpgrader) {
+
+ List<ImmutablePair<ElementTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
+
+ Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = Either.left(createdElementTypes);
+
+ Iterator<ElementTypeDefinition> elementTypeItr = elementTypesToCreate.iterator();
+
+ try {
+
+ while (elementTypeItr.hasNext()) {
+ ElementTypeDefinition elementType = elementTypeItr.next();
+ final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType);
+ ElementTypeEnum elementTypeEnum = elementInfo.left;
+ String elementName = elementInfo.right;
+
+ Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
+ if (validateElementType.isRight()) {
+ ResponseFormat responseFormat = validateElementType.right().value();
+ log.debug("Failed in validation of element type: {}. Response is {}", elementType, responseFormat.getFormattedMessage());
+ eitherResult = Either.right(responseFormat);
+ break;
+ }
+
+ log.info("send {} : {} to dao for create", elementTypeEnum, elementName);
+
+ Either<ElementTypeDefinition, StorageOperationStatus> findElementType = elementFetcher.apply(elementName);
+ if (findElementType.isRight()) {
+ StorageOperationStatus status = findElementType.right().value();
+ log.debug("searched {} finished with result:{}", elementTypeEnum, status.name());
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType);
+ eitherResult = Either.right(responseFormat);
+ break;
+ } else {
+ Either<ElementTypeDefinition, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType);
+
+ if (dataModelResponse.isRight()) {
+ try {
+ BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name());
+ log.debug("failed to create {}: {}", elementTypeEnum, elementName);
+ if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+
+ eitherResult = Either.right(responseFormat);
+ break;
+ } else {
+ createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
+ }
+ } finally {
+ propertyOperation.getTitanGenericDao().rollback();
+ }
+ } else {
+ propertyOperation.getTitanGenericDao().commit();
+ createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true));
+ log.debug("{} : {} was created successfully.", elementTypeEnum, elementName);
+ }
+ if (!elementTypeItr.hasNext()) {
+ log.info("all {} were created successfully!!!", elementTypeEnum);
+ }
+
+ }
+ } else {
+
+ if (elementUpgrader != null) {
+ Either<ElementTypeDefinition, StorageOperationStatus> upgradeResponse = null;
+ try {
+ upgradeResponse = elementUpgrader.apply(elementType, findElementType.left().value());
+ if (upgradeResponse.isRight()) {
+ StorageOperationStatus status = upgradeResponse.right().value();
+ if (status == StorageOperationStatus.OK) {
+ createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
+ } else {
+ ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+ eitherResult = Either.right(responseFormat);
+ break;
+ }
+ } else {
+ log.debug("{} : {} was upgraded successfully.", elementTypeEnum, elementName);
+ createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, true));
+ }
+ } finally {
+ if (upgradeResponse == null || upgradeResponse.isRight()) {
+ propertyOperation.getTitanGenericDao().rollback();
+ } else {
+ propertyOperation.getTitanGenericDao().commit();
+ }
+ }
+
+ } else {
+ // mshitrit Once GroupType Versions are supported add
+ // code here
+ createdElementTypes.add(new ImmutablePair<ElementTypeDefinition, Boolean>(elementType, false));
+ log.debug("{} : {} already exists.", elementTypeEnum, elementName);
+ }
+
+ }
+
+ }
+ } finally {
+ if (eitherResult.isRight()) {
+ propertyOperation.getTitanGenericDao().rollback();
+ }
+ }
+
+ return eitherResult;
+
+ }
+
+ public <ElementTypeDefinition> Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<ElementTypeDefinition>, ActionStatus>> elementTypeFromYmlCreater,
+ Function<List<ElementTypeDefinition>, Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) {
+
+ Either<List<ElementTypeDefinition>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml);
+ if (elementTypes.isRight()) {
+ ActionStatus status = elementTypes.right().value();
+ ResponseFormat responseFormat = getResponseFormatForElementType(status, elementTypeEnum, null);
+ return Either.right(responseFormat);
+ }
+ return elementTypeDaoCreater.apply(elementTypes.left().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 40e67aa876..4688aa4b8f 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
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -42,31 +35,17 @@ import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
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.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
-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.Resource;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ComponentCache;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
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;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.utils.CommonBeUtils;
@@ -79,1070 +58,1077 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
- @Autowired
- protected ArtifactsBusinessLogic artifactsBusinessLogic;
-
- @Autowired
- protected ComponentCache componentCache;
-
- @Autowired
- private GenericTypeBusinessLogic genericTypeBusinessLogic;
-
- public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) {
- this.genericTypeBusinessLogic = genericTypeBusinessLogic;
- }
-
- private static Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class.getName());
-
- private static final String TAG_FIELD_LABEL = "tag";
-
- public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents();
-
- public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
-
- public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText);
-
- /**
- *
- * @param componentId
- * @param dataParamsToReturn
- * @return
- */
- public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn);
-
- protected Either<User, ResponseFormat> validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
- Either<User, ResponseFormat> userValidationResult = validateUserNotEmpty(user, ecompErrorContext);
- ResponseFormat responseFormat;
- if (userValidationResult.isRight()) {
- user.setUserId("UNKNOWN");
- responseFormat = userValidationResult.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType());
- return Either.right(responseFormat);
- }
- Either<User, ResponseFormat> userResult = validateUserExists(user, ecompErrorContext, inTransaction);
- if (userResult.isRight()) {
- responseFormat = userResult.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", auditAction, component.getComponentType());
- return Either.right(responseFormat);
- }
- return userResult;
- }
-
- protected Either<Boolean, ResponseFormat> validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) {
- if (roles != null && roles.isEmpty()) {
- roles.add(Role.ADMIN);
- roles.add(Role.DESIGNER);
- }
- Either<Boolean, ResponseFormat> validationResult = validateUserRole(user, roles);
- if (validationResult.isRight()) {
- ComponentTypeEnum componentType = component.getComponentType();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- if (componentType.equals(ComponentTypeEnum.SERVICE)) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
- String distributionStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus();
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, distributionStatus);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, distributionStatus);
- }
- componentsUtils.auditComponent(validationResult.right().value(), user, component, "", "", auditAction, componentType, additionalParams);
- }
- return validationResult;
- }
-
- protected Either<Boolean, ResponseFormat> validateComponentName(User user, Component component, AuditingActionEnum actionEnum) {
- ComponentTypeEnum type = component.getComponentType();
- String componentName = component.getName();
- if (!ValidationUtils.validateStringNotEmpty(componentName)) {
- log.debug("component name is empty");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue());
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
-
- if (!ValidationUtils.validateComponentNameLength(componentName)) {
- log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
-
- if (!validateTagPattern(componentName)) {
- log.debug("Component name {} has invalid format", componentName);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue());
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
- component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName));
- component.setSystemName(ValidationUtils.convertToSystemName(componentName));
-
- return Either.left(true);
- }
-
- protected Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
- ComponentTypeEnum type = component.getComponentType();
- String description = component.getDescription();
- if (!ValidationUtils.validateStringNotEmpty(description)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue());
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
-
- description = cleanUpText(description);
- Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type);
- if (validatDescription.isRight()) {
- ResponseFormat responseFormat = validatDescription.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type);
- return Either.right(responseFormat);
- }
- component.setDescription(description);
- return Either.left(true);
- }
-
- public Either<Boolean, ResponseFormat> validateComponentDescription(String description, ComponentTypeEnum type) {
- if (description != null) {
- if (!ValidationUtils.validateDescriptionLength(description)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
- }
-
- if (!ValidationUtils.validateIsEnglish(description)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue()));
- }
- return Either.left(true);
- }
- return Either.left(false);
- }
-
- protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) {
- ComponentTypeEnum type = component.getComponentType();
- ResourceTypeEnum resourceType = null;
- if(component instanceof Resource){
- resourceType = ((Resource)component).getResourceType();
- }
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type);
-
- if (dataModelResponse.isLeft()) {
- if ( !dataModelResponse.left().value()) {
- return Either.left(true);
- } else {
- log.info("Component with name {} already exists", component.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName());
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
- }
- BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique");
- log.debug("Error while validateComponentNameUnique for component: {}", component.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
-
- protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) {
- log.debug("validate component contactId");
- ComponentTypeEnum type = component.getComponentType();
- String contactId = component.getContactId();
-
- if (!ValidationUtils.validateStringNotEmpty(contactId)) {
- log.info("contact is missing.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue());
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId, type);
- if (validateContactIdResponse.isRight()) {
- ResponseFormat responseFormat = validateContactIdResponse.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type);
- }
- return validateContactIdResponse;
- }
-
- private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) {
- if (contactId != null) {
- if (!ValidationUtils.validateContactId(contactId)) {
- log.info("contact is invalid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- return Either.left(false);
- }
-
-
- public Either<Boolean, ResponseFormat> 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 {}", componentUuid);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(errorResponse);
- }
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validateConformanceLevel", false);
- if (resp.isRight()) {
- log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId);
- return Either.right(resp.right().value());
- }
-
- Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
- if (eitherComponent.isRight()) {
- 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);
- }
-
- 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(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");
-
- return Either.left(result);
- }
-
- protected Either<Boolean, ResponseFormat> validateIcon(User user, Component component, AuditingActionEnum actionEnum) {
- log.debug("validate Icon");
- ComponentTypeEnum type = component.getComponentType();
- String icon = component.getIcon();
- if (!ValidationUtils.validateStringNotEmpty(icon)) {
- log.info("icon is missing.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue());
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, type);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon, type);
- if (validateIcon.isRight()) {
- ResponseFormat responseFormat = validateIcon.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, type);
- }
- return validateIcon;
- }
-
- private Either<Boolean, ResponseFormat> validateIcon(String icon, ComponentTypeEnum type) {
- if (icon != null) {
- if (!ValidationUtils.validateIconLength(icon)) {
- log.debug("icon exceeds max length");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH));
- }
-
- if (!ValidationUtils.validateIcon(icon)) {
- log.info("icon is invalid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- return Either.left(false);
- }
-
- protected Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) {
- List<String> tagsList = component.getTags();
-
- Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType());
- if (validateTags.isRight()) {
- ResponseFormat responseFormat = validateTags.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, component.getComponentType());
- return Either.right(responseFormat);
- }
- ValidationUtils.removeDuplicateFromList(tagsList);
- return Either.left(true);
- }
-
- protected Either<Boolean, ResponseFormat> validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType) {
- log.debug("validate component tags");
- boolean includesComponentName = false;
- int tagListSize = 0;
- if (tags != null && !tags.isEmpty()) {
- for (String tag : tags) {
- if (!ValidationUtils.validateTagLength(tag)) {
- log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH));
- }
- if (validateTagPattern(tag)) {
- if (!includesComponentName) {
- includesComponentName = name.equals(tag);
- }
- } else {
- log.debug("invalid tag {}", tag);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL));
- }
- tagListSize += tag.length() + 1;
- }
- if (tagListSize > 0) {
- tagListSize--;
- }
-
- if (!includesComponentName) {
- log.debug("tags must include component name");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME));
- }
- if (!ValidationUtils.validateTagListLength(tagListSize)) {
- log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH));
- }
- return Either.left(true);
- }
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS));
- }
-
- protected boolean validateTagPattern(String tag) {
- return ValidationUtils.validateComponentNamePattern(tag);
- }
-
- protected Either<Boolean, ResponseFormat> validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) {
- if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) {
- return Either.left(true);
- }
- log.debug("validate ProjectCode name ");
- String projectCode = component.getProjectCode();
-
- if (!ValidationUtils.validateStringNotEmpty(projectCode)) {
- log.info("projectCode is missing.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE);
- componentsUtils.auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, component.getComponentType());
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateProjectCodeResponse = validateProjectCode(projectCode);
- if (validateProjectCodeResponse.isRight()) {
- ResponseFormat responseFormat = validateProjectCodeResponse.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, component.getComponentType());
- }
- return validateProjectCodeResponse;
-
- }
-
- private Either<Boolean, ResponseFormat> validateProjectCode(String projectCode) {
- if (projectCode != null) {
- if (!ValidationUtils.validateProjectCode(projectCode)) {
- log.info("projectCode is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- return Either.left(false);
- }
-
- protected void checkComponentFieldsForOverrideAttempt(Component component) {
- if (component.getLifecycleState() != null) {
- log.info("LifecycleState cannot be defined by user. This field will be overridden by the application");
- }
- if (component.getVersion() != null) {
- log.info("Version cannot be defined by user. This field will be overridden by the application");
- }
- if ((component.getCreatorUserId() != null) || (component.getCreatorFullName() != null)) {
- log.info("Creator cannot be defined by user. This field will be overridden by the application");
- }
- if ((component.getLastUpdaterUserId() != null) || (component.getLastUpdaterFullName() != null)) {
- log.info("Last Updater cannot be defined by user. This field will be overridden by the application");
- }
- if ((component.getCreationDate() != null)) {
- log.info("Creation Date cannot be defined by user. This field will be overridden by the application");
- }
- if ((component.isHighestVersion() != null)) {
- log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application");
- }
- if ((component.getUUID() != null)) {
- log.info("UUID cannot be defined by user. This field will be overridden by the application");
- }
- if ((component.getLastUpdateDate() != null)) {
- log.info("Last Update Date cannot be defined by user. This field will be overridden by the application");
- }
- if (component.getUniqueId() != null) {
- log.info("uid cannot be defined by user. This field will be overridden by the application.");
- component.setUniqueId(null);
- }
- if (component.getInvariantUUID() != null) {
- log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application.");
- }
- }
-
- protected Either<Boolean, ResponseFormat> validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) {
- // validate component name uniqueness
- log.debug("validate component name ");
- Either<Boolean, ResponseFormat> componentNameValidation = validateComponentName(user, component, actionEnum);
- if (componentNameValidation.isRight()) {
- return componentNameValidation;
- }
-
- // validate description
- log.debug("validate description");
- Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, component, actionEnum);
- if (descValidation.isRight()) {
- return descValidation;
- }
-
- // validate tags
- log.debug("validate tags");
- Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum);
- if (tagsValidation.isRight()) {
- return tagsValidation;
- }
-
- // validate contact info
- log.debug("validate contact info");
- Either<Boolean, ResponseFormat> contactIdValidation = validateContactId(user, component, actionEnum);
- if (contactIdValidation.isRight()) {
- return contactIdValidation;
- }
-
- // validate icon
- log.debug("validate icon");
- Either<Boolean, ResponseFormat> iconValidation = validateIcon(user, component, actionEnum);
- if (iconValidation.isRight()) {
- return iconValidation;
- }
- return Either.left(true);
- }
-
- public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<CapReqDef, ResponseFormat> eitherRet = null;
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreCapabilities(false);
- filter.setIgnoreRequirements(false);
- filter.setIgnoreComponentInstances(false);
- Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter);
- if (eitherComponent.isLeft()) {
- eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities()));
- } else {
- BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId);
- eitherRet = Either.right(eitherComponent.right().value());
- }
- return eitherRet;
- }
-
- public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
- String userId) {
- ResponseFormat responseFormat = null;
- try{
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
-
- if (resp.isLeft()) {
- List<Component> result = new ArrayList<>();
- List<String> componentsUidToFetch = new ArrayList<>();
- componentsUidToFetch.addAll(componentUids);
-
- if (!componentsUidToFetch.isEmpty()) {
- log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
- Boolean isHighest = isHighest(highestFilter);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch);
-
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- result.addAll(nonCheckoutCompResponse.left().value());
- } else {
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
- }
- }
- return Either.left(result);
- } else {
- responseFormat = resp.right().value();
- }
- }
- finally{
- titanDao.commit();
- }
- return Either.right(responseFormat);
- }
-
- private Boolean isHighest(HighestFilterEnum highestFilter) {
- Boolean isHighest = null;
- switch (highestFilter) {
- case ALL:
- break;
- case HIGHEST_ONLY:
- isHighest = true;
- break;
- case NON_HIGHEST_ONLY:
- isHighest = false;
- break;
- default:
- break;
- }
- return isHighest;
- }
-
- public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
- ResponseFormat responseFormat = null;
-
- try{
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
- if (resp.isLeft()) {
-
- Boolean isHighest = isHighest(highestFilter);
- Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType);
-
- if (nonCheckoutCompResponse.isLeft()) {
- log.debug("Retrived Resource successfully.");
- return Either.left(nonCheckoutCompResponse.left().value());
- }
- responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
- } else {
- responseFormat = resp.right().value();
- }
- } finally {
- titanDao.commit();
- }
- return Either.right(responseFormat);
- }
-
- public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
-
- }
-
- @SuppressWarnings("unchecked")
- public void setToscaArtifactsPlaceHolders(Component component, User user) {
- Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts();
- if (artifactMap == null) {
- artifactMap = new HashMap<>();
- }
- String componentUniqueId = component.getUniqueId();
- String componentSystemName = component.getSystemName();
- String componentType = component.getComponentType().getValue().toLowerCase();
- Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts();
-
- if (toscaArtifacts != null) {
- for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) {
- Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue();
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
- artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
- }
- }
- component.setToscaArtifacts(artifactMap);
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) {
- return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true);
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) {
- Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId());
- if ( toscaElement.isRight() ){
- ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
- return Either.right(response);
- }
- component = toscaElement.left().value();
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaRes = null;
- if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) {
- ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()))
- .findAny().get();
- generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
- if (generateToscaRes.isRight()) {
- return generateToscaRes;
- }
- toscaArtifact = generateToscaRes.left().value().left().value();
- component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
- if(!isAbstractResource(component)){
- toscaArtifact = component.getToscaArtifacts().values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
- .findAny().get();
- generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
- if (generateToscaRes.isRight()) {
- return generateToscaRes;
- }
- toscaArtifact = generateToscaRes.left().value().left().value();
- component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
- }
- }
- return generateToscaRes;
- }
-
- private boolean isAbstractResource(Component component) {
- return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract();
- }
-
- public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock,
- boolean inTransaction, boolean fetchTemplatesFromDB) {
- return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
- }
-
- public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) {
-
- Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
- Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
-
- if (latestVersionEither.isRight()) {
- ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
- return Either.right(response);
- }
-
- List<Component> components = latestVersionEither.left().value();
-
- Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null);
- if(component == null){
- component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null);
- }
-
- if(component == null){
- ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType));
- return Either.right(response);
- }
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- // TODO remove after migration - handle artifact not found(no
- // placeholder)
- if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
- }
- ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
- .findAny().get();
- return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact);
- }
-
- protected StorageOperationStatus markComponentToDelete(Component component) {
-
- ComponentTypeEnum componentType = component.getComponentType();
- String uniqueId = component.getUniqueId();
- if ((component.getIsDeleted() != null) && (component.getIsDeleted() == true)) {
- log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType);
- return StorageOperationStatus.NOT_FOUND;
- }
-
- StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component);
- if (StorageOperationStatus.OK != markResourceToDelete) {
- log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete);
- return markResourceToDelete;
- } else {
- log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType);
- return StorageOperationStatus.OK;
- }
- }
-
- public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) {
- String descriptionUpdated = updatedComponent.getDescription();
- String descriptionCurrent = currentComponent.getDescription();
- if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
- Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction);
- if (validateDescriptionResponse.isRight()) {
- ResponseFormat errorRespons = validateDescriptionResponse.right().value();
- return Either.right(errorRespons);
- }
- currentComponent.setDescription(updatedComponent.getDescription());
- }
- return Either.left(true);
- }
-
- public Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) {
- String projectCodeUpdated = updatedComponent.getProjectCode();
- String projectCodeCurrent = currentComponent.getProjectCode();
- if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) {
- Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null);
- if (validatProjectCodeResponse.isRight()) {
- ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
- return Either.right(errorRespons);
- }
- currentComponent.setProjectCode(updatedComponent.getProjectCode());
- }
- return Either.left(true);
- }
-
- public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) {
- String iconUpdated = updatedComponent.getIcon();
- String iconCurrent = currentComponent.getIcon();
- if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, updatedComponent, null);
- if (validatIconResponse.isRight()) {
- ResponseFormat errorRespons = validatIconResponse.right().value();
- return Either.right(errorRespons);
- }
- currentComponent.setIcon(updatedComponent.getIcon());
- } else {
- log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase());
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
-
- log.trace("start deleteMarkedComponents");
- Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
-
- titanDao.commit();
- if ( deleteMarkedElements.isRight()){
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
- return Either.right(responseFormat);
- }
- log.trace("end deleteMarkedComponents");
- return Either.left(deleteMarkedElements.left().value());
- }
-
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) {
- List<ArtifactDefinition> artifacts = new ArrayList<>();
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId);
- if (artifactsResponse.isRight()) {
- if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- log.debug("failed to retrieve artifacts for {} {}", parentType, parentId);
- return Either.right(artifactsResponse.right().value());
- }
- } else {
- artifacts.addAll(artifactsResponse.left().value().values());
- }
- return Either.left(artifacts);
- }
-
- /**
- *
- * @param componentId
- * @param user
- * @param dataParamsToReturn - ui list of params to return
- * @return
- */
-
- public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) {
-
- if (user != null) {
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- }
-
- UiComponentDataTransfer result = new UiComponentDataTransfer();
-
- if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
- Either.left(result);
-
- } else {
- Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn);
- if(uiDataTransferEither.isRight()){
- return Either.right(uiDataTransferEither.right().value());
- }
- result = uiDataTransferEither.left().value();
- }
-
- return Either.left(result);
- }
-
- protected <T extends Component> void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) {
- List<InputDefinition> genericAndComponentInputs = new ArrayList<>();
- List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType);
- genericAndComponentInputs.addAll(genericInputs);
- if (null != component.getInputs()){
- List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs());
- genericAndComponentInputs.addAll(nonGenericInputsFromComponent);
- }
- component.setInputs(genericAndComponentInputs);
- }
-
- private List<InputDefinition> getAllNonGenericInputsFromComponent(List<InputDefinition> genericInputs, List<InputDefinition> componentInputs) {
- if (genericInputs == null) {
- return componentInputs;
- }
-
- Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName);
- List<InputDefinition> componentNonGenericInputs = new ArrayList<>();
- componentInputs.stream().forEach(input -> {
- if (!inputByNameMap.containsKey(input.getName())) {
- componentNonGenericInputs.add(input);
- }
- });
- return componentNonGenericInputs;
- }
-
- protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
- Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component);
- if(genericTypeEither.isRight()){
- log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType()));
- }
- Resource genericTypeResource = genericTypeEither.left().value();
- component.setDerivedFromGenericInfo(genericTypeResource);
- return Either.left(genericTypeResource);
- }
-
- public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) {
- Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null;
- Either<Component, StorageOperationStatus> getResourceRes = null;
- try{
- if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){
- response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- if (userId != null && response == null) {
- Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false);
- if (validateUserRes.isRight()) {
- response = Either.right(validateUserRes.right().value());
- }
- }
- if(response == null){
- getResourceRes = toscaOperationFacade.getToscaElement(componentId);
- if(getResourceRes.isRight()){
- response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
- }
- }
- if(response == null){
- response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters);
- }
- } catch(Exception e){
- log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId);
- response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally{
- if (response.isLeft()){
- toscaOperationFacade.commit();
- } else {
- toscaOperationFacade.rollback();
- }
- }
- return response;
- }
-
- private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) {
-
- Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
- Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties);
- List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE));
- String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
- boolean searchByFragment = propertyNameFragment.length() > 3 ;
- if(CollectionUtils.isNotEmpty(filteredInstances)){
- for(ComponentInstance instance : filteredInstances){
- if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){
- List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
- if(CollectionUtils.isNotEmpty(currProperties)){
- filteredProperties.put(instance.getUniqueId(), currProperties);
- }
- }
- if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){
- List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
- if(CollectionUtils.isNotEmpty(currInputs)){
- if(filteredProperties.get(instance.getUniqueId())!=null){
- filteredProperties.get(instance.getUniqueId()).addAll(currInputs);
- } else {
- filteredProperties.put(instance.getUniqueId(), currInputs);
- }
- }
- }
- }
- }
- return result;
- }
-
- private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) {
- return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
- }
-
- private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) {
- return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
- }
-
- private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) {
- boolean isMatching = false;
- if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){
- isMatching = true;
- }
- if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){
- isMatching = true;
- }
- return isMatching;
- }
-
- private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) {
- boolean isMatching = false;
- if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){
- isMatching = true;
- }
- if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
- isMatching = true;
- }
- if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){
- isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment);
- }
- return isMatching;
- }
-
- private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
- String propertyType;
- List<PropertyDefinition> dataTypeProperties;
- DataTypeDefinition currentProperty;
- if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){
- return true;
- }
- if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
- return true;
- }
-
- propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType();
-
- if(ToscaPropertyType.isScalarType(propertyType)){
- return false;
- }
- Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
- if(getDataTypeByNameRes.isRight()){
- return false;
- }
- currentProperty = getDataTypeByNameRes.left().value();
- dataTypeProperties = currentProperty.getProperties();
-
- if(CollectionUtils.isNotEmpty(dataTypeProperties)){
- for(PropertyDefinition prop : dataTypeProperties){
- if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
- return true;
- }
- }
- }
- dataTypeProperties = currentProperty.getDerivedFrom().getProperties();
- if(CollectionUtils.isNotEmpty(dataTypeProperties)){
- for(PropertyDefinition prop : dataTypeProperties){
- if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean isEmptyInnerType(PropertyDataDefinition property) {
- return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null;
- }
-
- public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) {
-
- if(!clonedComponent.deriveFromGeneric())
- return Either.left(false);
- Boolean shouldUpgrade = false;
- String currentGenericType = clonedComponent.getDerivedFromGenericType();
- String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
- Either<Resource, ResponseFormat> fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent);
- if(fetchAndSetLatestGeneric.isRight())
- return Either.right(fetchAndSetLatestGeneric.right().value());
- Resource genericTypeResource = fetchAndSetLatestGeneric.left().value();
- if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){
- shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource);
- if(!shouldUpgrade) {
- reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion);
- }
- }
- return Either.left(shouldUpgrade);
- }
-
- private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) {
- clonedComponent.setDerivedFromGenericType(currentGenericType);
- clonedComponent.setDerivedFromGenericVersion(currentGenericVersion);
- }
-
- private <T extends PropertyDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList, List<T> upgradedList) {
- Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList);
- Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList);
- return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true);
- }
-
- private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){
-
- List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
- Either<Map<String, PropertyDefinition>, 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<PropertyDefinition> 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;
- }
-
+ @Autowired
+ protected ArtifactsBusinessLogic artifactsBusinessLogic;
+
+ @Autowired
+ protected ComponentCache componentCache;
+
+ @Autowired
+ private GenericTypeBusinessLogic genericTypeBusinessLogic;
+
+ public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) {
+ this.genericTypeBusinessLogic = genericTypeBusinessLogic;
+ }
+
+ private static final Logger log = LoggerFactory.getLogger(ComponentBusinessLogic.class);
+
+ private static final String TAG_FIELD_LABEL = "tag";
+
+ public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents();
+
+ public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
+
+ public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText);
+
+ /**
+ *
+ * @param componentId
+ * @param dataParamsToReturn
+ * @return
+ */
+ public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn);
+
+ protected Either<User, ResponseFormat> validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
+ Either<User, ResponseFormat> userValidationResult = validateUserNotEmpty(user, ecompErrorContext);
+ ResponseFormat responseFormat;
+ if (userValidationResult.isRight()) {
+ user.setUserId("UNKNOWN");
+ responseFormat = userValidationResult.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
+ return Either.right(responseFormat);
+ }
+ Either<User, ResponseFormat> userResult = validateUserExists(user, ecompErrorContext, inTransaction);
+ if (userResult.isRight()) {
+ responseFormat = userResult.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
+ return Either.right(responseFormat);
+ }
+ return userResult;
+ }
+
+ protected Either<Boolean, ResponseFormat> validateUserRole(User user, Component component, List<Role> roles, AuditingActionEnum auditAction, String comment) {
+ if (roles != null && roles.isEmpty()) {
+ roles.add(Role.ADMIN);
+ roles.add(Role.DESIGNER);
+ }
+ Either<Boolean, ResponseFormat> validationResult = validateUserRole(user, roles);
+ if (validationResult.isRight()) {
+ String commentStr = null;
+ String distrStatus = null;
+ ComponentTypeEnum componentType = component.getComponentType();
+ if (componentType.equals(ComponentTypeEnum.SERVICE)) {
+ distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus();
+ commentStr = comment;
+ }
+ componentsUtils.auditComponent(validationResult.right().value(), user, component, auditAction, componentType,
+ ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(),
+ ResourceAuditData.newBuilder().distributionStatus(distrStatus).build(),
+ null, commentStr, null, null);
+
+
+ }
+ return validationResult;
+ }
+
+ protected Either<Boolean, ResponseFormat> validateComponentName(User user, Component component, AuditingActionEnum actionEnum) {
+ ComponentTypeEnum type = component.getComponentType();
+ String componentName = component.getName();
+ if (!ValidationUtils.validateStringNotEmpty(componentName)) {
+ log.debug("component name is empty");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, type.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateComponentNameLength(componentName)) {
+ log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+
+ if (!validateTagPattern(componentName)) {
+ log.debug("Component name {} has invalid format", componentName);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME, type.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+ component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName));
+ component.setSystemName(ValidationUtils.convertToSystemName(componentName));
+
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ ComponentTypeEnum type = component.getComponentType();
+ String description = component.getDescription();
+ if (!ValidationUtils.validateStringNotEmpty(description)) {
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_DESCRIPTION, type.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+
+ description = cleanUpText(description);
+ Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type);
+ if (validatDescription.isRight()) {
+ ResponseFormat responseFormat = validatDescription.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
+ return Either.right(responseFormat);
+ }
+ component.setDescription(description);
+ return Either.left(true);
+ }
+
+ public Either<Boolean, ResponseFormat> validateComponentDescription(String description, ComponentTypeEnum type) {
+ if (description != null) {
+ if (!ValidationUtils.validateDescriptionLength(description)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
+ }
+
+ if (!ValidationUtils.validateIsEnglish(description)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue()));
+ }
+ return Either.left(true);
+ }
+ return Either.left(false);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateComponentNameUnique(User user, Component component, AuditingActionEnum actionEnum) {
+ ComponentTypeEnum type = component.getComponentType();
+ ResourceTypeEnum resourceType = null;
+ if(component instanceof Resource){
+ resourceType = ((Resource)component).getResourceType();
+ }
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type);
+
+ if (dataModelResponse.isLeft()) {
+ if ( !dataModelResponse.left().value()) {
+ return Either.left(true);
+ } else {
+ log.info("Component with name {} already exists", component.getName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+ }
+ BeEcompErrorManager.getInstance().logBeSystemError("validateComponentNameUnique");
+ log.debug("Error while validateComponentNameUnique for component: {}", component.getName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateContactId(User user, Component component, AuditingActionEnum actionEnum) {
+ log.debug("validate component contactId");
+ ComponentTypeEnum type = component.getComponentType();
+ String contactId = component.getContactId();
+
+ if (!ValidationUtils.validateStringNotEmpty(contactId)) {
+ log.info("contact is missing.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+
+ Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId, type);
+ if (validateContactIdResponse.isRight()) {
+ ResponseFormat responseFormat = validateContactIdResponse.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
+ }
+ return validateContactIdResponse;
+ }
+
+ private Either<Boolean, ResponseFormat> validateContactId(String contactId, ComponentTypeEnum type) {
+ if (contactId != null) {
+ if (!ValidationUtils.validateContactId(contactId)) {
+ log.info("contact is invalid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ return Either.left(false);
+ }
+
+
+ public Either<Boolean, ResponseFormat> 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 {}", componentUuid);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(errorResponse);
+ }
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "validateConformanceLevel", false);
+ if (resp.isRight()) {
+ log.error("can't validate conformance level, user is not validated, uuid {}, userId {}", componentUuid, userId);
+ return Either.right(resp.right().value());
+ }
+
+ Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
+ if (eitherComponent.isRight()) {
+ 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);
+ }
+
+ 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(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");
+
+ return Either.left(result);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateIcon(User user, Component component, AuditingActionEnum actionEnum) {
+ log.debug("validate Icon");
+ ComponentTypeEnum type = component.getComponentType();
+ String icon = component.getIcon();
+ if (!ValidationUtils.validateStringNotEmpty(icon)) {
+ log.info("icon is missing.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, type.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
+ return Either.right(errorResponse);
+ }
+
+ Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon, type);
+ if (validateIcon.isRight()) {
+ ResponseFormat responseFormat = validateIcon.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
+ }
+ return validateIcon;
+ }
+
+ private Either<Boolean, ResponseFormat> validateIcon(String icon, ComponentTypeEnum type) {
+ if (icon != null) {
+ if (!ValidationUtils.validateIconLength(icon)) {
+ log.debug("icon exceeds max length");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH));
+ }
+
+ if (!ValidationUtils.validateIcon(icon)) {
+ log.info("icon is invalid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ return Either.left(false);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Component component, AuditingActionEnum actionEnum) {
+ List<String> tagsList = component.getTags();
+
+ Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, component.getName(), component.getComponentType());
+ if (validateTags.isRight()) {
+ ResponseFormat responseFormat = validateTags.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType());
+ return Either.right(responseFormat);
+ }
+ ValidationUtils.removeDuplicateFromList(tagsList);
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType) {
+ log.debug("validate component tags");
+ boolean includesComponentName = false;
+ int tagListSize = 0;
+ if (tags != null && !tags.isEmpty()) {
+ for (String tag : tags) {
+ if (!ValidationUtils.validateTagLength(tag)) {
+ log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH));
+ }
+ if (validateTagPattern(tag)) {
+ if (!includesComponentName) {
+ includesComponentName = name.equals(tag);
+ }
+ } else {
+ log.debug("invalid tag {}", tag);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FIELD_FORMAT, componentType.getValue(), TAG_FIELD_LABEL));
+ }
+ tagListSize += tag.length() + 1;
+ }
+ if (tagListSize > 0) {
+ tagListSize--;
+ }
+
+ if (!includesComponentName) {
+ log.debug("tags must include component name");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME));
+ }
+ if (!ValidationUtils.validateTagListLength(tagListSize)) {
+ log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH));
+ }
+ return Either.left(true);
+ }
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS));
+ }
+
+ protected boolean validateTagPattern(String tag) {
+ return ValidationUtils.validateComponentNamePattern(tag);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateProjectCode(User user, Component component, AuditingActionEnum actionEnum) {
+ if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) {
+ return Either.left(true);
+ }
+ log.debug("validate ProjectCode name ");
+ String projectCode = component.getProjectCode();
+
+ if (!ValidationUtils.validateStringNotEmpty(projectCode)) {
+ log.info("projectCode is missing.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_PROJECT_CODE);
+ componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build());
+ return Either.right(errorResponse);
+ }
+
+ Either<Boolean, ResponseFormat> validateProjectCodeResponse = validateProjectCode(projectCode);
+ if (validateProjectCodeResponse.isRight()) {
+ ResponseFormat responseFormat = validateProjectCodeResponse.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(), ResourceAuditData.newBuilder().build());
+ }
+ return validateProjectCodeResponse;
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateProjectCode(String projectCode) {
+ if (projectCode != null) {
+ if (!ValidationUtils.validateProjectCode(projectCode)) {
+ log.info("projectCode is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROJECT_CODE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ return Either.left(false);
+ }
+
+ protected void checkComponentFieldsForOverrideAttempt(Component component) {
+ if (component.getLifecycleState() != null) {
+ log.info("LifecycleState cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getVersion() != null) {
+ log.info("Version cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getCreatorUserId() != null || component.getCreatorFullName() != null) {
+ log.info("Creator cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getLastUpdaterUserId() != null || component.getLastUpdaterFullName() != null) {
+ log.info("Last Updater cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getCreationDate() != null) {
+ log.info("Creation Date cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.isHighestVersion() != null) {
+ log.info("Is Highest Version cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getUUID() != null) {
+ log.info("UUID cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getLastUpdateDate() != null) {
+ log.info("Last Update Date cannot be defined by user. This field will be overridden by the application");
+ }
+ if (component.getUniqueId() != null) {
+ log.info("uid cannot be defined by user. This field will be overridden by the application.");
+ component.setUniqueId(null);
+ }
+ if (component.getInvariantUUID() != null) {
+ log.info("Invariant UUID cannot be defined by user. This field will be overridden by the application.");
+ }
+ }
+
+ protected Either<Boolean, ResponseFormat> validateComponentFieldsBeforeCreate(User user, Component component, AuditingActionEnum actionEnum) {
+ // validate component name uniqueness
+ log.debug("validate component name ");
+ Either<Boolean, ResponseFormat> componentNameValidation = validateComponentName(user, component, actionEnum);
+ if (componentNameValidation.isRight()) {
+ return componentNameValidation;
+ }
+
+ // validate description
+ log.debug("validate description");
+ Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, component, actionEnum);
+ if (descValidation.isRight()) {
+ return descValidation;
+ }
+
+ // validate tags
+ log.debug("validate tags");
+ Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, component, actionEnum);
+ if (tagsValidation.isRight()) {
+ return tagsValidation;
+ }
+
+ // validate contact info
+ log.debug("validate contact info");
+ Either<Boolean, ResponseFormat> contactIdValidation = validateContactId(user, component, actionEnum);
+ if (contactIdValidation.isRight()) {
+ return contactIdValidation;
+ }
+
+ // validate icon
+ log.debug("validate icon");
+ Either<Boolean, ResponseFormat> iconValidation = validateIcon(user, component, actionEnum);
+ if (iconValidation.isRight()) {
+ return iconValidation;
+ }
+ return Either.left(true);
+ }
+
+ public Either<CapReqDef, ResponseFormat> getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<CapReqDef, ResponseFormat> eitherRet = null;
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreCapabilities(false);
+ filter.setIgnoreRequirements(false);
+ filter.setIgnoreComponentInstances(false);
+ Either<Component, ResponseFormat> eitherComponent = validateComponentExists(componentId, componentTypeEnum, filter);
+ if (eitherComponent.isLeft()) {
+ eitherRet = Either.left(new CapReqDef(eitherComponent.left().value().getRequirements(), eitherComponent.left().value().getCapabilities()));
+ } else {
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId);
+ eitherRet = Either.right(eitherComponent.right().value());
+ }
+ return eitherRet;
+ }
+
+ public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
+ String userId) {
+ ResponseFormat responseFormat = null;
+ try{
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
+
+ if (resp.isLeft()) {
+ List<Component> result = new ArrayList<>();
+ List<String> componentsUidToFetch = new ArrayList<>();
+ componentsUidToFetch.addAll(componentUids);
+
+ if (!componentsUidToFetch.isEmpty()) {
+ log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
+ Boolean isHighest = isHighest(highestFilter);
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType, componentsUidToFetch);
+
+ if (nonCheckoutCompResponse.isLeft()) {
+ log.debug("Retrived Resource successfully.");
+ result.addAll(nonCheckoutCompResponse.left().value());
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
+ }
+ }
+ return Either.left(result);
+ } else {
+ responseFormat = resp.right().value();
+ }
+ }
+ finally{
+ titanDao.commit();
+ }
+ return Either.right(responseFormat);
+ }
+
+ private Boolean isHighest(HighestFilterEnum highestFilter) {
+ Boolean isHighest = null;
+ switch (highestFilter) {
+ case ALL:
+ break;
+ case HIGHEST_ONLY:
+ isHighest = true;
+ break;
+ case NON_HIGHEST_ONLY:
+ isHighest = false;
+ break;
+ default:
+ break;
+ }
+ return isHighest;
+ }
+
+ public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
+ ResponseFormat responseFormat = null;
+
+ try{
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Latest Version Not Abstract Components", false);
+ if (resp.isLeft()) {
+
+ Boolean isHighest = isHighest(highestFilter);
+ Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, isHighest, componentTypeEnum, internalComponentType);
+
+ if (nonCheckoutCompResponse.isLeft()) {
+ log.debug("Retrived Resource successfully.");
+ return Either.left(nonCheckoutCompResponse.left().value());
+ }
+ responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value()));
+ } else {
+ responseFormat = resp.right().value();
+ }
+ } finally {
+ titanDao.commit();
+ }
+ return Either.right(responseFormat);
+ }
+
+ public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public void setToscaArtifactsPlaceHolders(Component component, User user) {
+ Map<String, ArtifactDefinition> artifactMap = component.getToscaArtifacts();
+ if (artifactMap == null) {
+ artifactMap = new HashMap<>();
+ }
+ String componentUniqueId = component.getUniqueId();
+ String componentSystemName = component.getSystemName();
+ String componentType = component.getComponentType().getValue().toLowerCase();
+ Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts();
+
+ if (toscaArtifacts != null) {
+ for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) {
+ Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue();
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
+ artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+ }
+ }
+ component.setToscaArtifacts(artifactMap);
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) {
+ return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true);
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB) {
+ Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId());
+ if ( toscaElement.isRight() ){
+ ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
+ return Either.right(response);
+ }
+ component = toscaElement.left().value();
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaRes = null;
+ if (component.getToscaArtifacts() != null && !component.getToscaArtifacts().isEmpty()) {
+ ArtifactDefinition toscaArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType()))
+ .findAny().get();
+ generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
+ if (generateToscaRes.isRight()) {
+ return generateToscaRes;
+ }
+ toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
+ if(!isAbstractResource(component)){
+ toscaArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
+ .findAny().get();
+ generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
+ if (generateToscaRes.isRight()) {
+ return generateToscaRes;
+ }
+ toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
+ }
+ }
+ return generateToscaRes;
+ }
+
+ private boolean isAbstractResource(Component component) {
+ return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract();
+ }
+
+ public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock,
+ boolean inTransaction, boolean fetchTemplatesFromDB) {
+ return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
+ }
+
+ public Either<ImmutablePair<String, byte[]>, ResponseFormat> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, EnumMap<AuditingFieldsKeysEnum, Object> additionalParam) {
+
+ Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null);
+
+ if (latestVersionEither.isRight()) {
+ ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
+ return Either.right(response);
+ }
+
+ List<Component> components = latestVersionEither.left().value();
+
+ Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null);
+ if(component == null){
+ component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null);
+ }
+
+ if(component == null){
+ ResponseFormat response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType));
+ return Either.right(response);
+ }
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
+ // TODO remove after migration - handle artifact not found(no
+ // placeholder)
+ if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
+ }
+ ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
+ .findAny().get();
+ return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact);
+ }
+
+ protected StorageOperationStatus markComponentToDelete(Component component) {
+
+ ComponentTypeEnum componentType = component.getComponentType();
+ String uniqueId = component.getUniqueId();
+ if (Boolean.TRUE.equals(component.getIsDeleted())) {
+ log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType);
+ return StorageOperationStatus.NOT_FOUND;
+ }
+
+ StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component);
+ if (StorageOperationStatus.OK != markResourceToDelete) {
+ log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete);
+ return markResourceToDelete;
+ } else {
+ log.debug("Component {} of type {} was marked as deleted", uniqueId, componentType);
+ return StorageOperationStatus.OK;
+ }
+ }
+
+ public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) {
+ String descriptionUpdated = updatedComponent.getDescription();
+ String descriptionCurrent = currentComponent.getDescription();
+ if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
+ Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction);
+ if (validateDescriptionResponse.isRight()) {
+ ResponseFormat errorRespons = validateDescriptionResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentComponent.setDescription(updatedComponent.getDescription());
+ }
+ return Either.left(true);
+ }
+
+ public Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Component currentComponent, Component updatedComponent) {
+ String projectCodeUpdated = updatedComponent.getProjectCode();
+ String projectCodeCurrent = currentComponent.getProjectCode();
+ if (projectCodeUpdated != null && !projectCodeCurrent.equals(projectCodeUpdated)) {
+ Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, updatedComponent, null);
+ if (validatProjectCodeResponse.isRight()) {
+ ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentComponent.setProjectCode(updatedComponent.getProjectCode());
+ }
+ return Either.left(true);
+ }
+
+ public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) {
+ String iconUpdated = updatedComponent.getIcon();
+ String iconCurrent = currentComponent.getIcon();
+ if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) {
+ if (!hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, updatedComponent, null);
+ if (validatIconResponse.isRight()) {
+ ResponseFormat errorRespons = validatIconResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentComponent.setIcon(updatedComponent.getIcon());
+ } else {
+ log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase());
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
+
+ log.trace("start deleteMarkedComponents");
+ Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
+
+ titanDao.commit();
+ if ( deleteMarkedElements.isRight()){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
+ return Either.right(responseFormat);
+ }
+ log.trace("end deleteMarkedComponents");
+ return Either.left(deleteMarkedElements.left().value());
+ }
+
+ public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType) {
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactToscaOperation.getArtifacts(parentId);
+ if (artifactsResponse.isRight()) {
+ if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ log.debug("failed to retrieve artifacts for {} {}", parentType, parentId);
+ return Either.right(artifactsResponse.right().value());
+ }
+ } else {
+ artifacts.addAll(artifactsResponse.left().value().values());
+ }
+ return Either.left(artifacts);
+ }
+
+ /**
+ *
+ * @param componentId
+ * @param user
+ * @param dataParamsToReturn - ui list of params to return
+ * @return
+ */
+
+ public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) {
+
+ if (user != null) {
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Get Component by filtered by ui params", false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ }
+
+ UiComponentDataTransfer result = new UiComponentDataTransfer();
+
+ if(dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
+ Either.left(result);
+
+ } else {
+ Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn);
+ if(uiDataTransferEither.isRight()){
+ return Either.right(uiDataTransferEither.right().value());
+ }
+ result = uiDataTransferEither.left().value();
+ }
+
+ return Either.left(result);
+ }
+
+ protected <T extends Component> void generateAndAddInputsFromGenericTypeProperties(T component, Resource genericType) {
+ List<InputDefinition> genericAndComponentInputs = new ArrayList<>();
+ List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType);
+ genericAndComponentInputs.addAll(genericInputs);
+ if (null != component.getInputs()){
+ List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs());
+ genericAndComponentInputs.addAll(nonGenericInputsFromComponent);
+ }
+ component.setInputs(genericAndComponentInputs);
+ }
+
+ private List<InputDefinition> getAllNonGenericInputsFromComponent(List<InputDefinition> genericInputs, List<InputDefinition> componentInputs) {
+ if (genericInputs == null) {
+ return componentInputs;
+ }
+
+ Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName);
+ List<InputDefinition> componentNonGenericInputs = new ArrayList<>();
+ componentInputs.stream().forEach(input -> {
+ if (!inputByNameMap.containsKey(input.getName())) {
+ componentNonGenericInputs.add(input);
+ }
+ });
+ return componentNonGenericInputs;
+ }
+
+ protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
+ Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component);
+ if(genericTypeEither.isRight()){
+ log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType()));
+ }
+ Resource genericTypeResource = genericTypeEither.left().value();
+ component.setDerivedFromGenericInfo(genericTypeResource);
+ return Either.left(genericTypeResource);
+ }
+
+ public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) {
+ Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null;
+ Either<Component, StorageOperationStatus> getResourceRes = null;
+ try{
+ if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ if (userId != null && response == null) {
+ Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "Get filtered component instance properties", false);
+ if (validateUserRes.isRight()) {
+ response = Either.right(validateUserRes.right().value());
+ }
+ }
+ if(response == null){
+ getResourceRes = toscaOperationFacade.getToscaElement(componentId);
+ if(getResourceRes.isRight()){
+ response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
+ }
+ }
+ if(response == null){
+ response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters);
+ }
+ } catch(Exception e){
+ log.debug("The exception {} occured during filtered instance properties fetching. the containing component is {}. ", e, componentId);
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally{
+ if (response.isLeft()){
+ toscaOperationFacade.commit();
+ } else {
+ toscaOperationFacade.rollback();
+ }
+ }
+ return response;
+ }
+
+ private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) {
+
+ Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
+ Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties);
+ List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE));
+ String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
+ boolean searchByFragment = propertyNameFragment.length() > 3 ;
+ if(CollectionUtils.isNotEmpty(filteredInstances)){
+ for(ComponentInstance instance : filteredInstances){
+ if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){
+ List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+ if(CollectionUtils.isNotEmpty(currProperties)){
+ filteredProperties.put(instance.getUniqueId(), currProperties);
+ }
+ }
+ if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){
+ List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+ if(CollectionUtils.isNotEmpty(currInputs)){
+ if(filteredProperties.get(instance.getUniqueId())!=null){
+ filteredProperties.get(instance.getUniqueId()).addAll(currInputs);
+ } else {
+ filteredProperties.put(instance.getUniqueId(), currInputs);
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) {
+ return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
+ }
+
+ private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) {
+ return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
+ }
+
+ private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) {
+ boolean isMatching = false;
+ if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){
+ isMatching = true;
+ }
+ if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){
+ isMatching = true;
+ }
+ return isMatching;
+ }
+
+ private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) {
+ boolean isMatching = false;
+ if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){
+ isMatching = true;
+ }
+ if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+ isMatching = true;
+ }
+ if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){
+ isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment);
+ }
+ return isMatching;
+ }
+
+ private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
+ String propertyType;
+ List<PropertyDefinition> dataTypeProperties;
+ DataTypeDefinition currentProperty;
+ if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){
+ return true;
+ }
+ if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+ return true;
+ }
+
+ propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType();
+
+ if(ToscaPropertyType.isScalarType(propertyType)){
+ return false;
+ }
+ Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
+ if(getDataTypeByNameRes.isRight()){
+ return false;
+ }
+ currentProperty = getDataTypeByNameRes.left().value();
+ dataTypeProperties = currentProperty.getProperties();
+
+ if(CollectionUtils.isNotEmpty(dataTypeProperties)){
+ for(PropertyDefinition prop : dataTypeProperties){
+ if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
+ return true;
+ }
+ }
+ }
+ dataTypeProperties = currentProperty.getDerivedFrom().getProperties();
+ if(CollectionUtils.isNotEmpty(dataTypeProperties)){
+ for(PropertyDefinition prop : dataTypeProperties){
+ if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean isEmptyInnerType(PropertyDataDefinition property) {
+ return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null;
+ }
+
+ public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) {
+
+ if(!clonedComponent.deriveFromGeneric())
+ return Either.left(false);
+ Boolean shouldUpgrade = false;
+ String currentGenericType = clonedComponent.getDerivedFromGenericType();
+ String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
+ Either<Resource, ResponseFormat> fetchAndSetLatestGeneric = fetchAndSetDerivedFromGenericType(clonedComponent);
+ if(fetchAndSetLatestGeneric.isRight())
+ return Either.right(fetchAndSetLatestGeneric.right().value());
+ Resource genericTypeResource = fetchAndSetLatestGeneric.left().value();
+ if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){
+ shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource);
+ if(!shouldUpgrade) {
+ reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion);
+ }
+ }
+ return Either.left(shouldUpgrade);
+ }
+
+ private void reverntUpdateOfGenericVersion(Component clonedComponent, String currentGenericType, String currentGenericVersion) {
+ clonedComponent.setDerivedFromGenericType(currentGenericType);
+ clonedComponent.setDerivedFromGenericVersion(currentGenericVersion);
+ }
+
+ private <T extends PropertyDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList, List<T> upgradedList) {
+ Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList);
+ Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList);
+ return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true);
+ }
+
+ private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){
+
+ List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
+ Either<Map<String, PropertyDefinition>, 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<PropertyDefinition> 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<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
- List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
- List<InputDefinition> currentList = new ArrayList<>();
- // nullify existing ownerId from existing list and merge into updated list
- if (null != componentToCheckOut.getInputs()) {
- for(InputDefinition input : componentToCheckOut.getInputs()) {
- InputDefinition copy = new InputDefinition(input);
- copy.setOwnerId(null);
- currentList.add(copy);
- }
- }
- if (null == genericTypeInputs) {
- componentToCheckOut.setInputs(currentList);
- return true;
- }
-
- Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList);
- if (eitherMerged.isRight()) {
- log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
- return false;
- }
- componentToCheckOut.setInputs(new ArrayList<InputDefinition>(eitherMerged.left().value().values()));
- return true;
- }
-
-
- private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) {
- List<ComponentInstance> filteredInstances = null;
- if(CollectionUtils.isEmpty(resourceTypes)){
- filteredInstances = component.getComponentInstances();
- }
- else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
- filteredInstances = component.getComponentInstances()
- .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList());
- }
- if(filteredInstances == null){
- filteredInstances = new ArrayList<>();
- }
- return filteredInstances;
- }
-
- private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) {
- boolean isMatchingType = false;
- for(String resourceType : resourceTypes){
- if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){
- isMatchingType = true;
- break;
- }
- }
- return isMatchingType;
- }
-
- protected String cleanUpText(String text){
- text = ValidationUtils.removeNoneUtf8Chars(text);
- text = ValidationUtils.normaliseWhitespace(text);
- text = ValidationUtils.stripOctets(text);
- text = ValidationUtils.removeHtmlTagsOnly(text);
- return text;
- }
-
- public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
- //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
+
+ if (!componentToCheckOut.shouldGenerateInputs()) {
+ //node type - validate properties and attributes
+ return shouldUpgradeNodeType(componentToCheckOut, latestGeneric);
+ }
+ List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
+ List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
+ List<InputDefinition> currentList = new ArrayList<>();
+ // nullify existing ownerId from existing list and merge into updated list
+ if (null != componentToCheckOut.getInputs()) {
+ for(InputDefinition input : componentToCheckOut.getInputs()) {
+ InputDefinition copy = new InputDefinition(input);
+ copy.setOwnerId(null);
+ currentList.add(copy);
+ }
+ }
+ if (null == genericTypeInputs) {
+ componentToCheckOut.setInputs(currentList);
+ return true;
+ }
+
+ Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList);
+ if (eitherMerged.isRight()) {
+ log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
+ return false;
+ }
+ componentToCheckOut.setInputs(new ArrayList<InputDefinition>(eitherMerged.left().value().values()));
+ return true;
+ }
+
+
+ private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) {
+ List<ComponentInstance> filteredInstances = null;
+ if(CollectionUtils.isEmpty(resourceTypes)){
+ filteredInstances = component.getComponentInstances();
+ }
+ else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
+ filteredInstances = component.getComponentInstances()
+ .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList());
+ }
+ if(filteredInstances == null){
+ filteredInstances = new ArrayList<>();
+ }
+ return filteredInstances;
+ }
+
+ private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) {
+ boolean isMatchingType = false;
+ for(String resourceType : resourceTypes){
+ if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){
+ isMatchingType = true;
+ break;
+ }
+ }
+ return isMatchingType;
+ }
+
+ protected String cleanUpText(String text){
+ text = ValidationUtils.removeNoneUtf8Chars(text);
+ text = ValidationUtils.normaliseWhitespace(text);
+ text = ValidationUtils.stripOctets(text);
+ text = ValidationUtils.removeHtmlTagsOnly(text);
+ return text;
+ }
+
+ public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
+ //general implementation. Must be error for service, VF . In ResourceBuisnessLogic exist override
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
}
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 b86b28a6c5..2eca73c560 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
@@ -20,25 +20,16 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-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.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
+import com.google.common.collect.Sets;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.version.PostChangeVersionOperationOrchestrator;
import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
+import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -46,6 +37,8 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
@@ -53,25 +46,10 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
@@ -92,286 +70,369 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
-public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
-
- private static Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class.getName());
-
- @Autowired
- private IComponentInstanceOperation componentInstanceOperation;
-
- @Autowired
- private ArtifactsBusinessLogic artifactBusinessLogic;
- @Autowired
- private ApplicationDataTypeCache dataTypeCache;
-
- @Autowired
- private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
-
- public static final String VF_MODULE = "org.openecomp.groups.VfModule";
-
- public ComponentInstanceBusinessLogic() {
- }
-
- public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
- return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
- }
-
- public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
-
- Component origComponent = null;
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- User user = null;
- org.openecomp.sdc.be.model.Component containerComponent = null;
- ComponentTypeEnum containerComponentType;
-
- try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- } else {
- user = resp.left().value();
- }
-
- Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
- if (validateValidJson.isRight()) {
- return Either.right(validateValidJson.right().value());
- }
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- } else {
- containerComponentType = validateComponentType.left().value();
- }
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- } else {
- containerComponent = validateComponentExists.left().value();
- }
-
- if (ModelConverter.isAtomicComponent(containerComponent)) {
- log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
- }
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
-
- if (resourceInstance != null && containerComponentType != null) {
- OriginTypeEnum originType = resourceInstance.getOriginType();
- if (originType == OriginTypeEnum.ServiceProxy) {
- Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
- if (serviceProxyOrigin.isRight()) {
- log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
- }
- origComponent = serviceProxyOrigin.left().value();
-
- StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
- if (fillProxyRes != StorageOperationStatus.OK) {
- log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
-
- }
-
- } else {
- Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
-
- if (getOriginComponentRes.isRight()) {
- return Either.right(getOriginComponentRes.right().value());
- } else {
- origComponent = getOriginComponentRes.left().value();
- }
- }
- }
- if (needLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
- log.debug("Try to create entry on graph");
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
- resourceInstance.setIsProxy(true);
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreCapabilities(false);
- filter.setIgnoreCapabiltyProperties(false);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreRequirements(false);
- Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
- if (serviceRes.isRight()) {
- return serviceRes.right().value();
- }
- Component service = serviceRes.left().value();
- Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
- resourceInstance.setCapabilities(capabilities);
- Map<String, List<RequirementDefinition>> req = service.getRequirements();
- resourceInstance.setRequirements(req);
-
- String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
- String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
- int lastIndexOf = toscaResourceName.lastIndexOf('.');
- if (lastIndexOf != -1) {
- String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
- resourceInstance.setToscaComponentName(proxyToscaName);
- }
- resourceInstance.setName(name);
- resourceInstance.setIsProxy(true);
- resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
- resourceInstance.setSourceModelName(service.getName());
- resourceInstance.setSourceModelUuid(service.getUUID());
- resourceInstance.setSourceModelUid(service.getUniqueId());
- resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
- resourceInstance.setDescription("A Proxy for Service " + service.getName());
- resourceInstance.setComponentVersion(service.getVersion());
-
- return StorageOperationStatus.OK;
- }
-
- public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
-
- Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
- ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
- RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- User user = resp.left().value();
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- if (ModelConverter.isAtomicComponent(containerComponent)) {
- log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
- }
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
-
- try {
- log.debug("Try to create entry on graph");
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance, true);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
- }
- Component origComponent = eitherResourceName.left().value();
-
- Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
- if (result.isRight()) {
- log.debug("Failed to create resource instance {}", containerComponentId);
- resultOp = Either.right(result.right().value());
- return resultOp;
-
- }
-
- log.debug("Entity on graph is created.");
- ComponentInstance resResourceInfo = result.left().value();
- if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
- associationInfo.setFromNode(resResourceInfo.getUniqueId());
- } else {
- associationInfo.setToNode(resResourceInfo.getUniqueId());
- }
-
- RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;// createRequirementCapabilityrelDef(associationInfo);
- Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
- if (resultReqCapDef.isLeft()) {
- log.debug("Enty on graph is created.");
- RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
- CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
- resultOp = Either.left(resInfo);
- return resultOp;
-
- } else {
- log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
- return resultOp;
- }
-
- } finally {
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance, boolean inTransaction) {
- Either<Component, ResponseFormat> eitherResponse;
- Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
- if (eitherComponent.isRight()) {
- log.debug("Failed to get origin component with id {} for component instance {} ", componentInstance.getComponentUid(), componentInstance.getName());
- eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
- } else {
- eitherResponse = Either.left(eitherComponent.left().value());
- }
- return eitherResponse;
- }
-
- private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
- Either<ComponentInstance, ResponseFormat> resultOp;
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
-
- if (result.isRight()) {
- log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
- return resultOp;
- }
-
- log.debug("Entity on graph is created.");
- Component updatedComponent = result.left().value().getLeft();
- Map<String, String> existingEnvVersions = new HashMap<>();
- // TODO existingEnvVersions ??
- Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
- if (addComponentInstanceArtifacts.isRight()) {
- log.debug("Failed to create component instance {}", componentInstance.getName());
- resultOp = Either.right(addComponentInstanceArtifacts.right().value());
- return resultOp;
- }
-
- Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
- if (!updatedInstanceOptional.isPresent()) {
- log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
- return resultOp;
- }
- resultOp = Either.left(updatedInstanceOptional.get());
- return resultOp;
- }
+import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
+
+@org.springframework.stereotype.Component
+public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
+
+ private static final Logger log = LoggerFactory.getLogger(ComponentInstanceBusinessLogic.class);
+
+ @Autowired
+ private IComponentInstanceOperation componentInstanceOperation;
+
+ @Autowired
+ private ArtifactsBusinessLogic artifactBusinessLogic;
+
+ @Autowired
+ private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
+
+ @Autowired
+ private PostChangeVersionOperationOrchestrator postChangeVersionOperationOrchestrator;
+
+ public static final String VF_MODULE = "org.openecomp.groups.VfModule";
+
+ public ComponentInstanceBusinessLogic() {
+ }
+
+ public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
+ return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
+ }
+
+ public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
+ List<ComponentInstanceProperty> resList = new ArrayList<>();
+ Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
+ if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
+ ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
+ @Override
+ public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
+ String ciName = "";
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
+ if(ciOp.isPresent())
+ ciName = ciOp.get().getName();
+ if (ciPropList != null && !ciPropList.isEmpty()) {
+ for(ComponentInstanceProperty prop: ciPropList){
+ List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
+ if(inputsValues != null && !inputsValues.isEmpty()){
+ for(GetInputValueDataDefinition inputData: inputsValues){
+ if(isGetInputValueForInput(inputData, inputId)){
+ prop.setComponentInstanceId(s);
+ prop.setComponentInstanceName(ciName);
+ resList.add(prop);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+ }
+ });
+ }
+ return resList;
+
+ }
+
+ public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
+ List<ComponentInstanceInput> resList = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
+ if(ciInputsMap != null && !ciInputsMap.isEmpty()){
+ ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
+ @Override
+ public void accept(String s, List<ComponentInstanceInput> ciPropList) {
+ String ciName = "";
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
+ if(ciOp.isPresent())
+ ciName = ciOp.get().getName();
+ if (ciPropList != null && !ciPropList.isEmpty()) {
+ for(ComponentInstanceInput prop: ciPropList){
+ List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
+ if(inputsValues != null && !inputsValues.isEmpty()){
+ for(GetInputValueDataDefinition inputData: inputsValues){
+ if(isGetInputValueForInput(inputData, inputId)){
+ prop.setComponentInstanceId(s);
+ prop.setComponentInstanceName(ciName);
+ resList.add(prop);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+ }
+ });
+ }
+ return resList;
+
+ }
+
+ public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
+
+ Component origComponent = null;
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ User user = null;
+ org.openecomp.sdc.be.model.Component containerComponent = null;
+ ComponentTypeEnum containerComponentType;
+
+ try {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", inTransaction);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ } else {
+ user = resp.left().value();
+ }
+
+ Either<Boolean, ResponseFormat> validateValidJson = validateJsonBody(resourceInstance, ComponentInstance.class);
+ if (validateValidJson.isRight()) {
+ return Either.right(validateValidJson.right().value());
+ }
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ } else {
+ containerComponentType = validateComponentType.left().value();
+ }
+
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ } else {
+ containerComponent = validateComponentExists.left().value();
+ }
+
+ if (ModelConverter.isAtomicComponent(containerComponent)) {
+ log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
+ }
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ if (resourceInstance != null && containerComponentType != null) {
+ OriginTypeEnum originType = resourceInstance.getOriginType();
+ if (originType == OriginTypeEnum.ServiceProxy) {
+ Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
+ if (serviceProxyOrigin.isRight()) {
+ log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
+ }
+ origComponent = serviceProxyOrigin.left().value();
+
+ StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
+ if (fillProxyRes != StorageOperationStatus.OK) {
+ log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
+
+ }
+
+ } else {
+ Either<Component, ResponseFormat> getOriginComponentRes = getAndValidateOriginComponentOfComponentInstance(containerComponentType, resourceInstance);
+
+ if (getOriginComponentRes.isRight()) {
+ return Either.right(getOriginComponentRes.right().value());
+ } else {
+ origComponent = getOriginComponentRes.left().value();
+ }
+ }
+ }
+ if (needLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createComponentInstance");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ log.debug("Try to create entry on graph");
+ resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
+ return resultOp;
+
+ } finally {
+ if (needLock)
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
+ resourceInstance.setIsProxy(true);
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreCapabilities(false);
+ filter.setIgnoreCapabiltyProperties(false);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreRequirements(false);
+ Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
+ if (serviceRes.isRight()) {
+ return serviceRes.right().value();
+ }
+ Component service = serviceRes.left().value();
+ Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
+ resourceInstance.setCapabilities(capabilities);
+ Map<String, List<RequirementDefinition>> req = service.getRequirements();
+ resourceInstance.setRequirements(req);
+
+ String name = service.getNormalizedName() + ToscaOperationFacade.PROXY_SUFFIX;
+ String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
+ int lastIndexOf = toscaResourceName.lastIndexOf('.');
+ if (lastIndexOf != -1) {
+ String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
+ resourceInstance.setToscaComponentName(proxyToscaName);
+ }
+ resourceInstance.setName(name);
+ resourceInstance.setIsProxy(true);
+ resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
+ resourceInstance.setSourceModelName(service.getName());
+ resourceInstance.setSourceModelUuid(service.getUUID());
+ resourceInstance.setSourceModelUid(service.getUniqueId());
+ resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
+ resourceInstance.setDescription("A Proxy for Service " + service.getName());
+ resourceInstance.setComponentVersion(service.getVersion());
+
+ return StorageOperationStatus.OK;
+ }
+
+ public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
+
+ Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
+ ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
+ RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create And Associate RI To RI", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ User user = resp.left().value();
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ }
+
+ final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
+
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
+
+ if (ModelConverter.isAtomicComponent(containerComponent)) {
+ log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
+ }
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "createAndAssociateRIToRI");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+
+ try {
+ log.debug("Try to create entry on graph");
+ Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(resourceInstance);
+
+ if (eitherResourceName.isRight()) {
+ resultOp = Either.right(eitherResourceName.right().value());
+ return resultOp;
+ }
+ Component origComponent = eitherResourceName.left().value();
+
+ Either<ComponentInstance, ResponseFormat> result = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
+ if (result.isRight()) {
+ log.debug("Failed to create resource instance {}", containerComponentId);
+ resultOp = Either.right(result.right().value());
+ return resultOp;
+
+ }
+
+ log.debug("Entity on graph is created.");
+ ComponentInstance resResourceInfo = result.left().value();
+ if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
+ associationInfo.setFromNode(resResourceInfo.getUniqueId());
+ } else {
+ associationInfo.setToNode(resResourceInfo.getUniqueId());
+ }
+
+ RequirementCapabilityRelDef requirementCapabilityRelDef = associationInfo;
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponentId, requirementCapabilityRelDef);
+ if (resultReqCapDef.isLeft()) {
+ log.debug("Enty on graph is created.");
+ RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
+ CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
+ resultOp = Either.left(resInfo);
+ return resultOp;
+
+ } else {
+ log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
+ return resultOp;
+ }
+
+ } finally {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
+ return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
+ }
+
+ private Either<Component, ResponseFormat> getInstanceOriginNode(ComponentInstance componentInstance) {
+ return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
+ }
+
+ private Either<Component, ResponseFormat> getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
+ Either<Component, ResponseFormat> eitherResponse;
+ Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
+ if (eitherComponent.isRight()) {
+ log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
+ eitherResponse = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null));
+ } else {
+ eitherResponse = Either.left(eitherComponent.left().value());
+ }
+ return eitherResponse;
+ }
+
+ private Either<ComponentInstance, ResponseFormat> createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
+ Either<ComponentInstance, ResponseFormat> resultOp;
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
+
+ if (result.isRight()) {
+ log.debug("Failed to create entry on graph for component instance {}", componentInstance.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
+ return resultOp;
+ }
+
+ log.debug("Entity on graph is created.");
+ Component updatedComponent = result.left().value().getLeft();
+ Map<String, String> existingEnvVersions = new HashMap<>();
+ // TODO existingEnvVersions ??
+ Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts = addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
+ if (addComponentInstanceArtifacts.isRight()) {
+ log.debug("Failed to create component instance {}", componentInstance.getName());
+ resultOp = Either.right(addComponentInstanceArtifacts.right().value());
+ return resultOp;
+ }
+
+ Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
+ if (!updatedInstanceOptional.isPresent()) {
+ log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+ return resultOp;
+ }
+ resultOp = Either.left(updatedInstanceOptional.get());
+ return resultOp;
+ }
/**
* addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
@@ -382,2012 +443,2196 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
* @param existingEnvVersions
* @return
*/
- protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
-
- log.debug("add artifacts to resource instance");
- List<GroupDefinition> filteredGroups = null;
- ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
- if (!ActionStatus.OK.equals(status)) {
- ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
- return Either.right(resultOp);
- }
- StorageOperationStatus artStatus;
- // generate heat_env if necessary
- Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
- if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
-
- Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
- Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
-
- 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;
- }
- if (artifact.checkEsIdExist()) {
- Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
- componentInstance.getName(), user, containerComponent, existingEnvVersions);
- if (createHeatEnvPlaceHolder.isRight()) {
- return Either.right(createHeatEnvPlaceHolder.right().value());
- }
- ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
- // put env
- finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
- if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
- filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
- }
- if (CollectionUtils.isNotEmpty(filteredGroups)) {
- for (GroupDefinition groupInstance : filteredGroups) {
- Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
- if (op.isPresent()) {
- List<ArtifactDefinition> artifactsUid;
- if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
- artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
- } else {
- artifactsUid = new ArrayList<>();
- }
- artifactsUid.add(artifactDefinition);
- groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
- break;
- }
- }
- }
- }
- }
- artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
- if (artStatus != StorageOperationStatus.OK) {
- log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
-
- }
- StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
- if (result != StorageOperationStatus.OK) {
- log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
- }
- componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
- }
-
- artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
- if (artStatus != StorageOperationStatus.OK) {
- log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
-
- }
- componentInstance.setArtifacts(originComponent.getArtifacts());
- return Either.left(ActionStatus.OK);
- }
-
- private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null);
-
- Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
- if (getResourceDeploymentArtifacts.isRight()) {
- StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
- if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
- log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
- return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
- }
- } else {
- deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
- }
-
- if (!deploymentArtifacts.isEmpty()) {
- Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
- for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
- if (!artifact.getValue().checkEsIdExist()) {
- tempDeploymentArtifacts.remove(artifact.getKey());
- }
- }
-
- resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
- }
-
- return ActionStatus.OK;
- }
-
- public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
- return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
- }
-
- public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
- boolean needLock, boolean createNewTransaction) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<ComponentInstance, ResponseFormat> resultOp = null;
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
- ComponentTypeEnum instanceType = getComponentType(containerComponentType);
- Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
- if (validateParentStatus.isRight()) {
- log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
- return resultOp;
- }
- if (!validateParentStatus.left().value()) {
- resultOp = Either.right(
- componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
- return resultOp;
- }
-
- if (needLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
- try {
-
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance, inTransaction);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
- }
- Component origComponent = eitherResourceName.left().value();
-
- resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- // New Multiple Instance Update API
- public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
- boolean createNewTransaction) {
-
- Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
- org.openecomp.sdc.be.model.Component containerComponent = null;
- try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
-
- ComponentParametersView componentFilter = new ComponentParametersView();
- componentFilter.disableAll();
- componentFilter.setIgnoreUsers(false);
- componentFilter.setIgnoreComponentInstances(false);
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter, true);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
-
- containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
-
- ComponentTypeEnum instanceType = getComponentType(containerComponentType);
-
- for (ComponentInstance componentInstance : componentInstanceList) {
- boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
- if (!validateParent) {
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
- containerComponentId));
- return resultOp;
- }
- }
-
- if (needLock) {
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
-
- List<ComponentInstance> updatedList = new ArrayList<>();
- List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
- List<ComponentInstance> listForUpdate = new ArrayList<>();
- if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
- containerComponent.setComponentInstances(componentInstanceList);
- else {
- Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
- while (iterator.hasNext()) {
- ComponentInstance origInst = iterator.next();
- Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
- if (op.isPresent()) {
- ComponentInstance updatedCi = op.get();
- updatedCi = buildComponentInstance(updatedCi, origInst);
-
- Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
- if (!isUniqueName) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
- return resultOp;
- }
-
- listForUpdate.add(updatedCi);
- } else
- listForUpdate.add(origInst);
- }
- containerComponent.setComponentInstances(listForUpdate);
-
- if (resultOp == null) {
- Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
- if (updateStatus.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
- return resultOp;
- }
- for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
- Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
- if (op.isPresent()) {
- updatedList.add(updatedInstance);
- }
- }
- }
- }
-
- resultOp = Either.left(updatedList);
- return resultOp;
-
- } finally {
- if (needLock) {
- unlockComponent(resultOp, containerComponent);
- }
- }
- }
-
- private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
- return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
- }
-
- private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
- if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
- return ComponentTypeEnum.SERVICE_INSTANCE;
- } else {
- return ComponentTypeEnum.RESOURCE_INSTANCE;
- }
- }
-
- private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
- ComponentInstance componentInstance) {
-
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- Optional<ComponentInstance> componentInstanceOptional = null;
- Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
- ComponentInstance oldComponentInstance = null;
- boolean isNameChanged = false;
-
- if (resultOp == null) {
- componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
- if (!componentInstanceOptional.isPresent()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
- }
- }
- if (resultOp == null) {
- oldComponentInstance = componentInstanceOptional.get();
- String newInstanceName = componentInstance.getName();
- if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
- isNameChanged = true;
- Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
- if (!isUniqueName) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
- }
- }
- if (resultOp == null) {
- updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
- if (updateRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
- updateRes.right().value());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
- } else {
- // region - Update instance Groups
- if (isNameChanged) {
- Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
- if (result.isRight())
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
- }
- // endregion
- }
- }
- if (resultOp == null) {
- String newInstanceId = updateRes.left().value().getRight();
- Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
-
- if (!updatedInstanceOptional.isPresent()) {
- log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
- } else {
- resultOp = Either.left(updatedInstanceOptional.get());
- }
-
- }
- if (resultOp == null) {
- resultOp = Either.left(componentInstanceOptional.get());
- }
- return resultOp;
- }
-
- /**
- * @param oldPrefix-
- * The normalized old vf name
- * @param newNormailzedPrefix-
- * The normalized new vf name
- * @param qualifiedGroupInstanceName-
- * old Group Instance Name
- **/
- // modify group names
- private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
- if (qualifiedGroupInstanceName == null) {
- log.info("CANNOT change group name ");
- return null;
- }
- if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
- return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
- return qualifiedGroupInstanceName;
- }
-
- private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
- oldComponentInstance.setName(newComponentInstance.getName());
- oldComponentInstance.setModificationTime(System.currentTimeMillis());
- oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
- if (oldComponentInstance.getGroupInstances() != null)
- oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
- return oldComponentInstance;
- }
-
- public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- // validate resource
- /*
- * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
- * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
- * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
- */
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- try {
- resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
- return resultOp;
-
- } finally {
- /*
- * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
- */
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
-
- Either<ComponentInstance, ResponseFormat> resultOp = null;
- ComponentInstance deletedInstance = null;
- Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
-
- if (deleteRes.isRight()) {
- log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
- ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
- resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
- }
- if (resultOp == null) {
- log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
- deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
- resultOp = Either.left(deletedInstance);
- }
- if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
- List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
- for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
- Map<String, String> members = currGroup.getMembers();
- if (members != null && members.containsKey(deletedInstance.getName())) {
- members.remove(deletedInstance.getName());
- groupsToUpdate.add(currGroup);
- }
- }
- Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, containerComponent.getComponentType(), groupsToUpdate);
- if (updateGroupsRes.isRight()) {
- log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
- ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
- resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
- }
- }
- if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
- List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
- if (CollectionUtils.isNotEmpty(inputsToDelete)) {
- StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
- if (deleteInputsRes != StorageOperationStatus.OK) {
- log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
- }
- }
- }
- return resultOp;
- }
-
- private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
- ComponentInstance foundInstance = null;
- for (ComponentInstance instance : containerComponent.getComponentInstances()) {
- if (instance.getUniqueId().equals(componentInstanceId)) {
- foundInstance = instance;
- containerComponent.getComponentInstances().remove(instance);
- break;
- }
- }
- return foundInstance;
- }
-
- public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
- return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
- }
-
- public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
- boolean createNewTransaction) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
- if (needLock) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
-
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
-
- try {
-
- resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
-
- return resultOp;
-
- } finally {
- if (needLock)
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
-
- log.debug("Try to create entry on graph");
- Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
-
- if (result.isLeft()) {
- log.debug("Enty on graph is created.");
- RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
- resultOp = Either.left(requirementCapabilityRelDef);
- return resultOp;
-
- } else {
- log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
- String fromNameOrId = "";
- String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
- Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
-
- toNameOrId = requirementDef.getFromNode();
- fromNameOrId = requirementDef.getFromNode();
- if (fromResult.isLeft()) {
- fromNameOrId = fromResult.left().value().getName();
- }
- if (toResult.isLeft()) {
- toNameOrId = toResult.left().value().getName();
- }
-
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
-
- return resultOp;
- }
-
- }
-
- public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
-
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- try {
- log.debug("Try to create entry on graph");
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
- if (result.isLeft()) {
- log.debug("Enty on graph is created.");
- RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
- resultOp = Either.left(requirementCapabilityRelDef);
- return resultOp;
-
- } else {
-
- log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
- String fromNameOrId = "";
- String toNameOrId = "";
- Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
- Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
-
- toNameOrId = requirementDef.getFromNode();
- fromNameOrId = requirementDef.getFromNode();
- if (fromResult.isLeft()) {
- fromNameOrId = fromResult.left().value().getName();
- }
- if (toResult.isLeft()) {
- toNameOrId = toResult.left().value().getName();
- }
-
- resultOp = Either
- .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
- return resultOp;
- }
- } finally {
- unlockComponent(resultOp, containerComponent);
- }
- }
- /**
- * Allows to get relation contained in specified component according to received Id
- * @param componentId
- * @param relationId
- * @param userId
- * @param componentTypeEnum
- * @return
- */
- public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
-
- Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
- try {
- org.openecomp.sdc.be.model.Component containerComponent = null;
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
- RequirementCapabilityRelDef foundRelation = null;
-
- Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false);
- if (validateUserRes.isRight()) {
- resultOp = Either.right(validateUserRes.right().value());
- }
- if(resultOp == null){
- validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
- if (validateComponentExists.isRight()) {
- resultOp = Either.right(validateComponentExists.right().value());
- }
- }
- if(resultOp == null){
- containerComponent = validateComponentExists.left().value();
- List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
- foundRelation = findRelation(relationId, requirementCapabilityRelations);
- if(foundRelation == null){
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
- log.debug("Relation with id {} was not found on the component", relationId, componentId);
- resultOp = Either.right(responseFormat);
- }
- }
- if(resultOp == null){
- resultOp = setRelatedCapability(foundRelation, containerComponent);
- }
- if(resultOp.isLeft()){
- resultOp = setRelatedRequirement(foundRelation, containerComponent);
- }
- } catch (Exception e) {
- log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return resultOp;
- }
-
- private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
- for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
- if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
- return relationship;
- }
- }
- return null;
- }
-
- private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
- Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
- RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation();
- String instanceId = foundRelation.getFromNode();
- Optional<RequirementDefinition> foundRequirement;
- Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
- if(!instance.isPresent()){
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
- log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
- result = Either.right(responseFormat);
- }
- if(result == null){
- for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
- foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
- if(foundRequirement.isPresent()){
- foundRelation.getSingleRelationship().setRequirement(foundRequirement.get());
- result = Either.left(foundRelation);
- }
- }
- }
- if(result == null){
- Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
- if(getfulfilledRequirementRes.isRight()){
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
- log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
- result = Either.right(responseFormat);
- } else {
- foundRelation.getSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
- }
- }
- if(result == null){
- result = Either.left(foundRelation);
- }
- return result;
- }
-
- private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
- return req.getRelationship().equals(relationshipInfo.getRelationship().getType()) &&
- req.getName().equals(relationshipInfo.getRequirement()) &&
- req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
- req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
- }
-
- private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
- Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
- RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation();
- String instanceId = foundRelation.getToNode();
- Optional<CapabilityDefinition> foundCapability;
- Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
- if(!instance.isPresent()){
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
- log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
- result = Either.right(responseFormat);
- }
- if(result == null){
- for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
- foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
- if(foundCapability.isPresent()){
- foundRelation.getSingleRelationship().setCapability(foundCapability.get());
- result = Either.left(foundRelation);
- }
- }
- }
- if(result == null){
- Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
- toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
- if(getfulfilledRequirementRes.isRight()){
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
- log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
- result = Either.right(responseFormat);
- } else {
- foundRelation.getSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
- }
- }
- if(result == null){
- result = Either.left(foundRelation);
- }
- return result;
- }
-
- private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
- return cap.getName().equals(relationshipInfo.getCapability()) &&
- cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
- cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
- }
-
- private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
- Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
- Either<ComponentInstanceProperty, ResponseFormat> result;
- if (eitherAttribute.isLeft()) {
- log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
- ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
-
- result = Either.left(instanceAttribute);
-
- } else {
- log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
-
- result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
-
- }
- return result;
- }
-
- private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
-
- Either<ComponentInstanceProperty, ResponseFormat> result;
-
- Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
-
- if (!errorWrapper.isEmpty()) {
- result = Either.right(errorWrapper.getInnerElement());
- } else {
- Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
- if (eitherAttribute.isLeft()) {
- log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
- ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
- result = Either.left(instanceAttribute);
-
- } else {
- log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
- result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
- }
- }
- return result;
- }
-
- /**
- * Create Or Updates Attribute Instance
- *
- * @param componentTypeEnum
- * @param componentId
- * @param resourceInstanceId
- * @param attribute
- * @param userId
- * @return
- */
- public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
- Either<ComponentInstanceProperty, ResponseFormat> result = null;
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-
- validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
- if (errorWrapper.isEmpty()) {
- validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- validateComponentLock(componentId, componentTypeEnum, errorWrapper);
- }
-
- try {
- if (errorWrapper.isEmpty()) {
- final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
- if (isCreate) {
- result = createAttributeValue(attribute, resourceInstanceId);
- } else {
- result = updateAttributeValue(attribute, resourceInstanceId);
- }
- } else {
- result = Either.right(errorWrapper.getInnerElement());
- }
- return result;
- }
-
- finally {
- if (result == null || result.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
- }
-
- private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
- return StringUtils.isNotEmpty(property.getValue())
- && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
- && ComponentTypeEnum.SERVICE == componentTypeEnum;
- }
-
- private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
- return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property));
- }
-
- // US833308 VLI in service - specific network_role property value logic
- private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
- for (ComponentInstanceProperty property: properties) {
- if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreComponentInstances(false);
- Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
- if (getServiceResult.isRight()) {
- return getServiceResult.right().value();
- }
- Component service = getServiceResult.left().value();
- Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
- if (!getInstance.isPresent()) {
- return StorageOperationStatus.NOT_FOUND;
- }
- String prefix = service.getSystemName() + ".";
- String value = property.getValue();
- if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
- property.setValue(prefix + value);
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private Either<String,ResponseFormat> updatePropertyObjectValue(ComponentInstanceProperty property, Map<String, DataTypeDefinition> allDataTypes) {
- String innerType = null;
- String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- innerType = propDef.getType();
- }
- // Specific Update Logic
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
- String newValue = property.getValue();
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, true);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
- }
- return Either.left(newValue);
- }
-
- public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdatePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property, String userId) {
-
- Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- return resultOp;
- }
- Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
- if (getResourceResult.isRight()) {
- log.debug("Failed to retrieve component, component id {}", componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- Component containerComponent = getResourceResult.left().value();
-
- if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
- log.info("Restricted operation for user: {} on service {}", userId, componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
- if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
- return resultOp;
- }
- ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
- // specific property value logic US833308
- StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertyValue(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, property);
- if (StorageOperationStatus.OK != fetchByIdsStatus) {
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
- return resultOp;
- }
- // lock resource
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock service {}", componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- return resultOp;
- }
- String innerType = null;
- String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- innerType = propDef.getType();
- }
- // Specific Update Logic
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
- }
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
-
- String newValue = property.getValue();
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes.left().value(), true);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
- }
-
- try {
- List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(resourceInstanceId);
- Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
- StorageOperationStatus status;
- instanceProperty.get().setValue(newValue);
- if (instanceProperty.isPresent()) {
- status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
- } else {
- status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
- }
- if (status != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- return resultOp;
- }
- List<String> path = new ArrayList<>();
- path.add(foundResourceInstance.getUniqueId());
- property.setPath(path);
-
- foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
- if (updateContainerRes.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- return resultOp;
- }
- resultOp = Either.left(property);
- return resultOp;
-
- } finally {
- if (resultOp == null || resultOp.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
-
- }
-
- public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInstanceInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput property, String userId) {
-
- Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- return resultOp;
- }
- Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
- if (getResourceResult.isRight()) {
- log.debug("Failed to retrieve component, component id {}", componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- Component containerComponent = getResourceResult.left().value();
-
- if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
- log.info("Restricted operation for user: {} on service {}", userId, componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
- if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
- return resultOp;
- }
-
- ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
-
- // lock resource
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock service {}", componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- return resultOp;
- }
- String innerType = null;
- String propertyType = property.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = property.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- innerType = propDef.getType();
- }
- // Specific Update Logic
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
- }
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes.left().value());
-
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (!res) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
- }
- }
-
- try {
- List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(resourceInstanceId);
- Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
- StorageOperationStatus status;
- if (instanceProperty.isPresent()) {
- instanceProperty.get().setValue(property.getValue());
- status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
- } else {
- status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), property);
- }
- if (status != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- return resultOp;
- }
- foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
- if (updateContainerRes.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- return resultOp;
- }
- resultOp = Either.left(property);
- return resultOp;
-
- } finally {
- if (resultOp == null || resultOp.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
-
- }
-
- public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
- String userId) {
-
- Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- return resultOp;
- }
-
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
- log.info("Restricted operation for user: {} on service: {}", userId, componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- // lock resource
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock service {}", componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- return resultOp;
- }
- try {
- String propertyValueUid = property.getValueUniqueUid();
-
- if (propertyValueUid == null) {
-
- Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
-
- if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
- StorageOperationStatus status = counterRes.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
- resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
- Integer index = counterRes.left().value();
- Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
-
- if (result.isLeft()) {
- log.trace("Property value was added to resource instance {}", resourceInstanceId);
- ComponentInstanceProperty instanceProperty = result.left().value();
-
- resultOp = Either.left(instanceProperty);
-
- } else {
- log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
-
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- }
-
- } else {
- Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
-
- if (result.isLeft()) {
- log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
- ComponentInstanceProperty instanceProperty = result.left().value();
-
- resultOp = Either.left(instanceProperty);
-
- } else {
- log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
-
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- }
- }
- if (resultOp.isLeft()) {
- StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
- if (updateCustomizationUUID != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
-
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
- }
- }
- return resultOp;
-
- } finally {
- if (resultOp == null || resultOp.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
-
- }
-
- public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
-
- Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- return resultOp;
- }
-
- if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
- log.info("Restricted operation for user: {} on service: {}", userId, componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- // lock resource
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock service {}", componentId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- return resultOp;
- }
- try {
- String propertyValueUid = inputProperty.getValueUniqueUid();
- if (propertyValueUid == null) {
-
- Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
-
- if (counterRes.isRight()) {
- log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
- StorageOperationStatus status = counterRes.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
- resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
- Integer index = counterRes.left().value();
- Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
-
- if (result.isLeft()) {
- log.debug("Property value was added to resource instance {}", resourceInstanceId);
- ComponentInstanceInput instanceProperty = result.left().value();
-
- resultOp = Either.left(instanceProperty);
- return resultOp;
-
- } else {
- log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
-
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
- return resultOp;
- }
-
- } else {
- Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
-
- if (result.isLeft()) {
- log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
- ComponentInstanceInput instanceProperty = result.left().value();
-
- resultOp = Either.left(instanceProperty);
- return resultOp;
-
- } else {
- log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
-
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
- return resultOp;
- }
- }
-
- } finally {
- if (resultOp == null || resultOp.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
- }
-
- }
-
- public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
-
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- return resultOp;
- }
-
- if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
- log.info("Restricted operation for user {} on service {}", userId, serviceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return resultOp;
- }
- // lock resource
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock service {}", serviceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- return resultOp;
- }
- try {
- Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
-
- if (result.isLeft()) {
- log.debug("Property value {} was removed from graph.", propertyValueId);
- ComponentInstanceProperty instanceProperty = result.left().value();
-
- resultOp = Either.left(instanceProperty);
- return resultOp;
-
- } else {
- log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
-
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
-
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
- return resultOp;
- }
-
- } finally {
- if (resultOp == null || resultOp.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
- }
-
- }
-
- private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
-
- Either<Component, ResponseFormat> eitherResponse = null;
- ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
- Component component;
- ResponseFormat errorResponse;
- Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
- if (getComponentRes.isRight()) {
- log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
- errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
- eitherResponse = Either.right(errorResponse);
- }
- if (eitherResponse == null) {
- component = getComponentRes.left().value();
- LifecycleStateEnum resourceCurrState = component.getLifecycleState();
- if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
- ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
- errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
- eitherResponse = Either.right(errorResponse);
- }
- }
- if (eitherResponse == null) {
- eitherResponse = Either.left(getComponentRes.left().value());
- }
- return eitherResponse;
- }
-
- public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- User user = resp.left().value();
- Either<ComponentInstance, ResponseFormat> resultOp = null;
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
- if (validateComponentType.isRight()) {
- return Either.right(validateComponentType.right().value());
- }
-
- final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
- if (validateComponentExists.isRight()) {
- return Either.right(validateComponentExists.right().value());
- }
- org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
-
- Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
- if (validateCanWorkOnComponent.isRight()) {
- return Either.right(validateCanWorkOnComponent.right().value());
- }
-
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
- if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
- return resultOp;
- }
-
- ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
-
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
-
- try {
-
-
- if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
- resultOp = Either.left(currentResourceInstance);
- return resultOp;
-
- }
- String resourceId = newComponentInstance.getComponentUid();
-
-
-
- Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
- if (componentExistsRes.isRight()) {
- log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
- return resultOp;
- } else if (!componentExistsRes.left().value()) {
- log.debug("The resource {} not found ", resourceId);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- return resultOp;
- }
-
- Either<Component, ResponseFormat> eitherOriginComponent = getOriginComponentFromComponentInstance(currentResourceInstance, true);
-
- if (eitherOriginComponent.isRight()) {
- resultOp = Either.right(eitherOriginComponent.right().value());
- return resultOp;
- }
- DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
- resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
- if (resultOp.isRight()) {
- log.debug("failed to delete resource instance {}", resourceId);
- return resultOp;
- }
- ComponentInstance resResourceInfo = resultOp.left().value();
- Component origComponent = null;
- OriginTypeEnum originType = currentResourceInstance.getOriginType();
- if (originType == OriginTypeEnum.ServiceProxy) {
- Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
- if (serviceProxyOrigin.isRight()) {
- log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
- }
- origComponent = serviceProxyOrigin.left().value();
-
- StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
-
- if (fillProxyRes != StorageOperationStatus.OK) {
- log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
-
- }
- newComponentInstance.setOriginType(originType);
- }else{
-
-
- Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance, true);
-
- if (eitherResourceName.isRight()) {
- resultOp = Either.right(eitherResourceName.right().value());
- return resultOp;
- }
-
- origComponent = eitherResourceName.left().value();
-
- newComponentInstance.setName(resResourceInfo.getName());
- //newComponentInstance.setToscaComponentName(((ResourceMetadataDataDefinition) origComponent.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName());
- }
-
- newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
- newComponentInstance.setPosX(resResourceInfo.getPosX());
- newComponentInstance.setPosY(resResourceInfo.getPosY());
- newComponentInstance.setDescription(resResourceInfo.getDescription());
-
- resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
-
- if (resultOp.isRight()) {
- log.debug("failed to create resource instance {}", resourceId);
- return resultOp;
- }
-
- ComponentInstance updatedComponentInstance = resultOp.left().value();
- if (resultOp.isRight()) {
- log.debug("failed to create resource instance {}", resourceId);
- return resultOp;
- }
-
- Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
- if (mergeStatusEither.isRight()) {
- return Either.right(mergeStatusEither.right().value());
- }
-
- /*
- * 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); if (addDeploymentArtifactsToComponentInstance != 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; } }
- */
-
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
- if (updatedComponentRes.isRight()) {
- StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
- log.debug("Component with id {} was not found", containerComponentId);
- return Either.right(responseFormat);
- }
- resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
- if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
- return resultOp;
- }
- resultOp = Either.left(resourceInstanceStatus.left().value());
- return resultOp;
-
- } finally {
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
-
- protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
-
- // US831698
- public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
- final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
- Component containerComponent = null;
-
- Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
- try {
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
- if (validateUserExists.isRight()) {
- resultOp = Either.right(validateUserExists.right().value());
- return resultOp;
- }
-
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
- if (validateComponentType.isRight()) {
- resultOp = Either.right(validateComponentType.right().value());
- return resultOp;
- }
-
- Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
- if (validateContainerComponentExists.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
- return resultOp;
- }
- containerComponent = validateContainerComponentExists.left().value();
-
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
- if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
- return resultOp;
- }
-
- List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
- if (CollectionUtils.isEmpty(instanceProperties)) {
- instanceProperties = new ArrayList<>();
- }
- resultOp = Either.left(instanceProperties);
- return resultOp;
- } finally {
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
- Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
-
- if (counterRes.isRight()) {
- log.debug("increase And Get {} failed resource instance {}", counterType.name(), resourceInstanceId);
- StorageOperationStatus status = counterRes.right().value();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
- errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
- } else {
- instaceCounterWrapper.setInnerElement(counterRes.left().value());
- }
-
- }
-
- /**
- * updates componentInstance modificationTime
- *
- * @param componentInstance
- * @param componentInstanceType
- * @param modificationTime
- * @param inTransaction
- * @return
- */
- public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
- Either<ComponentInstanceData, ResponseFormat> result;
- Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
- inTransaction);
- if (updateComponentInstanceRes.isRight()) {
- log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
- } else {
- result = Either.left(updateComponentInstanceRes.left().value());
- }
- return result;
- }
-
- public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
- // TODO Add implementation
- Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
- return result;
- }
-
- public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
- // TODO Add implementation
- Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
- return result;
- }
-
- public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
- // TODO Add implementation
- Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
- return result;
- }
-
- private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
- Boolean isUnique = true;
- String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
- if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
- Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
- if (foundComponentInstance.isPresent()) {
- isUnique = false;
- }
- }
- return isUnique;
- }
-
- private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
-
- Either<ComponentInstance, StorageOperationStatus> result = null;
- List<ComponentInstance> instances = containerComponent.getComponentInstances();
- Optional<ComponentInstance> foundInstance = null;
- if (CollectionUtils.isEmpty(instances)) {
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- if (result == null) {
- foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
- if (!foundInstance.isPresent()) {
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- if (result == null) {
- result = Either.left(foundInstance.get());
- }
- return result;
- }
-
- private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
-
- Long creationDate = origInstanceForUpdate.getCreationTime();
-
- Long modificationTime = System.currentTimeMillis();
- resourceInstanceForUpdate.setCreationTime(creationDate);
- resourceInstanceForUpdate.setModificationTime(modificationTime);
-
- resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
- resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
- }
-
- resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
- resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
- resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
- resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
-
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
- resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
-
- if (resourceInstanceForUpdate.getOriginType() == null) {
- resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
- }
- if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
- resourceInstanceForUpdate.setIsProxy(true);
- if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
- resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
- }
- if (resourceInstanceForUpdate.getSourceModelName() == null) {
- resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
- }
- if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
- resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
- }
- if (resourceInstanceForUpdate.getSourceModelUid() == null) {
- resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
- }
- return resourceInstanceForUpdate;
- }
- /**
- * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type
- * @param containerComponentType
- * @param containerComponentId
- * @param componentInstanceUniqueId
- * @param capabilityType
- * @param capabilityName
- * @param userId
- * @return
- */
- public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String userId) {
-
- Component containerComponent = null;
-
- Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
- try {
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false);
- if (validateUserExists.isRight()) {
- resultOp = Either.right(validateUserExists.right().value());
- }
- if(resultOp == null){
- Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
- if (validateComponentType.isRight()) {
- resultOp = Either.right(validateComponentType.right().value());
- }
- }
- if(resultOp == null){
- Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
- if (validateContainerComponentExists.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
- } else {
- containerComponent = validateContainerComponentExists.left().value();
- }
- }
- if(resultOp == null){
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
- if (resourceInstanceStatus.isRight()) {
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
- } else {
- resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, resourceInstanceStatus.left().value().getCapabilities());
- }
- }
- return resultOp;
- } finally {
- unlockComponent(resultOp, containerComponent);
- }
- }
-
- private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
- Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
- CapabilityDefinition foundCapability;
- if (MapUtils.isNotEmpty(instanceCapabilities)) {
- List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
- if (capabilitiesPerType != null) {
- Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName)).findFirst();
- if (capabilityOpt.isPresent()) {
- foundCapability = capabilityOpt.get();
- result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
- }
- }
- }
- if (result == null) {
- result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName);
- }
- return result;
- }
-
- private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName) {
- Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
- try {
- Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType);
- if(getComponentInstanceCapabilityProperties.isRight()){
- resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
- } else {
- resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
- }
- } catch(Exception e){
- log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
- resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return resultOp;
- }
-
- private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
- String capabilityType, String capabilityName) {
- String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
- StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
- sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
- String capKey = sb.toString();
-
- Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
- .orElse(Collections.emptyMap());
- List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
- Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
- if (cap.isPresent()) {
- List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
- if (capProperties != null) {
- Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
- StorageOperationStatus status;
- if (instanceProperty.isPresent()) {
- instanceProperty.get().setValue(newValue);
- List<String> path = new ArrayList<>();
- path.add(componentInstanceUniqueId);
- path.add(capKey);
- instanceProperty.get().setPath(path);
- status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
- if (status != StorageOperationStatus.OK) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
- return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
-
- }
- foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
- }
- }
- }
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
-
- public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
- List<ComponentInstanceProperty> properties, String userId) {
- Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- if (componentTypeEnum == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- }
- Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
-
- if (getResourceResult.isRight()) {
- log.debug("Failed to retrieve component, component id {}", containerComponentId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- Component containerComponent = getResourceResult.left().value();
-
- if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
- log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
- if (resourceInstanceStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
- }
- ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
- // lock resource
- StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
- if (lockStatus != StorageOperationStatus.OK) {
- log.debug("Failed to lock component {}", containerComponentId);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
- }
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
- }
-
- try {
- for (ComponentInstanceProperty property : properties) {
- Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, allDataTypes.left().value());
- newPropertyValueEither.bimap(updatedValue ->
- updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
- responseFormat -> Either.right(responseFormat));
- }
- Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
- if (updateContainerRes.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
- resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
- return resultOp;
- }
- resultOp = Either.left(properties);
- return resultOp;
-
- } finally {
- if (resultOp == null || resultOp.isRight()) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- // unlock resource
- graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
- }
- }
+ protected Either<ActionStatus, ResponseFormat> addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
+
+ log.debug("add artifacts to resource instance");
+ List<GroupDefinition> filteredGroups = null;
+ ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
+ if (!ActionStatus.OK.equals(status)) {
+ ResponseFormat resultOp = componentsUtils.getResponseFormatForResourceInstance(status, "", null);
+ return Either.right(resultOp);
+ }
+ StorageOperationStatus artStatus;
+ // generate heat_env if necessary
+ Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
+ if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
+
+ Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<String, ArtifactDefinition>();
+ Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
+
+ 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;
+ }
+ if (artifact.checkEsIdExist()) {
+ Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactBusinessLogic.createHeatEnvPlaceHolder(artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(), NodeTypeEnum.ResourceInstance,
+ componentInstance.getName(), user, containerComponent, existingEnvVersions);
+ if (createHeatEnvPlaceHolder.isRight()) {
+ return Either.right(createHeatEnvPlaceHolder.right().value());
+ }
+ ArtifactDefinition artifactDefinition = createHeatEnvPlaceHolder.left().value();
+ // put env
+ finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+
+ if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
+ filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
+ }
+ if (CollectionUtils.isNotEmpty(filteredGroups)) {
+ for (GroupDefinition groupInstance : filteredGroups) {
+ Optional<String> op = groupInstance.getArtifacts().stream().filter(p -> p.equals(artifactDefinition.getGeneratedFromId())).findAny();
+ if (op.isPresent()) {
+ List<ArtifactDefinition> artifactsUid;
+ if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
+ artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
+ } else {
+ artifactsUid = new ArrayList<>();
+ }
+ artifactsUid.add(artifactDefinition);
+ groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
+ break;
+ }
+ }
+ }
+ }
+ }
+ artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
+ if (artStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
+
+ }
+ StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
+ if (result != StorageOperationStatus.OK) {
+ log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
+ }
+ componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
+ }
+
+ artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
+ if (artStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
+
+ }
+ componentInstance.setArtifacts(originComponent.getArtifacts());
+ return Either.left(ActionStatus.OK);
+ }
+
+ private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
+ if (getResourceDeploymentArtifacts.isRight()) {
+ StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
+ if (!status.equals(StorageOperationStatus.NOT_FOUND)) {
+ log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
+ return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
+ }
+ } else {
+ deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
+ }
+
+ if (!deploymentArtifacts.isEmpty()) {
+ Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<String, ArtifactDefinition>(deploymentArtifacts);
+ for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
+ if (!artifact.getValue().checkEsIdExist()) {
+ tempDeploymentArtifacts.remove(artifact.getKey());
+ }
+ }
+
+ resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
+ }
+
+ return ActionStatus.OK;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
+ return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true, true);
+ }
+
+ public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
+ boolean needLock, boolean createNewTransaction) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", inTransaction);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ }
+
+ final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
+
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+ ComponentTypeEnum instanceType = getComponentType(containerComponentType);
+ Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
+ if (validateParentStatus.isRight()) {
+ log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase()));
+ return resultOp;
+ }
+ if (!validateParentStatus.left().value()) {
+ resultOp = Either.right(
+ componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId));
+ return resultOp;
+ }
+
+ if (needLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ }
+ try {
+
+ Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(componentInstance);
+
+ if (eitherResourceName.isRight()) {
+ resultOp = Either.right(eitherResourceName.right().value());
+ return resultOp;
+ }
+ Component origComponent = eitherResourceName.left().value();
+
+ resultOp = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
+ return resultOp;
+
+ } finally {
+ if (needLock)
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ // New Multiple Instance Update API
+ public Either<List<ComponentInstance>, ResponseFormat> updateComponentInstance(String containerComponentParam, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock,
+ boolean createNewTransaction) {
+
+ Either<List<ComponentInstance>, ResponseFormat> resultOp = null;
+ org.openecomp.sdc.be.model.Component containerComponent = null;
+ try {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "update Component Instance", true);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ }
+
+ final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
+
+ ComponentParametersView componentFilter = new ComponentParametersView();
+ componentFilter.disableAll();
+ componentFilter.setIgnoreUsers(false);
+ componentFilter.setIgnoreComponentInstances(false);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+
+ containerComponent = validateComponentExists.left().value();
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ ComponentTypeEnum instanceType = getComponentType(containerComponentType);
+
+ for (ComponentInstance componentInstance : componentInstanceList) {
+ boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
+ if (!validateParent) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
+ containerComponentId));
+ return resultOp;
+ }
+ }
+
+ if (needLock) {
+
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "updateComponentInstance");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ }
+
+ List<ComponentInstance> updatedList = new ArrayList<>();
+ List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
+ List<ComponentInstance> listForUpdate = new ArrayList<>();
+ if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
+ containerComponent.setComponentInstances(componentInstanceList);
+ else {
+ Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
+ while (iterator.hasNext()) {
+ ComponentInstance origInst = iterator.next();
+ Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
+ if (op.isPresent()) {
+ ComponentInstance updatedCi = op.get();
+ updatedCi = buildComponentInstance(updatedCi, origInst);
+
+ Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
+ if (!isUniqueName) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
+ return resultOp;
+ }
+
+ listForUpdate.add(updatedCi);
+ } else
+ listForUpdate.add(origInst);
+ }
+ containerComponent.setComponentInstances(listForUpdate);
+
+ if (resultOp == null) {
+ Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
+ if (updateStatus.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
+ return resultOp;
+ }
+ for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
+ Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
+ if (op.isPresent()) {
+ updatedList.add(updatedInstance);
+ }
+ }
+ }
+ }
+
+ resultOp = Either.left(updatedList);
+ return resultOp;
+
+ } finally {
+ if (needLock) {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+ }
+
+ private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
+ return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
+ }
+
+ private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
+ if (ComponentTypeEnum.PRODUCT.equals(containerComponentType)) {
+ return ComponentTypeEnum.SERVICE_INSTANCE;
+ } else {
+ return ComponentTypeEnum.RESOURCE_INSTANCE;
+ }
+ }
+
+ private Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
+ ComponentInstance componentInstance) {
+
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ Optional<ComponentInstance> componentInstanceOptional = null;
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
+ ComponentInstance oldComponentInstance = null;
+ boolean isNameChanged = false;
+
+ if (resultOp == null) {
+ componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
+ if (!componentInstanceOptional.isPresent()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+ }
+ }
+ if (resultOp == null) {
+ oldComponentInstance = componentInstanceOptional.get();
+ String newInstanceName = componentInstance.getName();
+ if (oldComponentInstance != null && oldComponentInstance.getName() != null && !oldComponentInstance.getName().equals(newInstanceName))
+ isNameChanged = true;
+ Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
+ if (!isUniqueName) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName()));
+ }
+ }
+ if (resultOp == null) {
+ updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
+ if (updateRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
+ updateRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
+ } else {
+ // region - Update instance Groups
+ if (isNameChanged) {
+ Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
+ if (result.isRight())
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
+ }
+ // endregion
+ }
+ }
+ if (resultOp == null) {
+ String newInstanceId = updateRes.left().value().getRight();
+ Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
+
+ if (!updatedInstanceOptional.isPresent()) {
+ log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+ } else {
+ resultOp = Either.left(updatedInstanceOptional.get());
+ }
+
+ }
+ if (resultOp == null) {
+ resultOp = Either.left(componentInstanceOptional.get());
+ }
+ return resultOp;
+ }
+
+ /**
+ * @param oldPrefix-
+ * The normalized old vf name
+ * @param newNormailzedPrefix-
+ * The normalized new vf name
+ * @param qualifiedGroupInstanceName-
+ * old Group Instance Name
+ **/
+ // modify group names
+ private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
+ if (qualifiedGroupInstanceName == null) {
+ log.info("CANNOT change group name ");
+ return null;
+ }
+ if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
+ return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
+ return qualifiedGroupInstanceName;
+ }
+
+ private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
+ oldComponentInstance.setName(newComponentInstance.getName());
+ oldComponentInstance.setModificationTime(System.currentTimeMillis());
+ oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ if (oldComponentInstance.getGroupInstances() != null)
+ oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
+ return oldComponentInstance;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Component Instance", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ }
+
+ final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "deleteComponentInstance");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ // validate resource
+ /*
+ * if (!ComponentValidationUtils.canWorkOnComponent(containerComponentId, serviceOperation, userId)) { log.info( "Restricted operation for user " + userId + " on service " + containerComponentId); return Either.right(componentsUtils
+ * .getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } // lock resource StorageOperationStatus lockStatus = graphLockOperation.lockComponent( containerComponentId, NodeTypeEnum.Service); if (lockStatus != StorageOperationStatus.OK) {
+ * log.debug("Failed to lock service {}", containerComponentId); resultOp = Either.right(componentsUtils .getResponseFormat(componentsUtils .convertFromStorageResponse(lockStatus))); return resultOp; }
+ */
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ try {
+ resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
+ if (resultOp.isRight()){
+ return resultOp;
+ }
+ Either<ComponentInstance, ResponseFormat> deleteEither = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, componentInstanceId,
+ containerComponentType, resultOp);
+ if (deleteEither.isRight()){
+ return deleteEither;
+ }
+ return deleteEither;
+
+ } finally {
+ /*
+ * if (resultOp == null || resultOp.isRight()) { titanGenericDao.rollback(); } else { titanGenericDao.commit(); } graphLockOperation.unlockComponent(containerComponentId, NodeTypeEnum.Service);
+ */
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ public Either<ComponentInstance, ResponseFormat> deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
+ String componentInstanceId, ComponentTypeEnum containerComponentType,
+ Either<ComponentInstance, ResponseFormat> resultOp) {
+ if(containerComponentType.equals(ComponentTypeEnum.SERVICE) && resultOp.isLeft() ){
+
+ List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstanceId);
+ if (!pathIDsToBeDeleted.isEmpty()) {
+ Either<Set<String>, ResponseFormat> deleteForwardingPathsEither = deleteForwardingPaths(containerComponentId,
+ pathIDsToBeDeleted);
+ if(deleteForwardingPathsEither.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+ }
+ return resultOp;
+ }
+
+
+ private Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
+
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
+ if(storageStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(storageStatus.right().value()));
+ }
+ Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
+ Sets.newHashSet(pathIdsToDelete));
+
+ if(result.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(result.right().value()));
+ }
+ return Either.left(result.left().value());
+ }
+
+ private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreForwardingPath(false);
+ Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
+ .getToscaElement(containerComponentId, filter);
+ Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
+ List<String> pathIDsToBeDeleted = new ArrayList<>();
+
+ allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
+ .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
+
+ return pathIDsToBeDeleted;
+ }
+
+ private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
+ String componentInstanceId){
+ return pathDataDefinition.getPathElements().getListToscaDataDefinition()
+ .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
+ elementDataDefinition.getToNode()
+ .equalsIgnoreCase(componentInstanceId));
+ }
+
+
+ private Either<ComponentInstance, ResponseFormat> deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
+
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+ ComponentInstance deletedInstance = null;
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
+
+ if (deleteRes.isRight()) {
+ log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
+ ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
+ resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
+ }
+ if (resultOp == null) {
+ log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
+ deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
+ resultOp = Either.left(deletedInstance);
+ }
+ if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getGroups())) {
+ List<GroupDataDefinition> groupsToUpdate = new ArrayList<>();
+ for (GroupDataDefinition currGroup : containerComponent.getGroups()) {
+ Map<String, String> members = currGroup.getMembers();
+ if (members != null && members.containsKey(deletedInstance.getName())) {
+ members.remove(deletedInstance.getName());
+ groupsToUpdate.add(currGroup);
+ }
+ }
+ Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsRes = toscaOperationFacade.updateGroupsOnComponent(containerComponent, groupsToUpdate);
+ if (updateGroupsRes.isRight()) {
+ log.debug("Failed to delete component instance {} from group members. ", componentInstanceId);
+ ActionStatus status = componentsUtils.convertFromStorageResponse(updateGroupsRes.right().value(), containerComponentType);
+ resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
+ }
+ }
+ if (resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
+ List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+ if (CollectionUtils.isNotEmpty(inputsToDelete)) {
+ StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
+ if (deleteInputsRes != StorageOperationStatus.OK) {
+ log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
+ }
+ }
+ }
+ return resultOp;
+ }
+
+ private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
+ ComponentInstance foundInstance = null;
+ for (ComponentInstance instance : containerComponent.getComponentInstances()) {
+ if (instance.getUniqueId().equals(componentInstanceId)) {
+ foundInstance = instance;
+ containerComponent.getComponentInstances().remove(instance);
+ break;
+ }
+ }
+ findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
+ return foundInstance;
+ }
+
+ private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
+ if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
+ containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
+ }
+ }
+
+ private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
+ return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
+ }
+
+ public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
+ return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true, true);
+ }
+
+ public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock,
+ boolean createNewTransaction) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "associate Ri To RI", inTransaction);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
+
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+ if (needLock) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
+
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ }
+
+ try {
+
+ resultOp = associateRIToRIOnGraph(validateComponentExists.left().value(), requirementDef, componentTypeEnum, inTransaction);
+
+ return resultOp;
+
+ } finally {
+ if (needLock)
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ public Either<RequirementCapabilityRelDef, ResponseFormat> associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction) {
+
+ log.debug("Try to create entry on graph");
+ Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
+
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(containerComponent.getUniqueId(), requirementDef);
+
+ if (result.isLeft()) {
+ log.debug("Enty on graph is created.");
+ RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
+ resultOp = Either.left(requirementCapabilityRelDef);
+ return resultOp;
+
+ } else {
+ log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
+ String fromNameOrId = "";
+ String toNameOrId = "";
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
+
+ toNameOrId = requirementDef.getFromNode();
+ fromNameOrId = requirementDef.getFromNode();
+ if (fromResult.isLeft()) {
+ fromNameOrId = fromResult.left().value().getName();
+ }
+ if (toResult.isLeft()) {
+ toNameOrId = toResult.left().value().getName();
+ }
+
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
+
+ return resultOp;
+ }
+
+ }
+
+ public Either<RequirementCapabilityRelDef, ResponseFormat> dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "dissociate RI From RI", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "associateRIToRI");
+
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+ try {
+ log.debug("Try to create entry on graph");
+ Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
+ if (result.isLeft()) {
+ log.debug("Enty on graph is created.");
+ RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
+ resultOp = Either.left(requirementCapabilityRelDef);
+ return resultOp;
+
+ } else {
+
+ log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
+ String fromNameOrId = "";
+ String toNameOrId = "";
+ Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+ Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
+
+ toNameOrId = requirementDef.getFromNode();
+ fromNameOrId = requirementDef.getFromNode();
+ if (fromResult.isLeft()) {
+ fromNameOrId = fromResult.left().value().getName();
+ }
+ if (toResult.isLeft()) {
+ toNameOrId = toResult.left().value().getName();
+ }
+
+ resultOp = Either
+ .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement()));
+ return resultOp;
+ }
+ } finally {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+ /**
+ * Allows to get relation contained in specified component according to received Id
+ * @param componentId
+ * @param relationId
+ * @param userId
+ * @param componentTypeEnum
+ * @return
+ */
+ public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
+ try {
+ org.openecomp.sdc.be.model.Component containerComponent = null;
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
+ RequirementCapabilityRelDef foundRelation = null;
+
+ Either<User, ResponseFormat> validateUserRes = validateUserExists(userId, "get relation by Id", false);
+ if (validateUserRes.isRight()) {
+ resultOp = Either.right(validateUserRes.right().value());
+ }
+ if(resultOp == null){
+ validateComponentExists = validateComponentExists(componentId, componentTypeEnum, null);
+ if (validateComponentExists.isRight()) {
+ resultOp = Either.right(validateComponentExists.right().value());
+ }
+ }
+ if(resultOp == null){
+ containerComponent = validateComponentExists.left().value();
+ List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
+ foundRelation = findRelation(relationId, requirementCapabilityRelations);
+ if(foundRelation == null){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
+ log.debug("Relation with id {} was not found on the component", relationId, componentId);
+ resultOp = Either.right(responseFormat);
+ }
+ }
+ if(resultOp == null){
+ resultOp = setRelatedCapability(foundRelation, containerComponent);
+ }
+ if(resultOp.isLeft()){
+ resultOp = setRelatedRequirement(foundRelation, containerComponent);
+ }
+ } catch (Exception e) {
+ log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return resultOp;
+ }
+
+ private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
+ for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
+ if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
+ return relationship;
+ }
+ }
+ return null;
+ }
+
+ private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
+ Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
+ RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
+ String instanceId = foundRelation.getFromNode();
+ Optional<RequirementDefinition> foundRequirement;
+ Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ if(!instance.isPresent()){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
+ log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
+ result = Either.right(responseFormat);
+ }
+ if(result == null){
+ for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
+ foundRequirement = requirements.stream().filter(r -> isBelongingRequirement(relationshipInfo, r)).findFirst();
+ if(foundRequirement.isPresent()){
+ foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
+ result = Either.left(foundRelation);
+ }
+ }
+ }
+ if(result == null){
+ Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, req)->isBelongingRequirement(rel, req));
+ if(getfulfilledRequirementRes.isRight()){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
+ log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
+ result = Either.right(responseFormat);
+ } else {
+ foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
+ }
+ }
+ if(result == null){
+ result = Either.left(foundRelation);
+ }
+ return result;
+ }
+
+ private boolean isBelongingRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
+ return req.getName().equals(relationshipInfo.getRequirement()) &&
+ req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
+ req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
+ }
+
+ private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
+ Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
+ RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
+ String instanceId = foundRelation.getToNode();
+ Optional<CapabilityDefinition> foundCapability;
+ Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ if(!instance.isPresent()){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
+ log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
+ result = Either.right(responseFormat);
+ }
+ if(result == null){
+ for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
+ foundCapability = capabilities.stream().filter(c -> isBelongingCapability(relationshipInfo, c)).findFirst();
+ if(foundCapability.isPresent()){
+ foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
+ result = Either.left(foundRelation);
+ }
+ }
+ }
+ if(result == null){
+ Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
+ toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, (rel, cap)->isBelongingCapability(rel, cap));
+ if(getfulfilledRequirementRes.isRight()){
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
+ log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
+ result = Either.right(responseFormat);
+ } else {
+ foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
+ }
+ }
+ if(result == null){
+ result = Either.left(foundRelation);
+ }
+ return result;
+ }
+
+ private boolean isBelongingCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
+ return cap.getName().equals(relationshipInfo.getCapability()) &&
+ cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
+ cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
+ }
+
+ private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
+ Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
+ Either<ComponentInstanceProperty, ResponseFormat> result;
+ if (eitherAttribute.isLeft()) {
+ log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
+ ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
+
+ result = Either.left(instanceAttribute);
+
+ } else {
+ log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
+
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
+
+ }
+ return result;
+ }
+
+ private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
+
+ Either<ComponentInstanceProperty, ResponseFormat> result;
+
+ Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
+
+ if (!errorWrapper.isEmpty()) {
+ result = Either.right(errorWrapper.getInnerElement());
+ } else {
+ Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
+ if (eitherAttribute.isLeft()) {
+ log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
+ ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
+ result = Either.left(instanceAttribute);
+
+ } else {
+ log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
+ result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Create Or Updates Attribute Instance
+ *
+ * @param componentTypeEnum
+ * @param componentId
+ * @param resourceInstanceId
+ * @param attribute
+ * @param userId
+ * @return
+ */
+ public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
+ Either<ComponentInstanceProperty, ResponseFormat> result = null;
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+
+ validateUserExist(userId, "create Or Update Attribute Value", errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
+ }
+ if (errorWrapper.isEmpty()) {
+ validateComponentLock(componentId, componentTypeEnum, errorWrapper);
+ }
+
+ try {
+ if (errorWrapper.isEmpty()) {
+ final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
+ if (isCreate) {
+ result = createAttributeValue(attribute, resourceInstanceId);
+ } else {
+ result = updateAttributeValue(attribute, resourceInstanceId);
+ }
+ } else {
+ result = Either.right(errorWrapper.getInnerElement());
+ }
+ return result;
+ }
+
+ finally {
+ if (result == null || result.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+ }
+
+ private boolean isNetworkRoleServiceProperty(ComponentInstanceProperty property, ComponentTypeEnum componentTypeEnum) {
+ return StringUtils.isNotEmpty(property.getValue())
+ && PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(property.getName())
+ && ComponentTypeEnum.SERVICE == componentTypeEnum;
+ }
+
+ private StorageOperationStatus concatServiceNameToVLINetworkRolePropertyValue(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty property) {
+ return concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, Arrays.asList(property));
+ }
+
+ // US833308 VLI in service - specific network_role property value logic
+ private StorageOperationStatus concatServiceNameToVLINetworkRolePropertiesValues(ToscaOperationFacade toscaOperationFacade, ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties) {
+ for (ComponentInstanceProperty property: properties) {
+ if (isNetworkRoleServiceProperty(property, componentTypeEnum)) {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreComponentInstances(false);
+ Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+ if (getServiceResult.isRight()) {
+ return getServiceResult.right().value();
+ }
+ Component service = getServiceResult.left().value();
+ Optional<ComponentInstance> getInstance = service.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(resourceInstanceId)).findAny();
+ if (!getInstance.isPresent()) {
+ return StorageOperationStatus.NOT_FOUND;
+ }
+ String prefix = service.getSystemName() + ".";
+ String value = property.getValue();
+ if (OriginTypeEnum.VL == getInstance.get().getOriginType() && (!value.startsWith(prefix) || value.equalsIgnoreCase(prefix))) {
+ property.setValue(prefix + value);
+ }
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+
+ /*-------------------------------Validations---------------------------------*/
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Properties Values", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ if (getResourceResult.isRight()) {
+ log.debug("Failed to retrieve component, component id {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Component containerComponent = getResourceResult.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
+ log.info("Restricted operation for user: {} on service {}", userId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
+ return resultOp;
+ }
+ ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
+ // specific property value logic US833308
+ StorageOperationStatus fetchByIdsStatus = concatServiceNameToVLINetworkRolePropertiesValues(toscaOperationFacade, componentTypeEnum, componentId, resourceInstanceId, properties);
+ if (StorageOperationStatus.OK != fetchByIdsStatus) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fetchByIdsStatus)));
+ return resultOp;
+ }
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+
+ try {
+ for (ComponentInstanceProperty property: properties) {
+ Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
+ updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance),
+ responseFormat -> Either.right(responseFormat));
+ }
+
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+ if (updateContainerRes.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ resultOp = Either.left(properties);
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+ }
+
+ private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
+ String capabilityType, String capabilityName) {
+ String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
+ StringBuffer sb = new StringBuffer(componentInstanceUniqueId);
+ sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
+ String capKey = sb.toString();
+
+ Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
+ .orElse(Collections.emptyMap());
+ List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
+ Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
+ if (cap.isPresent()) {
+ List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
+ if (capProperties != null) {
+ Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ StorageOperationStatus status;
+ if (instanceProperty.isPresent()) {
+ instanceProperty.get().setValue(newValue);
+ List<String> path = new ArrayList<>();
+ path.add(componentInstanceUniqueId);
+ path.add(capKey);
+ instanceProperty.get().setPath(path);
+ status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
+ if (status != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
+
+ }
+ foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ }
+ }
+ }
+
+
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
+ Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ StorageOperationStatus status;
+ instanceProperty.get().setValue(newValue);
+ if (instanceProperty.isPresent()) {
+ status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
+ } else {
+ status = toscaOperationFacade.addComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), property);
+ }
+ if (status != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
+ }
+ List<String> path = new ArrayList<>();
+ path.add(foundResourceInstance.getUniqueId());
+ property.setPath(path);
+
+ foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesEither = dataTypeCache.getAll();
+ if (allDataTypesEither.isRight()) {
+ TitanOperationStatus status = allDataTypesEither.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+ }
+ Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
+ String innerType = null;
+ String propertyType = property.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = property.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ innerType = propDef.getType();
+ }
+ // Specific Update Logic
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
+ String newValue = property.getValue();
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (res == false) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+ if (!isInput) {
+ ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
+ if (pair.getRight() != null && pair.getRight() == false) {
+ BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ }
+ return Either.left(newValue);
+ }
+
+ private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
+ List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
+ Optional<ComponentInstanceInput> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(input.getUniqueId())).findAny();
+ StorageOperationStatus status;
+ if (instanceProperty.isPresent()) {
+ instanceProperty.get().setValue(input.getValue());
+ status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
+ } else {
+ status = toscaOperationFacade.addComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
+ }
+ if (status != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
+ }
+ foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
+
+ Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ if (getResourceResult.isRight()) {
+ log.debug("Failed to retrieve component, component id {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Component containerComponent = getResourceResult.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
+ log.info("Restricted operation for user: {} on service {}", userId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
+ return resultOp;
+ }
+
+ ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
+
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+ try {
+ for (ComponentInstanceInput input: inputs) {
+ Either<String, ResponseFormat> updatedInputValue = updatePropertyObjectValue(input, true);
+ updatedInputValue.bimap(updatedValue -> updateInputOnContainerComponent(input,updatedValue, containerComponent, foundResourceInstance),
+ responseFormat -> Either.right(responseFormat));
+
+ }
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+
+ if (updateContainerRes.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ resultOp = Either.left(inputs);
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property,
+ String userId) {
+
+ Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Property Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
+ log.info("Restricted operation for user: {} on service: {}", userId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+ try {
+ String propertyValueUid = property.getValueUniqueUid();
+
+ if (propertyValueUid == null) {
+
+ Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
+
+ if (counterRes.isRight()) {
+ log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
+ StorageOperationStatus status = counterRes.right().value();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+ Integer index = counterRes.left().value();
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
+
+ if (result.isLeft()) {
+ log.trace("Property value was added to resource instance {}", resourceInstanceId);
+ ComponentInstanceProperty instanceProperty = result.left().value();
+
+ resultOp = Either.left(instanceProperty);
+
+ } else {
+ log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ }
+
+ } else {
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
+
+ if (result.isLeft()) {
+ log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
+ ComponentInstanceProperty instanceProperty = result.left().value();
+
+ resultOp = Either.left(instanceProperty);
+
+ } else {
+ log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ }
+ }
+ if (resultOp.isLeft()) {
+ StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
+ if (updateCustomizationUUID != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+
+ }
+ }
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ public Either<ComponentInstanceInput, ResponseFormat> createOrUpdateInputValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceInput inputProperty, String userId) {
+
+ Either<ComponentInstanceInput, ResponseFormat> resultOp = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Or Update Input Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateInputValue", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+
+ if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
+ log.info("Restricted operation for user: {} on service: {}", userId, componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", componentId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+ try {
+ String propertyValueUid = inputProperty.getValueUniqueUid();
+ if (propertyValueUid == null) {
+
+ Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
+
+ if (counterRes.isRight()) {
+ log.debug("increaseAndGetResourceInputCounter failed resource instance {} inputProperty {}", resourceInstanceId, inputProperty);
+ StorageOperationStatus status = counterRes.right().value();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+ Integer index = counterRes.left().value();
+ Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.addInputValueToResourceInstance(inputProperty, resourceInstanceId, index, true);
+
+ if (result.isLeft()) {
+ log.debug("Property value was added to resource instance {}", resourceInstanceId);
+ ComponentInstanceInput instanceProperty = result.left().value();
+
+ resultOp = Either.left(instanceProperty);
+ return resultOp;
+
+ } else {
+ log.debug("Failed to add input value {} to resource instance {}", inputProperty, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+
+ return resultOp;
+ }
+
+ } else {
+ Either<ComponentInstanceInput, StorageOperationStatus> result = componentInstanceOperation.updateInputValueInResourceInstance(inputProperty, resourceInstanceId, true);
+
+ if (result.isLeft()) {
+ log.debug("Input value {} was updated on graph.", inputProperty.getValueUniqueUid());
+ ComponentInstanceInput instanceProperty = result.left().value();
+
+ resultOp = Either.left(instanceProperty);
+ return resultOp;
+
+ } else {
+ log.debug("Failed to update property value {} in resource instance {}", inputProperty, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+
+ return resultOp;
+ }
+ }
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property Value", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertyValue", "invalid component type", ErrorSeverity.INFO);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ return resultOp;
+ }
+
+ if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
+ log.info("Restricted operation for user {} on service {}", userId, serviceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return resultOp;
+ }
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock service {}", serviceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ return resultOp;
+ }
+ try {
+ Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
+
+ if (result.isLeft()) {
+ log.debug("Property value {} was removed from graph.", propertyValueId);
+ ComponentInstanceProperty instanceProperty = result.left().value();
+
+ resultOp = Either.left(instanceProperty);
+ return resultOp;
+
+ } else {
+ log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
+
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
+
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+
+ return resultOp;
+ }
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ private Either<Component, ResponseFormat> getAndValidateOriginComponentOfComponentInstance(ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
+
+ Either<Component, ResponseFormat> eitherResponse = null;
+ ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponentType);
+ Component component;
+ ResponseFormat errorResponse;
+ Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
+ if (getComponentRes.isRight()) {
+ log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
+ errorResponse = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
+ eitherResponse = Either.right(errorResponse);
+ }
+ if (eitherResponse == null) {
+ component = getComponentRes.left().value();
+ LifecycleStateEnum resourceCurrState = component.getLifecycleState();
+ if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
+ ActionStatus actionStatus = ActionStatus.ILLEGAL_COMPONENT_STATE;
+ errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().toString(), component.getName(), resourceCurrState.toString());
+ eitherResponse = Either.right(errorResponse);
+ }
+ }
+ if (eitherResponse == null) {
+ eitherResponse = Either.left(getComponentRes.left().value());
+ }
+ return eitherResponse;
+ }
+
+ public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
+ String containerComponentId,
+ String componentInstanceId,
+ ComponentInstance newComponentInstance) {
+ Either<Set<String>, ResponseFormat> resultOp;
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ }
+ final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
+ ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
+
+ //Fetch Component
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists =
+ validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ Component containerComponent = validateComponentExists.left().value();
+
+ //Fetch current component instance
+ Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
+ getResourceInstanceById(containerComponent, componentInstanceId);
+ if (eitherResourceInstance.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
+ return resultOp;
+ }
+ ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
+
+ //Check whether new componentInstance exists
+ String resourceId = newComponentInstance.getComponentUid();
+ Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
+ if (componentExistsRes.isRight()) {
+ log.debug("Failed to find resource ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
+ (componentExistsRes.right().value()), resourceId));
+ return resultOp;
+ } else if (!componentExistsRes.left().value()) {
+ log.debug("The resource {} not found ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
+ return resultOp;
+ }
+
+ //Fetch component using new component instance uid
+ Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
+ if (eitherResourceName.isRight()) {
+ resultOp = Either.right(eitherResourceName.right().value());
+ return resultOp;
+ }
+ Component updatedContainerComponent=eitherResourceName.left().value();
+ Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
+ currentResourceInstance, updatedContainerComponent);
+ resultOp=Either.left(toDeleteForwardingPaths);
+
+ return resultOp;
+ }
+
+ private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
+ Component updatedContainerComponent) {
+ DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
+ dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
+
+ Service service = (Service) containerComponent;
+ ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
+
+ return forwardingPathUtils.
+ getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
+ }
+
+ private ComponentParametersView getComponentParametersViewForForwardingPath() {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.setIgnoreCapabiltyProperties(false);
+ componentParametersView.setIgnoreForwardingPath(false);
+ return componentParametersView;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "change Component Instance Version", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ User user = resp.left().value();
+ Either<ComponentInstance, ResponseFormat> resultOp = null;
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentParam);
+ if (validateComponentType.isRight()) {
+ return Either.right(validateComponentType.right().value());
+ }
+
+ final ComponentTypeEnum containerComponentType = validateComponentType.left().value();
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.setIgnoreCapabiltyProperties(false);
+ Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
+ if (validateComponentExists.isRight()) {
+ return Either.right(validateComponentExists.right().value());
+ }
+ org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
+
+ Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
+ if (validateCanWorkOnComponent.isRight()) {
+ return Either.right(validateCanWorkOnComponent.right().value());
+ }
+
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
+ return resultOp;
+ }
+
+ ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
+
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(containerComponent, "changeComponentInstanceVersion");
+ if (lockComponent.isRight()) {
+ return Either.right(lockComponent.right().value());
+ }
+
+ try {
+
+
+ if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
+ resultOp = Either.left(currentResourceInstance);
+ return resultOp;
+
+ }
+ String resourceId = newComponentInstance.getComponentUid();
+
+
+
+ Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
+ if (componentExistsRes.isRight()) {
+ log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId));
+ return resultOp;
+ } else if (!componentExistsRes.left().value()) {
+ log.debug("The resource {} not found ", resourceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
+ return resultOp;
+ }
+
+ Either<Component, ResponseFormat> eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
+
+ if (eitherOriginComponent.isRight()) {
+ resultOp = Either.right(eitherOriginComponent.right().value());
+ return resultOp;
+ }
+ DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent.left().value());
+ resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
+ if (resultOp.isRight()) {
+ log.debug("failed to delete resource instance {}", resourceId);
+ return resultOp;
+ }
+ ComponentInstance resResourceInfo = resultOp.left().value();
+ Component origComponent = null;
+ OriginTypeEnum originType = currentResourceInstance.getOriginType();
+ if (originType == OriginTypeEnum.ServiceProxy) {
+ Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
+ if (serviceProxyOrigin.isRight()) {
+ log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value())));
+ }
+ origComponent = serviceProxyOrigin.left().value();
+
+ StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
+
+ if (fillProxyRes != StorageOperationStatus.OK) {
+ log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(fillProxyRes)));
+
+ }
+ newComponentInstance.setOriginType(originType);
+ }else{
+
+
+ Either<Component, ResponseFormat> eitherResourceName = getOriginComponentFromComponentInstance(newComponentInstance);
+
+ if (eitherResourceName.isRight()) {
+ resultOp = Either.right(eitherResourceName.right().value());
+ return resultOp;
+ }
+
+ origComponent = eitherResourceName.left().value();
+
+ newComponentInstance.setName(resResourceInfo.getName());
+ }
+
+ newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
+ newComponentInstance.setPosX(resResourceInfo.getPosX());
+ newComponentInstance.setPosY(resResourceInfo.getPosY());
+ newComponentInstance.setDescription(resResourceInfo.getDescription());
+
+ resultOp = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
+
+ if (resultOp.isRight()) {
+ log.debug("failed to create resource instance {}", resourceId);
+ return resultOp;
+ }
+
+ ComponentInstance updatedComponentInstance = resultOp.left().value();
+ if (resultOp.isRight()) {
+ log.debug("failed to create resource instance {}", resourceId);
+ return resultOp;
+ }
+
+ Either<Component, ResponseFormat> mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
+ if (mergeStatusEither.isRight()) {
+ return Either.right(mergeStatusEither.right().value());
+ }
+
+ ActionStatus postChangeVersionResult = postChangeVersionOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
+ if (postChangeVersionResult != ActionStatus.OK) {
+ return Either.right(componentsUtils.getResponseFormat(postChangeVersionResult));
+ }
+
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
+ if (updatedComponentRes.isRight()) {
+ StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
+ log.debug("Component with id {} was not found", containerComponentId);
+ return Either.right(responseFormat);
+ }
+ resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId()));
+ return resultOp;
+ }
+ resultOp = Either.left(resourceInstanceStatus.left().value());
+ return resultOp;
+
+ } finally {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ // US831698
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
+ final String ECOMP_ERROR_CONTEXT = "Get Component Instance Properties By Id";
+ Component containerComponent = null;
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+ try {
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, ECOMP_ERROR_CONTEXT, false);
+ if (validateUserExists.isRight()) {
+ resultOp = Either.right(validateUserExists.right().value());
+ return resultOp;
+ }
+
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentTypeParam);
+ if (validateComponentType.isRight()) {
+ resultOp = Either.right(validateComponentType.right().value());
+ return resultOp;
+ }
+
+ Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
+ if (validateContainerComponentExists.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
+ return resultOp;
+ }
+ containerComponent = validateContainerComponentExists.left().value();
+
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ return resultOp;
+ }
+
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
+ if (CollectionUtils.isEmpty(instanceProperties)) {
+ instanceProperties = new ArrayList<>();
+ }
+ resultOp = Either.left(instanceProperties);
+ return resultOp;
+ } finally {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
+ Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
+
+ if (counterRes.isRight()) {
+ log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
+ StorageOperationStatus status = counterRes.right().value();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
+ } else {
+ instaceCounterWrapper.setInnerElement(counterRes.left().value());
+ }
+
+ }
+
+ /**
+ * updates componentInstance modificationTime
+ *
+ * @param componentInstance
+ * @param componentInstanceType
+ * @param modificationTime
+ * @param inTransaction
+ * @return
+ */
+ public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
+ Either<ComponentInstanceData, ResponseFormat> result;
+ Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
+ inTransaction);
+ if (updateComponentInstanceRes.isRight()) {
+ log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
+ } else {
+ result = Either.left(updateComponentInstanceRes.left().value());
+ }
+ return result;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
+ // TODO Add implementation
+ Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
+ return result;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
+ // TODO Add implementation
+ Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
+ return result;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
+ // TODO Add implementation
+ Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
+ return result;
+ }
+
+ private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
+ return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
+ }
+
+ private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
+
+ Either<ComponentInstance, StorageOperationStatus> result = null;
+ List<ComponentInstance> instances = containerComponent.getComponentInstances();
+ Optional<ComponentInstance> foundInstance = null;
+ if (CollectionUtils.isEmpty(instances)) {
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ if (result == null) {
+ foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ if (!foundInstance.isPresent()) {
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ if (result == null) {
+ result = Either.left(foundInstance.get());
+ }
+ return result;
+ }
+
+ private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
+
+ Long creationDate = origInstanceForUpdate.getCreationTime();
+
+ Long modificationTime = System.currentTimeMillis();
+ resourceInstanceForUpdate.setCreationTime(creationDate);
+ resourceInstanceForUpdate.setModificationTime(modificationTime);
+
+ resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
+
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
+ resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
+ }
+
+ resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
+
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
+ resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
+
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
+ resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
+
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
+ resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
+
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
+ resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
+
+ if (resourceInstanceForUpdate.getOriginType() == null) {
+ resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
+ }
+ if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
+ resourceInstanceForUpdate.setIsProxy(true);
+ if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
+ resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
+ }
+ if (resourceInstanceForUpdate.getSourceModelName() == null) {
+ resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
+ }
+ if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
+ resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
+ }
+ if (resourceInstanceForUpdate.getSourceModelUid() == null) {
+ resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
+ }
+ return resourceInstanceForUpdate;
+ }
+ /**
+ * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
+ * @param containerComponentType
+ * @param containerComponentId
+ * @param componentInstanceUniqueId
+ * @param capabilityType
+ * @param capabilityName
+ * @param userId
+ * @param ownerId
+ * @return
+ */
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
+
+ Component containerComponent = null;
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+ try {
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, "Get Component Instance Properties By Id", false);
+ if (validateUserExists.isRight()) {
+ resultOp = Either.right(validateUserExists.right().value());
+ }
+ if(resultOp == null){
+ Either<ComponentTypeEnum, ResponseFormat> validateComponentType = validateComponentType(containerComponentType);
+ if (validateComponentType.isRight()) {
+ resultOp = Either.right(validateComponentType.right().value());
+ }
+ }
+ if(resultOp == null){
+ Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaFullElement(containerComponentId);
+ if (validateContainerComponentExists.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())));
+ } else {
+ containerComponent = validateContainerComponentExists.left().value();
+ }
+ }
+ if(resultOp == null){
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ if (resourceInstanceStatus.isRight()) {
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ } else {
+ resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.left().value().getCapabilities());
+ }
+ }
+ return resultOp;
+ } finally {
+ unlockComponent(resultOp, containerComponent);
+ }
+ }
+
+ private Either<List<ComponentInstanceProperty>, ResponseFormat> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
+ Either<List<ComponentInstanceProperty>, ResponseFormat> result = null;
+ CapabilityDefinition foundCapability;
+ if (MapUtils.isNotEmpty(instanceCapabilities)) {
+ List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
+ if (capabilitiesPerType != null) {
+ Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
+ if (capabilityOpt.isPresent()) {
+ foundCapability = capabilityOpt.get();
+ result = Either.left(foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties());
+ }
+ }
+ }
+ if (result == null) {
+ result = fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
+ }
+ return result;
+ }
+
+ private Either<List<ComponentInstanceProperty>, ResponseFormat> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+ try {
+ Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties = toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
+ if(getComponentInstanceCapabilityProperties.isRight()){
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentInstanceCapabilityProperties.right().value()), capabilityType, instanceId, componentId));
+ } else {
+ resultOp = Either.left(getComponentInstanceCapabilityProperties.left().value());
+ }
+ } catch(Exception e){
+ log.error("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
+ resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return resultOp;
+ }
+
+ private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
+ String capabilityType, String capabilityName, String ownerId) {
+ String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
+ StringBuilder sb = new StringBuilder(componentInstanceUniqueId);
+ sb.append(ModelConverter.CAP_PROP_DELIM).append(property.getOwnerId()).append(ModelConverter.CAP_PROP_DELIM).append(capabilityType).append(ModelConverter.CAP_PROP_DELIM).append(capabilityName);
+ String capKey = sb.toString();
+
+ Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
+ .orElse(Collections.emptyMap());
+ List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
+ Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
+ if (cap.isPresent()) {
+ List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
+ if (capProperties != null) {
+ Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ StorageOperationStatus status;
+ if (instanceProperty.isPresent()) {
+ instanceProperty.get().setValue(newValue);
+ List<String> path = new ArrayList<>();
+ path.add(componentInstanceUniqueId);
+ path.add(capKey);
+ instanceProperty.get().setPath(path);
+ status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
+ if (status != StorageOperationStatus.OK) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+ return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
+
+ }
+ foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ }
+ }
+ }
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
+ List<ComponentInstanceProperty> properties, String userId) {
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
+
+ if (getResourceResult.isRight()) {
+ log.debug("Failed to retrieve component, component id {}", containerComponentId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ Component containerComponent = getResourceResult.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
+ log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ if (resourceInstanceStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ }
+ ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock component {}", containerComponentId);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ }
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+ }
+
+ try {
+ for (ComponentInstanceProperty property : properties) {
+ Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
+ newPropertyValueEither.bimap(updatedValue ->
+ updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
+ responseFormat -> Either.right(responseFormat));
+ }
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+
+ if (updateContainerRes.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ resultOp = Either.left(properties);
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
+ }
+ }
+
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
+ List<ComponentInstanceProperty> properties, String userId) {
+ Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "update instance capability property", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ if (componentTypeEnum == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", "invalid component type", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+ Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
+
+ if (getResourceResult.isRight()) {
+ log.debug("Failed to retrieve component, component id {}", containerComponentId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ Component containerComponent = getResourceResult.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
+ log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+ if (resourceInstanceStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+ }
+ ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
+ // lock resource
+ StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
+ if (lockStatus != StorageOperationStatus.OK) {
+ log.debug("Failed to lock component {}", containerComponentId);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
+ }
+
+ try {
+ for (ComponentInstanceProperty property : properties) {
+ Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(property, false);
+ newPropertyValueEither.bimap(updatedValue ->
+ updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
+ responseFormat -> Either.right(responseFormat));
+ }
+ Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+
+ if (updateContainerRes.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+ resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+ return resultOp;
+ }
+ resultOp = Either.left(properties);
+ return resultOp;
+
+ } finally {
+ if (resultOp == null || resultOp.isRight()) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ // unlock resource
+ graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
index f6a108cf75..90f807475f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
@@ -20,15 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-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.Set;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
@@ -39,7 +31,14 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+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.Set;
+import java.util.stream.Collectors;
/**
* This class holds the logic of arranging resource instance on the canvas for imported VF
@@ -49,240 +48,240 @@ import fj.data.Either;
*/
@Component("compositionBusinessLogic")
public class CompositionBusinessLogic {
- @Autowired
- private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic;
-
- private static final int VFC_CANVAS_ELEMENT_SIZE = 50;
- private static final int CP_CANVAS_ELEMENT_SIZE = 21;
- private static final int CANVAS_WIDTH = 1000;
- private static final int CANVAS_HEIGHT = 700;
- private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4;
- private static final double CP_RADIUS_FACTOR = 0.4;
-
- enum RelativePosition {
- LEFT, RIGHT, UP, DOWN
- };
-
- protected Either<List<ComponentInstance>, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) {
- Either<List<ComponentInstance>, ResponseFormat> result = Either.left(resource.getComponentInstances());
-
- boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null
- || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent();
-
- if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) {
- // Arrange Icons In Spiral Pattern
- Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource);
-
- // Set Relative Locations According to Canvas Size
- componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e));
-
- // Update in DB
- result = vfComponentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false);
-
- }
- return result;
-
- }
-
- private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) {
- int xCenter = CANVAS_WIDTH / 2;
- int yCenter = CANVAS_HEIGHT / 2;
-
- ImmutablePair<Double, Double> matrixPosition = entry.getKey();
- ComponentInstance componentInstance = entry.getValue();
- componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance));
- componentInstance.setPosY(calculateCompositionPosition(yCenter, matrixPosition.getRight(), componentInstance));
- }
-
- private String calculateCompositionPosition(int center, double relativePosition, ComponentInstance componentInstance) {
- final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS;
- double offsetedCanvasPosition;
- switch (componentInstance.getOriginType()) {
- case CP:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2;
- break;
- case VL:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2;
- break;
- case VF:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
- break;
- case VFC:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
- break;
- case VFCMT:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
- break;
- default:
- offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
- break;
- }
- return String.valueOf(offsetedCanvasPosition);
- }
-
- protected Map<ImmutablePair<Double, Double>, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(Resource resource) {
-
- Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = new HashMap<>();
-
- List<ComponentInstance> componentInstances = new ArrayList<>();
- componentInstances.addAll(resource.getComponentInstances());
- Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, resource);
- // Remove all cp that are connected from the list
- componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList()));
-
- buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances);
- buildCirclePatternForCps(componentInstanceLocations, connectededCps);
-
- return componentInstanceLocations;
- }
-
- protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations, Map<ComponentInstance, List<ComponentInstance>> connectedCps) {
-
- for (Entry<ComponentInstance, List<ComponentInstance>> vfcCpList : connectedCps.entrySet()) {
- Entry<ImmutablePair<Double, Double>, ComponentInstance> vfcOfTheCps = componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny().get();
- buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations);
- }
-
- }
-
- private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup, Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) {
- final int numberOfCps = cpsGroup.size();
- double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0;
- double currentAngle = 0;
- Double xCenter = vfcLocation.getLeft();
- Double yCenter = vfcLocation.getRight();
- for (ComponentInstance currCp : cpsGroup) {
- double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle);
- double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle);
- componentInstLocations.put(new ImmutablePair<Double, Double>(cpXposition, cpYposition), currCp);
- currentAngle += angleBetweenCps;
- }
-
- }
-
- private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, List<ComponentInstance> componentInstances) {
- int elementsCounter = 0;
- ImmutablePair<Double, Double> currPlacement;
- ImmutablePair<Double, Double> prevPlacement = null;
- RelativePosition relationToPrevElement = null;
- for (ComponentInstance curr : componentInstances) {
- elementsCounter++;
- if (elementsCounter == 1) {
- currPlacement = new ImmutablePair<Double, Double>(0D, 0D);
- } else if (elementsCounter == 2) {
- currPlacement = new ImmutablePair<Double, Double>(-1D, 0D);
- relationToPrevElement = RelativePosition.LEFT;
- } else {
- relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement);
- currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement);
-
- }
-
- componentInstanceLocations.put(currPlacement, curr);
- prevPlacement = currPlacement;
- }
- }
-
- protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances, Resource vf) {
- Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps = new HashMap<>();
- List<RequirementCapabilityRelDef> allRelations = vf.getComponentInstancesRelations();
- for (ComponentInstance curr : allComponentInstances) {
- // Filters Only CPs
- if (curr.getOriginType() == OriginTypeEnum.CP) {
- // List Of elements the CP is connected to
- List<RequirementCapabilityRelDef> connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList());
- // Adds Only CPs Which are connected to VFC
- filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList);
- }
- }
- return vfcWithItsCps;
- }
-
- private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps, ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) {
- if (!connectedToTheCPList.isEmpty()) {
- // Set Of Ids Of components Instances which are connected certain CP
- Set<String> mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet());
-
- // Vfc Component instance Connected to the CP
- Optional<ComponentInstance> optionalVfcConnectedToCP = allComponentInstances.stream().
- // All instances connected to CP
- filter(p -> mateIds.contains(p.getUniqueId())).
- // Filter in only VFC connected to the CP
- filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny();
-
- if (optionalVfcConnectedToCP.isPresent()) {
- final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get();
- if (vfcWithItsCps.containsKey(vfcWithCps)) {
- vfcWithItsCps.get(vfcWithCps).add(currCP);
- } else {
- List<ComponentInstance> cpsList = new ArrayList<>();
- cpsList.add(currCP);
- vfcWithItsCps.put(vfcWithCps, cpsList);
- }
- }
- }
- }
-
- private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair<Double, Double> prevPlacement) {
- switch (relationToPrevElement) {
- case LEFT: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP;
- break;
- }
- case RIGHT: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN;
- break;
- }
- case UP: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT;
- break;
- }
- case DOWN: {
- boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations);
- relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT;
- break;
- }
- default: {
- throw new UnsupportedOperationException();
- }
- }
- return relationToPrevElement;
- }
-
- private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement, Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) {
-
- ImmutablePair<Double, Double> adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement);
- return allElements.containsKey(adjacentElementPosition);
- }
-
- private ImmutablePair<Double, Double> getRelativeElementLocation(ImmutablePair<Double, Double> currElement, RelativePosition relativeLocation) {
- ImmutablePair<Double, Double> relativeElementPosition;
- switch (relativeLocation) {
-
- case LEFT: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() - 1, currElement.getRight());
- break;
- }
- case RIGHT: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() + 1, currElement.getRight());
- break;
- }
- case UP: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() + 1);
- break;
- }
- case DOWN: {
- relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() - 1);
- break;
- }
- default: {
- throw new UnsupportedOperationException();
- }
- }
- return relativeElementPosition;
- }
+ @Autowired
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+ private static final int VFC_CANVAS_ELEMENT_SIZE = 50;
+ private static final int CP_CANVAS_ELEMENT_SIZE = 21;
+ private static final int CANVAS_WIDTH = 1000;
+ private static final int CANVAS_HEIGHT = 700;
+ private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4;
+ private static final double CP_RADIUS_FACTOR = 0.4;
+
+ enum RelativePosition {
+ LEFT, RIGHT, UP, DOWN
+ };
+
+ protected Either<List<ComponentInstance>, ResponseFormat> setPositionsForComponentInstances(Resource resource, String userId) {
+ Either<List<ComponentInstance>, ResponseFormat> result = Either.left(resource.getComponentInstances());
+
+ boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null
+ || resource.getComponentInstances().stream().filter(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty())).findAny().isPresent();
+
+ if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) {
+ // Arrange Icons In Spiral Pattern
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource);
+
+ // Set Relative Locations According to Canvas Size
+ componentInstanceLocations.entrySet().stream().forEach(e -> setRelativePosition(e));
+
+ // Update in DB
+ result = componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUniqueId(), userId, resource.getComponentInstances(), false, false);
+
+ }
+ return result;
+
+ }
+
+ private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) {
+ int xCenter = CANVAS_WIDTH / 2;
+ int yCenter = CANVAS_HEIGHT / 2;
+
+ ImmutablePair<Double, Double> matrixPosition = entry.getKey();
+ ComponentInstance componentInstance = entry.getValue();
+ componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance));
+ componentInstance.setPosY(calculateCompositionPosition(yCenter, matrixPosition.getRight(), componentInstance));
+ }
+
+ private String calculateCompositionPosition(int center, double relativePosition, ComponentInstance componentInstance) {
+ final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS;
+ double offsetedCanvasPosition;
+ switch (componentInstance.getOriginType()) {
+ case CP:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2;
+ break;
+ case VL:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2;
+ break;
+ case VF:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
+ break;
+ case VFC:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
+ break;
+ case VFCMT:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
+ break;
+ default:
+ offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2;
+ break;
+ }
+ return String.valueOf(offsetedCanvasPosition);
+ }
+
+ protected Map<ImmutablePair<Double, Double>, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(Resource resource) {
+
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = new HashMap<>();
+
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ componentInstances.addAll(resource.getComponentInstances());
+ Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, resource);
+ // Remove all cp that are connected from the list
+ componentInstances.removeAll(connectededCps.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList()));
+
+ buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances);
+ buildCirclePatternForCps(componentInstanceLocations, connectededCps);
+
+ return componentInstanceLocations;
+ }
+
+ protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations, Map<ComponentInstance, List<ComponentInstance>> connectedCps) {
+
+ for (Entry<ComponentInstance, List<ComponentInstance>> vfcCpList : connectedCps.entrySet()) {
+ Entry<ImmutablePair<Double, Double>, ComponentInstance> vfcOfTheCps = componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny().get();
+ buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations);
+ }
+
+ }
+
+ private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup, Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) {
+ final int numberOfCps = cpsGroup.size();
+ double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0;
+ double currentAngle = 0;
+ Double xCenter = vfcLocation.getLeft();
+ Double yCenter = vfcLocation.getRight();
+ for (ComponentInstance currCp : cpsGroup) {
+ double cpXposition = xCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.cos(currentAngle);
+ double cpYposition = yCenter + CompositionBusinessLogic.CP_RADIUS_FACTOR * Math.sin(currentAngle);
+ componentInstLocations.put(new ImmutablePair<Double, Double>(cpXposition, cpYposition), currCp);
+ currentAngle += angleBetweenCps;
+ }
+
+ }
+
+ private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, List<ComponentInstance> componentInstances) {
+ int elementsCounter = 0;
+ ImmutablePair<Double, Double> currPlacement;
+ ImmutablePair<Double, Double> prevPlacement = null;
+ RelativePosition relationToPrevElement = null;
+ for (ComponentInstance curr : componentInstances) {
+ elementsCounter++;
+ if (elementsCounter == 1) {
+ currPlacement = new ImmutablePair<Double, Double>(0D, 0D);
+ } else if (elementsCounter == 2) {
+ currPlacement = new ImmutablePair<Double, Double>(-1D, 0D);
+ relationToPrevElement = RelativePosition.LEFT;
+ } else {
+ relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement);
+ currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement);
+
+ }
+
+ componentInstanceLocations.put(currPlacement, curr);
+ prevPlacement = currPlacement;
+ }
+ }
+
+ protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances, Resource vf) {
+ Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps = new HashMap<>();
+ List<RequirementCapabilityRelDef> allRelations = vf.getComponentInstancesRelations();
+ for (ComponentInstance curr : allComponentInstances) {
+ // Filters Only CPs
+ if (curr.getOriginType() == OriginTypeEnum.CP) {
+ // List Of elements the CP is connected to
+ List<RequirementCapabilityRelDef> connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList());
+ // Adds Only CPs Which are connected to VFC
+ filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList);
+ }
+ }
+ return vfcWithItsCps;
+ }
+
+ private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps, ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) {
+ if (!connectedToTheCPList.isEmpty()) {
+ // Set Of Ids Of components Instances which are connected certain CP
+ Set<String> mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet());
+
+ // Vfc Component instance Connected to the CP
+ Optional<ComponentInstance> optionalVfcConnectedToCP = allComponentInstances.stream().
+ // All instances connected to CP
+ filter(p -> mateIds.contains(p.getUniqueId())).
+ // Filter in only VFC connected to the CP
+ filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny();
+
+ if (optionalVfcConnectedToCP.isPresent()) {
+ final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get();
+ if (vfcWithItsCps.containsKey(vfcWithCps)) {
+ vfcWithItsCps.get(vfcWithCps).add(currCP);
+ } else {
+ List<ComponentInstance> cpsList = new ArrayList<>();
+ cpsList.add(currCP);
+ vfcWithItsCps.put(vfcWithCps, cpsList);
+ }
+ }
+ }
+ }
+
+ private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair<Double, Double> prevPlacement) {
+ switch (relationToPrevElement) {
+ case LEFT: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP;
+ break;
+ }
+ case RIGHT: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN;
+ break;
+ }
+ case UP: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT;
+ break;
+ }
+ case DOWN: {
+ boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations);
+ relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT;
+ break;
+ }
+ default: {
+ throw new UnsupportedOperationException();
+ }
+ }
+ return relationToPrevElement;
+ }
+
+ private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement, Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) {
+
+ ImmutablePair<Double, Double> adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement);
+ return allElements.containsKey(adjacentElementPosition);
+ }
+
+ private ImmutablePair<Double, Double> getRelativeElementLocation(ImmutablePair<Double, Double> currElement, RelativePosition relativeLocation) {
+ ImmutablePair<Double, Double> relativeElementPosition;
+ switch (relativeLocation) {
+
+ case LEFT: {
+ relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() - 1, currElement.getRight());
+ break;
+ }
+ case RIGHT: {
+ relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft() + 1, currElement.getRight());
+ break;
+ }
+ case UP: {
+ relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() + 1);
+ break;
+ }
+ case DOWN: {
+ relativeElementPosition = new ImmutablePair<Double, Double>(currElement.getLeft(), currElement.getRight() - 1);
+ break;
+ }
+ default: {
+ throw new UnsupportedOperationException();
+ }
+ }
+ return relativeElementPosition;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
index 9c5cefb24c..44ab4220c8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
@@ -20,8 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.Date;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -42,272 +41,271 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.Date;
@Component("ConsumerBusinessLogic")
public class ConsumerBusinessLogic extends BaseBusinessLogic {
- private static final String CONSUMER_NAME = "Consumer name";
- private static final String CONSUMER_SALT = "Consumer salt";
- private static final String CONSUMER_PW = "Consumer password";
-
- @javax.annotation.Resource
- private IUserBusinessLogic userAdmin;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
- @javax.annotation.Resource
- private ConsumerOperation consumerOperation;
-
- @javax.annotation.Resource
- private IGraphLockOperation graphLockOperation;
-
- private static Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class.getName());
-
- public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) {
-
- Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
-
- if (userValidation.isRight()) {
- return Either.right(userValidation.right().value());
- }
- checkFieldsForOverrideAttempt(consumer);
- user = userValidation.left().value();
- consumer.setLastModfierAtuid(user.getUserId());
-
- Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
- if (consumerValidationResponse.isRight()) {
- ResponseFormat responseFormat = consumerValidationResponse.right().value();
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- String consumerName = consumer.getConsumerName();
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "createConsumer");
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName);
- log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- try {
- Either<ConsumerData, StorageOperationStatus> getResponse = consumerOperation.getCredentials(consumerName);
- if (getResponse.isLeft() && getResponse.left().value() != null) {
- return updateConsumer(consumer, user, true);
- }
-
- Date date = new Date();
- consumer.setConsumerDetailsLastupdatedtime(date.getTime());
- consumer.setConsumerLastAuthenticationTime(Long.valueOf(0));
-
- Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer));
-
- if (createResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- log.debug("Consumer created successfully!!!");
- consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
- return Either.left(consumer);
- } finally {
- graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials);
- }
- }
-
- private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) {
-
- if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
- log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- log.debug("audit before sending response");
- componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- log.debug("get user from DB");
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
- log.debug("audit before sending response");
- componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
- return Either.right(responseFormat);
- }
-
- user = eitherCreator.left().value();
- // validate user role
- log.debug("validate user role");
- if (!user.getRole().equals(Role.ADMIN.name())) {
- log.info("role {} is not allowed to perform this action", user.getRole());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("audit before sending response");
- componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- return Either.left(user);
- }
-
- private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) {
- Either<ConsumerDefinition, ResponseFormat> validateConsumerName = validateConsumerName(consumer);
- if (validateConsumerName.isRight()) {
- return Either.right(validateConsumerName.right().value());
- }
- Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword = validateConsumerPassword(consumer);
- if (validateConsumerPassword.isRight()) {
- return Either.right(validateConsumerPassword.right().value());
- }
- consumer = validateConsumerPassword.left().value();
- Either<ConsumerDefinition, ResponseFormat> validateEcompUserSalt = validateConsumerSalt(consumer);
- if (validateEcompUserSalt.isRight()) {
- return Either.right(validateEcompUserSalt.right().value());
- }
- return Either.left(consumer);
-
- }
-
- private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) {
- String name = consumer.getConsumerName();
- if (!ValidationUtils.validateStringNotEmpty(name)) {
- log.debug("Consumer name cannot be empty.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME));
- }
- if (!ValidationUtils.validateConsumerName(name)) {
- log.debug("Consumer name is invalid.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
- }
- if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) {
- log.debug("Consumer name exceeds limit.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
- }
- if (!ValidationUtils.isUTF8Str(name)) {
- log.debug("Consumer name includes non UTF 8 characters.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
- }
-
- return Either.left(consumer);
- }
-
- private Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword(ConsumerDefinition consumer) {
- String password = consumer.getConsumerPassword();
- if (!ValidationUtils.validateStringNotEmpty(password)) {
- log.debug("Consumer password cannot be empty.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW));
- }
- if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) {
- log.debug("Consumer password length is not valid.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW));
- }
- consumer.setConsumerPassword(password.toLowerCase());
- if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) {
- log.debug("Consumer password is invalid.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW));
- }
-
- return Either.left(consumer);
- }
-
- private Either<ConsumerDefinition, ResponseFormat> validateConsumerSalt(ConsumerDefinition consumer) {
- String salt = consumer.getConsumerSalt();
- if (!ValidationUtils.validateStringNotEmpty(salt)) {
- log.debug("Consumer salt cannot be empty.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT));
- }
- if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) {
- log.debug("Consumer salt length is not valid.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT));
- }
- if (!ValidationUtils.validateConsumerPassSalt(salt)) {
- log.debug("Consumer salt is invalid.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT));
- }
-
- return Either.left(consumer);
- }
-
- public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId, User user) {
- ConsumerDefinition tmpConsumer = new ConsumerDefinition();
- tmpConsumer.setConsumerName(consumerId);
- // In case of filter (southbound) call
- if (user != null) {
- Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS);
- if (userValidation.isRight()) {
- return Either.right(userValidation.right().value());
- }
- user = userValidation.left().value();
- }
- Either<ConsumerData, StorageOperationStatus> getResult = consumerOperation.getCredentials(consumerId);
- if (getResult.isRight()) {
- ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value());
- ResponseFormat responseFormat;
- if (action == ActionStatus.ECOMP_USER_NOT_FOUND) {
- responseFormat = componentsUtils.getResponseFormat(action, consumerId);
- } else {
- responseFormat = componentsUtils.getResponseFormat(action);
- }
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
- return Either.left(consumer);
- }
-
- public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId) {
- return getConsumer(consumerId, null);
- }
-
- public Either<ConsumerDefinition, ResponseFormat> deleteConsumer(String consumerId, User user) {
- ConsumerDefinition tmpConsumer = new ConsumerDefinition();
- tmpConsumer.setConsumerName(consumerId);
- Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS);
- if (userValidation.isRight()) {
- return Either.right(userValidation.right().value());
- }
- user = userValidation.left().value();
- Either<ConsumerData, StorageOperationStatus> deleteResult = consumerOperation.deleteCredentials(consumerId);
- if (deleteResult.isRight()) {
- ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value());
- ResponseFormat responseFormat;
- if (action == ActionStatus.ECOMP_USER_NOT_FOUND) {
- responseFormat = componentsUtils.getResponseFormat(action, consumerId);
- } else {
- responseFormat = componentsUtils.getResponseFormat(action);
- }
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user);
- return Either.right(responseFormat);
- }
- ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
- return Either.left(consumer);
- }
-
- public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) {
- Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer));
- if (updateResult.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
- return Either.right(responseFormat);
- }
- consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition());
- return Either.left(consumer);
- }
-
- private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) {
- if (consumer.getConsumerDetailsLastupdatedtime() != null) {
- log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application");
- }
- if (consumer.getConsumerLastAuthenticationTime() != null) {
- log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application");
- }
- if (consumer.getLastModfierAtuid() != null) {
- log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application");
- }
- }
+ private static final String CONSUMER_NAME = "Consumer name";
+ private static final String CONSUMER_SALT = "Consumer salt";
+ private static final String CONSUMER_PW = "Consumer password";
+
+ @javax.annotation.Resource
+ private IUserBusinessLogic userAdmin;
+
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
+
+ @javax.annotation.Resource
+ private ConsumerOperation consumerOperation;
+
+ @javax.annotation.Resource
+ private IGraphLockOperation graphLockOperation;
+
+ private static final Logger log = LoggerFactory.getLogger(ConsumerBusinessLogic.class);
+
+ public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) {
+
+ Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
+
+ if (userValidation.isRight()) {
+ return Either.right(userValidation.right().value());
+ }
+ checkFieldsForOverrideAttempt(consumer);
+ user = userValidation.left().value();
+ consumer.setLastModfierAtuid(user.getUserId());
+
+ Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer, user, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
+ if (consumerValidationResponse.isRight()) {
+ ResponseFormat responseFormat = consumerValidationResponse.right().value();
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ String consumerName = consumer.getConsumerName();
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName);
+ log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ try {
+ Either<ConsumerData, StorageOperationStatus> getResponse = consumerOperation.getCredentials(consumerName);
+ if (getResponse.isLeft() && getResponse.left().value() != null) {
+ return updateConsumer(consumer, user, true);
+ }
+
+ Date date = new Date();
+ consumer.setConsumerDetailsLastupdatedtime(date.getTime());
+ consumer.setConsumerLastAuthenticationTime(Long.valueOf(0));
+
+ Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer));
+
+ if (createResponse.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ log.debug("Consumer created successfully!!!");
+ consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
+ return Either.left(consumer);
+ } finally {
+ graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials);
+ }
+ }
+
+ private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) {
+
+ if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
+ log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ log.debug("audit before sending response");
+ componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ log.debug("get user from DB");
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
+ log.debug("audit before sending response");
+ componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+
+ user = eitherCreator.left().value();
+ // validate user role
+ log.debug("validate user role");
+ if (!user.getRole().equals(Role.ADMIN.name())) {
+ log.info("role {} is not allowed to perform this action", user.getRole());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ log.debug("audit before sending response");
+ componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ return Either.left(user);
+ }
+
+ private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer, User user, AuditingActionEnum audatingAction) {
+ Either<ConsumerDefinition, ResponseFormat> validateConsumerName = validateConsumerName(consumer);
+ if (validateConsumerName.isRight()) {
+ return Either.right(validateConsumerName.right().value());
+ }
+ Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword = validateConsumerPassword(consumer);
+ if (validateConsumerPassword.isRight()) {
+ return Either.right(validateConsumerPassword.right().value());
+ }
+ consumer = validateConsumerPassword.left().value();
+ Either<ConsumerDefinition, ResponseFormat> validateEcompUserSalt = validateConsumerSalt(consumer);
+ if (validateEcompUserSalt.isRight()) {
+ return Either.right(validateEcompUserSalt.right().value());
+ }
+ return Either.left(consumer);
+
+ }
+
+ private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) {
+ String name = consumer.getConsumerName();
+ if (!ValidationUtils.validateStringNotEmpty(name)) {
+ log.debug("Consumer name cannot be empty.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME));
+ }
+ if (!ValidationUtils.validateConsumerName(name)) {
+ log.debug("Consumer name is invalid.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
+ }
+ if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) {
+ log.debug("Consumer name exceeds limit.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
+ }
+ if (!ValidationUtils.isUTF8Str(name)) {
+ log.debug("Consumer name includes non UTF 8 characters.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
+ }
+
+ return Either.left(consumer);
+ }
+
+ private Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword(ConsumerDefinition consumer) {
+ String password = consumer.getConsumerPassword();
+ if (!ValidationUtils.validateStringNotEmpty(password)) {
+ log.debug("Consumer password cannot be empty.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW));
+ }
+ if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) {
+ log.debug("Consumer password length is not valid.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW));
+ }
+ consumer.setConsumerPassword(password.toLowerCase());
+ if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) {
+ log.debug("Consumer password is invalid.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW));
+ }
+
+ return Either.left(consumer);
+ }
+
+ private Either<ConsumerDefinition, ResponseFormat> validateConsumerSalt(ConsumerDefinition consumer) {
+ String salt = consumer.getConsumerSalt();
+ if (!ValidationUtils.validateStringNotEmpty(salt)) {
+ log.debug("Consumer salt cannot be empty.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT));
+ }
+ if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) {
+ log.debug("Consumer salt length is not valid.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT));
+ }
+ if (!ValidationUtils.validateConsumerPassSalt(salt)) {
+ log.debug("Consumer salt is invalid.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT));
+ }
+
+ return Either.left(consumer);
+ }
+
+ public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId, User user) {
+ ConsumerDefinition tmpConsumer = new ConsumerDefinition();
+ tmpConsumer.setConsumerName(consumerId);
+ // In case of filter (southbound) call
+ if (user != null) {
+ Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS);
+ if (userValidation.isRight()) {
+ return Either.right(userValidation.right().value());
+ }
+ user = userValidation.left().value();
+ }
+ Either<ConsumerData, StorageOperationStatus> getResult = consumerOperation.getCredentials(consumerId);
+ if (getResult.isRight()) {
+ ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value());
+ ResponseFormat responseFormat;
+ if (action == ActionStatus.ECOMP_USER_NOT_FOUND) {
+ responseFormat = componentsUtils.getResponseFormat(action, consumerId);
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(action);
+ }
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
+ return Either.left(consumer);
+ }
+
+ public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId) {
+ return getConsumer(consumerId, null);
+ }
+
+ public Either<ConsumerDefinition, ResponseFormat> deleteConsumer(String consumerId, User user) {
+ ConsumerDefinition tmpConsumer = new ConsumerDefinition();
+ tmpConsumer.setConsumerName(consumerId);
+ Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS);
+ if (userValidation.isRight()) {
+ return Either.right(userValidation.right().value());
+ }
+ user = userValidation.left().value();
+ Either<ConsumerData, StorageOperationStatus> deleteResult = consumerOperation.deleteCredentials(consumerId);
+ if (deleteResult.isRight()) {
+ ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value());
+ ResponseFormat responseFormat;
+ if (action == ActionStatus.ECOMP_USER_NOT_FOUND) {
+ responseFormat = componentsUtils.getResponseFormat(action, consumerId);
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(action);
+ }
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user);
+ return Either.right(responseFormat);
+ }
+ ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
+ return Either.left(consumer);
+ }
+
+ public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer, User modifier, boolean isCreateRequest) {
+ Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer));
+ if (updateResult.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
+ return Either.right(responseFormat);
+ }
+ consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition());
+ return Either.left(consumer);
+ }
+
+ private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) {
+ if (consumer.getConsumerDetailsLastupdatedtime() != null) {
+ log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application");
+ }
+ if (consumer.getConsumerLastAuthenticationTime() != null) {
+ log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application");
+ }
+ if (consumer.getLastModfierAtuid() != null) {
+ log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application");
+ }
+ }
}
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 53dceb8112..6fbc22454d 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
@@ -20,19 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Properties;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -44,35 +32,40 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
public class CsarValidationUtils {
- private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(CsarValidationUtils.class);
- private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version";
+ private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version";
- private static final String CSAR_VERSION = "CSAR-Version";
+ private static final String CSAR_VERSION = "CSAR-Version";
- private static final String CREATED_BY = "Created-By";
+ private static final String CREATED_BY = "Created-By";
- private static final String NEW_LINE_DELM = "\n";
+ private static final String NEW_LINE_DELM = "\n";
- //public final static String TOSCA_METADATA_FILE = "TOSCA-Metadata/TOSCA.meta";
- public final static String TOSCA_METADATA = "TOSCA-Metadata";
- public final static String TOSCA_FILE = "TOSCA.meta";
- public final static String DEL_PATTERN = "([/\\\\]+)";
- public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
- // Artifact Group (i.e Deployment/Informational)
- DEL_PATTERN + TOSCA_FILE;
+ public final static String TOSCA_METADATA = "TOSCA-Metadata";
+ public final static String TOSCA_FILE = "TOSCA.meta";
+ public final static String DEL_PATTERN = "([/\\\\]+)";
+ public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
+ // Artifact Group (i.e Deployment/Informational)
+ DEL_PATTERN + TOSCA_FILE;
- public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
+ public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
- private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
+ private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
- public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta";
+ public final static String ARTIFACTS_METADATA_FILE = "HEAT.meta";
- public static final String TOSCA_CSAR_EXTENSION = ".csar";
+ public static final String TOSCA_CSAR_EXTENSION = ".csar";
/**
* Validates Csar
* @param csar
@@ -80,275 +73,269 @@ public class CsarValidationUtils {
* @param componentsUtils
* @return
*/
- public static Either<Boolean, ResponseFormat> validateCsar(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
- Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
- if (validateStatus.isRight()) {
- return Either.right(validateStatus.right().value());
- }
-
- removeNonUniqueArtifactsFromCsar(csar);
-
- log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID);
- validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
- if (validateStatus.isRight()) {
- return Either.right(validateStatus.right().value());
- }
- return Either.left(true);
- }
-
- private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) {
-
- List<String> nonUniqueArtifactsToRemove = new ArrayList<>();
- String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]);
- int numberOfArtifacts = paths.length;
- for(int i = 0; i < numberOfArtifacts; ++i ){
- collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
- }
- nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path));
- }
-
- private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
-
- String[] parsedPath = paths[currInd].split("/");
- String[] otherParsedPath;
- int artifactNameInd = parsedPath.length - 1;
- for(int j = currInd + 1; j < numberOfArtifacts; ++j ){
- otherParsedPath = paths[j].split("/");
- if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){
- log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
- parsedPath[artifactNameInd], paths[currInd], paths[j]);
- nonUniqueArtifactsToRemove.add(paths[j]);
- }
- }
- }
-
- private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) {
- boolean isEqualArtifactNames = false;
- int artifactNameInd = parsedPath.length - 1;
- int artifactGroupTypeInd = parsedPath.length - 3;
- String groupType = parsedPath[artifactGroupTypeInd];
- String artifactName = parsedPath[artifactNameInd];
- String otherGroupType = otherParsedPath[artifactGroupTypeInd];
- String otherArtifactName = otherParsedPath[artifactNameInd];
- String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null;
-
- if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){
- isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]);
- }
- return isEqualArtifactNames;
- }
-
- public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
- Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
- if (validateStatus.isRight()) {
- return Either.right(validateStatus.right().value());
- }
- Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
- Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
- byte[] toscaMetaBytes = csar.get(keyOp.get());
- Properties props = new Properties();
- try {
- //props.load(new ByteArrayInputStream(toscaMetaBytes));
- String propStr = new String(toscaMetaBytes);
- props.load(new StringReader(propStr.replace("\\","\\\\")));
- } catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
-
- String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS);
- String[] ops = yamlFileName.split(DEL_PATTERN);
- List<String> list = Arrays.asList(ops);
- String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN));
- keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
- log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
- }
-
- log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID);
- byte[] yamlFileBytes = csar.get(yamlFileName);
- if (yamlFileBytes == null) {
- log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
- }
-
- String yamlFileContents = new String(yamlFileBytes);
-
- return Either.left(new ImmutablePair<String, String>(yamlFileName, yamlFileContents));
- }
-
- public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
- if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
- log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
- }
-
- log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID);
- byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
- if (artifactsMetaBytes == null) {
- log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
- }
-
- String artifactsFileContents = new String(artifactsMetaBytes);
-
- return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
- }
-
- public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
- if (!csar.containsKey(artifactPath)) {
- log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
- }
-
- log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID);
- byte[] artifactFileBytes = csar.get(artifactPath);
- if (artifactFileBytes == null) {
- log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
- }
-
- return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes));
- }
-
- private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
- Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
- Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
-
- byte[] toscaMetaBytes = csar.get(keyOp.get());
- String toscaMetadata = new String(toscaMetaBytes);
- String[] splited = toscaMetadata.split(NEW_LINE_DELM);
- if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
- /*
- * if(splited.length == TOSCA_METADATA_FIELDS.length){ if(!toscaMetadata.endsWith(NEW_LINE_DELM)){ log. debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}" , csarUUID);
- * BeEcompErrorManager.getInstance(). logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " +csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR); return
- * Either.right(componentsUtils.getResponseFormat(ActionStatus. CSAR_INVALID_FORMAT, csarUUID)); } }
- */
-
- Either<Boolean, ResponseFormat> block_0Status = validateBlock_0(csarUUID, splited, componentsUtils);
- if (block_0Status.isRight()) {
- return Either.right(block_0Status.right().value());
- }
-
- return Either.left(true);
-
- }
-
- private static Either<Boolean, ResponseFormat> validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) {
- int index = 0;
- for (String toscaField : TOSCA_METADATA_FIELDS) {
-
- Properties props = new Properties();
-
- try {
- props.load(new ByteArrayInputStream(splited[index].getBytes()));
- } catch (IOException e) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
- if (!props.containsKey(toscaField)) {
- log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
- String value = props.getProperty(toscaField);
- if (value == null || value.isEmpty()) {
- log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
-
- // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format
- // validation
- if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) {
- if (!validateTOSCAMetaProperty(value)) {
- log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
- BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
- }
- }
- index++;
- }
- return Either.left(true);
- }
-
- private static boolean validateTOSCAMetaProperty(String toscaProperty) {
- final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$";
- final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING);
-
- Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty);
- return floatMatcher.matches();
- }
-
- private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
- if (csar == null || csar.isEmpty()) {
- log.debug("Error when fetching csar with ID {}", csarUUID);
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID);
- return Either.right(responseFormat);
- }
-
- Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
- Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if(!keyOp.isPresent()){
-
- 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);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
- }
- byte[] toscaMetaBytes = csar.get(keyOp.get());
- // && 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);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
- }
-
- return Either.left(Boolean.TRUE);
- }
-
- public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils);
- if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) {
- log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID);
- return Either.right(toscaYamlRes.right().value());
- }
-
- String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes());
- return Either.left(newCheckSum);
-
- }
-
- public static boolean isCsarPayloadName(String payloadName) {
- if (payloadName == null)
- return false;
- return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);
- }
+ public static Either<Boolean, ResponseFormat> validateCsar(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+ Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
+ if (validateStatus.isRight()) {
+ return Either.right(validateStatus.right().value());
+ }
+
+ removeNonUniqueArtifactsFromCsar(csar);
+
+ log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID);
+ validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
+ if (validateStatus.isRight()) {
+ return Either.right(validateStatus.right().value());
+ }
+ return Either.left(true);
+ }
+
+ private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) {
+
+ List<String> nonUniqueArtifactsToRemove = new ArrayList<>();
+ String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]);
+ int numberOfArtifacts = paths.length;
+ for(int i = 0; i < numberOfArtifacts; ++i ){
+ collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
+ }
+ nonUniqueArtifactsToRemove.stream().forEach(path->csar.remove(path));
+ }
+
+ private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
+
+ String[] parsedPath = paths[currInd].split("/");
+ String[] otherParsedPath;
+ int artifactNameInd = parsedPath.length - 1;
+ for(int j = currInd + 1; j < numberOfArtifacts; ++j ){
+ otherParsedPath = paths[j].split("/");
+ if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){
+ log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
+ parsedPath[artifactNameInd], paths[currInd], paths[j]);
+ nonUniqueArtifactsToRemove.add(paths[j]);
+ }
+ }
+ }
+
+ private static boolean isEqualArtifactNames(String[] parsedPath, String[] otherParsedPath) {
+ boolean isEqualArtifactNames = false;
+ int artifactNameInd = parsedPath.length - 1;
+ int artifactGroupTypeInd = parsedPath.length - 3;
+ String groupType = parsedPath[artifactGroupTypeInd];
+ String artifactName = parsedPath[artifactNameInd];
+ String otherGroupType = otherParsedPath[artifactGroupTypeInd];
+ String otherArtifactName = otherParsedPath[artifactNameInd];
+ String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null;
+
+ if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){
+ isEqualArtifactNames = vfcToscaName == null ? true : vfcToscaName.equalsIgnoreCase(otherParsedPath[1]);
+ }
+ return isEqualArtifactNames;
+ }
+
+ public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+ Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
+ if (validateStatus.isRight()) {
+ return Either.right(validateStatus.right().value());
+ }
+ Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
+ Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
+ if(!keyOp.isPresent()){
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+ byte[] toscaMetaBytes = csar.get(keyOp.get());
+ Properties props = new Properties();
+ try {
+ String propStr = new String(toscaMetaBytes);
+ props.load(new StringReader(propStr.replace("\\","\\\\")));
+ } catch (IOException e) {
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+
+ String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS);
+ String[] ops = yamlFileName.split(DEL_PATTERN);
+ List<String> list = Arrays.asList(ops);
+ String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN));
+ keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny();
+ if(!keyOp.isPresent()){
+ log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
+ }
+
+ log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID);
+ byte[] yamlFileBytes = csar.get(yamlFileName);
+ if (yamlFileBytes == null) {
+ log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + yamlFileName + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
+ }
+
+ String yamlFileContents = new String(yamlFileBytes);
+
+ return Either.left(new ImmutablePair<String, String>(yamlFileName, yamlFileContents));
+ }
+
+ public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+
+ if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
+ log.debug("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
+ }
+
+ log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID);
+ byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
+ if (artifactsMetaBytes == null) {
+ log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
+ }
+
+ String artifactsFileContents = new String(artifactsMetaBytes);
+
+ return Either.left(new ImmutablePair<String, String>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
+ }
+
+ public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactsContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
+ if (!csar.containsKey(artifactPath)) {
+ log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions entry not found in TOSCA-Metadata/TOSCA.meta file in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
+ }
+
+ log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID);
+ byte[] artifactFileBytes = csar.get(artifactPath);
+ if (artifactFileBytes == null) {
+ log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("Entry-Definitions " + artifactPath + " file not found in CSAR with id " + csarUUID, "CSAR structure is invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
+ }
+
+ return Either.left(new ImmutablePair<String, byte[]>(artifactName, artifactFileBytes));
+ }
+
+ private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+
+ Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
+ Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
+ if(!keyOp.isPresent()){
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+
+ byte[] toscaMetaBytes = csar.get(keyOp.get());
+ String toscaMetadata = new String(toscaMetaBytes);
+ String[] splited = toscaMetadata.split(NEW_LINE_DELM);
+ if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) {
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+
+ Either<Boolean, ResponseFormat> block_0Status = validateBlock_0(csarUUID, splited, componentsUtils);
+ if (block_0Status.isRight()) {
+ return Either.right(block_0Status.right().value());
+ }
+
+ return Either.left(true);
+
+ }
+
+ private static Either<Boolean, ResponseFormat> validateBlock_0(String csarUUID, String[] splited, ComponentsUtils componentsUtils) {
+ int index = 0;
+ for (String toscaField : TOSCA_METADATA_FIELDS) {
+
+ Properties props = new Properties();
+
+ try {
+ props.load(new ByteArrayInputStream(splited[index].getBytes()));
+ } catch (IOException e) {
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID, e);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+ if (!props.containsKey(toscaField)) {
+ log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+ String value = props.getProperty(toscaField);
+ if (value == null || value.isEmpty()) {
+ log.debug("TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+
+ // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format
+ // validation
+ if (toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) {
+ if (!validateTOSCAMetaProperty(value)) {
+ log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
+ BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not in expected key-value form in CSAR with id " + csarUUID, "CSAR internals are invalid", ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
+ }
+ }
+ index++;
+ }
+ return Either.left(true);
+ }
+
+ private static boolean validateTOSCAMetaProperty(String toscaProperty) {
+ final String FLOAT_STRING = "^\\d{1}[.]\\d{1}$";
+ final Pattern FLOAT_PATTERN = Pattern.compile(FLOAT_STRING);
+
+ Matcher floatMatcher = FLOAT_PATTERN.matcher(toscaProperty);
+ return floatMatcher.matches();
+ }
+
+ private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+ if (csar == null || csar.isEmpty()) {
+ log.debug("Error when fetching csar with ID {}", csarUUID);
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID);
+ return Either.right(responseFormat);
+ }
+
+ Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
+ Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
+ if(!keyOp.isPresent()){
+
+ 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);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
+ }
+ byte[] toscaMetaBytes = csar.get(keyOp.get());
+ // && 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);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
+ }
+
+ return Either.left(Boolean.TRUE);
+ }
+
+ public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+
+ Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils);
+ if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) {
+ log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID);
+ return Either.right(toscaYamlRes.right().value());
+ }
+
+ String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes());
+ return Either.left(newCheckSum);
+
+ }
+
+ public static boolean isCsarPayloadName(String payloadName) {
+ if (payloadName == null)
+ return false;
+ return payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
index e5fba0dff5..aa5cb4e2ba 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
@@ -20,16 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -45,211 +36,214 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
@Component("dataTypeImportManager")
public class DataTypeImportManager {
- public static void main(String[] args) {
-
- List<PropertyDefinition> properties = new ArrayList<>();
- PropertyDefinition propertyDefintion = new PropertyDefinition();
- propertyDefintion.setName("aaa");
- properties.add(propertyDefintion);
-
- List<String> allParentsProps = new ArrayList<>();
- allParentsProps.add("aaa");
- allParentsProps.add("bbb");
-
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- System.out.println(alreadyExistPropsCollection);
-
- }
-
- private static Logger log = LoggerFactory.getLogger(DataTypeImportManager.class.getName());
- @Resource
- private PropertyOperation propertyOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private CommonImportManager commonImportManager;
-
- public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) {
- return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType);
- }
-
- private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) {
-
- return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData));
-
- }
-
- private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) {
-
- return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()),
- dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
- }
-
- private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
-
- String dataTypeName = dataType.getName();
- List<PropertyDefinition> properties = dataType.getProperties();
- if (properties == null) {
- // At least one parameter should be defined either in the properties
- // section or at one of the parents
- String derivedDataType = dataType.getDerivedFromName();
- // If there are no properties, then we can create a data type if it
- // is an abstract one or it derives from non abstract data type
- if ((derivedDataType == null || derivedDataType.isEmpty())) {
- if (false == isAbstract(dataType.getName())) {
- if (false == ToscaPropertyType.isScalarType(dataTypeName)) {
- log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
- } else {
- // if it is not a scalar data type and it derives from abstract
- // data type, we should reject the request.
- if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) {
- log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
- } else {
- // properties tag cannot be empty
- if (properties.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
-
- return Either.right(responseFormat);
- }
-
- // check no duplicates
- Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
- if (collect != null) {
- if (properties.size() != collect.size()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
-
- List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
- if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
- log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
-
- return Either.right(responseFormat);
- }
- }
-
- String derivedDataType = dataType.getDerivedFromName();
- if (derivedDataType != null) {
- Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
- if (derivedDataTypeByName.isRight()) {
- StorageOperationStatus status = derivedDataTypeByName.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
-
- return Either.right(responseFormat);
- } else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
-
- return Either.right(responseFormat);
-
- }
- } else {
-
- DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
- if (properties != null && properties.isEmpty() == false) {
-
- if (true == isScalarType(derivedDataTypeDef)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
-
- return Either.right(responseFormat);
- }
-
- Set<String> allParentsProps = new HashSet<>();
- do {
- List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
- if (currentParentsProps != null) {
- for (PropertyDefinition propertyDefinition : currentParentsProps) {
- allParentsProps.add(propertyDefinition.getName());
- }
- }
- derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
- } while (derivedDataTypeDef != null);
-
- // Check that no property is already defined in one of the
- // ancestors
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
- List<String> duplicateProps = new ArrayList<>();
- duplicateProps.addAll(alreadyExistPropsCollection);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
-
- return Either.right(responseFormat);
- }
-
- }
- }
- }
- return Either.left(ActionStatus.OK);
- }
-
- private boolean isAbstract(String dataTypeName) {
-
- ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
- return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
-
- }
-
- private boolean isScalarType(DataTypeDefinition dataTypeDef) {
-
- boolean isScalar = false;
- DataTypeDefinition dataType = dataTypeDef;
-
- while (dataType != null) {
-
- String name = dataType.getName();
- if (ToscaPropertyType.isScalarType(name)) {
- isScalar = true;
- break;
- }
+ public static void main(String[] args) {
+
+ List<PropertyDefinition> properties = new ArrayList<>();
+ PropertyDefinition propertyDefintion = new PropertyDefinition();
+ propertyDefintion.setName("aaa");
+ properties.add(propertyDefintion);
+
+ List<String> allParentsProps = new ArrayList<>();
+ allParentsProps.add("aaa");
+ allParentsProps.add("bbb");
+
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
+ System.out.println(alreadyExistPropsCollection);
+
+ }
+
+ private static final Logger log = LoggerFactory.getLogger(DataTypeImportManager.class);
+ @Resource
+ private PropertyOperation propertyOperation;
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Resource
+ private CommonImportManager commonImportManager;
+
+ public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) {
+ return commonImportManager.createElementTypes(dataTypeYml, elementTypeYml -> createDataTypesFromYml(elementTypeYml), elementTypesList -> createDataTypesByDao(elementTypesList), ElementTypeEnum.DataType);
+ }
+
+ private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) {
+
+ return commonImportManager.createElementTypesFromYml(dataTypesYml, (dataTypeName, dataTypeJsonData) -> createDataType(dataTypeName, dataTypeJsonData));
+
+ }
+
+ private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) {
+
+ return commonImportManager.createElementTypesByDao(dataTypesToCreate, dataType -> validateDataType(dataType), dataType -> new ImmutablePair<>(ElementTypeEnum.DataType, dataType.getName()),
+ dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
+ }
+
+ private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
+
+ String dataTypeName = dataType.getName();
+ List<PropertyDefinition> properties = dataType.getProperties();
+ if (properties == null) {
+ // At least one parameter should be defined either in the properties
+ // section or at one of the parents
+ String derivedDataType = dataType.getDerivedFromName();
+ // If there are no properties, then we can create a data type if it
+ // is an abstract one or it derives from non abstract data type
+ if (derivedDataType == null || derivedDataType.isEmpty()) {
+ if (!isAbstract(dataType.getName()) && !ToscaPropertyType.isScalarType(dataTypeName)) {
+ log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+ return Either.right(responseFormat);
+ }
+ } else {
+ // if it is not a scalar data type and it derives from abstract
+ // data type, we should reject the request.
+ if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) {
+ log.debug("Data type {} which derived from abstract data type must have at least one property", dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+ return Either.right(responseFormat);
+ }
+ }
+ } else {
+ // properties tag cannot be empty
+ if (properties.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+
+ // check no duplicates
+ Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
+ if (collect != null) {
+ if (properties.size() != collect.size()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+ }
+
+ List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
+ if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
+ log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
+
+ return Either.right(responseFormat);
+ }
+ }
+
+ String derivedDataType = dataType.getDerivedFromName();
+ if (derivedDataType != null) {
+ Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
+ if (derivedDataTypeByName.isRight()) {
+ StorageOperationStatus status = derivedDataTypeByName.right().value();
+ if (status == StorageOperationStatus.NOT_FOUND) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
+
+ return Either.right(responseFormat);
+ } else {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
+
+ return Either.right(responseFormat);
+
+ }
+ } else {
+
+ DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
+ if (properties != null && properties.isEmpty() == false) {
+
+ if (true == isScalarType(derivedDataTypeDef)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
+
+ return Either.right(responseFormat);
+ }
+
+ Set<String> allParentsProps = new HashSet<>();
+ do {
+ List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
+ if (currentParentsProps != null) {
+ for (PropertyDefinition propertyDefinition : currentParentsProps) {
+ allParentsProps.add(propertyDefinition.getName());
+ }
+ }
+ derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
+ } while (derivedDataTypeDef != null);
+
+ // Check that no property is already defined in one of the
+ // ancestors
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
+ if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
+ List<String> duplicateProps = new ArrayList<>();
+ duplicateProps.addAll(alreadyExistPropsCollection);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
+
+ return Either.right(responseFormat);
+ }
+
+ }
+ }
+ }
+ return Either.left(ActionStatus.OK);
+ }
+
+ private boolean isAbstract(String dataTypeName) {
+
+ ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
+
+ return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
+
+ }
+
+ private boolean isScalarType(DataTypeDefinition dataTypeDef) {
+
+ boolean isScalar = false;
+ DataTypeDefinition dataType = dataTypeDef;
+
+ while (dataType != null) {
+
+ String name = dataType.getName();
+ if (ToscaPropertyType.isScalarType(name)) {
+ isScalar = true;
+ break;
+ }
- dataType = dataType.getDerivedFrom();
- }
+ dataType = dataType.getDerivedFrom();
+ }
- return isScalar;
- }
+ return isScalar;
+ }
- private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) {
- DataTypeDefinition dataType = new DataTypeDefinition();
+ private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) {
+ DataTypeDefinition dataType = new DataTypeDefinition();
- dataType.setName(dataTypeName);
+ dataType.setName(dataTypeName);
- if (toscaJson != null) {
- // Description
- final Consumer<String> descriptionSetter = description -> dataType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
- // Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
- // Properties
- commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values));
+ if (toscaJson != null) {
+ // Description
+ final Consumer<String> descriptionSetter = description -> dataType.setDescription(description);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
+ // Derived From
+ final Consumer<String> derivedFromSetter = derivedFrom -> dataType.setDerivedFromName(derivedFrom);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
+ // Properties
+ commonImportManager.setProperties(toscaJson, (values) -> dataType.setProperties(values));
- setConstraints(toscaJson, dataType);
- }
- return dataType;
- }
+ setConstraints(toscaJson, dataType);
+ }
+ return dataType;
+ }
- private void setConstraints(Map<String, Object> toscaJson, DataTypeDefinition dataType) {
- // TODO Auto-generated method stub
+ private void setConstraints(Map<String, Object> toscaJson, DataTypeDefinition dataType) {
+ // TODO Auto-generated method stub
- }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
index be3ac13cc9..5469d79653 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
@@ -20,12 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import fj.data.Either;
import org.apache.http.HttpStatus;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
@@ -46,172 +41,170 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.*;
@Component("distributionMonitoringBusinessLogic")
public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
- private static final String DEPLOYED = "Deployed";
-
- private static final String ERROR = "Error";
-
- private static final String DISTRIBUTED = "Distributed";
-
- private static final String IN_PROGRESS = "In Progress";
-
- private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
-
- // @javax.annotation.Resource
- // private AuditingDao auditingDao;
-
- @Autowired
- private AuditCassandraDao cassandraDao;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
- public DistributionMonitoringBusinessLogic() {
- }
-
- public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Status", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- log.trace("getListOfDistributionStatus for did {}", did);
- Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did);
- if (distributionStatus.isRight()) {
- log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value());
- return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did));
- }
- List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<DistributionStatusInfo>();
- List<DistributionStatusEvent> distributionStatusEventList = distributionStatus.left().value();
- if (distributionStatusEventList != null) {
- for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) {
- distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent));
- }
- }
-
- DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse();
- distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList);
- log.trace("list statuses for did {} is {} ", did, distribStatusInfoList);
- return Either.left(distributionStatusListResponse);
- }
-
- public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Service Status", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid);
- Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid);
- if (status.isRight()) {
- log.debug("failed to find service distribution statuses. error: {}", status);
- return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid));
- }
- List<DistributionStatusOfServiceInfo> distribStatusInfoList = new ArrayList<DistributionStatusOfServiceInfo>();
- List<? extends AuditingGenericEvent> distributionStatusEventList = status.left().value();
- distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList);
- DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce();
- distributionStatusListResponse.setDistributionStatusOfServiceList(distribStatusInfoList);
- return Either.left(distributionStatusListResponse);
- }
-
- private List<DistributionStatusOfServiceInfo> handleAuditingDaoResponse(List<? extends AuditingGenericEvent> distribStatusInfoList) {
- List<DistributionStatusOfServiceInfo> reslist = new ArrayList<DistributionStatusOfServiceInfo>();
- Map<String, List<AuditingGenericEvent>> serviceDidMap = createServiceDidMap(distribStatusInfoList);
- Set<String> didSet = serviceDidMap.keySet();
- for (String did : didSet) {
- DistributionStatusOfServiceInfo distributionStatusOfServiceInfo = new DistributionStatusOfServiceInfo();
- distributionStatusOfServiceInfo.setDistributionID(did);
- String dReguestStatus = "";
- String dNotifyStatus = "";
- boolean isResult = false;
- List<? extends AuditingGenericEvent> auditingGenericEventList = serviceDidMap.get(did);
- ESTimeBasedEvent resAuditingGenericEvent = null;
- for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) {
- auditingGenericEvent.fillFields();
-
- String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName());
- Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName());
- if (modifierUserId != null) {
- distributionStatusOfServiceInfo.setUserId((String) modifierUserId);
- }
-
- if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) {
-
- isResult = true;
- resAuditingGenericEvent = auditingGenericEvent;
- break;
- } else if (action.equals(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName())) {
- dReguestStatus = getStatusFromAuditEvent(auditingGenericEvent);
- } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) {
- dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent);
- }
-
- resAuditingGenericEvent = auditingGenericEvent;
-
- }
- distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName()));
-
- if (!isResult) {
- if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
- if (dNotifyStatus.isEmpty()) {
- distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS);
-
- } else {
- if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK)))
- distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED);
- else
- distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
- }
- } else
- distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
- } else
- distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED);
- reslist.add(distributionStatusOfServiceInfo);
- }
-
- return reslist;
- }
-
- private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) {
- String status = "";
- Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());
- if (requestStatus instanceof String) {
- status = (String) requestStatus;
- }
- return status;
- }
-
- private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) {
-
- Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<String, List<AuditingGenericEvent>>();
- for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) {
- List<AuditingGenericEvent> auditingGenericEventList = null;
- String did = "";
- auditingGenericEvent.fillFields();
-
- Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName());
- if (didValue != null) {
- did = (String) didValue;
- }
-
- if (!did.isEmpty()) {
- if (serviceDidMap.containsKey(did)) {
- auditingGenericEventList = serviceDidMap.get(did);
- }
- if (auditingGenericEventList == null) {
- auditingGenericEventList = new ArrayList();
-
- }
- auditingGenericEventList.add(auditingGenericEvent);
- serviceDidMap.put(did, auditingGenericEventList);
- }
- }
- return serviceDidMap;
- }
+ private static final String DEPLOYED = "Deployed";
+
+ private static final String ERROR = "Error";
+
+ private static final String DISTRIBUTED = "Distributed";
+
+ private static final String IN_PROGRESS = "In Progress";
+
+ private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
+
+
+ @Autowired
+ private AuditCassandraDao cassandraDao;
+
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
+
+ public DistributionMonitoringBusinessLogic() {
+ }
+
+ public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Status", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ log.trace("getListOfDistributionStatus for did {}", did);
+ Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did);
+ if (distributionStatus.isRight()) {
+ log.debug("not found distribution statuses for did {} status is {} ", did, distributionStatus.right().value());
+ return Either.right(componentsUtils.getResponseFormat(distributionStatus.right().value(), did));
+ }
+ List<DistributionStatusInfo> distribStatusInfoList = new ArrayList<DistributionStatusInfo>();
+ List<DistributionStatusEvent> distributionStatusEventList = distributionStatus.left().value();
+ if (distributionStatusEventList != null) {
+ for (ESTimeBasedEvent distributionStatusEvent : distributionStatusEventList) {
+ distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent));
+ }
+ }
+
+ DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse();
+ distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList);
+ log.trace("list statuses for did {} is {} ", did, distribStatusInfoList);
+ return Either.left(distributionStatusListResponse);
+ }
+
+ public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get List Of Distribution Service Status", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid);
+ Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid);
+ if (status.isRight()) {
+ log.debug("failed to find service distribution statuses. error: {}", status);
+ return Either.right(componentsUtils.getResponseFormat(status.right().value(), serviceUuid));
+ }
+ List<DistributionStatusOfServiceInfo> distribStatusInfoList = new ArrayList<DistributionStatusOfServiceInfo>();
+ List<? extends AuditingGenericEvent> distributionStatusEventList = status.left().value();
+ distribStatusInfoList = handleAuditingDaoResponse(distributionStatusEventList);
+ DistributionStatusOfServiceListResponce distributionStatusListResponse = new DistributionStatusOfServiceListResponce();
+ distributionStatusListResponse.setDistributionStatusOfServiceList(distribStatusInfoList);
+ return Either.left(distributionStatusListResponse);
+ }
+
+ private List<DistributionStatusOfServiceInfo> handleAuditingDaoResponse(List<? extends AuditingGenericEvent> distribStatusInfoList) {
+ List<DistributionStatusOfServiceInfo> reslist = new ArrayList<DistributionStatusOfServiceInfo>();
+ Map<String, List<AuditingGenericEvent>> serviceDidMap = createServiceDidMap(distribStatusInfoList);
+ Set<String> didSet = serviceDidMap.keySet();
+ for (String did : didSet) {
+ DistributionStatusOfServiceInfo distributionStatusOfServiceInfo = new DistributionStatusOfServiceInfo();
+ distributionStatusOfServiceInfo.setDistributionID(did);
+ String dReguestStatus = "";
+ String dNotifyStatus = "";
+ boolean isResult = false;
+ List<? extends AuditingGenericEvent> auditingGenericEventList = serviceDidMap.get(did);
+ ESTimeBasedEvent resAuditingGenericEvent = null;
+ for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) {
+ auditingGenericEvent.fillFields();
+
+ String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName());
+ Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName());
+ if (modifierUserId != null) {
+ distributionStatusOfServiceInfo.setUserId((String) modifierUserId);
+ }
+
+ if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) {
+
+ isResult = true;
+ resAuditingGenericEvent = auditingGenericEvent;
+ break;
+ } else if (action.equals(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName())) {
+ dReguestStatus = getStatusFromAuditEvent(auditingGenericEvent);
+ } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) {
+ dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent);
+ }
+
+ resAuditingGenericEvent = auditingGenericEvent;
+
+ }
+ distributionStatusOfServiceInfo.setTimestamp((String) resAuditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName()));
+
+ if (!isResult) {
+ if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
+ if (dNotifyStatus.isEmpty()) {
+ distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS);
+
+ } else {
+ if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK)))
+ distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED);
+ else
+ distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
+ }
+ } else
+ distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
+ } else
+ distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED);
+ reslist.add(distributionStatusOfServiceInfo);
+ }
+
+ return reslist;
+ }
+
+ private String getStatusFromAuditEvent(ESTimeBasedEvent auditingGenericEvent) {
+ String status = "";
+ Object requestStatus = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());
+ if (requestStatus instanceof String) {
+ status = (String) requestStatus;
+ }
+ return status;
+ }
+
+ private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) {
+
+ Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<String, List<AuditingGenericEvent>>();
+ for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) {
+ List<AuditingGenericEvent> auditingGenericEventList = null;
+ String did = "";
+ auditingGenericEvent.fillFields();
+
+ Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName());
+ if (didValue != null) {
+ did = (String) didValue;
+ }
+
+ if (!did.isEmpty()) {
+ if (serviceDidMap.containsKey(did)) {
+ auditingGenericEventList = serviceDidMap.get(did);
+ }
+ if (auditingGenericEventList == null) {
+ auditingGenericEventList = new ArrayList();
+
+ }
+ auditingGenericEventList.add(auditingGenericEvent);
+ serviceDidMap.put(did, auditingGenericEventList);
+ }
+ }
+ return serviceDidMap;
+ }
}
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 54bed5ae56..ac72c98252 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
@@ -20,20 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
@@ -54,7 +41,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ArtifactType;
@@ -65,10 +51,10 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Product;
import org.openecomp.sdc.be.model.PropertyScope;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.Tag;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
@@ -91,1328 +77,1297 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.thinkaurelius.titan.core.TitanGraph;
-
-import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("elementsBusinessLogic")
public class ElementBusinessLogic extends BaseBusinessLogic {
- private static Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class.getName());
-
- @javax.annotation.Resource
- private IElementOperation elementOperation;
-
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
-
- @javax.annotation.Resource
- private UserBusinessLogic userAdminManager;
-
- /**
- *
- * @param user
- * @return
- */
- public Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowed(User user) {
- // Used for not getting duplicated followed. Cheaper than checking ArrayList.contains
- Either<Map<String, Set<? extends Component>>, ResponseFormat> response = null;
- // Used for returning as the code requires.
- Either<Map<String, List<? extends Component>>, ResponseFormat> arrayResponse = null;
-
- // Getting the role
- String role = user.getRole();
- String userId = null;
- Role currentRole = Role.valueOf(role);
-
- switch (currentRole) {
- case DESIGNER:
- userId = user.getUserId();
- response = handleDesigner(userId);
- break;
-
- case TESTER:
- userId = user.getUserId();
- response = handleTester(userId);
- break;
-
- case GOVERNOR:
- userId = user.getUserId();
- response = handleGovernor(userId);
- break;
-
- case OPS:
- userId = user.getUserId();
- response = handleOps(userId);
- break;
-
- case PRODUCT_STRATEGIST:
- userId = user.getUserId();
- response = handleProductStrategist(userId);
- break;
-
- case PRODUCT_MANAGER:
- userId = user.getUserId();
- response = handleProductManager(userId);
- break;
-
- case ADMIN:
- response = handleAdmin();
- break;
-
- default:
- response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- break;
- }
- //converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice)
- return convertedToListResponse(response);
-
- }
-
- private Either<Map<String,List<? extends Component>>,ResponseFormat> convertedToListResponse(Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) {
-
- Map<String, List<? extends Component>> arrayResponse = new HashMap<>();
- if (setResponse.isLeft()) {
- for (Map.Entry<String, Set<? extends Component>> entry : setResponse.left().value().entrySet()) {
- arrayResponse.put(entry.getKey(), (new ArrayList(new HashSet(entry.getValue()))));
- }
- return Either.left(arrayResponse);
- }
- return Either.right(setResponse.right().value());
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleAdmin() {
- Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
- // userId should stay null
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
- lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
- response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates);
- return response;
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleDesigner(String userId) {
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
- Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
- lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
- // more states
- lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates);
- return response;
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor(String userId) {
- Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(null);
- return result;
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist(String userId) {
- // Should be empty list according to Ella, 13/03/16
- Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>();
- result.put("products", new HashSet<>());
- return Either.left(result);
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductManager(String userId) {
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
- Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
- lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
- // more states
- lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- response = getFollowedProducts(userId, lifecycleStates, lastStateStates);
- return response;
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps(String userId) {
- Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>();
- distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED);
- distStatus.add(DistributionStatusEnum.DISTRIBUTED);
-
- Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus);
- return result;
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) {
-
- Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus);
- if (services.isLeft()) {
- Map<String, Set<? extends Component>> result = new HashMap<>();
- Set<Service> set = new HashSet<>();
- set.addAll(services.left().value());
- result.put("services", set);
- return Either.left(result);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
- }
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester(String userId) {
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<Map<String, Set<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null);
-
- return result;
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
-
- try {
- Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
-
- if (resources.isLeft()) {
- Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
- if (services.isLeft()) {
- Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>();
- result.put("services", services.left().value());
- result.put("resources", resources.left().value());
- return Either.left(result);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
- }
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
- }
- } finally {
- titanDao.commit();
- }
- }
-
- private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
- Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
- if (products.isLeft()) {
- Map<String, Set<? extends Component>> result = new HashMap<>();
- result.put("products", products.left().value());
- return Either.left(result);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(products.right().value())));
- }
- }
-
- /*
- * New categories flow - start
- */
- public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() {
- return elementOperation.getAllResourceCategories();
- }
-
- public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() {
- return elementOperation.getAllServiceCategories();
- }
-
- public Either<CategoryDefinition, ResponseFormat> createCategory(CategoryDefinition category, String componentTypeParamName, String userId) {
-
- AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
- String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue());
- CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY;
-
- User user = new User();
- Either<User, ResponseFormat> validateUser = validateUser(userId);
- if (validateUser.isRight()) {
- log.debug("Validation of user failed, userId {}", userId);
- ResponseFormat responseFormat = validateUser.right().value();
- user = new User();
- user.setUserId(userId);
- String currCategoryName = (category == null ? null : category.getName());
- handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- user = validateUser.left().value();
-
- if (category == null) {
- log.debug("Category json is invalid");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- String categoryName = category.getName();
- // For auditing of failures we need the original non-normalized name
- String origCategoryName = categoryName;
- if (componentTypeEnum == null) {
- log.debug("Component type {} is invalid", componentTypeParamName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
- if (validateUserRole.isRight()) {
- log.debug("Validation of user role failed, userId {}", userId);
- ResponseFormat responseFormat = validateUserRole.right().value();
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) {
- log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName);
-
- if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) {
- log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- category.setName(categoryName);
-
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName);
- category.setNormalizedName(normalizedName);
-
- NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType);
-
- Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName);
- if (categoryUniqueEither.isRight()) {
- log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(categoryUniqueEither.right().value());
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Boolean isCategoryUnique = categoryUniqueEither.left().value();
- if (!isCategoryUnique) {
- log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Either<CategoryDefinition, ActionStatus> createCategoryByType = elementOperation.createCategory(category, nodeType);
- if (createCategoryByType.isRight()) {
- log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
- handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
- return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value()));
- }
- category = createCategoryByType.left().value();
- log.debug("Created category for component {}, name {}, uniqueId {}", componentType, categoryName, category.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- handleCategoryAuditing(responseFormat, user, category.getName(), auditingAction, componentType);
- return Either.left(category);
- }
-
- public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) {
-
- AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
- String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue());
- CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY;
- // For auditing
- String parentCategoryName = parentCategoryId;
-
- if (subCategory == null) {
- log.debug("Sub-category json is invalid");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- String subCategoryName = subCategory.getName();
- // For auditing of failures we need the original non-normalized name
- String origSubCategoryName = subCategoryName;
-
- User user = new User();
- Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false);
- if (validateUser.isRight()) {
- log.debug("Validation of user failed, userId {}", userId);
- ResponseFormat responseFormat = validateUser.right().value();
- user = new User();
- user.setUserId(userId);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- user = validateUser.left().value();
-
- if (componentTypeEnum == null) {
- log.debug("Component type {} is invalid", componentTypeParamName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
- if (validateComponentType.isRight()) {
- log.debug("Validation of component type for sub-category failed");
- ResponseFormat responseFormat = validateComponentType.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
- if (validateUserRole.isRight()) {
- log.debug("Validation of user role failed, userId {}", userId);
- ResponseFormat responseFormat = validateUserRole.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
- NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
-
- CategoryDefinition categoryDefinition;
- Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum);
- if (validateCategoryExists.isRight()) {
- log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId);
- ResponseFormat responseFormat = validateCategoryExists.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- categoryDefinition = validateCategoryExists.left().value();
- parentCategoryName = categoryDefinition.getName();
-
- if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) {
- log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName);
-
- if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) {
- log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName);
- subCategory.setNormalizedName(normalizedName);
-
- // Uniqueness under this category
- Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId);
- if (subCategoryUniqueForCategory.isRight()) {
- log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Boolean isSubUnique = subCategoryUniqueForCategory.left().value();
- if (!isSubUnique) {
- log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- // Setting name of subcategory to fit the similar subcategory name
- // ignoring cases.
- // For example if Network-->kUKU exists for service category Network,
- // and user is trying to create Router-->Kuku for service category
- // Router,
- // his subcategory name will be Router-->kUKU.
- Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName);
- if (subCategoryUniqueForType.isRight()) {
- log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
- SubCategoryDefinition subCategoryDefinition = subCategoryUniqueForType.left().value();
- if (subCategoryDefinition != null) {
- subCategoryName = subCategoryDefinition.getName();
- }
-
- subCategory.setName(subCategoryName);
- ///////////////////////////////////////////// Validations end
-
- Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType);
- if (createSubCategory.isRight()) {
- log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- SubCategoryDefinition subCategoryCreated = createSubCategory.left().value();
- log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, subCategoryCreated.getName(), auditingAction, componentType);
- return Either.left(subCategoryCreated);
- }
-
- public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) {
-
- AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING;
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
- String componentType = (componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue());
- CategoryTypeEnum categoryType = CategoryTypeEnum.GROUPING;
- // For auditing
- String parentCategoryName = grandParentCategoryId;
- String parentSubCategoryName = parentSubCategoryId;
-
- User user;
- Either<User, ResponseFormat> validateUser = validateUserExists(userId, "create Grouping", false);
- if (validateUser.isRight()) {
- log.debug("Validation of user failed, userId {}", userId);
- ResponseFormat responseFormat = validateUser.right().value();
- user = new User();
- user.setUserId(userId);
- String groupingNameForAudit = (grouping == null ? null : grouping.getName());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- user = validateUser.left().value();
-
- if (grouping == null) {
- log.debug("Grouping json is invalid");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- String groupingName = grouping.getName();
- // For auditing of failures we need the original non-normalized name
- String origGroupingName = groupingName;
-
- if (componentTypeEnum == null) {
- log.debug("Component type {} is invalid", componentTypeParamName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
- if (validateComponentType.isRight()) {
- log.debug("Validation of component type for grouping failed");
- ResponseFormat responseFormat = validateComponentType.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
- if (validateUserRole.isRight()) {
- log.debug("Validation of user role failed, userId {}", userId);
- ResponseFormat responseFormat = validateUserRole.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
- NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
- NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
-
- // Validate category
- CategoryDefinition categoryDefinition;
- Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum);
- if (validateCategoryExists.isRight()) {
- log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId);
- ResponseFormat responseFormat = validateCategoryExists.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- categoryDefinition = validateCategoryExists.left().value();
- parentCategoryName = categoryDefinition.getName();
-
- // Validate subcategory
- SubCategoryDefinition subCategoryDefinition;
- Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum);
- if (validateSubCategoryExists.isRight()) {
- log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId);
- ResponseFormat responseFormat = validateSubCategoryExists.right().value();
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- subCategoryDefinition = validateSubCategoryExists.left().value();
- parentSubCategoryName = subCategoryDefinition.getName();
-
- if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) {
- log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName);
-
- if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) {
- log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName);
- grouping.setNormalizedName(normalizedName);
-
- // Uniqueness under this category
- Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId);
- if (groupingUniqueForSubCategory.isRight()) {
- log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value();
- if (!isGroupingUnique) {
- log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- // Setting name of grouping to fit the similar grouping name ignoring
- // cases.
- // For example if Network-->kUKU exists for service sub-category
- // Network, and user is trying to create grouping Router-->Kuku for
- // service sub-category Router,
- // his grouping name will be Router-->kUKU.
- Either<GroupingDefinition, ActionStatus> groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName);
- if (groupingUniqueForType.isRight()) {
- log.debug("Failed validation of whether similar grouping exists, normalizedName {} componentType {}", normalizedName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForType.right().value());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
- GroupingDefinition groupingDefinition = groupingUniqueForType.left().value();
- if (groupingDefinition != null) {
- groupingName = groupingDefinition.getName();
- }
-
- grouping.setName(groupingName);
- ///////////////////////////////////////////// Validations end
-
- Either<GroupingDefinition, ActionStatus> createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType);
- if (createGrouping.isRight()) {
- log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(createGrouping.right().value());
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
- return Either.right(responseFormat);
- }
-
- GroupingDefinition groupingCreated = createGrouping.left().value();
- log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType);
- return Either.left(groupingCreated);
- }
-
- public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) {
- AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
- ResponseFormat responseFormat;
- User user = new User();
- if (userId == null) {
- user.setUserId("UNKNOWN");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
- return Either.right(responseFormat);
- }
-
- Either<User, ResponseFormat> validateUser = validateUserExists(userId, "get All Categories", false);
- if (validateUser.isRight()) {
- user.setUserId(userId);
- log.debug("Validation of user failed, userId {}", userId);
- responseFormat = validateUser.right().value();
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
- return Either.right(responseFormat);
- }
- user = validateUser.left().value();
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- if (componentTypeEnum == null) {
- log.debug("Cannot create category for component type {}", componentType);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type");
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
- return Either.right(responseFormat);
- }
-
- NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
- Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false);
- if (getAllCategoriesByType.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
- return Either.right(responseFormat);
- }
- List<CategoryDefinition> categories = getAllCategoriesByType.left().value();
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
- return Either.left(categories);
- }
-
- public Either<UiCategories, ResponseFormat> getAllCategories(String userId) {
- AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
- ResponseFormat responseFormat;
- UiCategories categories = new UiCategories();
-
- Either<User, ResponseFormat> userResponse = validateUserExists(userId, "get all categories", false);
-
- if (userResponse.isRight()) {
- return Either.right(userResponse.right().value());
- }
- User user = userResponse.left().value();
-
- //GET resource categories
- Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
- if (getResourceCategoriesByType.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
- return Either.right(responseFormat);
- }
- categories.setResourceCategories(getResourceCategoriesByType.left().value());
-
- //GET service categories
- Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
- if (getServiceCategoriesByType.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
- return Either.right(responseFormat);
- }
- categories.setServiceCategories(getServiceCategoriesByType.left().value());
-
- //GET product categories
- Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false);
- if (getProductCategoriesByType.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value());
- componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat);
- return Either.right(responseFormat);
- }
-
- categories.setProductCategories(getProductCategoriesByType.left().value());
- return Either.left(categories);
-
- }
-
- public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Category", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
- if (componentTypeEnum == null) {
- log.debug("Cannot create category for component type {}", componentTypeParamName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
-
- Either<CategoryDefinition, ActionStatus> deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId);
- if (deleteCategoryByType.isRight()) {
- // auditing, logging here...
- return Either.right(componentsUtils.getResponseFormat(deleteCategoryByType.right().value()));
- }
- CategoryDefinition category = deleteCategoryByType.left().value();
- log.debug("Delete category for component {}, name {}, uniqueId {}", nodeTypeEnum, category.getName(), category.getUniqueId());
- return Either.left(category);
- }
-
- public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Sub Category", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
- if (componentTypeEnum == null) {
- log.debug("Cannot delete sub-category for component type {}", componentTypeParamName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
-
- Either<SubCategoryDefinition, ActionStatus> deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId);
- if (deleteSubCategoryByType.isRight()) {
- // auditing, logging here...
- return Either.right(componentsUtils.getResponseFormat(deleteSubCategoryByType.right().value()));
- }
- SubCategoryDefinition subCategory = deleteSubCategoryByType.left().value();
- log.debug("Deleted sub-category for component {}, name {}, uniqueId {}", nodeTypeEnum, subCategory.getName(), subCategory.getUniqueId());
- return Either.left(subCategory);
- }
-
- public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Grouping", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
- if (componentTypeEnum == null) {
- log.debug("Cannot delete grouping for component type {}", componentTypeParamName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
-
- Either<GroupingDefinition, ActionStatus> deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId);
- if (deleteGroupingByType.isRight()) {
- // auditing, logging here...
- return Either.right(componentsUtils.getResponseFormat(deleteGroupingByType.right().value()));
- }
- GroupingDefinition deletedGrouping = deleteGroupingByType.left().value();
- log.debug("Deleted grouping for component {}, name {}, uniqueId {}", nodeTypeEnum, deletedGrouping.getName(), deletedGrouping.getUniqueId());
- return Either.left(deletedGrouping);
- }
-
- private Either<User, ResponseFormat> validateUser(String userId) {
-
- // validate user exists
- if (userId == null) {
- log.debug("UserId is null");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION));
- }
-
- Either<User, ActionStatus> userResult = userAdminManager.getUser(userId, false);
- if (userResult.isRight()) {
- ResponseFormat responseFormat;
- if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
- log.debug("Not authorized user, userId = {}", userId);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- } else {
- log.debug("Failed to authorize user, userId = {}", userId);
- responseFormat = componentsUtils.getResponseFormat(userResult.right().value());
- }
-
- return Either.right(responseFormat);
- }
- return Either.left(userResult.left().value());
- // ========================================-
- }
-
- private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) {
- String role = user.getRole();
- boolean validAdminAction = (role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE));
- boolean validProductAction = (role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT));
-
- if (!(validAdminAction || validProductAction)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum);
- return Either.right(responseFormat);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) {
- boolean validResourceAction = (componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY));
- boolean validServiceAction = (componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY);
- boolean validProductAction = (componentType == ComponentTypeEnum.PRODUCT); // can
- // be
- // any
- // category
- // type
-
- if (!(validResourceAction || validServiceAction || validProductAction)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType);
- return Either.right(responseFormat);
- }
- return Either.left(true);
- }
-
- private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) {
- Either<CategoryDefinition, ActionStatus> categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId);
- if (categoryByTypeAndId.isRight()) {
- log.debug("Failed to fetch parent category, parent categoryId {}", categoryId);
- ActionStatus actionStatus = categoryByTypeAndId.right().value();
- ResponseFormat responseFormat;
- if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
- responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), "");
- } else {
- responseFormat = componentsUtils.getResponseFormat(actionStatus);
- }
- return Either.right(responseFormat);
- }
- return Either.left(categoryByTypeAndId.left().value());
- }
-
- private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) {
- Either<SubCategoryDefinition, ActionStatus> subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId);
- if (subCategoryByTypeAndId.isRight()) {
- log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId);
- ActionStatus actionStatus = subCategoryByTypeAndId.right().value();
- ResponseFormat responseFormat;
- if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
- responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), "");
- } else {
- responseFormat = componentsUtils.getResponseFormat(actionStatus);
- }
- return Either.right(responseFormat);
- }
- return Either.left(subCategoryByTypeAndId.left().value());
- }
-
- private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) {
- componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType);
- }
-
- private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) {
- componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType);
- }
-
- private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) {
- componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType);
- }
-
- /*
- * New categories flow - end
- */
-
- public Either<List<Tag>, ActionStatus> getAllTags(String userId) {
- Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Tags");
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- return elementOperation.getAllTags();
- }
-
- public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes(String userId) {
- Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Property Scopes");
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- return elementOperation.getAllPropertyScopes();
- }
-
- public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes(String userId) {
- Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Artifact Types");
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- return elementOperation.getAllArtifactTypes();
- }
-
- public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() {
- return elementOperation.getAllDeploymentArtifactTypes();
- }
-
- public Either<Integer, ActionStatus> getDefaultHeatTimeout() {
- return elementOperation.getDefaultHeatTimeout();
- }
-
- public Either<Map<String, List<? extends Component>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Map<String, List<? extends Component>> resMap = new HashMap<>();
-
- Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE,excludeTypes, true);
- if (resResources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE,excludeTypes, true);
- if (resServices.isLeft()) {
- // Either<List<Product>, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false);
- // if (resProducts.isLeft()) {
- resMap.put("resources", resResources.left().value());
- resMap.put("services", resServices.left().value());
- resMap.put("products", new ArrayList<>());
-
- return Either.left(resMap);
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resServices.right().value())));
- }
- } else {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resResources.right().value())));
- }
- }
-
- public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters, String query) {
- ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
-
- if (query != null) {
- Optional<NameValuePair> invalidFilter = findInvalidFilter(query, assetTypeEnum);
- if (invalidFilter.isPresent()) {
- log.debug("getFilteredAssetList: invalid filter key");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString()));
- }
- }
-
- if (filters == null || filters.isEmpty()) {
- Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum,null, false);
- if(componentsList.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value())));
- }
- return Either.left(componentsList.left().value());
- }
-
- Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false);
-
- // category hierarchy mismatch or category/subCategory/distributionStatus not found
- if (result.isRight()) {
- List<String> params = getErrorResponseParams(filters, assetTypeEnum);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2)));
- }
- if (result.left().value().isEmpty()) {// no assets found for requested
- // criteria
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query));
- }
- return Either.left(result.left().value());
- }
-
- private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) {
- Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>());
- if(assetType == ComponentTypeEnum.RESOURCE){
-
- assetResult = getFilteredResouces(filters, inTransaction);
-
- } else if (assetType == ComponentTypeEnum.SERVICE){
-
- assetResult = getFilteredServices(filters, inTransaction);
- }
- return assetResult;
- }
-
- private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
- Either<List<T>, StorageOperationStatus> components = null;
-
- String categoryName = filters.get(FilterKeyEnum.CATEGORY);
- String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS);
- DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus);
- if (distributionStatus != null && distEnum == null) {
- filters.remove(FilterKeyEnum.CATEGORY);
- return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
- }
-
- if (categoryName != null) { // primary filter
- components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null);
- if (components.isLeft() && distEnum != null) {// secondary filter
- Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum);
- return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList()));
- }
- filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
- return components;
- }
-
- Set<DistributionStatusEnum> distStatusSet = new HashSet<>();
- distStatusSet.add(distEnum);
- Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null);
- if (servicesWithDistStatus.isRight()) { // not found == empty list
- return Either.left(new ArrayList<>());
- }
-
- return Either.left((List<T>)servicesWithDistStatus.left().value());
- }
-
- public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) {
-
- if (assetType == null || assetType == null) {
- log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
-
- if (assetTypeEnum == null) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- switch (assetTypeEnum) {
- case RESOURCE:
- additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- break;
- case SERVICE:
- additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- break;
- default:
- log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
- if(componentsListByUuid.isRight()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue()+ " fetching failed");
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum);
- return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
- }
-
- log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful");
- return Either.left(componentsListByUuid.left().value());
- }
-
- public List<String> getAllComponentTypesParamNames() {
- List<String> paramNames = new ArrayList<>();
- paramNames.add(ComponentTypeEnum.SERVICE_PARAM_NAME);
- paramNames.add(ComponentTypeEnum.RESOURCE_PARAM_NAME);
- paramNames.add(ComponentTypeEnum.PRODUCT_PARAM_NAME);
- return paramNames;
- }
-
- public List<String> getAllSupportedRoles() {
- Role[] values = Role.values();
- List<String> roleNames = new ArrayList<>();
- for (Role role : values) {
- roleNames.add(role.name());
- }
- return roleNames;
- }
-
- public Either<Map<String, String>, ActionStatus> getResourceTypesMap() {
- return elementOperation.getResourceTypesMap();
- }
-
- private Optional<NameValuePair> findInvalidFilter(String query, ComponentTypeEnum assetType) {
- List<NameValuePair> params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8);
- List<String> validKeys = FilterKeyEnum.getValidFiltersByAssetType(assetType);
- Predicate<NameValuePair> noMatch = p -> !validKeys.contains(p.getName());
- return params.stream().filter(noMatch).findAny();
- }
-
- private List<String> getErrorResponseParams(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType) {
- List<String> params = new ArrayList<String>();
- if (1 == filters.size()) {
- params.add(assetType.getValue().toLowerCase());
- params.add(filters.keySet().iterator().next().getName());
- params.add(filters.values().iterator().next());
- } else {
- params.add(assetType.getValue());
- params.add(filters.get(FilterKeyEnum.SUB_CATEGORY));
- params.add(filters.get(FilterKeyEnum.CATEGORY));
- }
- return params;
- }
-
- public Either<List<Component>, StorageOperationStatus> getFilteredResouces(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
- String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY);
- String categoryName = filters.get(FilterKeyEnum.CATEGORY);
- ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE));
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null;
- Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
-
- if (categoryName != null) {
- subcategories = getAllSubCategories(categoryName);
- if (subcategories.isRight()) {
- filters.remove(FilterKeyEnum.SUB_CATEGORY);
- return Either.right(subcategories.right().value());
- }
- }
- if (subCategoryName != null) { // primary filter
- if (categoryName != null) {
- subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName);
- if (!subCategoryData.isPresent()) {
- return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
- }
- return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction,
- ResourceMetadataData.class, resourceType);
- }
-
- return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
- }
- if(subcategories != null){
- return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
- }
- return fetchComponentMetaDataByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction);
- }
-
- private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) {
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
- if (categoryResult.isRight()) {
- return Either.right(categoryResult.right().value());
- }
- CategoryData categoryData = categoryResult.left().value();
-
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
- if (childrenNodes.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value()));
- }
- return Either.left(childrenNodes.left().value());
- }
-
- private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
- Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
- return childNodes.stream().filter(matchName).findAny();
- }
-
- protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz, ResourceTypeEnum resourceType) {
- try {
- Either<TitanGraph, TitanOperationStatus> graph = titanDao.getGraph();
- if (graph.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
-
- }
- return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType);
-
- } finally {
- if (false == inTransaction) {
- titanDao.commit();
- }
- }
- }
-
- protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz, ResourceTypeEnum resourceType) {
- List<T> components = new ArrayList<>();
- try {
- Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
- Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz);
- if (getCategory.isRight()) {
- return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
- }
- Either<TitanGraph, TitanOperationStatus> graph = titanDao.getGraph();
- if (graph.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
-
- }
- for (GraphNode category : getCategory.left().value()) {
- Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType);
- if (result.isRight()) {
- return result;
- }
- components.addAll(result.left().value());
- }
-
- return Either.left(components);
- } finally {
- if (false == inTransaction) {
- titanDao.commit();
- }
- }
- }
-
- private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) {
- List<T> components = new ArrayList<>();
- Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz);
- if (parentNodes.isLeft()) {
- for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) {
- ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition();
- Boolean isHighest = componentData.isHighestVersion();
- boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
-
- if (isHighest && isMatchingResourceType) {
- Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
- if (result.isRight()) {
- return Either.right(result.right().value());
- }
- components.add(result.left().value());
- }
- }
- }
- return Either.left(components);
- }
-
- private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
- ComponentMetadataDataDefinition componentData) {
-
- boolean isMatching;
- if (componentType == NodeTypeEnum.Resource) {
- if (resourceType == null) {
- isMatching = true;
- } else {
- isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType();
- }
- } else {
- isMatching = true;
- }
- return isMatching;
- }
-
- private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
- List<T> components = new ArrayList<>();
-
- for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
- Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource,
- inTransaction, ResourceMetadataData.class, resourceType);
- if (fetched.isRight()) {
- // return fetched;
- continue;
- }
- components.addAll(fetched.left().value());
- }
- return Either.left(components);
- }
-
- private Either<List<Component>, StorageOperationStatus> fetchComponentMetaDataByResourceType(String resourceType, boolean inTransaction) {
- List<Component> components = null;
- StorageOperationStatus status;
- Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
- Either<List<Component>, StorageOperationStatus> result;
- try {
- ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue()));
- Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter);
- if (getResources.isRight()) {
- status = getResources.right().value();
- if(status != StorageOperationStatus.NOT_FOUND){
- statusWrapper.setInnerElement(getResources.right().value());
- }else{
- components = new ArrayList<>();
- }
- } else{
- components = getResources.left().value();
- }
- if(!statusWrapper.isEmpty()){
- result = Either.right(statusWrapper.getInnerElement());
- }else{
- result = Either.left(components);
- }
- return result;
- } finally {
- if (!inTransaction) {
- titanDao.commit();
- }
- }
- }
-
- Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) {
- return convertResourceDataToResource((ResourceMetadataData) componentMetadataData);
- }
- private Resource convertResourceDataToResource(ResourceMetadataData resourceData) {
-
- ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition());
-
- Resource resource = new Resource(resourceMetadataDataDefinition);
-
- return resource;
- }
- private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status);
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria(props, inTransaction);
- }
-
- private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props, boolean inTransaction) {
- props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName());
- Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
-
- if (byCriteria.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
- }
- List<Service> services = new ArrayList<Service>();
- List<ServiceMetadataData> servicesDataList = byCriteria.left().value();
- for (ServiceMetadataData data : servicesDataList) {
- Either<Component, StorageOperationStatus> service = toscaOperationFacade.getToscaElement(data.getMetadataDataDefinition().getUniqueId());
- if (service.isLeft()) {
- services.add((Service)service.left().value());
- } else {
- log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId());
- }
- }
- return Either.left(services);
- }
-
+ private static final Logger log = LoggerFactory.getLogger(ElementBusinessLogic.class);
+
+ @javax.annotation.Resource
+ private IElementOperation elementOperation;
+
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
+
+ @javax.annotation.Resource
+ private UserBusinessLogic userAdminManager;
+
+ /**
+ *
+ * @param user
+ * @return
+ */
+ public Either<Map<String, List<? extends Component>>, ResponseFormat> getFollowed(User user) {
+ // Used for not getting duplicated followed. Cheaper than checking ArrayList.contains
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> response = null;
+ // Getting the role
+ String role = user.getRole();
+ String userId = null;
+ Role currentRole = Role.valueOf(role);
+
+ switch (currentRole) {
+ case DESIGNER:
+ userId = user.getUserId();
+ response = handleDesigner(userId);
+ break;
+
+ case TESTER:
+ userId = user.getUserId();
+ response = handleTester(userId);
+ break;
+
+ case GOVERNOR:
+ userId = user.getUserId();
+ response = handleGovernor(userId);
+ break;
+
+ case OPS:
+ userId = user.getUserId();
+ response = handleOps(userId);
+ break;
+
+ case PRODUCT_STRATEGIST:
+ userId = user.getUserId();
+ response = handleProductStrategist(userId);
+ break;
+
+ case PRODUCT_MANAGER:
+ userId = user.getUserId();
+ response = handleProductManager(userId);
+ break;
+
+ case ADMIN:
+ response = handleAdmin();
+ break;
+
+ default:
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ break;
+ }
+ // converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice)
+ return convertedToListResponse(response);
+
+ }
+
+ private Either<Map<String, List<? extends Component>>, ResponseFormat> convertedToListResponse(Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) {
+
+ Map<String, List<? extends Component>> arrayResponse = new HashMap<>();
+ if (setResponse.isLeft()) {
+ for (Map.Entry<String, Set<? extends Component>> entry : setResponse.left().value().entrySet()) {
+ arrayResponse.put(entry.getKey(), new ArrayList(new HashSet(entry.getValue())));
+ }
+ return Either.left(arrayResponse);
+ }
+ return Either.right(setResponse.right().value());
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleAdmin() {
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
+ // userId should stay null
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
+ Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
+ lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
+ response = getFollowedResourcesAndServices(null, lifecycleStates, lastStateStates);
+ return response;
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleDesigner(String userId) {
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
+ Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
+ lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
+ // more states
+ lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ response = getFollowedResourcesAndServices(userId, lifecycleStates, lastStateStates);
+ return response;
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleGovernor(String userId) {
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(null);
+ return result;
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductStrategist(String userId) {
+ // Should be empty list according to Ella, 13/03/16
+ Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>();
+ result.put("products", new HashSet<>());
+ return Either.left(result);
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleProductManager(String userId) {
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
+ Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> response;
+ lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ lifecycleStates.add(LifecycleStateEnum.CERTIFIED);
+ // more states
+ lastStateStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ response = getFollowedProducts(userId, lifecycleStates, lastStateStates);
+ return response;
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleOps(String userId) {
+ Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>();
+ distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ distStatus.add(DistributionStatusEnum.DISTRIBUTED);
+
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> result = handleFollowedCertifiedServices(distStatus);
+ return result;
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleFollowedCertifiedServices(Set<DistributionStatusEnum> distStatus) {
+
+ Either<List<Service>, StorageOperationStatus> services = toscaOperationFacade.getCertifiedServicesWithDistStatus(distStatus);
+ if (services.isLeft()) {
+ Map<String, Set<? extends Component>> result = new HashMap<>();
+ Set<Service> set = new HashSet<>();
+ set.addAll(services.left().value());
+ result.put("services", set);
+ return Either.left(result);
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
+ }
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> handleTester(String userId) {
+ Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
+ lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ lifecycleStates.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ Either<Map<String, Set<? extends Component>>, ResponseFormat> result = getFollowedResourcesAndServices(null, lifecycleStates, null);
+
+ return result;
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
+
+ try {
+ Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
+
+ if (resources.isLeft()) {
+ Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
+ if (services.isLeft()) {
+ Map<String, Set<? extends Component>> result = new HashMap<String, Set<? extends Component>>();
+ result.put("services", services.left().value());
+ result.put("resources", resources.left().value());
+ return Either.left(result);
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(services.right().value())));
+ }
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resources.right().value())));
+ }
+ } finally {
+ titanDao.commit();
+ }
+ }
+
+ private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
+ Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
+ if (products.isLeft()) {
+ Map<String, Set<? extends Component>> result = new HashMap<>();
+ result.put("products", products.left().value());
+ return Either.left(result);
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(products.right().value())));
+ }
+ }
+
+ /*
+ * New categories flow - start
+ */
+ public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() {
+ return elementOperation.getAllResourceCategories();
+ }
+
+ public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() {
+ return elementOperation.getAllServiceCategories();
+ }
+
+ public Either<CategoryDefinition, ResponseFormat> createCategory(CategoryDefinition category, String componentTypeParamName, String userId) {
+
+ AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY;
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
+ String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
+ CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY;
+
+ User user = new User();
+ Either<User, ResponseFormat> validateUser = validateUser(userId);
+ if (validateUser.isRight()) {
+ log.debug("Validation of user failed, userId {}", userId);
+ ResponseFormat responseFormat = validateUser.right().value();
+ user = new User();
+ user.setUserId(userId);
+ String currCategoryName = (category == null ? null : category.getName());
+ handleCategoryAuditing(responseFormat, user, currCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ user = validateUser.left().value();
+
+ if (category == null) {
+ log.debug("Category json is invalid");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ String categoryName = category.getName();
+ // For auditing of failures we need the original non-normalized name
+ String origCategoryName = categoryName;
+ if (componentTypeEnum == null) {
+ log.debug("Component type {} is invalid", componentTypeParamName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
+ if (validateUserRole.isRight()) {
+ log.debug("Validation of user role failed, userId {}", userId);
+ ResponseFormat responseFormat = validateUserRole.right().value();
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) {
+ log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName);
+
+ if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) {
+ log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ category.setName(categoryName);
+
+ String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName);
+ category.setNormalizedName(normalizedName);
+
+ NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType);
+
+ Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName);
+ if (categoryUniqueEither.isRight()) {
+ log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(categoryUniqueEither.right().value());
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Boolean isCategoryUnique = categoryUniqueEither.left().value();
+ if (!isCategoryUnique) {
+ log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Either<CategoryDefinition, ActionStatus> createCategoryByType = elementOperation.createCategory(category, nodeType);
+ if (createCategoryByType.isRight()) {
+ log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
+ handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
+ return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value()));
+ }
+ category = createCategoryByType.left().value();
+ log.debug("Created category for component {}, name {}, uniqueId {}", componentType, categoryName, category.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ handleCategoryAuditing(responseFormat, user, category.getName(), auditingAction, componentType);
+ return Either.left(category);
+ }
+
+ public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) {
+
+ AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY;
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
+ String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
+ CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY;
+ // For auditing
+ String parentCategoryName = parentCategoryId;
+
+ if (subCategory == null) {
+ log.debug("Sub-category json is invalid");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ String subCategoryName = subCategory.getName();
+ // For auditing of failures we need the original non-normalized name
+ String origSubCategoryName = subCategoryName;
+
+ User user = new User();
+ Either<User, ResponseFormat> validateUser = validateUserExists(userId, "createSubCategory", false);
+ if (validateUser.isRight()) {
+ log.debug("Validation of user failed, userId {}", userId);
+ ResponseFormat responseFormat = validateUser.right().value();
+ user = new User();
+ user.setUserId(userId);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ user = validateUser.left().value();
+
+ if (componentTypeEnum == null) {
+ log.debug("Component type {} is invalid", componentTypeParamName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
+ if (validateComponentType.isRight()) {
+ log.debug("Validation of component type for sub-category failed");
+ ResponseFormat responseFormat = validateComponentType.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
+ if (validateUserRole.isRight()) {
+ log.debug("Validation of user role failed, userId {}", userId);
+ ResponseFormat responseFormat = validateUserRole.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
+ NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
+
+ CategoryDefinition categoryDefinition;
+ Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum);
+ if (validateCategoryExists.isRight()) {
+ log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId);
+ ResponseFormat responseFormat = validateCategoryExists.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ categoryDefinition = validateCategoryExists.left().value();
+ parentCategoryName = categoryDefinition.getName();
+
+ if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) {
+ log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName);
+
+ if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) {
+ log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName);
+ subCategory.setNormalizedName(normalizedName);
+
+ // Uniqueness under this category
+ Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId);
+ if (subCategoryUniqueForCategory.isRight()) {
+ log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Boolean isSubUnique = subCategoryUniqueForCategory.left().value();
+ if (!isSubUnique) {
+ log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ // Setting name of subcategory to fit the similar subcategory name
+ // ignoring cases.
+ // For example if Network-->kUKU exists for service category Network,
+ // and user is trying to create Router-->Kuku for service category
+ // Router,
+ // his subcategory name will be Router-->kUKU.
+ Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName);
+ if (subCategoryUniqueForType.isRight()) {
+ log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+ SubCategoryDefinition subCategoryDefinition = subCategoryUniqueForType.left().value();
+ if (subCategoryDefinition != null) {
+ subCategoryName = subCategoryDefinition.getName();
+ }
+
+ subCategory.setName(subCategoryName);
+ ///////////////////////////////////////////// Validations end
+
+ Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType);
+ if (createSubCategory.isRight()) {
+ log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ SubCategoryDefinition subCategoryCreated = createSubCategory.left().value();
+ log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, subCategoryCreated.getName(), auditingAction, componentType);
+ return Either.left(subCategoryCreated);
+ }
+
+ public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) {
+
+ AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING;
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
+ String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
+ CategoryTypeEnum categoryType = CategoryTypeEnum.GROUPING;
+ // For auditing
+ String parentCategoryName = grandParentCategoryId;
+ String parentSubCategoryName = parentSubCategoryId;
+
+ User user;
+ Either<User, ResponseFormat> validateUser = validateUserExists(userId, "create Grouping", false);
+ if (validateUser.isRight()) {
+ log.debug("Validation of user failed, userId {}", userId);
+ ResponseFormat responseFormat = validateUser.right().value();
+ user = new User();
+ user.setUserId(userId);
+ String groupingNameForAudit = grouping == null ? null : grouping.getName();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ user = validateUser.left().value();
+
+ if (grouping == null) {
+ log.debug("Grouping json is invalid");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ String groupingName = grouping.getName();
+ // For auditing of failures we need the original non-normalized name
+ String origGroupingName = groupingName;
+
+ if (componentTypeEnum == null) {
+ log.debug("Component type {} is invalid", componentTypeParamName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
+ if (validateComponentType.isRight()) {
+ log.debug("Validation of component type for grouping failed");
+ ResponseFormat responseFormat = validateComponentType.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
+ if (validateUserRole.isRight()) {
+ log.debug("Validation of user role failed, userId {}", userId);
+ ResponseFormat responseFormat = validateUserRole.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
+ NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
+ NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
+
+ // Validate category
+ CategoryDefinition categoryDefinition;
+ Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum);
+ if (validateCategoryExists.isRight()) {
+ log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId);
+ ResponseFormat responseFormat = validateCategoryExists.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ categoryDefinition = validateCategoryExists.left().value();
+ parentCategoryName = categoryDefinition.getName();
+
+ // Validate subcategory
+ SubCategoryDefinition subCategoryDefinition;
+ Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum);
+ if (validateSubCategoryExists.isRight()) {
+ log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId);
+ ResponseFormat responseFormat = validateSubCategoryExists.right().value();
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ subCategoryDefinition = validateSubCategoryExists.left().value();
+ parentSubCategoryName = subCategoryDefinition.getName();
+
+ if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) {
+ log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName);
+
+ if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) {
+ log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName);
+ grouping.setNormalizedName(normalizedName);
+
+ // Uniqueness under this category
+ Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId);
+ if (groupingUniqueForSubCategory.isRight()) {
+ log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value();
+ if (!isGroupingUnique) {
+ log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ // Setting name of grouping to fit the similar grouping name ignoring
+ // cases.
+ // For example if Network-->kUKU exists for service sub-category
+ // Network, and user is trying to create grouping Router-->Kuku for
+ // service sub-category Router,
+ // his grouping name will be Router-->kUKU.
+ Either<GroupingDefinition, ActionStatus> groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName);
+ if (groupingUniqueForType.isRight()) {
+ log.debug("Failed validation of whether similar grouping exists, normalizedName {} componentType {}", normalizedName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForType.right().value());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+ GroupingDefinition groupingDefinition = groupingUniqueForType.left().value();
+ if (groupingDefinition != null) {
+ groupingName = groupingDefinition.getName();
+ }
+
+ grouping.setName(groupingName);
+ ///////////////////////////////////////////// Validations end
+
+ Either<GroupingDefinition, ActionStatus> createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType);
+ if (createGrouping.isRight()) {
+ log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(createGrouping.right().value());
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
+ return Either.right(responseFormat);
+ }
+
+ GroupingDefinition groupingCreated = createGrouping.left().value();
+ log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType);
+ return Either.left(groupingCreated);
+ }
+
+ public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) {
+ AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
+ ResponseFormat responseFormat;
+ User user = new User();
+ if (userId == null) {
+ user.setUserId("UNKNOWN");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ResponseFormat> validateUser = validateUserExists(userId, "get All Categories", false);
+ if (validateUser.isRight()) {
+ user.setUserId(userId);
+ log.debug("Validation of user failed, userId {}", userId);
+ responseFormat = validateUser.right().value();
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ return Either.right(responseFormat);
+ }
+ user = validateUser.left().value();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ if (componentTypeEnum == null) {
+ log.debug("Cannot create category for component type {}", componentType);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, "component type");
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ return Either.right(responseFormat);
+ }
+
+ NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
+ Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false);
+ if (getAllCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getAllCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ return Either.right(responseFormat);
+ }
+ List<CategoryDefinition> categories = getAllCategoriesByType.left().value();
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, componentType, responseFormat);
+ return Either.left(categories);
+ }
+
+ public Either<UiCategories, ResponseFormat> getAllCategories(String userId) {
+ AuditingActionEnum auditingAction = AuditingActionEnum.GET_CATEGORY_HIERARCHY;
+ ResponseFormat responseFormat;
+ UiCategories categories = new UiCategories();
+
+ Either<User, ResponseFormat> userResponse = validateUserExists(userId, "get all categories", false);
+
+ if (userResponse.isRight()) {
+ return Either.right(userResponse.right().value());
+ }
+ User user = userResponse.left().value();
+
+ // GET resource categories
+ Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
+ if (getResourceCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
+ return Either.right(responseFormat);
+ }
+ categories.setResourceCategories(getResourceCategoriesByType.left().value());
+
+ // GET service categories
+ Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
+ if (getServiceCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
+ return Either.right(responseFormat);
+ }
+ categories.setServiceCategories(getServiceCategoriesByType.left().value());
+
+ // GET product categories
+ Either<List<CategoryDefinition>, ActionStatus> getProductCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ProductCategory, false);
+ if (getProductCategoriesByType.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(getProductCategoriesByType.right().value());
+ componentsUtils.auditGetCategoryHierarchy(auditingAction, user, ComponentTypeEnum.PRODUCT.getValue(), responseFormat);
+ return Either.right(responseFormat);
+ }
+
+ categories.setProductCategories(getProductCategoriesByType.left().value());
+ return Either.left(categories);
+
+ }
+
+ public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Category", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
+ if (componentTypeEnum == null) {
+ log.debug("Cannot create category for component type {}", componentTypeParamName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
+
+ Either<CategoryDefinition, ActionStatus> deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId);
+ if (deleteCategoryByType.isRight()) {
+ // auditing, logging here...
+ return Either.right(componentsUtils.getResponseFormat(deleteCategoryByType.right().value()));
+ }
+ CategoryDefinition category = deleteCategoryByType.left().value();
+ log.debug("Delete category for component {}, name {}, uniqueId {}", nodeTypeEnum, category.getName(), category.getUniqueId());
+ return Either.left(category);
+ }
+
+ public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String grandParentCategoryId, String parentSubCategoryId, String componentTypeParamName, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Sub Category", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
+ if (componentTypeEnum == null) {
+ log.debug("Cannot delete sub-category for component type {}", componentTypeParamName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
+
+ Either<SubCategoryDefinition, ActionStatus> deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId);
+ if (deleteSubCategoryByType.isRight()) {
+ // auditing, logging here...
+ return Either.right(componentsUtils.getResponseFormat(deleteSubCategoryByType.right().value()));
+ }
+ SubCategoryDefinition subCategory = deleteSubCategoryByType.left().value();
+ log.debug("Deleted sub-category for component {}, name {}, uniqueId {}", nodeTypeEnum, subCategory.getName(), subCategory.getUniqueId());
+ return Either.left(subCategory);
+ }
+
+ public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String grandParentCategoryId, String parentSubCategoryId, String groupingId, String componentTypeParamName, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Grouping", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
+ if (componentTypeEnum == null) {
+ log.debug("Cannot delete grouping for component type {}", componentTypeParamName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
+
+ Either<GroupingDefinition, ActionStatus> deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId);
+ if (deleteGroupingByType.isRight()) {
+ // auditing, logging here...
+ return Either.right(componentsUtils.getResponseFormat(deleteGroupingByType.right().value()));
+ }
+ GroupingDefinition deletedGrouping = deleteGroupingByType.left().value();
+ log.debug("Deleted grouping for component {}, name {}, uniqueId {}", nodeTypeEnum, deletedGrouping.getName(), deletedGrouping.getUniqueId());
+ return Either.left(deletedGrouping);
+ }
+
+ private Either<User, ResponseFormat> validateUser(String userId) {
+
+ // validate user exists
+ if (userId == null) {
+ log.debug("UserId is null");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION));
+ }
+
+ Either<User, ActionStatus> userResult = userAdminManager.getUser(userId, false);
+ if (userResult.isRight()) {
+ ResponseFormat responseFormat;
+ if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
+ log.debug("Not authorized user, userId = {}", userId);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ } else {
+ log.debug("Failed to authorize user, userId = {}", userId);
+ responseFormat = componentsUtils.getResponseFormat(userResult.right().value());
+ }
+
+ return Either.right(responseFormat);
+ }
+ return Either.left(userResult.left().value());
+ // ========================================-
+ }
+
+ private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) {
+ String role = user.getRole();
+ boolean validAdminAction = role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE);
+ boolean validProductAction = role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT);
+
+ if (!(validAdminAction || validProductAction)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) {
+ boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY);
+ boolean validServiceAction = componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY;
+ boolean validProductAction = componentType == ComponentTypeEnum.PRODUCT; // can
+ // be
+ // any
+ // category
+ // type
+
+ if (!(validResourceAction || validServiceAction || validProductAction)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ }
+
+ private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) {
+ Either<CategoryDefinition, ActionStatus> categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId);
+ if (categoryByTypeAndId.isRight()) {
+ log.debug("Failed to fetch parent category, parent categoryId {}", categoryId);
+ ActionStatus actionStatus = categoryByTypeAndId.right().value();
+ ResponseFormat responseFormat;
+ if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
+ responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), "");
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(actionStatus);
+ }
+ return Either.right(responseFormat);
+ }
+ return Either.left(categoryByTypeAndId.left().value());
+ }
+
+ private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) {
+ Either<SubCategoryDefinition, ActionStatus> subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId);
+ if (subCategoryByTypeAndId.isRight()) {
+ log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId);
+ ActionStatus actionStatus = subCategoryByTypeAndId.right().value();
+ ResponseFormat responseFormat;
+ if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
+ responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), "");
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(actionStatus);
+ }
+ return Either.right(responseFormat);
+ }
+ return Either.left(subCategoryByTypeAndId.left().value());
+ }
+
+ private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) {
+ componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType);
+ }
+
+ private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) {
+ componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType);
+ }
+
+ private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) {
+ componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType);
+ }
+
+ /*
+ * New categories flow - end
+ */
+
+ public Either<List<Tag>, ActionStatus> getAllTags(String userId) {
+ Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Tags");
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ return elementOperation.getAllTags();
+ }
+
+ public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes(String userId) {
+ Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Property Scopes");
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ return elementOperation.getAllPropertyScopes();
+ }
+
+ public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes(String userId) {
+ Either<User, ActionStatus> resp = validateUserExistsActionStatus(userId, "get All Artifact Types");
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ return elementOperation.getAllArtifactTypes();
+ }
+
+ public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() {
+ return elementOperation.getAllDeploymentArtifactTypes();
+ }
+
+ public Either<Integer, ActionStatus> getDefaultHeatTimeout() {
+ return elementOperation.getDefaultHeatTimeout();
+ }
+
+ public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId) {
+ try {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", true);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ return toscaOperationFacade.getCatalogComponents().bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
+ } finally {
+ titanDao.commit();
+ }
+ }
+
+ private Map<String, List<CatalogComponent>> groupByComponentType(List<CatalogComponent> components) {
+ Map<String, List<CatalogComponent>> map = components.stream().collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType())));
+
+ // fixed response for UI!!! UI need to receive always map!
+ if (map == null) {
+ map = new HashMap<>();
+ }
+ if (map.get("resources") == null) {
+ map.put("resources", new ArrayList());
+ }
+ if (map.get("services") == null) {
+ map.put("services", new ArrayList());
+ }
+ return map;
+ }
+
+ private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) {
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ return "resources";
+ case SERVICE:
+ return "services";
+ default:
+ throw new IllegalStateException("resources or services only");
+ }
+ }
+
+ public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters, String query) {
+ ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
+
+ if (query != null) {
+ Optional<NameValuePair> invalidFilter = findInvalidFilter(query, assetTypeEnum);
+ if (invalidFilter.isPresent()) {
+ log.debug("getFilteredAssetList: invalid filter key");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString()));
+ }
+ }
+
+ if (filters == null || filters.isEmpty()) {
+ Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, null, false);
+ if (componentsList.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value())));
+ }
+ return Either.left(componentsList.left().value());
+ }
+
+ Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false);
+
+ // category hierarchy mismatch or category/subCategory/distributionStatus not found
+ if (result.isRight()) {
+ List<String> params = getErrorResponseParams(filters, assetTypeEnum);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2)));
+ }
+ if (result.left().value().isEmpty()) {// no assets found for requested
+ // criteria
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query));
+ }
+ return Either.left(result.left().value());
+ }
+
+ private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) {
+ Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>());
+ if (assetType == ComponentTypeEnum.RESOURCE) {
+
+ assetResult = getFilteredResouces(filters, inTransaction);
+
+ } else if (assetType == ComponentTypeEnum.SERVICE) {
+
+ assetResult = getFilteredServices(filters, inTransaction);
+ }
+ return assetResult;
+ }
+
+ private <T> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
+
+ Either<List<T>, StorageOperationStatus> components = null;
+
+ String categoryName = filters.get(FilterKeyEnum.CATEGORY);
+ String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS);
+ DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus);
+ if (distributionStatus != null && distEnum == null) {
+ filters.remove(FilterKeyEnum.CATEGORY);
+ return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
+ }
+
+ if (categoryName != null) { // primary filter
+ components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null);
+ if (components.isLeft() && distEnum != null) {// secondary filter
+ Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum);
+ return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList()));
+ }
+ filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
+ return components;
+ }
+
+ Set<DistributionStatusEnum> distStatusSet = new HashSet<>();
+ distStatusSet.add(distEnum);
+ Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null);
+ if (servicesWithDistStatus.isRight()) { // not found == empty list
+ return Either.left(new ArrayList<>());
+ }
+
+ return Either.left((List<T>) servicesWithDistStatus.left().value());
+ }
+
+ public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) {
+
+ if (assetType == null || uuid == null) {
+ log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
+
+ if (assetTypeEnum == null) {
+ log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ switch (assetTypeEnum) {
+ case RESOURCE:
+ additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ break;
+ case SERVICE:
+ additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ break;
+ default:
+ log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
+ if (componentsListByUuid.isRight()) {
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + " fetching failed");
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
+ }
+
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful");
+ return Either.left(componentsListByUuid.left().value());
+ }
+
+ public List<String> getAllComponentTypesParamNames() {
+ List<String> paramNames = new ArrayList<>();
+ paramNames.add(ComponentTypeEnum.SERVICE_PARAM_NAME);
+ paramNames.add(ComponentTypeEnum.RESOURCE_PARAM_NAME);
+ paramNames.add(ComponentTypeEnum.PRODUCT_PARAM_NAME);
+ return paramNames;
+ }
+
+ public List<String> getAllSupportedRoles() {
+ Role[] values = Role.values();
+ List<String> roleNames = new ArrayList<>();
+ for (Role role : values) {
+ roleNames.add(role.name());
+ }
+ return roleNames;
+ }
+
+ public Either<Map<String, String>, ActionStatus> getResourceTypesMap() {
+ return elementOperation.getResourceTypesMap();
+ }
+
+ private Optional<NameValuePair> findInvalidFilter(String query, ComponentTypeEnum assetType) {
+ List<NameValuePair> params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8);
+ List<String> validKeys = FilterKeyEnum.getValidFiltersByAssetType(assetType);
+ Predicate<NameValuePair> noMatch = p -> !validKeys.contains(p.getName());
+ return params.stream().filter(noMatch).findAny();
+ }
+
+ private List<String> getErrorResponseParams(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType) {
+ List<String> params = new ArrayList<String>();
+ if (1 == filters.size()) {
+ params.add(assetType.getValue().toLowerCase());
+ params.add(filters.keySet().iterator().next().getName());
+ params.add(filters.values().iterator().next());
+ } else {
+ params.add(assetType.getValue());
+ params.add(filters.get(FilterKeyEnum.SUB_CATEGORY));
+ params.add(filters.get(FilterKeyEnum.CATEGORY));
+ }
+ return params;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getFilteredResouces(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
+
+ String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY);
+ String categoryName = filters.get(FilterKeyEnum.CATEGORY);
+ ResourceTypeEnum resourceType = ResourceTypeEnum.getType(filters.get(FilterKeyEnum.RESOURCE_TYPE));
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null;
+ Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
+
+ if (categoryName != null) {
+ subcategories = getAllSubCategories(categoryName);
+ if (subcategories.isRight()) {
+ filters.remove(FilterKeyEnum.SUB_CATEGORY);
+ return Either.right(subcategories.right().value());
+ }
+ }
+ if (subCategoryName != null) { // primary filter
+ if (categoryName != null) {
+ subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName);
+ if (!subCategoryData.isPresent()) {
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
+ return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction,
+ ResourceMetadataData.class, resourceType);
+ }
+
+ return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
+ }
+ if (subcategories != null) {
+ return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
+ }
+ return fetchComponentMetaDataByResourceType(filters.get(FilterKeyEnum.RESOURCE_TYPE), inTransaction);
+ }
+
+ private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) {
+ Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
+ if (categoryResult.isRight()) {
+ return Either.right(categoryResult.right().value());
+ }
+ CategoryData categoryData = categoryResult.left().value();
+
+ Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
+ GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
+ if (childrenNodes.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value()));
+ }
+ return Either.left(childrenNodes.left().value());
+ }
+
+ private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
+ Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
+ return childNodes.stream().filter(matchName).findAny();
+ }
+
+ protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
+ Class<S> clazz, ResourceTypeEnum resourceType) {
+ try {
+ return collectComponents(neededType, categoryUid, categoryType, clazz, resourceType);
+ } finally {
+ if (false == inTransaction) {
+ titanDao.commit();
+ }
+ }
+ }
+
+ protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
+ Class<S> clazz, ResourceTypeEnum resourceType) {
+ List<T> components = new ArrayList<>();
+ try {
+ Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
+ Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz);
+ if (getCategory.isRight()) {
+ return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
+ }
+ for (GraphNode category : getCategory.left().value()) {
+ Either<List<T>, StorageOperationStatus> result = collectComponents(neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType);
+ if (result.isRight()) {
+ return result;
+ }
+ components.addAll(result.left().value());
+ }
+
+ return Either.left(components);
+ } finally {
+ if (false == inTransaction) {
+ titanDao.commit();
+ }
+ }
+ }
+
+ private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) {
+ List<T> components = new ArrayList<>();
+ Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz);
+ if (parentNodes.isLeft()) {
+ for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) {
+ ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition();
+ Boolean isHighest = componentData.isHighestVersion();
+ boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
+ boolean isDeleted = componentData.isDeleted() != null && componentData.isDeleted();
+
+ if (isHighest && isMatchingResourceType && !isDeleted) {
+ Either<T, StorageOperationStatus> result = (Either<T, StorageOperationStatus>) toscaOperationFacade.getToscaElement(componentData.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (result.isRight()) {
+ return Either.right(result.right().value());
+ }
+ components.add(result.left().value());
+ }
+ }
+ }
+ return Either.left(components);
+ }
+
+ private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, ComponentMetadataDataDefinition componentData) {
+
+ boolean isMatching;
+ if (componentType == NodeTypeEnum.Resource) {
+ if (resourceType == null) {
+ isMatching = true;
+ } else {
+ isMatching = resourceType == ((ResourceMetadataDataDefinition) componentData).getResourceType();
+ }
+ } else {
+ isMatching = true;
+ }
+ return isMatching;
+ }
+
+ private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
+ List<T> components = new ArrayList<>();
+
+ for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
+ Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource,
+ inTransaction, ResourceMetadataData.class, resourceType);
+ if (fetched.isRight()) {
+ continue;
+ }
+ components.addAll(fetched.left().value());
+ }
+ return Either.left(components);
+ }
+
+ private Either<List<Component>, StorageOperationStatus> fetchComponentMetaDataByResourceType(String resourceType, boolean inTransaction) {
+ List<Component> components = null;
+ StorageOperationStatus status;
+ Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
+ Either<List<Component>, StorageOperationStatus> result;
+ try {
+ ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue()));
+ Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter);
+ if (getResources.isRight()) {
+ status = getResources.right().value();
+ if (status != StorageOperationStatus.NOT_FOUND) {
+ statusWrapper.setInnerElement(getResources.right().value());
+ } else {
+ components = new ArrayList<>();
+ }
+ } else {
+ components = getResources.left().value();
+ }
+ if (!statusWrapper.isEmpty()) {
+ result = Either.right(statusWrapper.getInnerElement());
+ } else {
+ result = Either.left(components);
+ }
+ return result;
+ } finally {
+ if (!inTransaction) {
+ titanDao.commit();
+ }
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
new file mode 100644
index 0000000000..7233ba7657
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
@@ -0,0 +1,127 @@
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.dto.ExternalRefDTO;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created by yavivi on 04/02/2018.
+ */
+@org.springframework.stereotype.Component
+public class ExternalRefsBusinessLogic {
+
+ private static final Logger log = LoggerFactory.getLogger(ExternalRefsBusinessLogic.class);
+
+ private ExternalReferencesOperation externalReferencesOperation;
+ private ToscaOperationFacade toscaOperationFacade;
+ private GraphLockOperation graphLockOperation;
+
+ public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, GraphLockOperation graphLockOperation){
+ this.externalReferencesOperation = externalReferencesOperation;
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.graphLockOperation = graphLockOperation;
+ }
+
+ public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){
+ Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version);
+ if (componentsResult == null || componentsResult.isRight()) {
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+ Component component = componentsResult.left().value();
+ return this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), componentInstanceName, objectType);
+ }
+
+ public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType){
+ Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version);
+ if (componentsResult == null || componentsResult.isRight()) {
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ Component component = componentsResult.left().value();
+
+ Either<Map<String, List<String>>, ActionStatus> externalReferencesResult = this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), objectType);
+ if (externalReferencesResult.isRight()){
+ return Either.right(externalReferencesResult.right().value());
+ } else {
+ return Either.left(externalReferencesResult.left().value());
+ }
+ }
+
+ public Either<String, ActionStatus> addExternalReference(String uuid, String componentInstanceName, String objectType, ExternalRefDTO ref) {
+ return this.doAction("POST", uuid, componentInstanceName, objectType, ref.getReferenceUUID(), "");
+ }
+
+
+ public Either<String, ActionStatus> deleteExternalReference(String uuid, String componentInstanceName, String objectType, String reference) {
+ return this.doAction("DELETE", uuid, componentInstanceName, objectType, reference, "");
+ }
+
+ public Either<String, ActionStatus> updateExternalReference(String uuid, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) {
+ return this.doAction("PUT", uuid, componentInstanceName, objectType, oldRefValue, newRefValue);
+ }
+
+ private Either<String, ActionStatus> doAction(String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){
+ Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch());
+ if (latestServiceByUuid == null || latestServiceByUuid.isRight()){
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ //Get Component Unique ID
+ Component component = latestServiceByUuid.left().value();
+ String uniqueId = component.getUniqueId();
+
+ //Lock Asset
+ StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service);
+ if (lockStatus != StorageOperationStatus.OK){
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ Either<String, ActionStatus> opResult = Either.right(ActionStatus.GENERAL_ERROR);
+ try {
+ switch (action) {
+ case "POST":
+ opResult = this.externalReferencesOperation.addExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1);
+ break;
+ case "PUT":
+ opResult = this.externalReferencesOperation.updateExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1, ref2);
+ break;
+ case "DELETE":
+ opResult = this.externalReferencesOperation.deleteExternalReferenceWithCommit(uniqueId, componentInstanceName, objectType, ref1);
+ break;
+ default:
+ break;
+ }
+ } catch (Exception e) {
+ opResult = Either.right(ActionStatus.GENERAL_ERROR);
+ log.error("Failed to execute external ref action:{} on asset:{} component:{} objectType:{}", action, uuid, componentInstanceName, objectType);
+ log.error("Cause is:" , e);
+ } finally {
+ //Unlock Asset
+ this.graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service);
+ }
+ return opResult;
+ }
+
+ private Map<GraphPropertyEnum, Object> createPropsToMatch() {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ return propertiesToMatch;
+ }
+
+}
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 de571b0f03..63b72b932e 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
@@ -20,29 +20,20 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.utils.Utils;
+import org.openecomp.sdc.be.components.validation.AccessValidations;
+import org.openecomp.sdc.be.components.validation.ComponentValidations;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
@@ -69,2084 +60,1666 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
-import fj.data.Either;
+import static java.util.stream.Collectors.toList;
@org.springframework.stereotype.Component("groupBusinessLogic")
public class GroupBusinessLogic extends BaseBusinessLogic {
- private static String ADDING_GROUP = "AddingGroup";
-
- public static final String INITIAL_VERSION = "1";
-
- private static final String CREATE_GROUP = "CreateGroup";
-
- private static final String UPDATE_GROUP = "UpdateGroup";
-
- private static final String GET_GROUP = "GetGroup";
-
- private static Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class.getName());
-
- public GroupBusinessLogic() {
-
- }
-
- @javax.annotation.Resource
- private GroupTypeOperation groupTypeOperation;
-
- @Autowired
- ArtifactsOperations artifactsOperation;
-
- @Autowired
- private GroupsOperation groupsOperation;
- @Autowired
- private ApplicationDataTypeCache dataTypeCache;
-
- /**
- *
- * 1. validate user exist
- *
- * 2. validate component can be edited
- *
- * 3. verify group not already exist
- *
- * 4. verify type of group exist
- *
- * 5. verify Component instances exist under the component
- *
- * 6. verify the component instances type are allowed according to the member types in the group type
- *
- * 7. verify the artifacts belongs to the component
- *
- * @param componentId
- * @param userId
- * @param componentType
- * @param groupDefinition
- * @param inTransaction
- * @return
- */
- /*
- * public Either<GroupDefinition, ResponseFormat> createGroup(String componentId, String userId, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
- *
- * Either<GroupDefinition, ResponseFormat> result = null;
- *
- * try { Either<User, ResponseFormat> 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<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
- *
- * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value(); Either<Boolean, ResponseFormat> 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";
- if (component instanceof Resource) {
- componentTypeForResponse = ((Resource) component).getResourceType().name();
- }
- return componentTypeForResponse;
- }
-
- /**
- * Verify that the artifact members belongs to the component
- *
- * @param component
- * @param artifacts
- * @return
- */
- private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
-
- if (artifacts == null || true == artifacts.isEmpty()) {
- return Either.left(true);
- }
-
- Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
- if (deploymentArtifacts == null || true == deploymentArtifacts.isEmpty()) {
- BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
- 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));
- }
-
- return Either.left(true);
-
- }
-
- /**
- * verify that the members are component instances of the component
- *
- * @param component
- * @param componentType
- * @param groupMembers
- * @param memberToscaTypes
- * @return
- */
- private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, ComponentTypeEnum componentType, String groupName, String groupType, Map<String, String> groupMembers, List<String> memberToscaTypes) {
-
- if (groupMembers == null || true == groupMembers.isEmpty()) {
- return Either.left(true);
- }
-
- if (memberToscaTypes == null || true == memberToscaTypes.isEmpty()) {
- return Either.left(true);
- }
-
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null && false == componentInstances.isEmpty()) {
- Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p));
-
- Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
-
- for (Entry<String, String> groupMember : groupMembers.entrySet()) {
- String compName = groupMember.getKey();
- String compUid = groupMember.getValue();
-
- if (false == allCompInstances.contains(compUid)) {
- /*
- * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
- */
- String componentTypeForResponse = getComponentTypeForResponse(component);
-
- BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
- }
- }
-
- // ComponentOperation componentOperation = getComponentOperationByParentComponentType(componentType);
- // if (componentOperation instanceof ResourceOperation) {
- // ResourceOperation resourceOperation = (ResourceOperation) componentOperation;
- //
- // for (Entry<String, String> groupMember : groupMembers.entrySet()) {
- //
- // String componentInstName = groupMember.getKey();
- // String componentInstUid = groupMember.getValue();
- //
- // ComponentInstance componentInstance = compInstUidToCompInstMap.get(componentInstUid);
- // String componentUid = componentInstance.getComponentUid();
- // List<String> 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));
- // }
-
- }
-
- return Either.left(true);
- }
-
- /**
- * Update specific group version
- *
- * @param groupDefinition
- * @param inTransaction
- * @return
- */
- /*
- * public Either<GroupDefinition, StorageOperationStatus> updateGroupVersion(GroupDefinition groupDefinition, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; List<String> groupIdsToUpdateVersion = new
- * ArrayList<>(); groupIdsToUpdateVersion.add(groupDefinition.getUniqueId()); Either<List<GroupDefinition>, 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
- *
- * @param groupsUniqueId
- * @param inTransaction
- * @return
- */
- /*
- * public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsUniqueId, boolean inTransaction) {
- *
- * Either<List<GroupDefinition>, 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<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
-
- Either<GroupDefinition, ResponseFormat> result = null;
- try {
- // Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction);
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
- // Validate component exist
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
- // validate we can work on component
- Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId());
- if (canWork.isRight()) {
- result = Either.right(canWork.right().value());
- return result;
- }
- List<GroupDefinition> currentGroups = component.getGroups();
- 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<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
- 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;
- }
- GroupDefinition currentGroup = currentGroupOpt.get();
- if ( shouldLock ){
- Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
- if (lockResult.isRight()) {
- result = Either.right(lockResult.right().value());
- return result;
- }
- }
- // Validate group type is vfModule
- if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- 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);
- return result;
- }
- result = updateGroupMetadata(component, currentGroup, updatedGroup);
- return result;
-
- } finally {
- if (result.isLeft()) {
- titanDao.commit();
- } else {
- titanDao.rollback();
- }
- if( shouldLock )
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
- }
- }
-
- private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
- String currentGroupName = currentGroup.getName();
- Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
-
- if (result.isRight()) {
- log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
- }
- if (result.isLeft()) {
- result = updateGroup(component, currentGroup, currentGroupName);
- }
- return result;
- }
-
- private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) {
- Either<GroupDefinition, StorageOperationStatus> handleGroupRes;
- Either<GroupDefinition, ResponseFormat> result = null;
- if (updatedGroup.getName().equals(currentGroupName)) {
- handleGroupRes = groupsOperation.updateGroup(component, updatedGroup);
- 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) {
- log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName());
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus)));
- }
- handleGroupRes = groupsOperation.addGroup(component, updatedGroup);
- 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) {
- result = Either.left(updatedGroup);
- }
- return result;
- }
-
- /**
- * Validate and Update Group Property
- *
- * @param componentId
- * @param groupUniqueId
- * @param user
- * @param componentType
- * @param groupPropertiesToUpdate
- * @param inTransaction
- * @return
- */
- public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) {
-
- Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate);
- try {
- Optional<GroupDefinition> 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 (result.isLeft()) {
- // VF exist because lock succedded
- Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value();
- 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()));
- }
- }
-
- if (result.isLeft()) {
- currentGroup = optionalGroupConnectedToVf.get();
- result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate);
- }
- if (result.isLeft()) {
- result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction);
- if (result.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties");
- log.debug("failed to update Vf {}", componentId);
- }
- }
-
- } catch (Exception e) {
- log.debug("Error in validateAndUpdateGroupProperty {}", e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally {
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
- }
- return result;
- }
-
- private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
- Map<String, GroupProperty> originalProperties =
- // 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())) {
- gp.setValue(originalProperties.get(gp.getName()).getDefaultValue());
- }
- }
-
- }
-
- private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
-
- Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup);
- if (ret.isLeft()) {
- resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup);
- }
- if (ret.isLeft()) {
- // Validate Type Match Value
- Optional<StorageOperationStatus> 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()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get());
- ret = Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
-
- }
- if (ret.isLeft()) {
- // Validate min max ect...
- ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
- }
-
- return ret;
- }
-
- private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
-
- Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
-
- Map<PropertyNames, String> nameValueMap = new HashMap<>();
- for (GroupProperty gp : groupPropertiesToUpdate) {
- // Filter out non special properties which does not have Enum
- final PropertyNames gpEnum = PropertyNames.findName(gp.getName());
- 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)) {
-
- Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup);
-
- Either<Boolean, ResponseFormat> 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))) {
-
- Optional<ResponseFormat> 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()) {
- ret = Either.right(optionalError.get());
- }
-
- }
- }
-
- return ret;
- }
-
- private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
- Map<PropertyNames, String> 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)) {
- oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue());
- }
- }
- if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) {
- oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
- }
- return oldValueMap;
- }
-
- private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
-
- Either<List<GroupProperty>, ResponseFormat> ret = Either.left(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 {
- Map<String, GroupProperty> namePropertyMap =
- // Original Group Properties Stream
- originalGroup.convertToGroupProperties().stream().
- // Collect to map with name as key
- collect(Collectors.toMap(e -> e.getName(), e -> e));
-
- Optional<GroupProperty> 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();
-
- if (optionalMissingProperty.isPresent()) {
- ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName()));
- } else {
- Optional<GroupProperty> 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();
- if (optionalNonValueChange.isPresent()) {
- 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
- 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 = new GroupProperty(groupProperty2);
- groupProperty2Duplicate.setValue(null);
- groupProperty2Duplicate.setSchema(null);
- groupProperty2Duplicate.setParentUniqueId(null);
- return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid());
- } catch (Exception e) {
- log.debug("Failed validate group properties. ", e);
- return false;
- }
- }
-
- /**
- * Validate and update GroupDefinition metadata
- *
- * @param user
- * @param currentGroup
- * @param groupUpdate
- * @return
- **/
- private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
- // Check if to update, and update GroupDefinition name.
- Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- // Do not allow to update GroupDefinition version directly.
- String versionUpdated = groupUpdate.getVersion();
- String versionCurrent = currentGroup.getVersion();
- if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
- log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
- }
-
- return Either.left(currentGroup);
- }
-
- /**
- * Validate and update GroupDefinition name
- *
- * @param user
- * @param currentGroup
- * @param groupUpdate
- * @return
- */
- private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
- String nameUpdated = groupUpdate.getName();
- String nameCurrent = currentGroup.getName();
- if (!nameCurrent.equals(nameUpdated)) {
- Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
- if (validatNameResponse.isRight()) {
- ResponseFormat errorRespons = validatNameResponse.right().value();
- return Either.right(errorRespons);
- }
- currentGroup.setName(groupUpdate.getName());
- }
- return Either.left(true);
- }
-
- /**
- * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part
- * MyDesc was changed.
- *
- * @param currentGroupName
- * @param groupUpdateName
- * @return
- */
- private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
- try {
- // Check if the group name is in old format.
- if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
- log.error("Group name {} is in old format", groupUpdateName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
- }
-
- // Check that name pats 1 and 3 did not changed (only the second
- // part can be changed)
- // But verify before that the current group format is the new one
- if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
- String[] split1 = currentGroupName.split("\\.\\.");
- String currentResourceName = split1[0];
- String currentCounter = split1[2];
-
- String[] split2 = groupUpdateName.split("\\.\\.");
- String groupUpdateResourceName = split2[0];
- String groupUpdateCounter = split2[2];
- if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes]
- if (!currentResourceName.equals(groupUpdateResourceName)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
- }
-
- if (!currentCounter.equals(groupUpdateCounter)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
- }
- }
-
- }
-
- return Either.left(true);
- } catch (Exception e) {
- log.error("Error valiadting group name", e);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- }
-
- /**
- * associate artifacts to a given group
- *
- * @param componentId
- * @param userId
- * @param componentType
- * @param groups
- * @param shouldLockComp
- * @param inTransaction
- * @return
- */
- /*
- * public Either<List<GroupDefinition>, ResponseFormat> associateArtifactsToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
- *
- * Either<List<GroupDefinition>, 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<Component, ResponseFormat> 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<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
- *
- * List<GroupDefinition> updatedGroups = new ArrayList<>();
- *
- * List<GroupDefinition> 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<String> componentArtifacts =
- * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); if (artifactsSizeInGroup > 0) { List<String> 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<GroupDefinition, StorageOperationStatus> 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<List<GroupDefinition>, ResponseFormat> associateMembersToGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
- *
- * Either<List<GroupDefinition>, 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<Component, ResponseFormat> 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<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Associate Members"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
- *
- * List<GroupDefinition> updatedGroups = new ArrayList<>();
- *
- * // per group, associate to it the members for (GroupDefinition groupDefinition : groups) {
- *
- * Either<GroupDefinition, StorageOperationStatus> 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
- *
- * @param componentId
- * @param userId
- * @param componentType
- * @param groups
- * @param shouldLockComp
- * @param inTransaction
- * @return
- */
- public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
-
- Either<GroupDefinitionInfo, ResponseFormat> result = null;
-
- // Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
-
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
-
- // Validate component exist
- org.openecomp.sdc.be.model.Component component = null;
- String realComponentId = componentId;
-
- try {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreArtifacts(false);
- componentParametersView.setIgnoreUsers(false);
-
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- component = validateComponent.left().value();
-
- Either<GroupDefinition, StorageOperationStatus> 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<GroupProperty> props = group.convertToGroupProperties();
- if (props != null && !props.isEmpty()) {
- Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
- if (isBasePropOp.isPresent()) {
- GroupProperty propIsBase = isBasePropOp.get();
- isBase = Boolean.parseBoolean(propIsBase.getValue());
-
- } else {
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
- // return
- // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
-
- }
- }
-
- List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
- List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
- List<String> artifactsIds = group.getArtifacts();
-
- Map<String, ArtifactDefinition> deploymentArtifacts = null;
- 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) {
- 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));
- result = Either.right(responseFormat);
- return result;
- }
- artifactsFromComponent.add(deploymentArtifacts.get(id));
- }
- if (!artifactsFromComponent.isEmpty()) {
- for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
- ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
- artifacts.add(artifactDefinitionInfo);
- }
- }
-
- }
- GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
- resultInfo.setIsBase(isBase);
- if (!artifacts.isEmpty())
- resultInfo.setArtifacts(artifacts);
-
- result = Either.left(resultInfo);
-
- 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 Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
- if (CollectionUtils.isNotEmpty(component.getGroups())) {
- Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
- if (foundGroup.isPresent()) {
- result = Either.left(foundGroup.get());
- }
- }
- if (result == null) {
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- return result;
- }
-
- /**
- * @param componentId
- * @param userId
- * @param componentType
- * @param groups
- * @param inTransaction
- * @return
- */
- private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateGroupsBeforeUpdate(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean inTransaction) {
-
- Either<org.openecomp.sdc.be.model.Component, ResponseFormat> result;
-
- // Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, inTransaction);
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
-
- // Validate component exist
- String realComponentId = componentId;
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreArtifacts(false);
- componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreComponentInstances(false);
-
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
-
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
-
- // validate we can work on component
- Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
- if (canWork.isRight()) {
- result = Either.right(canWork.right().value());
- return result;
- }
-
- // Validate groups exists in the component
- ResponseFormat validateGroupsInComponent = validateGroupsInComponentByFunc(groups, component, p -> p.getUniqueId());
- if (validateGroupsInComponent != null) {
- result = Either.right(validateGroupsInComponent);
- return result;
- }
-
- Set<String> artifacts = new HashSet<>();
- groups.forEach(p -> {
- if (p.getArtifacts() != null) {
- artifacts.addAll(p.getArtifacts());
- }
- });
- // validate all artifacts belongs to the component
- Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent = verifyArtifactsBelongsToComponent(component, new ArrayList<>(artifacts), UPDATE_GROUP);
- if (verifyArtifactsBelongsToComponent.isRight()) {
- result = Either.right(verifyArtifactsBelongsToComponent.right().value());
- return result;
- }
-
- return Either.left(component);
- }
-
- /**
- * @param groups
- * @param component
- * @param getByParam
- * - the method to fetch the key of the GroupDefinition(from groups) in order to compare to groups in the component
- * @return
- */
- private ResponseFormat validateGroupsInComponentByFunc(List<GroupDefinition> groups, org.openecomp.sdc.be.model.Component component, Function<GroupDefinition, String> getByParam) {
- ResponseFormat result = null;
-
- List<GroupDefinition> currentGroups = component.getGroups();
-
- boolean found = false;
- List<String> updatedGroupsName = groups.stream().map(getByParam).collect(Collectors.toList());
-
- List<String> missingGroupNames = updatedGroupsName;
-
- if (currentGroups != null && false == currentGroups.isEmpty()) {
- List<String> 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<String> 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<List<GroupDefinition>, ResponseFormat> dissociateArtifactsFromGroup(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groups, boolean shouldLockComp, boolean inTransaction) {
- *
- * Either<List<GroupDefinition>, 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<Component, ResponseFormat> 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<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Group - Dissociate Artifacts"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
- *
- * List<GroupDefinition> updatedGroups = new ArrayList<>();
- *
- * List<GroupDefinition> 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<String> componentArtifacts =
- * componentGroup.getArtifacts(); int artifactsSizeInGroup = componentArtifacts == null ? 0 : componentArtifacts.size(); List<String> 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<GroupDefinition, StorageOperationStatus> 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<List<GroupDefinition>, ResponseFormat> createGroups(String componentId, String userId, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean shouldLockComp, boolean inTransaction) {
- *
- * Either<List<GroupDefinition>, ResponseFormat> result = null;
- *
- * List<GroupDefinition> 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<User, ResponseFormat> 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<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
- *
- * if (validateComponent.isRight()) { result = Either.right(validateComponent.right().value()); return result; } component = validateComponent.left().value();
- *
- * if (shouldLockComp) { Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "CreateGroups"); if (lockComponent.isRight()) { return Either.right(lockComponent.right().value()); } }
- *
- * Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); if (canWork.isRight()) { result = Either.right(canWork.right().value()); return result; }
- *
- * for (GroupDefinition groupDefinition : groupDefinitions) { Either<GroupDefinition, ResponseFormat> 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<GroupDefinition, ResponseFormat> createGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, boolean inTransaction) {
- *
- * Either<GroupDefinition, ResponseFormat> result = null;
- *
- * log.trace("Going to create group {}" , groupDefinition);
- *
- * try {
- *
- * // 3. verify group not already exist List<GroupDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<Boolean, ResponseFormat> 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<Boolean, ResponseFormat> 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<GroupDefinition, StorageOperationStatus> 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<List<GroupDefinition>, ResponseFormat> updateVfModuleGroupNames(String resourceSystemName, List<GroupDefinition> groups, boolean inTransaction) { List<GroupDefinition> updatedGroups = new ArrayList<>();
- * Either<List<GroupDefinition>, ResponseFormat> updateGroupNamesRes = Either.left(updatedGroups); Either<GroupDefinition, StorageOperationStatus> updateGroupNameRes; Either<String, ResponseFormat> 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<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) {
- Either<List<GroupProperty>, ResponseFormat> result;
-
- Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate);
- if (eitherUpdate.isRight()) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
- } else {
- result = Either.left(eitherUpdate.left().value());
- }
- return result;
- }
-
- public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
- Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
- Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
- for (ArtifactTemplateInfo group : allGroups) {
- Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
- if (validateGenerateGroupNameRes.isRight()) {
- validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
- break;
- }
- group.setGroupName(validateGenerateGroupNameRes.left().value());
- }
- return validateGenerateGroupNamesRes;
- }
-
- /**
- * Generate module name from resourceName, description and counter
- *
- * @param resourceSystemName
- * @param description
- * @param groupCounter
- * @return
- */
- private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) {
- Either<String, ResponseFormat> validateGenerateGroupNameRes;
- if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
- final String fileName = description.replaceAll("\\.\\.", "\\.");
- validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
- } else {
- validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
- }
- return validateGenerateGroupNameRes;
- }
-
- public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
-
- Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
- Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
- for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
- GroupDefinition curGroup = groupEntry.getValue();
- String groupType = curGroup.getType();
- String groupName = groupEntry.getKey();
- int counter;
- String description;
- Either<String, ResponseFormat> newGroupNameRes;
- if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
-
- if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
- counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
- description = curGroup.getDescription();
- } else {
- counter = getNextVfModuleNameCounter(updatedNamesGroups);
- description = groupName;
- }
- newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
- if (newGroupNameRes.isRight()) {
- log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
- result = Either.right(newGroupNameRes.right().value());
- break;
- }
- groupName = newGroupNameRes.left().value();
- curGroup.setName(groupName);
- }
- updatedNamesGroups.put(groupName, curGroup);
- }
- return result;
- }
-
- public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) {
- int counter = 0;
- if (groups != null && !groups.isEmpty()) {
- counter = getNextVfModuleNameCounter(groups.values());
- }
- return counter;
- }
-
- public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
- int counter = 0;
- if (groups != null && !groups.isEmpty()) {
- List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
- .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(Collectors.toList());
- counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1;
- }
- return counter;
- }
-
- public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) {
- List<GroupDefinition> updatedGroups = new ArrayList<>();
- Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups);
-
- for (GroupDefinition group : groups) {
- String groupType = group.getType();
- String oldGroupName = group.getName();
- String newGroupName;
- Either<String, ResponseFormat> newGroupNameRes;
- Either<GroupDefinition, StorageOperationStatus> updateGroupNameRes;
- int counter;
- if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
- counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
- newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
- if (newGroupNameRes.isRight()) {
- log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
- result = Either.right(newGroupNameRes.right().value());
- break;
- }
- newGroupName = newGroupNameRes.left().value();
- group.setName(newGroupName);
-
- }
- updatedGroups.add(group);
-
- }
-
- result = Either.left(updatedGroups);
- return result;
- }
-
- /*
- * public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions, boolean inTransaction) {
- *
- * List<GroupDefinition> generatedGroups = new ArrayList<>(); Either<List<GroupDefinition>, ResponseFormat> result = Either.left(generatedGroups);
- *
- * try {
- *
- * if (groupDefinitions != null && false == groupDefinitions.isEmpty()) { for (GroupDefinition groupDefinition : groupDefinitions) { Either<GroupDefinition, ResponseFormat> 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<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
- Either<GroupDefinitionInfo, ResponseFormat> result = null;
-
- // Validate user exist
- Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
-
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
-
- // Validate component exist
- org.openecomp.sdc.be.model.Component component = null;
- String realComponentId = componentId;
-
- try {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreComponentInstances(false);
- componentParametersView.setIgnoreArtifacts(false);
-
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- component = validateComponent.left().value();
- Either<ImmutablePair<ComponentInstance, GroupInstance>, 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()));
- result = Either.right(responseFormat);
- return result;
- }
-
- GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
- ComponentInstance componentInstance = findComponentInstanceAndGroupInstanceRes.left().value().getLeft();
-
- Boolean isBase = null;// Constants.IS_BASE;
- List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
- if (props != null && !props.isEmpty()) {
- Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
- if (isBasePropOp.isPresent()) {
- GroupProperty propIsBase = isBasePropOp.get();
- isBase = Boolean.parseBoolean(propIsBase.getValue());
-
- } else {
- BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
- // return
- // Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
-
- }
- }
-
- List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
- List<String> artifactsIds = group.getArtifacts();
- if (artifactsIds != null && !artifactsIds.isEmpty()) {
-
- List<ComponentInstance> instances = component.getComponentInstances();
- if (instances != null) {
- Optional<ComponentInstance> findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst();
- if (findFirst.isPresent()) {
- ComponentInstance ci = findFirst.get();
- Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
- for (String id : artifactsIds) {
- Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst();
- if (artOp.isPresent()) {
- artifacts.add(new ArtifactDefinitionInfo(artOp.get()));
- }
- }
- List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
- for (String id : instArtifactsIds) {
- Optional<ArtifactDefinition> 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);
- if (!artifacts.isEmpty())
- resultInfo.setArtifacts(artifacts);
-
- result = Either.left(resultInfo);
-
- 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 Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
-
- Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
- if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
- Optional<GroupInstance> foundGroup;
- Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
- if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
- foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
- if (foundGroup.isPresent()) {
- result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get()));
- }
- }
- }
- if (result == null) {
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- return result;
- }
-
- private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) {
- String value;
- if (newValues.containsKey(propertyKey)) {
- value = newValues.get(propertyKey);
- } else {
- value = parentValues.get(propertyKey);
- }
- return Integer.valueOf(value);
- }
-
- private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, final PropertyNames minInstances) {
- return newValues.containsKey(minInstances) && newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
- }
-
- private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> 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<Boolean, ResponseFormat> 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)));
- }
- }
- 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)));
- }
-
- }
- 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)));
- }
-
- }
- return result;
- }
-
- private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
-
- Either<Boolean, ResponseFormat> result;
- for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
- PropertyNames currPropertyName = entry.getKey();
- 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<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
- if (result.isRight()) {
- return result;
- }
- } 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<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
- if (result.isRight()) {
- return result;
- }
- } 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<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
- new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
- if (result.isRight()) {
- return result;
- }
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
- Either<Boolean, ResponseFormat> 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) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY));
- } 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.left(true);
- }
- return result;
- }
-
- private int parseIntValue(String value, PropertyNames propertyName) {
- int result;
- if (propertyName == PropertyNames.MAX_INSTANCES) {
- result = convertIfUnboundMax(value);
- } else if (NumberUtils.isNumber(value)) {
- result = Integer.parseInt(value);
- } 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
- */
- public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) {
-
- Either<GroupInstance, ResponseFormat> actionResult = null;
- Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
- Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
- if (validateRes.isRight()) {
- log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName());
- actionResult = Either.right(validateRes.right().value());
- }
- if (actionResult == null) {
- List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value();
- updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
- if (updateGroupInstanceResult.isRight()) {
- log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
- }
- }
- if (actionResult == null) {
- actionResult = Either.left(updateGroupInstanceResult.left().value());
- }
- return actionResult;
- }
-
- private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
-
- Either<Boolean, ResponseFormat> validationRes = null;
- Either<List<GroupInstanceProperty>, ResponseFormat> actionResult;
- Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
- Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
- List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
- String currPropertyName;
- try {
- for (GroupInstanceProperty currNewProperty : newProperties) {
- currPropertyName = currNewProperty.getName();
- validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName));
- if (validationRes.isRight()) {
- log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName());
- break;
- }
- }
- if (validationRes == null || validationRes.isLeft()) {
- Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class);
- Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
- fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues);
- validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues);
- }
- if (validationRes.isLeft()) {
- actionResult = Either.left(reducedProperties);
- } else {
- actionResult = Either.right(validationRes.right().value());
- }
- } 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<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
- PropertyNames[] allPropertyNames = PropertyNames.values();
- 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<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
-
- Either<Boolean, ResponseFormat> validationRes = null;
- String currPropertyName = currNewProperty.getName();
- PropertyNames propertyName = PropertyNames.findName(currPropertyName);
- 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)) {
- validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty);
- if (validationRes.isRight()) {
- log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName);
- } else {
- addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
- }
- } else {
- validateImmutableProperty(currExistingProperty, currNewProperty);
- }
- if (validationRes == null) {
- validationRes = Either.left(true);
- }
- } 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));
- }
- return validationRes;
- }
-
- private boolean isUpdatable(PropertyNames updatablePropertyName) {
- return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
- }
-
- private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> 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)) {
- 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)) {
- result = true;
- }
- return result;
- }
-
- private int convertIfUnboundMax(String value) {
-
- int result;
- if (!NumberUtils.isNumber(value)) {
- result = Integer.MAX_VALUE;
- } else {
- result = Integer.parseInt(value);
- }
- return result;
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
-
- Either<Boolean, ResponseFormat> validationRes = null;
- String parentValue = existingProperty.getParentValue();
-
- newProperty.setParentValue(parentValue);
- if (StringUtils.isEmpty(newProperty.getValue())) {
- newProperty.setValue(parentValue);
- }
- if (StringUtils.isEmpty(existingProperty.getValue())) {
- existingProperty.setValue(parentValue);
- }
- 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) {
- 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());
- }
- }
-
- public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
-
- Map<String, GroupDataDefinition> groups = new HashMap<>();
- // Map<String, MapPropertiesDataDefinition> groupsPropertiesMap = new HashMap<>();
- Either<List<GroupDefinition>, ResponseFormat> result = null;
- Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
-
- }
-
- // handle groups and convert to tosca data
- if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
- for (GroupDefinition groupDefinition : groupDefinitions) {
- Either<GroupDefinition, ResponseFormat> 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) {
- createGroupsResult = groupsOperation.createGroups(component, user, componentType, groups);
- 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<List<GroupDefinition>, ResponseFormat> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
-
- Either<List<GroupDefinition>, ResponseFormat> result = null;
- Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
- List<GroupDataDefinition> groups = new ArrayList<>();
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
-
- }
-
- // handle groups and convert to tosca data
- if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
- for (GroupDefinition groupDefinition : groupDefinitions) {
- Either<GroupDefinition, ResponseFormat> 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.add(new GroupDataDefinition(handledGroup));
- }
- }
- if (result == null) {
- createGroupsResult = groupsOperation.addGroups(component, user, componentType, groups);
- 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<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
-
- Either<List<GroupDefinition>, ResponseFormat> result = null;
- Either<List<GroupDefinition>, 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) {
- result = Either.left(createGroupsResult.left().value());
- }
- return result;
- }
-
- /**
- * Update specific group version
- *
- * @param groupDefinition
- * @param inTransaction
- * @return
- */
- public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDefinition> groupDefinitions) {
-
- Either<List<GroupDefinition>, ResponseFormat> result = null;
- Either<List<GroupDefinition>, 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) {
- result = Either.left(createGroupsResult.left().value());
- }
- return result;
- }
-
- public Either<GroupDefinition, ResponseFormat> handleGroup(Component component, User user, ComponentTypeEnum componentType, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
-
- Either<GroupDefinition, ResponseFormat> result = null;
-
- log.trace("Going to create group {}", groupDefinition);
- // 3. verify group not already exist
- List<GroupDefinition> 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<GroupTypeDefinition, StorageOperationStatus> 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<Boolean, ResponseFormat> 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<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
- if (areValidArtifacts.isRight()) {
- ResponseFormat responseFormat = areValidArtifacts.right().value();
- result = Either.right(responseFormat);
- return result;
- }
- List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-
- List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
- List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
- if (properties != null && false == properties.isEmpty()) {
-
- if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
- BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND))));
- }
-
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
-
- Either<GroupProperty, TitanOperationStatus> addPropertyResult = null;
- int i = 1;
- for (GroupProperty prop : properties) {
- addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes);
- 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) {
- String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinition.getName());
- groupDefinition.setUniqueId(uid);
- }
- groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
- groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
- groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
- groupDefinition.setVersion(INITIAL_VERSION);
- groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
-
- return Either.left(groupDefinition);
- }
-
- public Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes) {
-
- if (prop == null) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
-
- PropertyDataDefinition propDataDef = prop;
- String propertyType = propDataDef.getType();
- String value = groupProperty.getValue();
-
- Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
- if (checkInnerType.isRight()) {
- TitanOperationStatus status = checkInnerType.right().value();
- return Either.right(status);
- }
-
- String innerType = checkInnerType.left().value();
-
- log.debug("Before validateAndUpdatePropertyValue");
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
- log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) prop.getUniqueId(), index);
-
- groupProperty.setUniqueId(uniqueId);
- groupProperty.setValue(newValue);
- 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);
- }
+ public static final String GROUP_DELIMITER_REGEX = "\\.\\.";
+ private static String ADDING_GROUP = "AddingGroup";
+
+ public static final String INITIAL_VERSION = "1";
+
+ private static final String CREATE_GROUP = "CreateGroup";
+
+ private static final String UPDATE_GROUP = "UpdateGroup";
+
+ private static final String GET_GROUP = "GetGroup";
+
+ private static final String DELETE_GROUP = "GetGroup";
+
+ private static final Logger log = LoggerFactory.getLogger(GroupBusinessLogic.class);
+
+ @javax.annotation.Resource
+ private AccessValidations accessValidations;
+
+ @javax.annotation.Resource
+ private GroupTypeOperation groupTypeOperation;
+
+ @Autowired
+ private ArtifactsOperations artifactsOperation;
+
+ @Autowired
+ private GroupsOperation groupsOperation;
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
+ private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
+ String componentTypeForResponse = "SERVICE";
+ if (component instanceof Resource) {
+ componentTypeForResponse = ((Resource) component).getResourceType().name();
+ }
+ return componentTypeForResponse;
+ }
+
+ /**
+ * Verify that the artifact members belongs to the component
+ *
+ * @param component
+ * @param artifacts
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
+
+ if (CollectionUtils.isEmpty(artifacts)) {
+ return Either.left(true);
+ }
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
+ if (MapUtils.isEmpty(deploymentArtifacts)) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ List<String> currentArtifacts = deploymentArtifacts.values().stream().map(p -> p.getUniqueId()).collect(toList());
+ log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
+ if (!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));
+ }
+
+ return Either.left(true);
+
+ }
+
+ /**
+ * verify that the members are component instances of the component
+ *
+ * @param component
+ * @param groupMembers
+ * @param memberToscaTypes
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName, Map<String, String> groupMembers, List<String> memberToscaTypes) {
+
+ if (MapUtils.isEmpty(groupMembers)) {
+ return Either.left(true);
+ }
+
+ if (CollectionUtils.isEmpty(memberToscaTypes)) {
+ return Either.left(true);
+ }
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (CollectionUtils.isNotEmpty(componentInstances)) {
+ Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p));
+
+ Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
+
+ for (Entry<String, String> groupMember : groupMembers.entrySet()) {
+ String compName = groupMember.getKey();
+ String compUid = groupMember.getValue();
+
+ if (!allCompInstances.contains(compUid)) {
+ /*
+ * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
+ */
+ String componentTypeForResponse = getComponentTypeForResponse(component);
+
+ BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
+ }
+ }
+ }
+
+ return Either.left(true);
+ }
+
+
+
+ /**
+ * Update GroupDefinition metadata
+ *
+ * @param componentId
+ * @param user
+ * @param componentType
+ * @param updatedGroup
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
+
+ Either<GroupDefinition, ResponseFormat> result = null;
+ try {
+ // Validate user exist
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(user.getUserId(), UPDATE_GROUP, inTransaction);
+ if (validateUserExists.isRight()) {
+ result = Either.right(validateUserExists.right().value());
+ return result;
+ }
+ // Validate component exist
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ org.openecomp.sdc.be.model.Component component = validateComponent.left().value();
+ // validate we can work on component
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, user.getUserId());
+ if (canWork.isRight()) {
+ result = Either.right(canWork.right().value());
+ return result;
+ }
+ List<GroupDefinition> currentGroups = component.getGroups();
+ 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<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
+ 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;
+ }
+ GroupDefinition currentGroup = currentGroupOpt.get();
+ if ( shouldLock ){
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
+ if (lockResult.isRight()) {
+ result = Either.right(lockResult.right().value());
+ return result;
+ }
+ }
+ // Validate group type is vfModule
+ if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) {
+ log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType());
+ result = Either.right(responseFormat);
+ return result;
+ }
+ result = updateGroupMetadata(component, currentGroup, updatedGroup);
+ return result;
+
+ } finally {
+ if (result.isLeft()) {
+ titanDao.commit();
+ } else {
+ titanDao.rollback();
+ }
+ if (shouldLock) {
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ }
+ }
+ }
+
+ private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
+ String currentGroupName = currentGroup.getName();
+ Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
+
+ if (result.isRight()) {
+ log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
+ }
+ if (result.isLeft()) {
+ result = updateGroup(component, currentGroup, currentGroupName);
+ }
+ return result;
+ }
+
+ private Either<GroupDefinition, ResponseFormat> updateGroup(Component component, GroupDefinition updatedGroup, String currentGroupName) {
+ Either<GroupDefinition, StorageOperationStatus> handleGroupRes;
+ Either<GroupDefinition, ResponseFormat> result = null;
+ if (updatedGroup.getName().equals(currentGroupName)) {
+ handleGroupRes = groupsOperation.updateGroup(component, updatedGroup);
+ 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) {
+ log.debug("Failed to delete the group {} from component {}. ", updatedGroup.getName(), component.getName());
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteStatus)));
+ }
+ handleGroupRes = groupsOperation.addGroup(component, updatedGroup);
+ 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) {
+ result = Either.left(updatedGroup);
+ }
+ return result;
+ }
+
+ /**
+ * Validate and Update Group Property
+ *
+ * @param componentId
+ * @param groupUniqueId
+ * @param user
+ * @param componentType
+ * @param groupPropertiesToUpdate
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<GroupProperty>, ResponseFormat> validateAndUpdateGroupProperties(String componentId, String groupUniqueId, User user, ComponentTypeEnum componentType, List<GroupProperty> groupPropertiesToUpdate, boolean inTransaction) {
+
+ Either<List<GroupProperty>, ResponseFormat> result = Either.left(groupPropertiesToUpdate);
+ try {
+ Optional<GroupDefinition> 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 (result.isLeft()) {
+ // VF exist because lock succedded
+ Resource vf = (Resource) toscaOperationFacade.getToscaElement(componentId).left().value();
+ 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()));
+ }
+ }
+
+ if (result.isLeft()) {
+ currentGroup = optionalGroupConnectedToVf.get();
+ result = validateGroupPropertyAndResetEmptyValue(currentGroup, groupPropertiesToUpdate);
+ }
+ if (result.isLeft()) {
+ result = updateGroupPropertiesValue(componentId, currentGroup, groupPropertiesToUpdate, inTransaction);
+ if (result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Update GroupProperties");
+ log.debug("failed to update Vf {}", componentId);
+ }
+ }
+
+ } catch (Exception e) {
+ log.debug("Error in validateAndUpdateGroupProperty {}", e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ }
+ return result;
+ }
+
+ private void resetEmptyValueWithDefaults(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+ Map<String, GroupProperty> originalProperties =
+ // 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())) {
+ gp.setValue(originalProperties.get(gp.getName()).getDefaultValue());
+ }
+ }
+
+ }
+
+ private Either<List<GroupProperty>, ResponseFormat> validateGroupPropertyAndResetEmptyValue(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
+
+ Either<List<GroupProperty>, ResponseFormat> ret = validateOnlyValueChanged(groupPropertiesToUpdate, originalGroup);
+ if (ret.isLeft()) {
+ resetEmptyValueWithDefaults(groupPropertiesToUpdate, originalGroup);
+ }
+ if (ret.isLeft()) {
+ // Validate Type Match Value
+ Optional<StorageOperationStatus> 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()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(optionalError.get());
+ ret = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ }
+ if (ret.isLeft()) {
+ // Validate min max ect...
+ ret = validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
+ }
+
+ return ret;
+ }
+
+ private Either<List<GroupProperty>, ResponseFormat> validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+
+ Either<List<GroupProperty>, ResponseFormat> ret = Either.left(groupPropertiesToUpdate);
+
+ Map<PropertyNames, String> nameValueMap = new HashMap<>();
+ for (GroupProperty gp : groupPropertiesToUpdate) {
+ // Filter out non special properties which does not have Enum
+ final PropertyNames gpEnum = PropertyNames.findName(gp.getName());
+ 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)) {
+
+ Map<PropertyNames, String> oldValueMap = prepareMapWithOriginalProperties(originalGroup);
+
+ Either<Boolean, ResponseFormat> 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))) {
+
+ Optional<ResponseFormat> 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()) {
+ ret = Either.right(optionalError.get());
+ }
+
+ }
+ }
+
+ return ret;
+ }
+
+ private Map<PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
+ Map<PropertyNames, String> 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(), PropertyNames::findName, propertiesToCheck)) {
+ oldValueMap.put(PropertyNames.findName(gp.getName()), gp.getValue());
+ }
+ }
+ if (StringUtils.isEmpty(oldValueMap.get(PropertyNames.MAX_INSTANCES))) {
+ oldValueMap.put(PropertyNames.MAX_INSTANCES, String.valueOf(Integer.MAX_VALUE));
+ }
+ return oldValueMap;
+ }
+
+ private Either<List<GroupProperty>, ResponseFormat> validateOnlyValueChanged(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
+
+ Either<List<GroupProperty>, ResponseFormat> ret = Either.left(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 {
+ Map<String, GroupProperty> namePropertyMap =
+ // Original Group Properties Stream
+ originalGroup.convertToGroupProperties().stream().
+ // Collect to map with name as key
+ collect(Collectors.toMap(e -> e.getName(), e -> e));
+
+ Optional<GroupProperty> 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();
+
+ if (optionalMissingProperty.isPresent()) {
+ ret = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, optionalMissingProperty.get().getName()));
+ } else {
+ Optional<GroupProperty> 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();
+ if (optionalNonValueChange.isPresent()) {
+ 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
+ try {
+ GroupProperty groupPropertyDuplicate = new GroupProperty(groupProperty);
+ groupPropertyDuplicate.setValue(null);
+ groupPropertyDuplicate.setSchema(null);
+ groupPropertyDuplicate.setParentUniqueId(null);
+ GroupProperty groupProperty2Duplicate = new GroupProperty(groupProperty2);
+ groupProperty2Duplicate.setValue(null);
+ groupProperty2Duplicate.setSchema(null);
+ groupProperty2Duplicate.setParentUniqueId(null);
+ return groupPropertyDuplicate.equals(groupProperty2Duplicate) && StringUtils.equals(groupPropertyDuplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid());
+ } catch (Exception e) {
+ log.debug("Failed validate group properties. ", e);
+ return false;
+ }
+ }
+
+ /**
+ * Validate and update GroupDefinition metadata
+ *
+ * @param currentGroup
+ * @param groupUpdate
+ * @return
+ **/
+ private Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
+ // Check if to update, and update GroupDefinition name.
+ Either<Boolean, ResponseFormat> response = validateAndUpdateGroupName(currentGroup, groupUpdate);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ // Do not allow to update GroupDefinition version directly.
+ String versionUpdated = groupUpdate.getVersion();
+ String versionCurrent = currentGroup.getVersion();
+ if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
+ log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
+ }
+
+ return Either.left(currentGroup);
+ }
+
+ /**
+ * Validate and update GroupDefinition name
+ *
+ * @param currentGroup
+ * @param groupUpdate
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> validateAndUpdateGroupName(GroupDefinition currentGroup, GroupDefinition groupUpdate) {
+ String nameUpdated = groupUpdate.getName();
+ String nameCurrent = currentGroup.getName();
+ if (!nameCurrent.equals(nameUpdated)) {
+ Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
+ if (validatNameResponse.isRight()) {
+ ResponseFormat errorRespons = validatNameResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentGroup.setName(groupUpdate.getName());
+ }
+ return Either.left(true);
+ }
+
+ /**
+ * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part
+ * MyDesc was changed.
+ *
+ * @param currentGroupName
+ * @param groupUpdateName
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
+ try {
+ // Check if the group name is in old format.
+ if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
+ log.error("Group name {} is in old format", groupUpdateName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
+ }
+
+ // Check that name pats 1 and 3 did not changed (only the second
+ // part can be changed)
+ // But verify before that the current group format is the new one
+ if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
+ String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX);
+ String currentResourceName = split1[0];
+ String currentCounter = split1[2];
+
+ String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX);
+ String groupUpdateResourceName = split2[0];
+ String groupUpdateCounter = split2[2];
+ if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes]
+ if (!currentResourceName.equals(groupUpdateResourceName)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
+ }
+
+ if (!currentCounter.equals(groupUpdateCounter)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
+ }
+ }
+
+ }
+
+ return Either.left(true);
+ } catch (Exception e) {
+ log.error("Error valiadting group name", e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ }
+
+
+ /**
+ * associate artifacts to a given group
+ *
+ * @param componentId
+ * @param userId
+ * @param componentType
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
+
+ Either<GroupDefinitionInfo, ResponseFormat> result = null;
+
+ // Validate user exist
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, GET_GROUP, true);
+
+ if (validateUserExists.isRight()) {
+ result = Either.right(validateUserExists.right().value());
+ return result;
+ }
+
+ // Validate component exist
+ org.openecomp.sdc.be.model.Component component = null;
+ String realComponentId = componentId;
+
+ try {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreGroups(false);
+ componentParametersView.setIgnoreArtifacts(false);
+ componentParametersView.setIgnoreUsers(false);
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ component = validateComponent.left().value();
+
+ Either<GroupDefinition, StorageOperationStatus> 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;
+ List<GroupProperty> props = group.convertToGroupProperties();
+ if (props != null && !props.isEmpty()) {
+ Optional<GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (isBasePropOp.isPresent()) {
+ GroupProperty propIsBase = isBasePropOp.get();
+ isBase = Boolean.parseBoolean(propIsBase.getValue());
+
+ } else {
+ BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+ }
+ }
+
+ List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
+ List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
+ List<String> artifactsIds = group.getArtifacts();
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = null;
+ 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) {
+ 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));
+ result = Either.right(responseFormat);
+ return result;
+ }
+ artifactsFromComponent.add(deploymentArtifacts.get(id));
+ }
+ if (!artifactsFromComponent.isEmpty()) {
+ for (ArtifactDefinition artifactDefinition : artifactsFromComponent) {
+ ArtifactDefinitionInfo artifactDefinitionInfo = new ArtifactDefinitionInfo(artifactDefinition);
+ artifacts.add(artifactDefinitionInfo);
+ }
+ }
+
+ }
+ GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
+ resultInfo.setIsBase(isBase);
+ if (!artifacts.isEmpty()) {
+ resultInfo.setArtifacts(artifacts);
+ }
+ result = Either.left(resultInfo);
+
+ return result;
+
+ } finally {
+
+ if (!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 Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
+
+ Either<GroupDefinition, StorageOperationStatus> result = null;
+ if (CollectionUtils.isNotEmpty(component.getGroups())) {
+ Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
+ if (foundGroup.isPresent()) {
+ result = Either.left(foundGroup.get());
+ }
+ }
+ if (result == null) {
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ return result;
+ }
+
+ public String getAsString(List<String> 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());
+
+ }
+
+
+ private Either<List<GroupProperty>, ResponseFormat> updateGroupPropertiesValue(String componentId, GroupDefinition currentGroup, List<GroupProperty> groupPropertyToUpdate, boolean inTransaction) {
+ Either<List<GroupProperty>, ResponseFormat> result;
+
+ Either<List<GroupProperty>, StorageOperationStatus> eitherUpdate = groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, groupPropertyToUpdate);
+ if (eitherUpdate.isRight()) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(eitherUpdate.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ } else {
+ result = Either.left(eitherUpdate.left().value());
+ }
+ return result;
+ }
+
+ public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
+ Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
+ Collections.sort(allGroups, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
+ for (ArtifactTemplateInfo group : allGroups) {
+ Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
+ if (validateGenerateGroupNameRes.isRight()) {
+ validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
+ break;
+ }
+ group.setGroupName(validateGenerateGroupNameRes.left().value());
+ }
+ return validateGenerateGroupNamesRes;
+ }
+
+ /**
+ * Generate module name from resourceName, description and counter
+ *
+ * @param resourceSystemName
+ * @param description
+ * @param groupCounter
+ * @return
+ */
+ private Either<String, ResponseFormat> validateGenerateVfModuleGroupName(String resourceSystemName, String description, int groupCounter) {
+ Either<String, ResponseFormat> validateGenerateGroupNameRes;
+ if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
+ final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\.");
+ validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
+ } else {
+ validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
+ }
+ return validateGenerateGroupNameRes;
+ }
+
+ public Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
+
+ Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
+ Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
+ for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
+ GroupDefinition curGroup = groupEntry.getValue();
+ String groupType = curGroup.getType();
+ String groupName = groupEntry.getKey();
+ int counter;
+ String description;
+ Either<String, ResponseFormat> newGroupNameRes;
+ if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
+
+ if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
+ counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
+ description = curGroup.getDescription();
+ } else {
+ counter = getNextVfModuleNameCounter(updatedNamesGroups);
+ description = groupName;
+ }
+ newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
+ if (newGroupNameRes.isRight()) {
+ log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
+ result = Either.right(newGroupNameRes.right().value());
+ break;
+ }
+ groupName = newGroupNameRes.left().value();
+ curGroup.setName(groupName);
+ }
+ updatedNamesGroups.put(groupName, curGroup);
+ }
+ return result;
+ }
+
+ public int getNextVfModuleNameCounter(Map<String, GroupDefinition> groups) {
+ int counter = 0;
+ if (groups != null && !groups.isEmpty()) {
+ counter = getNextVfModuleNameCounter(groups.values());
+ }
+ return counter;
+ }
+
+ public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
+ int counter = 0;
+ if (groups != null && !groups.isEmpty()) {
+ List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
+ .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
+ counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max((a, b) -> Integer.compare(a, b)).get() + 1;
+ }
+ return counter;
+ }
+
+ public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component, boolean inTransaction) {
+ List<GroupDefinition> updatedGroups = new ArrayList<>();
+ Either<List<GroupDefinition>, ResponseFormat> result = Either.left(updatedGroups);
+
+ for (GroupDefinition group : groups) {
+ String groupType = group.getType();
+ String oldGroupName = group.getName();
+ String newGroupName;
+ Either<String, ResponseFormat> newGroupNameRes;
+ int counter;
+ if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
+ counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
+ newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
+ if (newGroupNameRes.isRight()) {
+ log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
+ result = Either.right(newGroupNameRes.right().value());
+ break;
+ }
+ newGroupName = newGroupNameRes.left().value();
+ group.setName(newGroupName);
+
+ }
+ updatedGroups.add(group);
+
+ }
+
+ result = Either.left(updatedGroups);
+ return result;
+ }
+
+
+ public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
+ Either<GroupDefinitionInfo, ResponseFormat> result = null;
+
+ // Validate user exist
+ Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, UPDATE_GROUP, true);
+
+ if (validateUserExists.isRight()) {
+ result = Either.right(validateUserExists.right().value());
+ return result;
+ }
+
+ // Validate component exist
+ org.openecomp.sdc.be.model.Component component = null;
+ String realComponentId = componentId;
+
+ try {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreUsers(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+ componentParametersView.setIgnoreArtifacts(false);
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, componentType, componentParametersView);
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ component = validateComponent.left().value();
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, 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()));
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
+
+ Boolean isBase = null;
+ List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
+ if (props != null && !props.isEmpty()) {
+ Optional<? extends GroupProperty> isBasePropOp = props.stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+ if (isBasePropOp.isPresent()) {
+ GroupProperty propIsBase = isBasePropOp.get();
+ isBase = Boolean.parseBoolean(propIsBase.getValue());
+
+ } else {
+ BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+ }
+ }
+
+ List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
+ List<String> artifactsIds = group.getArtifacts();
+ if (artifactsIds != null && !artifactsIds.isEmpty()) {
+
+ List<ComponentInstance> instances = component.getComponentInstances();
+ if (instances != null) {
+ Optional<ComponentInstance> findFirst = instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst();
+ if (findFirst.isPresent()) {
+ ComponentInstance ci = findFirst.get();
+ Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
+ for (String id : artifactsIds) {
+ Optional<ArtifactDefinition> artOp = deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst();
+ if (artOp.isPresent()) {
+ artifacts.add(new ArtifactDefinitionInfo(artOp.get()));
+ }
+ }
+ List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
+ for (String id : instArtifactsIds) {
+ Optional<ArtifactDefinition> 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);
+ if (!artifacts.isEmpty()) {
+ resultInfo.setArtifacts(artifacts);
+ }
+ result = Either.left(resultInfo);
+
+ return result;
+
+ } finally {
+
+ if (!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 Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
+
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
+ if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
+ Optional<GroupInstance> foundGroup;
+ Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
+ if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
+ foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
+ if (foundGroup.isPresent()) {
+ result = Either.left(new ImmutablePair<>(foundComponent.get(), foundGroup.get()));
+ }
+ }
+ }
+ if (result == null) {
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ return result;
+ }
+
+ private int getLatestIntProperty(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, PropertyNames propertyKey) {
+ String value;
+ if (newValues.containsKey(propertyKey)) {
+ value = newValues.get(propertyKey);
+ } else {
+ value = parentValues.get(propertyKey);
+ }
+ return Integer.valueOf(value);
+ }
+
+ private boolean isPropertyChanged(Map<PropertyNames, String> newValues, Map<PropertyNames, String> parentValues, final PropertyNames minInstances) {
+ return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
+ }
+
+ private Either<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogicVF(Map<PropertyNames, String> newValues, Map<PropertyNames, String> 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<Boolean, ResponseFormat> result = Either.left(true);
+
+ if (isPropertyChanged(newValues, parentValues, PropertyNames.INITIAL_COUNT) && result.isLeft()
+ && (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)));
+ }
+ if (isPropertyChanged(newValues, parentValues, PropertyNames.MAX_INSTANCES) && result.isLeft() &&
+ latestMaxInstances < 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() && latestMinInstances > 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<Boolean, ResponseFormat> validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
+
+ Either<Boolean, ResponseFormat> result;
+ for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
+ PropertyNames currPropertyName = entry.getKey();
+ 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<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ if (result.isRight()) {
+ return result;
+ }
+ } 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<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ if (result.isRight()) {
+ return result;
+ }
+ } 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<PropertyNames, String>(currPropertyName, entry.getValue()), new ImmutablePair<PropertyNames, String>(PropertyNames.MIN_INSTANCES, minValue),
+ new ImmutablePair<PropertyNames, String>(PropertyNames.MAX_INSTANCES, maxValue));
+ if (result.isRight()) {
+ return result;
+ }
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
+ Either<Boolean, ResponseFormat> 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) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY));
+ } 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.left(true);
+ }
+ return result;
+ }
+
+ private int parseIntValue(String value, PropertyNames propertyName) {
+ int result;
+ if (propertyName == PropertyNames.MAX_INSTANCES) {
+ result = convertIfUnboundMax(value);
+ } else if (NumberUtils.isNumber(value)) {
+ result = Integer.parseInt(value);
+ } else {
+ result = -1;
+ }
+ return result;
+ }
+
+ /**
+ * validates received new property values and updates group instance in case of success
+ *
+ * @param oldGroupInstance
+ * @param newProperties
+ * @param inTransaction
+ * @return
+ */
+ public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, boolean inTransaction) {
+
+ Either<GroupInstance, ResponseFormat> actionResult = null;
+ Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
+ Either<List<GroupInstanceProperty>, ResponseFormat> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
+ if (validateRes.isRight()) {
+ log.debug("Failed to validate group instance {} properties before update. ", oldGroupInstance.getName());
+ actionResult = Either.right(validateRes.right().value());
+ }
+ if (actionResult == null) {
+ List<GroupInstanceProperty> validatedReducedNewProperties = validateRes.left().value();
+ updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
+ if (updateGroupInstanceResult.isRight()) {
+ log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
+ }
+ }
+ if (actionResult == null) {
+ actionResult = Either.left(updateGroupInstanceResult.left().value());
+ }
+ return actionResult;
+ }
+
+ private Either<List<GroupInstanceProperty>, ResponseFormat> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
+
+ Either<Boolean, ResponseFormat> validationRes = null;
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResult;
+ Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+ Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
+ List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
+ String currPropertyName;
+ try {
+ for (GroupInstanceProperty currNewProperty : newProperties) {
+ currPropertyName = currNewProperty.getName();
+ validationRes = handleAndAddProperty(reducedProperties, newPropertyValues, currNewProperty, existingProperties.get(currPropertyName));
+ if (validationRes.isRight()) {
+ log.debug("Failed to handle property {} of group instance {}. ", currPropertyName, oldGroupInstance.getName());
+ break;
+ }
+ }
+ if (validationRes == null || validationRes.isLeft()) {
+ Map<PropertyNames, String> existingPropertyValues = new EnumMap<>(PropertyNames.class);
+ Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
+ fillValuesAndParentValuesFromExistingProperties(existingProperties, existingPropertyValues, parentPropertyValues);
+ validationRes = validateMinMaxAndInitialCountPropertyLogic(newPropertyValues, existingPropertyValues, parentPropertyValues);
+ }
+ if (validationRes.isLeft()) {
+ actionResult = Either.left(reducedProperties);
+ } else {
+ actionResult = Either.right(validationRes.right().value());
+ }
+ } 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<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
+ PropertyNames[] allPropertyNames = PropertyNames.values();
+ 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<Boolean, ResponseFormat> handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
+
+ Either<Boolean, ResponseFormat> validationRes = null;
+ String currPropertyName = currNewProperty.getName();
+ PropertyNames propertyName = PropertyNames.findName(currPropertyName);
+ 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)) {
+ validationRes = validateAndUpdatePropertyValue(currNewProperty, currExistingProperty);
+ if (validationRes.isRight()) {
+ log.debug("Failed to validate property value {} of property {}. ", currNewProperty.getValue(), currPropertyName);
+ } else {
+ addPropertyUpdatedValues(reducedProperties, propertyName, newPropertyValues, currNewProperty, currExistingProperty);
+ }
+ } else {
+ validateImmutableProperty(currExistingProperty, currNewProperty);
+ }
+ if (validationRes == null) {
+ validationRes = Either.left(true);
+ }
+ } 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));
+ }
+ return validationRes;
+ }
+
+ private boolean isUpdatable(PropertyNames updatablePropertyName) {
+ return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
+ }
+
+ private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> 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)) {
+ 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)) {
+ result = true;
+ }
+ return result;
+ }
+
+ private int convertIfUnboundMax(String value) {
+
+ int result;
+ if (!NumberUtils.isNumber(value)) {
+ result = Integer.MAX_VALUE;
+ } else {
+ result = Integer.parseInt(value);
+ }
+ return result;
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
+
+ Either<Boolean, ResponseFormat> validationRes = null;
+ String parentValue = existingProperty.getParentValue();
+
+ newProperty.setParentValue(parentValue);
+ if (StringUtils.isEmpty(newProperty.getValue())) {
+ newProperty.setValue(parentValue);
+ }
+ if (StringUtils.isEmpty(existingProperty.getValue())) {
+ existingProperty.setValue(parentValue);
+ }
+ 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) {
+ 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());
+ }
+ }
+
+ public GroupDefinition createGroup(String groupType, ComponentTypeEnum componentTypeEnum, String componentId,
+ String userId) {
+
+ try {
+ Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, CREATE_GROUP);
+
+ validateGroupTypePerComponent(groupType, component);
+
+ GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
+ .left()
+ .on(se -> onGroupTypeNotFound(component));
+
+ boolean isFirstGroup = component.getGroups() == null;
+ GroupDefinition groupDefinition = new GroupDefinition();
+ groupDefinition.setType(groupType);
+
+ //find next valid counter
+ int nextCounter = 0;
+ if (!isFirstGroup) {
+ nextCounter = getNewGroupCounter(component);
+ }
+ String name = TopologyTemplateOperation.buildSubComponentName(component.getName(), groupType, nextCounter);
+ groupDefinition.setName(name);
+
+ //Add default type properties
+ List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
+ List<GroupProperty> properties = groupTypeProperties.stream()
+ .map(GroupProperty::new)
+ .collect(toList());
+ groupDefinition.convertFromGroupProperties(properties);
+
+ List<GroupDefinition> gdList;
+ if (isFirstGroup) {
+ gdList = createGroups(component, Arrays.asList(groupDefinition))
+ .left()
+ .on(this::onFailedGroupDBOperation);
+ } else {
+ gdList = addGroups(component, Arrays.asList(groupDefinition))
+ .left()
+ .on(this::onFailedGroupDBOperation);
+ }
+ return gdList.get(0);
+ } finally {
+ titanDao.commit();
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+ }
+
+ private void validateGroupTypePerComponent(String groupType, Component component) {
+ String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType();
+ if (!component.isTopologyTemplate()) {
+ throw new ComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType,
+ specificType);
+ }
+ Map<String, Set<String>> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getExcludedGroupTypesMapping();
+
+ if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) {
+ Set<String> excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType);
+ if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) {
+ throw new ComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
+ }
+ }
+ }
+
+ private int getNewGroupCounter(Component component) {
+ List<String> existingNames = component.getGroups()
+ .stream()
+ .map(GroupDataDefinition::getName)
+ .collect(toList());
+ List<String> existingIds = component.getGroups()
+ .stream()
+ .map(GroupDataDefinition::getUniqueId)
+ .collect(toList());
+ existingIds.addAll(existingNames);
+
+ return Utils.getNextCounter(existingIds);
+ }
+
+ public GroupDefinition updateGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId,
+ String userId, GroupDefinition updatedGroup) {
+ try {
+ Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, UPDATE_GROUP);
+
+ GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
+ .left()
+ .on(se -> onGroupNotFoundInComponentError(component, groupId));
+
+ String existingGroupName = existingGroup.getName();
+ String updatedGroupName = updatedGroup.getName();
+ assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
+ existingGroup.setName(updatedGroupName);
+
+ return updateGroup(component, existingGroup, existingGroupName)
+ .left()
+ .on(this::onFailedUpdateGroupDBOperation);
+ } finally {
+ titanDao.commit();
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+
+ }
+
+ private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) {
+ if (!ValidationUtils.validateResourceInstanceNameLength(updatedGroupName)) {
+ throw new ComponentException(ActionStatus.EXCEEDS_LIMIT, "Group Name", ValidationUtils.RSI_NAME_MAX_LENGTH.toString());
+ }
+ if (!ValidationUtils.validateResourceInstanceName(updatedGroupName)) {
+ throw new ComponentException(ActionStatus.INVALID_VF_MODULE_NAME, updatedGroupName);
+ }
+ if (!ComponentValidations.validateNameIsUniqueInComponent(currentGroupName, updatedGroupName, component)) {
+ throw new ComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, "Group", updatedGroupName);
+ }
+ }
+
+ public GroupDefinition deleteGroup(ComponentTypeEnum componentTypeEnum, String componentId, String groupId,
+ String userId) {
+ try {
+ Component component = accessValidations.validateUserCanWorkOnComponentAndLockIt(componentTypeEnum, componentId, userId, DELETE_GROUP);
+
+ GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
+ .left()
+ .on(se -> onGroupNotFoundInComponentError(component, groupId));
+
+ List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
+ .left()
+ .on(this::onFailedGroupDBOperation);
+ return gdList.get(0);
+ } finally {
+ titanDao.commit();
+ graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
+ }
+ }
+
+ private List<GroupDefinition> onFailedGroupDBOperation(ResponseFormat responseFormat) {
+ titanDao.rollback();
+ throw new ComponentException(responseFormat);
+ }
+
+ private GroupDefinition onFailedUpdateGroupDBOperation(ResponseFormat responseFormat) {
+ titanDao.rollback();
+ throw new ComponentException(responseFormat);
+ }
+
+ private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) {
+ throw new ComponentException(ActionStatus.GROUP_IS_MISSING, groupId,
+ component.getSystemName(), getComponentTypeForResponse(component));
+ }
+
+ private GroupTypeDefinition onGroupTypeNotFound(Component component) {
+ throw new ComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(),
+ component.getComponentType().toString());
+ }
+
+ private Boolean onFailedToLockComponent(ResponseFormat responseFormat) {
+ throw new ComponentException(responseFormat);
+ }
+
+
+ public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions) {
+
+ Map<String, GroupDataDefinition> groups = new HashMap<>();
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+
+ }
+
+ // handle groups and convert to tosca data
+ if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
+ for (GroupDefinition groupDefinition : groupDefinitions) {
+ Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, 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) {
+ createGroupsResult = groupsOperation.createGroups(component, groups);
+ 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<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions) {
+
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
+ List<GroupDataDefinition> groups = new ArrayList<>();
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status))));
+
+ }
+
+ // handle groups and convert to tosca data
+ if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
+ for (GroupDefinition groupDefinition : groupDefinitions) {
+ Either<GroupDefinition, ResponseFormat> handleGroupRes = handleGroup(component, groupDefinition, allDataTypes.left().value());
+ if (handleGroupRes.isRight()) {
+ result = Either.right(handleGroupRes.right().value());
+ break;
+ }
+ GroupDefinition handledGroup = handleGroupRes.left().value();
+ groups.add(new GroupDataDefinition(handledGroup));
+ }
+ }
+ if (result == null) {
+ createGroupsResult = groupsOperation.addGroups(component, groups);
+ 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<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, List<GroupDefinition> groupDefinitions) {
+
+ Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult;
+
+ deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(x -> new GroupDataDefinition(x)).collect(toList()));
+ if (deleteGroupsResult.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value())));
+ }
+ return Either.left(deleteGroupsResult.left().value());
+ }
+
+ /**
+ * Update specific group version
+ *
+ */
+ public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions) {
+
+ Either<List<GroupDefinition>, ResponseFormat> result = null;
+ Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult;
+
+ createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(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<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
+
+ log.trace("Going to create group {}", groupDefinition);
+ // 3. verify group not already exist
+ String groupDefinitionName = groupDefinition.getName();
+ if (groupExistsInComponent(groupDefinitionName, component)) {
+ String componentTypeForResponse = getComponentTypeForResponse(component);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
+ }
+ // 4. verify type of group exist
+ String groupType = groupDefinition.getType();
+ if (StringUtils.isEmpty(groupType)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupDefinitionName));
+ }
+ Either<GroupTypeDefinition, StorageOperationStatus> 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);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
+ } else {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ // 6. verify the component instances type are allowed according to
+ // the member types in the group type
+ GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
+
+ Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
+
+ if (areValidMembers.isRight()) {
+ ResponseFormat responseFormat = areValidMembers.right().value();
+ return Either.right(responseFormat);
+ }
+ // 7. verify the artifacts belongs to the component
+ Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
+ if (areValidArtifacts.isRight()) {
+ ResponseFormat responseFormat = areValidArtifacts.right().value();
+ return Either.right(responseFormat);
+ }
+ List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
+
+ List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
+ List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
+ if (CollectionUtils.isNotEmpty(properties)) {
+ if (CollectionUtils.isEmpty(groupTypeProperties)) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.MATCH_NOT_FOUND))));
+ }
+
+ Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+
+ Either<GroupProperty, TitanOperationStatus> addPropertyResult;
+ int i = 1;
+ for (GroupProperty prop : properties) {
+ addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType);
+ if (addPropertyResult.isRight()) {
+ BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyResult.right().value()))));
+ }
+ updatedGroupTypeProperties.add(addPropertyResult.left().value());
+
+ i++;
+ }
+ }
+ if (groupDefinition.getUniqueId() == null) {
+ String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName);
+ groupDefinition.setUniqueId(uid);
+ }
+ groupDefinition.convertFromGroupProperties(updatedGroupTypeProperties);
+ groupDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+ groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
+ groupDefinition.setVersion(INITIAL_VERSION);
+ groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
+
+ return Either.left(groupDefinition);
+ }
+
+ private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
+ boolean found = false;
+ List<GroupDefinition> groups = component.getGroups();
+ if (CollectionUtils.isNotEmpty(groups)) {
+ found = groups.stream().filter(p -> p.getName().equalsIgnoreCase(groupDefinitionName)).findFirst().orElse(null) != null;
+ }
+ return found;
+ }
+
+ private Either<GroupProperty, TitanOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes, String groupType) {
+
+ if (prop == null) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+
+ PropertyDataDefinition propDataDef = prop;
+ String propertyType = propDataDef.getType();
+ String value = groupProperty.getValue();
+
+ Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
+ if (checkInnerType.isRight()) {
+ TitanOperationStatus status = checkInnerType.right().value();
+ return Either.right(status);
+ }
+
+ String innerType = checkInnerType.left().value();
+
+ log.debug("Before validateAndUpdatePropertyValue");
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
+ log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
+
+ String newValue = value;
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (!res) {
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+
+ String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index)
+ : prop.getUniqueId();
+
+ groupProperty.setUniqueId(uniqueId);
+ groupProperty.setValue(newValue);
+ 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);
+ }
+
+ // For old groups we want to leave indexing of property
+ // For new groups we just need the types
+ private boolean shouldReconstructUniqueId(String groupType) {
+ return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
new file mode 100644
index 0000000000..cdd1b30656
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
@@ -0,0 +1,46 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+import java.util.Set;
+
+@Component
+public class GroupTypeBusinessLogic {
+
+ private final GroupTypeOperation groupTypeOperation;
+ private final TitanDao titanDao;
+ private final UserValidations userValidations;
+
+ public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, TitanDao titanDao, UserValidations userValidations) {
+ this.groupTypeOperation = groupTypeOperation;
+ this.titanDao = titanDao;
+ this.userValidations = userValidations;
+ }
+
+
+ public List<GroupTypeDefinition> getAllGroupTypes(String userId, String internalComponentType) {
+ try {
+ userValidations.validateUserExists(userId, "get group types", true)
+ .left()
+ .on(this::onUserError);
+
+ Set<String> excludeGroupTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping().get(internalComponentType);
+ return groupTypeOperation.getAllGroupTypes(excludeGroupTypes);
+ } finally {
+ titanDao.commit();
+ }
+ }
+
+ private User onUserError(ResponseFormat responseFormat) {
+ throw new ComponentException(responseFormat);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
index b3448b27ef..5cdb589d2a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
@@ -20,21 +20,14 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
@@ -45,104 +38,152 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
@Component("groupTypeImportManager")
public class GroupTypeImportManager {
- public static void main(String[] args) {
-
- List<PropertyDefinition> properties = new ArrayList<>();
- PropertyDefinition propertyDefintion = new PropertyDefinition();
- propertyDefintion.setName("aaa");
- properties.add(propertyDefintion);
-
- List<String> allParentsProps = new ArrayList<>();
- allParentsProps.add("aaa");
- allParentsProps.add("bbb");
-
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- System.out.println(alreadyExistPropsCollection);
-
- }
-
- private static Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class.getName());
- @Resource
- private IGroupTypeOperation groupTypeOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private ToscaOperationFacade toscaOperationFacade;
-
- @Resource
- private CommonImportManager commonImportManager;
-
- public Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypes(String groupTypesYml) {
- return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType);
- }
-
- private Either<List<GroupTypeDefinition>, ActionStatus> createGroupTypesFromYml(String groupTypesYml) {
-
- return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData));
- }
-
- private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) {
- return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()),
- groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), null);
- }
-
- private Either<ActionStatus, ResponseFormat> validateGroupType(GroupTypeDefinition groupType) {
- Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK);
- if (groupType.getMembers() != null) {
- if (groupType.getMembers().isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_MEMBER_EMPTY, groupType.getType());
- result = Either.right(responseFormat);
- } else {
- for (String member : groupType.getMembers()) {
- // Verify that such Resource exist
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member);
- if (eitherMemberExist.isRight()) {
- StorageOperationStatus operationStatus = eitherMemberExist.right().value();
- log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus);
- ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Import GroupType", "resource", member);
- result = Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, member));
- break;
- }
- }
-
- }
- }
- return result;
- }
-
- private GroupTypeDefinition createGroupType(String groupTypeName, Map<String, Object> toscaJson) {
-
- GroupTypeDefinition groupType = new GroupTypeDefinition();
-
- if (toscaJson != null) {
- // Description
- final Consumer<String> descriptionSetter = description -> groupType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
- // Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> groupType.setDerivedFrom(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
- // Properties
- commonImportManager.setProperties(toscaJson, (values) -> groupType.setProperties(values));
- // Metadata
- final Consumer<Map<String, String>> metadataSetter = metadata -> groupType.setMetadata(metadata);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
- // Members
- final Consumer<List<String>> membersSetter = members -> groupType.setMembers(members);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), membersSetter);
-
- groupType.setType(groupTypeName);
-
- groupType.setHighestVersion(true);
-
- groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
- }
- return groupType;
- }
+ public static void main(String[] args) {
+
+ List<PropertyDefinition> properties = new ArrayList<>();
+ PropertyDefinition propertyDefintion = new PropertyDefinition();
+ propertyDefintion.setName("aaa");
+ properties.add(propertyDefintion);
+
+ List<String> allParentsProps = new ArrayList<>();
+ allParentsProps.add("aaa");
+ allParentsProps.add("bbb");
+
+ Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
+ System.out.println(alreadyExistPropsCollection);
+
+ }
+
+ private static final Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class);
+ @Resource
+ private IGroupTypeOperation groupTypeOperation;
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Resource
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Resource
+ private CommonImportManager commonImportManager;
+
+ public Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypes(String groupTypesYml) {
+ return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createGroupTypesFromYml(elementTypeYml), groupTypesList -> createGroupTypesByDao(groupTypesList), ElementTypeEnum.GroupType);
+ }
+
+ private Either<List<GroupTypeDefinition>, ActionStatus> createGroupTypesFromYml(String groupTypesYml) {
+
+ return commonImportManager.createElementTypesFromYml(groupTypesYml, (groupTypeName, groupTypeJsonData) -> createGroupType(groupTypeName, groupTypeJsonData));
+ }
+
+ private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> createGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(groupTypesToCreate, groupType -> validateGroupType(groupType), groupType -> new ImmutablePair<>(ElementTypeEnum.GroupType, groupType.getType()),
+ groupTypeName -> groupTypeOperation.getLatestGroupTypeByType(groupTypeName), groupType -> groupTypeOperation.addGroupType(groupType), groupTypeOperation::upgradeGroupType);
+ }
+
+ private Either<ActionStatus, ResponseFormat> validateGroupType(GroupTypeDefinition groupType) {
+ Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK);
+ if (groupType.getMembers() != null) {
+ if (groupType.getMembers().isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_MEMBER_EMPTY, groupType.getType());
+ result = Either.right(responseFormat);
+ } else {
+ for (String member : groupType.getMembers()) {
+ // Verify that such Resource exist
+ Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member);
+ if (eitherMemberExist.isRight()) {
+ StorageOperationStatus operationStatus = eitherMemberExist.right().value();
+ log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus);
+ ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("Import GroupType", "resource", member);
+ result = Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, member));
+ break;
+ }
+ }
+
+ }
+ }
+ return result;
+ }
+
+ private GroupTypeDefinition createGroupType(String groupTypeName, Map<String, Object> toscaJson) {
+
+ GroupTypeDefinition groupType = new GroupTypeDefinition();
+
+ if (toscaJson != null) {
+ // Description
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription);
+ // Derived From
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), groupType::setDerivedFrom);
+ // Properties
+ commonImportManager.setProperties(toscaJson, groupType::setProperties);
+ // Metadata
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), groupType::setMetadata);
+ // Capabilities
+ List<CapabilityTypeDefinition> capabilityTypes = createGroupCapabilityTypes(toscaJson);
+ groupType.setCapabilityTypes(capabilityTypes);
+ // Members
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers);
+
+ groupType.setType(groupTypeName);
+
+ groupType.setHighestVersion(true);
+
+ groupType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
+ }
+ return groupType;
+ }
+
+ /**
+ * @param toscaJson
+ * @return
+ */
+ private List<CapabilityTypeDefinition> createGroupCapabilityTypes(Map<String, Object> toscaJson) {
+ CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder();
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
+ List<CapabilityTypeDefinition> capabilityTypes;
+ if (capabilityTypeToscaJsonHolder.isEmpty()) {
+ capabilityTypes = Collections.emptyList();
+ }
+ else {
+ capabilityTypes = commonImportManager.createElementTypesFromToscaJsonMap(this::createGroupCapabilityType, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
+ }
+ return capabilityTypes;
+ }
+
+ private class CapabilityTypeToscaJsonHolder {
+ private Map<String, Object> capabilityTypeToscaJson;
+
+ public Map<String, Object> getCapabilityTypeToscaJson() {
+ return capabilityTypeToscaJson;
+ }
+
+ public boolean isEmpty() {
+ return capabilityTypeToscaJson == null;
+ }
+
+ public void setCapabilityTypeToscaJson(Map<String, Object> capabilityTypeToscaJson) {
+ this.capabilityTypeToscaJson = capabilityTypeToscaJson;
+ }
+ }
+
+ private CapabilityTypeDefinition createGroupCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
+ CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
+
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capabilityType::setType);
+ // Properties
+ commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties);
+
+ return capabilityType;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
deleted file mode 100644
index eff3d39f7f..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
+++ /dev/null
@@ -1,526 +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.components.impl;
-
-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 java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import javax.annotation.Resource;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.Pair;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.util.EntityUtils;
-import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth;
-import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.api.HealthCheckInfo;
-import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
-import org.openecomp.sdc.common.impl.ExternalConfiguration;
-import org.openecomp.sdc.common.util.HealthCheckUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Component("healthCheckBusinessLogic")
-public class HealthCheckBusinessLogic {
-
- protected static String BE_HEALTH_LOG_CONTEXT = "be.healthcheck";
-
- private static Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT);
-
- private static final String BE_HEALTH_CHECK_STR = "beHealthCheck";
- private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s";
-
- @Resource
- private TitanGenericDao titanGenericDao;
-
- @Resource
- private IEsHealthCheckDao esHealthCheckDao;
-
- @Resource
- private DistributionEngineClusterHealth distributionEngineClusterHealth;
-
- @Resource
- private CassandraHealthCheck cassandraHealthCheck;
-
- @Autowired
- private SwitchoverDetector switchoverDetector;
-
- private static Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName());
-
- private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
-
- public HealthCheckBusinessLogic() {
-
- }
-
- private ScheduledFuture<?> scheduledFuture = null;
-
- ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "BE-Health-Check-Task");
- }
- });
-
- HealthCheckScheduledTask healthCheckScheduledTask = null;
-
- @PostConstruct
- public void init() {
-
- prevBeHealthCheckInfos = getBeHealthCheckInfos();
-
- log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
-
- healthCheckScheduledTask = new HealthCheckScheduledTask();
-
- if (this.scheduledFuture == null) {
- this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, TimeUnit.SECONDS);
- }
-
- }
-
- public boolean isDistributionEngineUp() {
-
- HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
- if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) {
- return false;
- }
- return true;
- }
-
- public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() {
-
- return new ImmutablePair<Boolean, List<HealthCheckInfo>>(getAggregateBeStatus(prevBeHealthCheckInfos), prevBeHealthCheckInfos);
-
- }
-
- private Boolean getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
-
- Boolean status = true;
-
- for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
- if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && !healthCheckInfo.getHealthCheckComponent().equals(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE)) {
- status = false;
- break;
- }
- }
- return status;
- }
-
-
- private List<HealthCheckInfo> getBeHealthCheckInfos() {
-
- log.trace("In getBeHealthCheckInfos");
-
- List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>();
-
- // BE
- getBeHealthCheck(healthCheckInfos);
-
- // Titan
- getTitanHealthCheck(healthCheckInfos);
-
- // Distribution Engine
- getDistributionEngineCheck(healthCheckInfos);
-
- //Cassandra
- getCassandraHealthCheck(healthCheckInfos);
-
- // Amdocs
- getAmdocsHealthCheck(healthCheckInfos);
-
- //DCAE
- getDcaeHealthCheck(healthCheckInfos);
-
- return healthCheckInfos;
- }
-
- private List<HealthCheckInfo> getBeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
- String appVersion = ExternalConfiguration.getAppVersion();
- String description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.UP, appVersion, description));
- return healthCheckInfos;
- }
-
- //Removed from aggregate HC - TDP 293490
- /* private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
-
- // ES health check and version
- HealthCheckStatus healthCheckStatus;
- String description;
-
- try {
- healthCheckStatus = esHealthCheckDao.getClusterHealthStatus();
- } catch (Exception e) {
- healthCheckStatus = HealthCheckStatus.DOWN;
- description = "ES cluster error: " + e.getMessage();
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
- return healthCheckInfos;
- }
- if (healthCheckStatus.equals(HealthCheckStatus.DOWN)) {
- description = "ES cluster is down";
- } else {
- description = "OK";
- }
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
- return healthCheckInfos;
- }
- */
- public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
- // Titan health check and version
- String description;
- boolean isTitanUp;
-
- try {
- isTitanUp = titanGenericDao.isGraphOpen();
- } catch (Exception e) {
- description = "Titan error: " + e.getMessage();
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description));
- return healthCheckInfos;
- }
- if (isTitanUp) {
- description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, description));
- } else {
- description = "Titan graph is down";
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, description));
- }
- return healthCheckInfos;
- }
-
- private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
-
- String description;
- boolean isCassandraUp;
-
- try {
- isCassandraUp = cassandraHealthCheck.getCassandraStatus();
- } catch (Exception e) {
- isCassandraUp = false;
- description = "Cassandra error: " + e.getMessage();
- }
- if (isCassandraUp) {
- description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.UP, null, description));
- } else {
- description = "Cassandra is down";
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.DOWN, null, description));
- }
- return healthCheckInfos;
-
- }
-
- private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) {
-
- HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
-
- healthCheckInfos.add(healthCheckInfo);
-
- }
-
- private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
- HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl());
- healthCheckInfos.add(beHealthCheckInfo);
- return healthCheckInfos;
- }
-
- private List<HealthCheckInfo> getDcaeHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
- HealthCheckInfo beHealthCheckInfo = getHostedComponentsBeHealthCheck(Constants.HC_COMPONENT_DCAE, buildDcaeHealthCheckUrl());
- healthCheckInfos.add(beHealthCheckInfo);
- return healthCheckInfos;
- }
-
- private HealthCheckInfo getHostedComponentsBeHealthCheck(String componentName, String healthCheckUrl) {
- HealthCheckStatus healthCheckStatus;
- String description;
- String version = null;
- List<HealthCheckInfo> componentsInfo = new ArrayList<>();
-
- CloseableHttpClient httpClient = getHttpClient();
-
- if (healthCheckUrl != null) {
- HttpGet httpGet = new HttpGet(healthCheckUrl);
- CloseableHttpResponse beResponse;
- int beStatus;
- try {
- beResponse = httpClient.execute(httpGet);
- beStatus = beResponse.getStatusLine().getStatusCode();
-
- String aggDescription = "";
-
- if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
- HttpEntity entity = beResponse.getEntity();
- String beJsonResponse = EntityUtils.toString(entity);
- log.trace("{} Health Check response: {}", componentName, beJsonResponse);
-
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>(){});
- version = healthCheckMap.get("sdcVersion") != null ? healthCheckMap.get("sdcVersion").toString() : null;
- if (healthCheckMap.containsKey("componentsInfo")) {
- componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {});
- }
-
- if (componentsInfo.size() > 0) {
- aggDescription = HealthCheckUtil.getAggregateDescription(componentsInfo, null);
- } else {
- componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, null));
- }
- } else {
- log.trace("{} Health Check Response code: {}", componentName, beStatus);
- }
-
- if (beStatus != HttpStatus.SC_OK) {
- healthCheckStatus = HealthCheckStatus.DOWN;
- description = aggDescription.length() > 0
- ? aggDescription
- : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN.
- if (componentsInfo.size() == 0) {
- componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description));
- }
- } else {
- healthCheckStatus = HealthCheckStatus.UP;
- description = "OK";
- }
-
- } catch (Exception e) {
- log.error("{} unexpected response: ", componentName, e);
- healthCheckStatus = HealthCheckStatus.DOWN;
- description = componentName + " unexpected response: " + e.getMessage();
- if (componentsInfo != null && componentsInfo.size() == 0) {
- componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description));
- }
- } finally {
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- log.error("closing http client has failed" , e);
- }
- }
- }
- } else {
- healthCheckStatus = HealthCheckStatus.DOWN;
- description = componentName + " health check Configuration is missing";
- componentsInfo.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, description));
- }
-
- return new HealthCheckInfo(componentName, healthCheckStatus, version, description, componentsInfo);
- }
-
- private CloseableHttpClient getHttpClient() {
- int timeout = 3000;
- RequestConfig.Builder requestBuilder = RequestConfig.custom();
- requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout);
-
- HttpClientBuilder builder = HttpClientBuilder.create();
- builder.setDefaultRequestConfig(requestBuilder.build());
- return builder.build();
- }
-
- @PreDestroy
- private void destroy() {
-
- if (scheduledFuture != null) {
- scheduledFuture.cancel(true);
- scheduledFuture = null;
- }
-
- if (healthCheckScheduler != null) {
- healthCheckScheduler.shutdown();
- }
-
- }
-
- public class HealthCheckScheduledTask implements Runnable {
-
- List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();
-
- public HealthCheckScheduledTask() {
-
- }
-
- @Override
- public void run() {
-
- healthLogger.trace("Executing BE Health Check Task");
-
- List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
- boolean healthStatus = getAggregateBeStatus(currentBeHealthCheckInfos);
-
- boolean prevHealthStatus = getAggregateBeStatus(prevBeHealthCheckInfos);
-
- boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
-
- if (prevHealthStatus != healthStatus || anyStatusChanged) {
- log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
-
- prevBeHealthCheckInfos = currentBeHealthCheckInfos;
- logAlarm(healthStatus);
- }
-
- }
- }
-
- private void logAlarm(boolean prevHealthState) {
- if (prevHealthState) {
- BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR);
- } else {
- BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);
- }
- }
-
- private void logAlarm(String componentChangedMsg) {
- BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg);
- }
-
-
- public String getSiteMode() {
- return switchoverDetector.getSiteMode();
- }
-
- public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
-
- boolean result = false;
-
- if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
-
- Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
- Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
-
- if (currentValues != null && prevValues != null) {
- int currentSize = currentValues.size();
- int prevSize = prevValues.size();
-
- if (currentSize != prevSize) {
-
- result = true; //extra/missing component
-
- Map<String, HealthCheckStatus> notPresent = null;
- if (currentValues.keySet().containsAll(prevValues.keySet())) {
- notPresent = new HashMap<>(currentValues);
- notPresent.keySet().removeAll(prevValues.keySet());
- } else {
- notPresent = new HashMap<>(prevValues);
- notPresent.keySet().removeAll(currentValues.keySet());
- }
-
- for (String component : notPresent.keySet()) {
- logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
- }
- // HealthCheckComponent changedComponent = notPresent.keySet().iterator().next();
-
- } else {
-
- for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) {
- String key = entry.getKey();
- HealthCheckStatus value = entry.getValue();
-
- if (!prevValues.containsKey(key)) {
- result = true; //component missing
- logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
- break;
- }
-
- HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
-
- if (value != prevHealthCheckStatus) {
- result = true; //component status changed
- logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
- break;
- }
- }
- }
- }
-
- } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
- result = false;
- } else {
- logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
- result = true;
- }
-
- return result;
- }
-
- private String buildOnBoardingHealthCheckUrl() {
-
- Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
-
- if (onboardingConfig != null) {
- String protocol = onboardingConfig.getProtocol();
- String host = onboardingConfig.getHost();
- Integer port = onboardingConfig.getPort();
- String uri = onboardingConfig.getHealthCheckUri();
-
- return protocol + "://" + host + ":" + port + uri;
- }
-
- log.error("onboarding health check configuration is missing.");
- return null;
- }
-
- private String buildDcaeHealthCheckUrl() {
-
- Configuration.DcaeConfig dcaeConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getDcae();
-
- if (dcaeConfig != null) {
- String protocol = dcaeConfig.getProtocol();
- String host = dcaeConfig.getHost();
- Integer port = dcaeConfig.getPort();
- String uri = dcaeConfig.getHealthCheckUri();
-
- return protocol + "://" + host + ":" + port + uri;
- }
-
- log.error("dcae health check configuration is missing.");
- return null;
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java
new file mode 100644
index 0000000000..84df217815
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java
@@ -0,0 +1,8 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+
+public interface HealthCheckInformer {
+
+ HealthCheckInfo getHealthCheckInfo();
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
index 66c1868223..57e6eb54a7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
@@ -23,5 +23,5 @@ package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
public interface IDeploymentArtifactTypeConfigGetter {
- ArtifactTypeConfig getDeploymentArtifactConfig();
+ ArtifactTypeConfig getDeploymentArtifactConfig();
}
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 01d64f519f..3db76a9398 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
@@ -20,20 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.Consumer;
-import java.util.function.Function;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
import org.apache.commons.lang3.StringEscapeUtils;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
@@ -45,7 +35,6 @@ import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.util.GsonFactory;
import org.springframework.beans.factory.config.YamlProcessor;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
@@ -54,719 +43,607 @@ import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.Consumer;
+import java.util.function.Function;
public final class ImportUtils {
- private ImportUtils() {
-
- }
-
- private static CustomResolver customResolver = new CustomResolver();
- private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader();
-
- private static class CustomResolver extends Resolver {
- @Override
- protected void addImplicitResolvers() {
- // avoid implicit resolvers for strings that can be interpreted as boolean values
- addImplicitResolver(Tag.STR, EMPTY, "");
- addImplicitResolver(Tag.STR, NULL, null);
- addImplicitResolver(Tag.NULL, NULL, "~nN\0");
- addImplicitResolver(Tag.NULL, EMPTY, null);
- addImplicitResolver(Tag.INT, INT, "-+0123456789");
- addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
- addImplicitResolver(Tag.YAML, YAML, "!&*");
- }
- }
-
-
- private static void buildMap(Map<String, Object> output, Map<String, Object> map) {
- for (Entry<String, Object> entry : map.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof Map) {
- Map<String, Object> result = new LinkedHashMap<>();
- buildMap(result, (Map) value);
- output.put(key, result);
- }
- else if (value instanceof Collection) {
- Map<String, Object> result = new LinkedHashMap<>();
- int i = 0;
- for(Object item : (Collection<Object>) value) {
- buildMap(result, Collections.singletonMap("[" + (i++) + "]", item));
- }
- output.put(key, new ArrayList<>(result.values()));
- }
- else {
- output.put(key, value);
- }
- }
- }
-
- public static Map<String, Object> loadYamlAsStrictMap(String content){
- Map<String, Object> result = new LinkedHashMap<>();
- Object map = STRICT_MAPPING_YAML_LOADER.load(content);
- buildMap(result, (Map<String, Object>)map);
- return result;
- }
-
- private static class YamlLoader extends YamlProcessor {
- public Yaml getStrictYamlLoader() {
- return createYaml();
- }
- }
-
- @SuppressWarnings("unchecked")
- public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) {
- Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload);
- return getHeatParameters(heatData, artifactType);
- }
-
- public static class Constants {
-
- public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0";
- public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
- public static final String VENDOR_NAME = "ATT (Tosca)";
- public static final String VENDOR_RELEASE = "1.0.0.wd03";
- public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
- public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
- public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
- // public static final String ABSTRACT_CATEGORY = "Generic/Abstract";
- public static final String ABSTRACT_CATEGORY_NAME = "Generic";
- public static final String ABSTRACT_SUBCATEGORY = "Abstract";
- public static final String DEFAULT_ICON = "defaulticon";
- public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC";
- public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
- public static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_";
- public static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1");
- public static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar");
- public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
- public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
- }
-
- public enum ResultStatusEnum {
- 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 {
- BOOLEAN, STRING, MAP, LIST, ALL
- }
-
- public enum ToscaTagNamesEnum {
- DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"),
- // Properties
- PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"),
- // Group Types
- MEMBERS("members"), METADATA("metadata"),
- // Policy Types
- TARGETS("targets"),
- // Capabilities
- CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"),
- // Requirements
- REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"),
- // Heat env Validation
- PARAMETERS("parameters"),
- // Import Validations
- TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"),
- SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"),
- // Attributes
- ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input");
-
- private String elementName;
-
- private ToscaTagNamesEnum(String elementName) {
- this.elementName = elementName;
- }
-
- public String getElementName() {
- return elementName;
- }
- }
-
- @SuppressWarnings("unchecked")
- private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List<Object> returnedList) {
- if (elementValue instanceof Map) {
- ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
- } else if (elementValue instanceof List) {
- ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList);
- }
- }
-
- @SuppressWarnings("unchecked")
- private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList, Object elementValue) {
-
- if (elementValue instanceof Boolean) {
- if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) {
- returnedList.add(elementValue);
- }
- }
-
- else if (elementValue instanceof String) {
- if (elementType == ToscaElementTypeEnum.STRING || elementType == ToscaElementTypeEnum.ALL) {
- returnedList.add(elementValue);
- }
- } else if (elementValue instanceof Map) {
- if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) {
- returnedList.add(elementValue);
- }
- ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
-
- } else if (elementValue instanceof List) {
- if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) {
- returnedList.add(elementValue);
- }
- ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList);
-
- }
- // For Integer, Double etc...
- else if (elementType == ToscaElementTypeEnum.ALL) {
- if (elementValue != null) {
- returnedList.add(String.valueOf(elementValue));
- }
- }
- }
-
- private static void findAllToscaElementsInList(List<Object> list, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) {
- Iterator<Object> listItr = list.iterator();
- while (listItr.hasNext()) {
- Object elementValue = listItr.next();
- handleElementNameNotFound(elementName, elementValue, elementType, returnedList);
- }
-
- }
-
- public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) {
- List<Object> foundElements = new ArrayList<>();
- Either<Object, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements);
- if (foundElements.size() > 0) {
- returnedElement = Either.left(foundElements.get(0));
- }
- return returnedElement;
-
- }
-
- /**
- * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br>
- * Returns Either element with:<br>
- * List with all value if values found<br>
- * Or ELEMENT_NOT_FOUND ActionStatus
- *
- * @param toscaJson
- * @param toscaTagName
- * @return
- */
- public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) {
- Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- String skipKey = null;
- if (toscaJson.containsKey(elementName)) {
- Object elementValue = toscaJson.get(elementName);
- handleElementNameFound(elementName, elementType, returnedList, elementValue);
- skipKey = elementName;
- }
-
- Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator();
- while (keyValItr.hasNext()) {
- Entry<String, Object> keyValEntry = keyValItr.next();
- if (!String.valueOf(keyValEntry.getKey()).equals(skipKey)) {
- handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList);
- }
- }
-
- if (returnedList.size() > 0) {
- returnedElement = Either.left(returnedList);
- }
-
- return returnedElement;
- }
-
- @SuppressWarnings("unchecked")
- public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
- Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST);
- if (findFirstToscaElement.isLeft()) {
- returnedElement = Either.left((List<T>) findFirstToscaElement.left().value());
- }
- return returnedElement;
-
- }
-
- @SuppressWarnings("unchecked")
- public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
- Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP);
- if (findFirstToscaElement.isLeft()) {
- returnedElement = Either.left((Map<String, T>) findFirstToscaElement.left().value());
- }
- return returnedElement;
-
- }
-
- public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
- Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING);
- if (findFirstToscaElements.isLeft()) {
- returnedElement = Either.left((String) findFirstToscaElements.left().value());
- }
- return returnedElement;
- }
-
- /**
- * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status
- *
- * @param toscaJson
- * @param toscaTagName
- * @return
- */
- public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
- Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN);
- if (findFirstToscaElements.isLeft()) {
- returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value()));
- }
- return returnedElement;
- }
-
- private static void setPropertyConstraints(Map<String, Object> propertyValue, PropertyDefinition property) {
- Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS);
- if (propertyFieldconstraints.isLeft()) {
- List<Object> jsonConstraintList = propertyFieldconstraints.left().value();
-
- List<PropertyConstraint> constraintList = new ArrayList<>();
- Type constraintType = new TypeToken<PropertyConstraint>() {
- }.getType();
- Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
-
- for (Object constraintJson : jsonConstraintList) {
- PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType);
- constraintList.add(propertyConstraint);
- }
- property.setConstraints(constraintList);
- }
- }
-
- public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) {
-
- PropertyDefinition propertyDef = new PropertyDefinition();
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type));
- ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef);
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc));
-
- Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (findToscaElement.isLeft()) {
- String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType());
- propertyDef.setDefaultValue(propertyJsonStringValue);
- }
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
- ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status));
- ImportUtils.setPropertyScheme(propertyValue, propertyDef);
- ImportUtils.setPropertyConstraints(propertyValue, propertyDef);
-
- return propertyDef;
- }
-
- public static InputDefinition createModuleInput(Map<String, Object> inputValue) {
-
- InputDefinition inputDef = new InputDefinition();
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc));
-
- Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (findToscaElement.isLeft()) {
- String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType());
- inputDef.setDefaultValue(propertyJsonStringValue);
- }
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable)));
- ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label));
- ImportUtils.setPropertyScheme(inputValue, inputDef);
- ImportUtils.setPropertyConstraints(inputValue, inputDef);
-
- return inputDef;
- }
-
- public static PropertyDefinition createModuleAttribute(Map<String, Object> attributeMap) {
-
- 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));
- Either<Object, ResultStatusEnum> eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (eitherDefaultValue.isLeft()) {
- String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType());
- attributeDef.setDefaultValue(attributeDefaultValue);
- }
- Either<Object, ResultStatusEnum> eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL);
- if (eitherValue.isLeft()) {
- String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType());
- attributeDef.setValue(attributeValue);
- }
- ImportUtils.setAttributeScheme(attributeMap, attributeDef);
- return attributeDef;
- }
-
- private static void setPropertyFieldStatus(Map<String, Object> propertyValue, PropertyDefinition propertyDef) {
- Either<String, ResultStatusEnum> propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS);
- if (propertyFieldIsStatus.isLeft()) {
- propertyDef.setStatus(propertyFieldIsStatus.left().value());
- }
-
- }
-
- private static void setAttributeFieldStatus(Map<String, Object> propertyValue, PropertyDefinition propertyDef) {
- Either<String, ResultStatusEnum> propertyFieldIsStatus = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.STATUS);
- if (propertyFieldIsStatus.isLeft()) {
- propertyDef.setStatus(propertyFieldIsStatus.left().value());
- }
-
- }
-
- private static void setPropertyScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
- Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue);
- if (eitherSchema.isLeft()) {
- SchemaDefinition schemaDef = new SchemaDefinition();
- schemaDef.setProperty(eitherSchema.left().value().getProperty());
- propertyDefinition.setSchema(schemaDef);
- }
-
- }
-
- private static void setAttributeScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
- Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue);
- if (eitherSchema.isLeft()) {
- SchemaDefinition schemaDef = new SchemaDefinition();
- schemaDef.setProperty(eitherSchema.left().value().getProperty());
- propertyDefinition.setSchema(schemaDef);
- }
-
- }
-
- private static Either<SchemaDefinition, ResultStatusEnum> getSchema(Map<String, Object> propertyValue) {
- Either<SchemaDefinition, ResultStatusEnum> result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL);
- if (propertyFieldEntryScheme.isLeft()) {
- if (propertyFieldEntryScheme.left().value() instanceof String) {
- String schemaType = (String) propertyFieldEntryScheme.left().value();
- SchemaDefinition schema = new SchemaDefinition();
- PropertyDefinition schemeProperty = new PropertyDefinition();
- schemeProperty.setType(schemaType);
- schema.setProperty(schemeProperty);
- result = Either.left(schema);
-
- } else if (propertyFieldEntryScheme.left().value() instanceof Map) {
- PropertyDefinition schemeProperty = createModuleProperty((Map<String, Object>) propertyFieldEntryScheme.left().value());
- SchemaDefinition schema = new SchemaDefinition();
- schema.setProperty(schemeProperty);
- result = Either.left(schema);
-
- }
-
- }
- return result;
- }
-
- private static void setPropertyFieldIsPassword(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldIsPassword = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.IS_PASSWORD);
- if (propertyFieldIsPassword.isLeft()) {
- dataDefinition.setPassword(Boolean.parseBoolean(propertyFieldIsPassword.left().value()));
- }
- }
-
- private static ResultStatusEnum setPropertyFieldDefaultValue(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<Object, ResultStatusEnum> propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- Gson gson = GsonFactory.getGson();
- if (propertyFieldDefaultValue.isLeft()) {
- Object defaultValue = propertyFieldDefaultValue.left().value();
- String type = dataDefinition.getType();
- ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(type);
- // esofer - supporting customized data types. The validation of the
- // type will be in the creation of the property.
- // if(innerToscaType == null){
- // return ResultStatusEnum.MISSING_ENTRY_SCHEMA_TYPE;
- // }
- // customized data types value is represented as json.
- // Also customized data types which are scalar ones, for example,
- // data type which derived from integer, their value will be
- // represented as json.
- if (innerToscaType == null || innerToscaType.equals(ToscaPropertyType.LIST) || innerToscaType.equals(ToscaPropertyType.MAP)) {
- String jsonObj = null;
- if (defaultValue != null) {
- jsonObj = gson.toJson(defaultValue);
- }
-
- dataDefinition.setDefaultValue(jsonObj);
- } else {
- dataDefinition.setDefaultValue(String.valueOf(defaultValue));
- }
-
- }
-
- return ResultStatusEnum.OK;
- }
-
- private static ResultStatusEnum setAttributeFieldDefaultValue(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<Object, ResultStatusEnum> propertyFieldDefaultValue = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- Gson gson = GsonFactory.getGson();
- if (propertyFieldDefaultValue.isLeft()) {
- Object defaultValue = propertyFieldDefaultValue.left().value();
- String type = dataDefinition.getType();
- ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(type);
- // esofer - supporting customized data types. The validation of the
- // type will be in the creation of the property.
- // if(innerToscaType == null){
- // return ResultStatusEnum.MISSING_ENTRY_SCHEMA_TYPE;
- // }
- // customized data types value is represented as json.
- // Also customized data types which are scalar ones, for example,
- // data type which derived from integer, their value will be
- // represented as json.
- if (innerToscaType == null || innerToscaType.equals(ToscaPropertyType.LIST) || innerToscaType.equals(ToscaPropertyType.MAP)) {
- String jsonObj = null;
- if (defaultValue != null) {
- jsonObj = gson.toJson(defaultValue);
- }
-
- dataDefinition.setDefaultValue(jsonObj);
- } else {
- dataDefinition.setDefaultValue(String.valueOf(defaultValue));
- }
-
- }
-
- return ResultStatusEnum.OK;
- }
-
- public static void setField(Map<String, Object> toscaJson, ToscaTagNamesEnum tagName, Consumer<String> setter) {
- Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName);
- if (fieldStringValue.isLeft()) {
- setter.accept(fieldStringValue.left().value());
- }
-
- }
-
- private static void setPropertyFieldDescription(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION);
- if (propertyFieldDescription.isLeft()) {
- dataDefinition.setDescription(propertyFieldDescription.left().value());
- }
- }
-
- private static void setPropertyFieldRequired(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED);
- if (propertyFieldRequired.isLeft()) {
- dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value()));
- }
- }
-
- private static void setAttributeFieldType(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE);
- if (propertyFieldType.isLeft()) {
- dataDefinition.setType(propertyFieldType.left().value());
- }
- }
-
- private static void setPropertyFieldType(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE);
- if (propertyFieldType.isLeft()) {
- dataDefinition.setType(propertyFieldType.left().value());
- }
- }
-
- private static void setAttributeFieldDescription(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
- Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION);
- if (propertyFieldDescription.isLeft()) {
- dataDefinition.setDescription(propertyFieldDescription.left().value());
- }
- }
-
- public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) {
- Function<String, PropertyDefinition> elementGenByName = elementName -> createProperties(elementName);
- Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleProperty(map);
-
- return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func);
-
- }
-
- public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson) {
- Function<String, InputDefinition> elementGenByName = elementName -> createInputs(elementName);
- Function<Map<String, Object>, InputDefinition> func = map -> createModuleInput(map);
-
- return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func);
-
- }
-
- public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getAttributes(Map<String, Object> toscaJson) {
- Function<String, PropertyDefinition> elementGenByName = elementName -> createAttribute(elementName);
- Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleAttribute(map);
-
- return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func);
- }
-
- public static <ElementDefinition> Either<Map<String, ElementDefinition>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementTagName, Function<String, ElementDefinition> elementGenByName,
- Function<Map<String, Object>, ElementDefinition> func) {
- Either<Map<String, ElementDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName);
- if (toscaAttributes.isLeft()) {
- Map<String, Object> jsonAttributes = toscaAttributes.left().value();
- Map<String, ElementDefinition> moduleAttributes = new HashMap<>();
- Iterator<Entry<String, Object>> propertiesNameValue = jsonAttributes.entrySet().iterator();
- while (propertiesNameValue.hasNext()) {
- Entry<String, Object> attributeNameValue = propertiesNameValue.next();
- if (attributeNameValue.getValue() instanceof Map) {
- @SuppressWarnings("unchecked")
- ElementDefinition attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
- moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute);
- } else {
-
- ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue()));
-
- moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element);
- }
-
- }
-
- if (moduleAttributes.size() > 0) {
- eitherResult = Either.left(moduleAttributes);
- }
-
- }
- return eitherResult;
-
- }
-
- private static PropertyDefinition createAttribute(String name) {
- PropertyDefinition attribute = new PropertyDefinition();
-
- attribute.setName(name);
- return attribute;
- }
-
- private static PropertyDefinition createProperties(String name) {
- PropertyDefinition property = new PropertyDefinition();
- property.setDefaultValue(name);
- property.setName(name);
- return property;
- }
-
- private static InputDefinition createInputs(String name) {
- InputDefinition input = new InputDefinition();
-
- input.setName(name);
- return input;
- }
-
- public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) {
-
- Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
- Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS);
- if (toscaProperties.isLeft()) {
- Map<String, Object> jsonProperties = toscaProperties.left().value();
- List<HeatParameterDefinition> moduleProperties = new ArrayList<>();
- Iterator<Entry<String, Object>> propertiesNameValue = jsonProperties.entrySet().iterator();
- while (propertiesNameValue.hasNext()) {
- Entry<String, Object> propertyNameValue = propertiesNameValue.next();
- if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) {
- if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
- @SuppressWarnings("unchecked")
- Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter((Map<String, Object>) propertyNameValue.getValue());
- if (propertyStatus.isRight()) {
- return Either.right(propertyStatus.right().value());
- }
- HeatParameterDefinition property = propertyStatus.left().value();
- property.setName(String.valueOf(propertyNameValue.getKey()));
- moduleProperties.add(property);
- } else {
- addHeatParamDefinition(moduleProperties, propertyNameValue, true);
- }
- } else {
- addHeatParamDefinition(moduleProperties, propertyNameValue, false);
- }
-
- }
-
- if (moduleProperties.size() > 0) {
- eitherResult = Either.left(moduleProperties);
- }
-
- }
- return eitherResult;
-
- }
-
- private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties, Entry<String, Object> propertyNameValue, boolean isJson) {
- HeatParameterDefinition property = new HeatParameterDefinition();
- Object value = propertyNameValue.getValue();
- if (value != null) {
- property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)));
- }
- property.setName(String.valueOf(propertyNameValue.getKey()));
- moduleProperties.add(property);
- }
-
- private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) {
- HeatParameterDefinition propertyDef = new HeatParameterDefinition();
- String type;
- Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE);
- if (propertyFieldType.isLeft()) {
- type = propertyFieldType.left().value();
- propertyDef.setType(type);
- } else {
- return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE);
- }
- Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION);
- if (propertyFieldDescription.isLeft()) {
- propertyDef.setDescription(propertyFieldDescription.left().value());
- }
-
- Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
- if (propertyFieldDefaultVal.isLeft()) {
- if (propertyFieldDefaultVal.left().value() == null) {
- return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE);
- }
- Object value = propertyFieldDefaultVal.left().value();
- String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value));
- propertyDef.setDefaultValue(defaultValue);
- propertyDef.setCurrentValue(defaultValue);
- }
-
- return Either.left(propertyDef);
- }
-
- public static String getPropertyJsonStringValue(Object value, String type) {
- Gson gson = new Gson();
- if (type == null) {
- return null;
- }
- ToscaPropertyType validType = ToscaPropertyType.isValidType(type);
- if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) {
- return gson.toJson(value);
- }
- return value.toString();
- }
-
- /**
- * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson
- *
- * @param toscaJson
- * @param elementName
- */
- public static void removeElementFromJsonMap(Map<String, Object> toscaJson, String elementName) {
- for (Entry<String, Object> entry : toscaJson.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (key.equals(elementName)) {
- toscaJson.remove(elementName);
- return;
- } else if (value instanceof Map) {
- removeElementFromJsonMap((Map<String, Object>) value, elementName);
- }
- }
- }
+ private ImportUtils() {
+
+ }
+
+ private static CustomResolver customResolver = new CustomResolver();
+ private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader();
+
+ private static class CustomResolver extends Resolver {
+ @Override
+ protected void addImplicitResolvers() {
+ // avoid implicit resolvers for strings that can be interpreted as boolean values
+ addImplicitResolver(Tag.STR, EMPTY, "");
+ addImplicitResolver(Tag.STR, NULL, null);
+ addImplicitResolver(Tag.NULL, NULL, "~nN\0");
+ addImplicitResolver(Tag.NULL, EMPTY, null);
+ addImplicitResolver(Tag.INT, INT, "-+0123456789");
+ addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
+ addImplicitResolver(Tag.YAML, YAML, "!&*");
+ }
+ }
+
+
+ private static void buildMap(Map<String, Object> output, Map<String, Object> map) {
+ for (Entry<String, Object> entry : map.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (value instanceof Map) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ buildMap(result, (Map) value);
+ output.put(key, result);
+ }
+ else if (value instanceof Collection) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ int i = 0;
+ for(Object item : (Collection<Object>) value) {
+ buildMap(result, Collections.singletonMap("[" + (i++) + "]", item));
+ }
+ output.put(key, new ArrayList<>(result.values()));
+ }
+ else {
+ output.put(key, value);
+ }
+ }
+ }
+
+ public static Map<String, Object> loadYamlAsStrictMap(String content){
+ Map<String, Object> result = new LinkedHashMap<>();
+ Object map = STRICT_MAPPING_YAML_LOADER.load(content);
+ buildMap(result, (Map<String, Object>)map);
+ return result;
+ }
+
+ private static class YamlLoader extends YamlProcessor {
+ public Yaml getStrictYamlLoader() {
+ return createYaml();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload, String artifactType) {
+ Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver).load(heatDecodedPayload);
+ return getHeatParameters(heatData, artifactType);
+ }
+
+ public static class Constants {
+
+ public static final String FIRST_CERTIFIED_VERSION_VERSION = "1.0";
+ public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
+ public static final String VENDOR_NAME = "ATT (Tosca)";
+ public static final String VENDOR_RELEASE = "1.0.0.wd03";
+ public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
+ public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
+ public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
+ public static final String ABSTRACT_CATEGORY_NAME = "Generic";
+ public static final String ABSTRACT_SUBCATEGORY = "Abstract";
+ public static final String DEFAULT_ICON = "defaulticon";
+ public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC";
+ public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
+ public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
+ public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
+ }
+
+ public enum ResultStatusEnum {
+ 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 {
+ BOOLEAN, STRING, MAP, LIST, ALL
+ }
+
+ public enum ToscaTagNamesEnum {
+ DERIVED_FROM("derived_from"), IS_PASSWORD("is_password"),
+ // Properties
+ PROPERTIES("properties"), TYPE("type"), STATUS("status"), ENTRY_SCHEMA("entry_schema"), REQUIRED("required"), DESCRIPTION("description"), DEFAULT_VALUE("default"), VALUE("value"), CONSTRAINTS("constraints"),
+ // Group Types
+ MEMBERS("members"), METADATA("metadata"),
+ // Policy Types
+ TARGETS("targets"),
+ // Capabilities
+ CAPABILITIES("capabilities"), VALID_SOURCE_TYPES("valid_source_types"),
+ // Requirements
+ REQUIREMENTS("requirements"), NODE("node"), RELATIONSHIP("relationship"), CAPABILITY("capability"), INTERFACES("interfaces"),
+ // Heat env Validation
+ PARAMETERS("parameters"),
+ // Import Validations
+ TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"),
+ SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"),
+ // Attributes
+ ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input");
+
+ private String elementName;
+
+ private ToscaTagNamesEnum(String elementName) {
+ this.elementName = elementName;
+ }
+
+ public String getElementName() {
+ return elementName;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ if (elementValue instanceof Map) {
+ ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
+ } else if (elementValue instanceof List) {
+ ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static void handleElementNameFound(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList, Object elementValue) {
+
+ if (elementValue instanceof Boolean) {
+ if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) {
+ returnedList.add(elementValue);
+ }
+ }
+
+ else if (elementValue instanceof String) {
+ if (elementType == ToscaElementTypeEnum.STRING || elementType == ToscaElementTypeEnum.ALL) {
+ returnedList.add(elementValue);
+ }
+ } else if (elementValue instanceof Map) {
+ if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) {
+ returnedList.add(elementValue);
+ }
+ ImportUtils.findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
+
+ } else if (elementValue instanceof List) {
+ if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) {
+ returnedList.add(elementValue);
+ }
+ ImportUtils.findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList);
+
+ }
+ // For Integer, Double etc...
+ else if (elementType == ToscaElementTypeEnum.ALL) {
+ if (elementValue != null) {
+ returnedList.add(String.valueOf(elementValue));
+ }
+ }
+ }
+
+ private static void findAllToscaElementsInList(List<Object> list, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ Iterator<Object> listItr = list.iterator();
+ while (listItr.hasNext()) {
+ Object elementValue = listItr.next();
+ handleElementNameNotFound(elementName, elementValue, elementType, returnedList);
+ }
+
+ }
+
+ public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) {
+ List<Object> foundElements = new ArrayList<>();
+ Either<Object, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements);
+ if (foundElements.size() > 0) {
+ returnedElement = Either.left(foundElements.get(0));
+ }
+ return returnedElement;
+
+ }
+
+ /**
+ * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br>
+ * Returns Either element with:<br>
+ * List with all value if values found<br>
+ * Or ELEMENT_NOT_FOUND ActionStatus
+ *
+ * @param toscaJson
+ * @param toscaTagName
+ * @return
+ */
+ public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList) {
+ Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ String skipKey = null;
+ if (toscaJson.containsKey(elementName)) {
+ Object elementValue = toscaJson.get(elementName);
+ handleElementNameFound(elementName, elementType, returnedList, elementValue);
+ skipKey = elementName;
+ }
+
+ Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator();
+ while (keyValItr.hasNext()) {
+ Entry<String, Object> keyValEntry = keyValItr.next();
+ if (!String.valueOf(keyValEntry.getKey()).equals(skipKey)) {
+ handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList);
+ }
+ }
+
+ if (returnedList.size() > 0) {
+ returnedElement = Either.left(returnedList);
+ }
+
+ return returnedElement;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST);
+ if (findFirstToscaElement.isLeft()) {
+ returnedElement = Either.left((List<T>) findFirstToscaElement.left().value());
+ }
+ return returnedElement;
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP);
+ if (findFirstToscaElement.isLeft()) {
+ returnedElement = Either.left((Map<String, T>) findFirstToscaElement.left().value());
+ }
+ return returnedElement;
+
+ }
+
+ public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING);
+ if (findFirstToscaElements.isLeft()) {
+ returnedElement = Either.left((String) findFirstToscaElements.left().value());
+ }
+ return returnedElement;
+ }
+
+ /**
+ * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status
+ *
+ * @param toscaJson
+ * @param toscaTagName
+ * @return
+ */
+ public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson, ToscaTagNamesEnum toscaTagName) {
+ Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN);
+ if (findFirstToscaElements.isLeft()) {
+ returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value()));
+ }
+ return returnedElement;
+ }
+
+ private static void setPropertyConstraints(Map<String, Object> propertyValue, PropertyDefinition property) {
+ Either<List<Object>, ResultStatusEnum> propertyFieldconstraints = findFirstToscaListElement(propertyValue, ToscaTagNamesEnum.CONSTRAINTS);
+ if (propertyFieldconstraints.isLeft()) {
+ List<Object> jsonConstraintList = propertyFieldconstraints.left().value();
+
+ List<PropertyConstraint> constraintList = new ArrayList<>();
+ Type constraintType = new TypeToken<PropertyConstraint>() {
+ }.getType();
+ Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+
+ for (Object constraintJson : jsonConstraintList) {
+ PropertyConstraint propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType);
+ constraintList.add(propertyConstraint);
+ }
+ property.setConstraints(constraintList);
+ }
+ }
+
+ public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) {
+
+ PropertyDefinition propertyDef = new PropertyDefinition();
+ ImportUtils.setField(propertyValue, ToscaTagNamesEnum.TYPE, type -> propertyDef.setType(type));
+ ImportUtils.setPropertyFieldRequired(propertyValue, propertyDef);
+ ImportUtils.setField(propertyValue, ToscaTagNamesEnum.DESCRIPTION, desc -> propertyDef.setDescription(desc));
+
+ Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+ if (findToscaElement.isLeft()) {
+ String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), propertyDef.getType());
+ propertyDef.setDefaultValue(propertyJsonStringValue);
+ }
+ ImportUtils.setField(propertyValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
+ ImportUtils.setField(propertyValue, ToscaTagNamesEnum.STATUS, status -> propertyDef.setStatus(status));
+ ImportUtils.setPropertyScheme(propertyValue, propertyDef);
+ ImportUtils.setPropertyConstraints(propertyValue, propertyDef);
+
+ return propertyDef;
+ }
+
+ public static InputDefinition createModuleInput(Map<String, Object> inputValue) {
+
+ InputDefinition inputDef = new InputDefinition();
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.TYPE, type -> inputDef.setType(type));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req)));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.DESCRIPTION, desc -> inputDef.setDescription(desc));
+
+ Either<Object, ResultStatusEnum> findToscaElement = ImportUtils.findToscaElement(inputValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+ if (findToscaElement.isLeft()) {
+ String propertyJsonStringValue = getPropertyJsonStringValue(findToscaElement.left().value(), inputDef.getType());
+ inputDef.setDefaultValue(propertyJsonStringValue);
+ }
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass)));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.STATUS, status -> inputDef.setStatus(status));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden)));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.HIDDEN, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable)));
+ ImportUtils.setField(inputValue, ToscaTagNamesEnum.LABEL, label -> inputDef.setLabel(label));
+ ImportUtils.setPropertyScheme(inputValue, inputDef);
+ ImportUtils.setPropertyConstraints(inputValue, inputDef);
+
+ return inputDef;
+ }
+
+ public static PropertyDefinition createModuleAttribute(Map<String, Object> attributeMap) {
+
+ 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));
+ Either<Object, ResultStatusEnum> eitherDefaultValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+ if (eitherDefaultValue.isLeft()) {
+ String attributeDefaultValue = getPropertyJsonStringValue(eitherDefaultValue.left().value(), attributeDef.getType());
+ attributeDef.setDefaultValue(attributeDefaultValue);
+ }
+ Either<Object, ResultStatusEnum> eitherValue = ImportUtils.findToscaElement(attributeMap, ToscaTagNamesEnum.VALUE, ToscaElementTypeEnum.ALL);
+ if (eitherValue.isLeft()) {
+ String attributeValue = getPropertyJsonStringValue(eitherValue.left().value(), attributeDef.getType());
+ attributeDef.setValue(attributeValue);
+ }
+ ImportUtils.setAttributeScheme(attributeMap, attributeDef);
+ return attributeDef;
+ }
+
+ private static void setPropertyScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
+ Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue);
+ if (eitherSchema.isLeft()) {
+ SchemaDefinition schemaDef = new SchemaDefinition();
+ schemaDef.setProperty(eitherSchema.left().value().getProperty());
+ propertyDefinition.setSchema(schemaDef);
+ }
+
+ }
+
+ private static void setAttributeScheme(Map<String, Object> propertyValue, PropertyDefinition propertyDefinition) {
+ Either<SchemaDefinition, ResultStatusEnum> eitherSchema = getSchema(propertyValue);
+ if (eitherSchema.isLeft()) {
+ SchemaDefinition schemaDef = new SchemaDefinition();
+ schemaDef.setProperty(eitherSchema.left().value().getProperty());
+ propertyDefinition.setSchema(schemaDef);
+ }
+
+ }
+
+ private static Either<SchemaDefinition, ResultStatusEnum> getSchema(Map<String, Object> propertyValue) {
+ Either<SchemaDefinition, ResultStatusEnum> result = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Object, ResultStatusEnum> propertyFieldEntryScheme = findToscaElement(propertyValue, ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL);
+ if (propertyFieldEntryScheme.isLeft()) {
+ if (propertyFieldEntryScheme.left().value() instanceof String) {
+ String schemaType = (String) propertyFieldEntryScheme.left().value();
+ SchemaDefinition schema = new SchemaDefinition();
+ PropertyDefinition schemeProperty = new PropertyDefinition();
+ schemeProperty.setType(schemaType);
+ schema.setProperty(schemeProperty);
+ result = Either.left(schema);
+
+ } else if (propertyFieldEntryScheme.left().value() instanceof Map) {
+ PropertyDefinition schemeProperty = createModuleProperty((Map<String, Object>) propertyFieldEntryScheme.left().value());
+ SchemaDefinition schema = new SchemaDefinition();
+ schema.setProperty(schemeProperty);
+ result = Either.left(schema);
+
+ }
+
+ }
+ return result;
+ }
+
+ public static void setField(Map<String, Object> toscaJson, ToscaTagNamesEnum tagName, Consumer<String> setter) {
+ Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName);
+ if (fieldStringValue.isLeft()) {
+ setter.accept(fieldStringValue.left().value());
+ }
+
+ }
+
+ private static void setPropertyFieldRequired(Map<String, Object> propertyValue, PropertyDefinition dataDefinition) {
+ Either<String, ResultStatusEnum> propertyFieldRequired = findFirstToscaBooleanElement(propertyValue, ToscaTagNamesEnum.REQUIRED);
+ if (propertyFieldRequired.isLeft()) {
+ dataDefinition.setRequired(Boolean.parseBoolean(propertyFieldRequired.left().value()));
+ }
+ }
+
+ public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) {
+ Function<String, PropertyDefinition> elementGenByName = elementName -> createProperties(elementName);
+ Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleProperty(map);
+
+ return getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES, elementGenByName, func);
+
+ }
+
+ public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson) {
+ Function<String, InputDefinition> elementGenByName = elementName -> createInputs(elementName);
+ Function<Map<String, Object>, InputDefinition> func = map -> createModuleInput(map);
+
+ return getElements(toscaJson, ToscaTagNamesEnum.INPUTS, elementGenByName, func);
+
+ }
+
+ public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getAttributes(Map<String, Object> toscaJson) {
+ Function<String, PropertyDefinition> elementGenByName = elementName -> createAttribute(elementName);
+ Function<Map<String, Object>, PropertyDefinition> func = map -> createModuleAttribute(map);
+
+ return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func);
+ }
+
+ public static <ElementDefinition> Either<Map<String, ElementDefinition>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementTagName, Function<String, ElementDefinition> elementGenByName,
+ Function<Map<String, Object>, ElementDefinition> func) {
+ Either<Map<String, ElementDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName);
+ if (toscaAttributes.isLeft()) {
+ Map<String, Object> jsonAttributes = toscaAttributes.left().value();
+ Map<String, ElementDefinition> moduleAttributes = new HashMap<>();
+ Iterator<Entry<String, Object>> propertiesNameValue = jsonAttributes.entrySet().iterator();
+ while (propertiesNameValue.hasNext()) {
+ Entry<String, Object> attributeNameValue = propertiesNameValue.next();
+ if (attributeNameValue.getValue() instanceof Map) {
+ @SuppressWarnings("unchecked")
+ ElementDefinition attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
+ moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute);
+ } else {
+
+ ElementDefinition element = elementGenByName.apply(String.valueOf(attributeNameValue.getValue()));
+
+ moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), element);
+ }
+
+ }
+
+ if (moduleAttributes.size() > 0) {
+ eitherResult = Either.left(moduleAttributes);
+ }
+
+ }
+ return eitherResult;
+
+ }
+
+ private static PropertyDefinition createAttribute(String name) {
+ PropertyDefinition attribute = new PropertyDefinition();
+
+ attribute.setName(name);
+ return attribute;
+ }
+
+ private static PropertyDefinition createProperties(String name) {
+ PropertyDefinition property = new PropertyDefinition();
+ property.setDefaultValue(name);
+ property.setName(name);
+ return property;
+ }
+
+ private static InputDefinition createInputs(String name) {
+ InputDefinition input = new InputDefinition();
+
+ input.setName(name);
+ return input;
+ }
+
+ public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) {
+
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+ Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, ToscaTagNamesEnum.PARAMETERS);
+ if (toscaProperties.isLeft()) {
+ Map<String, Object> jsonProperties = toscaProperties.left().value();
+ List<HeatParameterDefinition> moduleProperties = new ArrayList<>();
+ Iterator<Entry<String, Object>> propertiesNameValue = jsonProperties.entrySet().iterator();
+ while (propertiesNameValue.hasNext()) {
+ Entry<String, Object> propertyNameValue = propertiesNameValue.next();
+ if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) {
+ if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
+ @SuppressWarnings("unchecked")
+ Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter((Map<String, Object>) propertyNameValue.getValue());
+ if (propertyStatus.isRight()) {
+ return Either.right(propertyStatus.right().value());
+ }
+ HeatParameterDefinition property = propertyStatus.left().value();
+ property.setName(String.valueOf(propertyNameValue.getKey()));
+ moduleProperties.add(property);
+ } else {
+ addHeatParamDefinition(moduleProperties, propertyNameValue, true);
+ }
+ } else {
+ addHeatParamDefinition(moduleProperties, propertyNameValue, false);
+ }
+
+ }
+
+ if (moduleProperties.size() > 0) {
+ eitherResult = Either.left(moduleProperties);
+ }
+
+ }
+ return eitherResult;
+
+ }
+
+ private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties, Entry<String, Object> propertyNameValue, boolean isJson) {
+ HeatParameterDefinition property = new HeatParameterDefinition();
+ Object value = propertyNameValue.getValue();
+ if (value != null) {
+ property.setDefaultValue(isJson ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value)));
+ }
+ property.setName(String.valueOf(propertyNameValue.getKey()));
+ moduleProperties.add(property);
+ }
+
+ private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) {
+ HeatParameterDefinition propertyDef = new HeatParameterDefinition();
+ String type;
+ Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.TYPE);
+ if (propertyFieldType.isLeft()) {
+ type = propertyFieldType.left().value();
+ propertyDef.setType(type);
+ } else {
+ return Either.right(ResultStatusEnum.INVALID_PROPERTY_TYPE);
+ }
+ Either<String, ResultStatusEnum> propertyFieldDescription = findFirstToscaStringElement(propertyValue, ToscaTagNamesEnum.DESCRIPTION);
+ if (propertyFieldDescription.isLeft()) {
+ propertyDef.setDescription(propertyFieldDescription.left().value());
+ }
+
+ Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+ if (propertyFieldDefaultVal.isLeft()) {
+ if (propertyFieldDefaultVal.left().value() == null) {
+ return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE);
+ }
+ Object value = propertyFieldDefaultVal.left().value();
+ String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value).toString() : StringEscapeUtils.escapeJava(String.valueOf(value));
+ propertyDef.setDefaultValue(defaultValue);
+ propertyDef.setCurrentValue(defaultValue);
+ }
+
+ return Either.left(propertyDef);
+ }
+
+ public static String getPropertyJsonStringValue(Object value, String type) {
+ Gson gson = new Gson();
+ if (type == null) {
+ return null;
+ }
+ ToscaPropertyType validType = ToscaPropertyType.isValidType(type);
+ if (validType == null || validType.equals(ToscaPropertyType.JSON) ||validType.equals(ToscaPropertyType.MAP) || validType.equals(ToscaPropertyType.LIST)) {
+ return gson.toJson(value);
+ }
+ return value.toString();
+ }
+
+ /**
+ * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson
+ *
+ * @param toscaJson
+ * @param elementName
+ */
+ public static void removeElementFromJsonMap(Map<String, Object> toscaJson, String elementName) {
+ for (Entry<String, Object> entry : toscaJson.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (key.equals(elementName)) {
+ toscaJson.remove(elementName);
+ return;
+ } else if (value instanceof Map) {
+ removeElementFromJsonMap((Map<String, Object>) value, elementName);
+ }
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java
deleted file mode 100644
index 52dcce9e2e..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InformationDeployedArtifactsBusinessLogic.java
+++ /dev/null
@@ -1,92 +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.components.impl;
-
-//Pavel
-//currently NOT IN USE - there are no informational deployed artifacts after US601880
-
-@org.springframework.stereotype.Component("informationDeployedArtifactsBusinessLogic")
-public class InformationDeployedArtifactsBusinessLogic {
-
- /*
- * private static Logger log = LoggerFactory.getLogger(InformationDeployedArtifactsBusinessLogic.class. getName());
- *
- * @javax.annotation.Resource private ArtifactsBusinessLogic artifactBusinessLogic;
- *
- * public boolean isInformationDeployedArtifact(ArtifactDefinition artifactInfo) { log.debug("checking if artifact {} is informationalDeployable", artifactInfo.getArtifactName()); boolean informationDeployedArtifact = false; Map<String,
- * DeploymentArtifactTypeConfig> resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() .getResourceInformationalDeployedArtifacts(); if( resourceInformationalDeployedArtifacts != null &&
- * resourceInformationalDeployedArtifacts.containsKey(artifactInfo. getArtifactType())){ if( artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL && artifactInfo.checkEsIdExist()){ informationDeployedArtifact = true;
- *
- * } } String message = (informationDeployedArtifact) ? "artifact {} is informationalDeployable" : "artifact {} is not informationalDeployable"; log.debug(message, artifactInfo.getArtifactName()); return informationDeployedArtifact; }
- *
- * public Either<Boolean, ResponseFormat> validateArtifact(boolean isCreate, ArtifactDefinition artifactInfo, Component parent, NodeTypeEnum parentType) {
- *
- * log.debug("checking if informationalDeployable artifact {} is valid ", artifactInfo.getArtifactName()); Wrapper<ResponseFormat> responseFormatWrapper = new Wrapper<ResponseFormat>(); Map<String, DeploymentArtifactTypeConfig>
- * resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration(). getResourceInformationalDeployedArtifacts();
- *
- *
- * artifactBusinessLogic.validateArtifactTypeExists(responseFormatWrapper, artifactInfo); if( responseFormatWrapper.isEmpty() && isCreate ){ artifactBusinessLogic.validateSingleArtifactType(responseFormatWrapper,
- * ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parent, parentType); } if( responseFormatWrapper.isEmpty() ){ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
- * artifactBusinessLogic.validateFileExtension(responseFormatWrapper, () -> resourceInformationalDeployedArtifacts.get(artifactInfo.getArtifactType() ), artifactInfo, parentType, artifactType); }
- *
- * if( responseFormatWrapper.isEmpty() ){ validatePayloadContent(responseFormatWrapper, artifactInfo); }
- *
- * Either<Boolean, ResponseFormat> response; if( responseFormatWrapper.isEmpty() ){ response = Either.left(true); } else{ response = Either.right(responseFormatWrapper.getInnerElement()); }
- *
- * String message = (response.isLeft()) ? "informationalDeployable artifact {} is valid" : "informationalDeployable artifact {} is not valid"; log.debug(message, artifactInfo.getArtifactName()); return response; }
- *
- * private void validatePayloadContent(Wrapper<ResponseFormat> responseFormatWrapper, ArtifactDefinition artifactToVerify) { ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactToVerify.getArtifactType()); if( artifactType ==
- * ArtifactTypeEnum.YANG_XML ){ String rawPayloadData = artifactToVerify.getPayloadData(); String xmlToParse = new String(org.apache.commons.codec.binary.Base64.decodeBase64(rawPayloadData ));
- *
- * boolean isXmlValid = artifactBusinessLogic.isValidXml(xmlToParse.getBytes()); if( !isXmlValid ){ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus. INVALID_XML,
- * artifactToVerify.getArtifactType()); responseFormatWrapper.setInnerElement(responseFormat); log.debug("Xml is not valid for artifact : {}", artifactToVerify.getArtifactName()); } } }
- *
- *
- *
- *
- * public List<ArtifactDefinition> getInformationalDeployedArtifactsForResourceInstance( ComponentInstance resourceInstance ) { String resourceUid = resourceInstance.getComponentUid(); String resourceName = resourceInstance.getComponentName();
- * return getInformationalDeployedArtifactsForResource(resourceUid, resourceName); }
- *
- * private List<ArtifactDefinition> getInformationalDeployedArtifactsForResource( String resourceUid, String resourceName) { List<ArtifactDefinition> informationalDeployedArtifacts = new ArrayList<ArtifactDefinition>(); log.
- * debug("checking if informationalDeployable artifacts exist for resource {} " , resourceName); Map<String, DeploymentArtifactTypeConfig> resourceInformationalDeployedArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- * .getResourceInformationalDeployedArtifacts();
- *
- *
- * Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherArtifacts = artifactBusinessLogic.getArtifacts(resourceUid, NodeTypeEnum.Resource, false, ArtifactGroupTypeEnum.INFORMATIONAL);
- *
- * if( eitherArtifacts.isLeft() && resourceInformationalDeployedArtifacts != null ){ Predicate<ArtifactDefinition> predicate = p -> resourceInformationalDeployedArtifacts.containsKey(p.getArtifactType()) && p.checkEsIdExist() &&
- * p.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL; informationalDeployedArtifacts = eitherArtifacts.left().value().values().stream().filter( predicate ).collect(Collectors.toList()); }
- *
- * if( informationalDeployedArtifacts.isEmpty() ){ log.debug("no informationalDeployable artifacts exist for resource {} ", resourceName); } else{ log. debug("informationalDeployable artifacts found for resource {} are :{}", resourceName,
- * informationalDeployedArtifacts.toString()); }
- *
- *
- * return informationalDeployedArtifacts; }
- *
- * public List<ArtifactDefinition> getAllDeployableArtifacts( Resource resource ){ List<ArtifactDefinition> merged = new ArrayList<ArtifactDefinition>();
- *
- * List<ArtifactDefinition> deploymentArtifacts = artifactBusinessLogic.getDeploymentArtifacts(resource, NodeTypeEnum.Resource); merged.addAll(deploymentArtifacts);
- *
- * List<ArtifactDefinition> informationalDeployedArtifactsForResource = getInformationalDeployedArtifactsForResource( resource.getUniqueId(), resource.getName()); merged.addAll(informationalDeployedArtifactsForResource);
- *
- * return merged; }
- */
-}
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 a9e7f0b34b..7b51e92ba2 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
@@ -20,28 +20,12 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.BiConsumer;
-import java.util.stream.Collectors;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.collections.MapUtils;
-import org.json.simple.JSONObject;
+import fj.data.Either;
+import org.openecomp.sdc.be.components.property.PropertyDecelerationOrchestrator;
import org.openecomp.sdc.be.components.validation.ComponentValidations;
-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.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -49,1415 +33,651 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
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.ComponentInstancePropInput;
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.IComponentInstanceConnectedElement;
import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.User;
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.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import org.yaml.snakeyaml.Yaml;
-
-import com.google.gson.Gson;
-import fj.data.Either;
-import jline.internal.Log;
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
@Component("inputsBusinessLogic")
public class InputsBusinessLogic extends BaseBusinessLogic {
- private static final String CREATE_INPUT = "CreateInput";
- private static final String UPDATE_INPUT = "UpdateInput";
-
- private static Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class.getName());
-
- private static final String GET_INPUT = "get_input";
-
- private static final short LOOP_PROTECTION_LEVEL = 10 ;
-
- private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty";
- private Gson gson = new Gson();
-
-
- /**
- * associate inputs to a given component with paging
- *
- * @param componentId
- * @param userId
- * @param fromId
- * @param amount
- * @return
- */
- public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId, String fromName, int amount) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
-
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
-
- ComponentParametersView filters = new ComponentParametersView();
- filters.disableAll();
- filters.setIgnoreInputs(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
- List<InputDefinition> inputs = component.getInputs();
-
- return Either.left(inputs);
-
- }
-
- public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
-
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
-
- ComponentParametersView filters = new ComponentParametersView();
- filters.disableAll();
- filters.setIgnoreInputs(false);
- filters.setIgnoreComponentInstances(false);
- filters.setIgnoreComponentInstancesInputs(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
-
- if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){
- ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
- log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
- Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap());
- return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList()));
- }
-
- /**
- * associate properties to a given component instance input
- *
- * @param instanceId
- * @param userId
- * @param inputId
- * @return
- */
-
- public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- String parentId = componentId;
- org.openecomp.sdc.be.model.Component component = null;
- ComponentParametersView filters = new ComponentParametersView();
- filters.disableAll();
- filters.setIgnoreComponentInstances(false);
-
- if(!instanceId.equals(inputId)){
-
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
- if(getComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- component = getComponentEither.left().value();
- Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny();
- if(ciOp.isPresent()){
- parentId = ciOp.get().getComponentUid();
- }
-
- }
-
- filters.setIgnoreInputs(false);
-
- filters.setIgnoreComponentInstancesProperties(false);
- filters.setIgnoreComponentInstancesInputs(false);
- filters.setIgnoreProperties(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
- if(getComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- component = getComponentEither.left().value();
-
- Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
- if(!op.isPresent()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
-
- return Either.left(getComponentInstancePropertiesByInputId(component, inputId));
-
- }
-
- public Either<InputDefinition, ResponseFormat> updateInputValue(ComponentTypeEnum componentType, String componentId, InputDefinition input, String userId, boolean shouldLockComp, boolean inTransaction) {
-
- Either<InputDefinition, ResponseFormat> result = null;
- org.openecomp.sdc.be.model.Component component = null;
-
-
- try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false);
-
- if (resp.isRight()) {
- result = Either.right(resp.right().value());
- return result;
- }
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreInputs(false);
- componentParametersView.setIgnoreUsers(false);
-
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
-
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- component = validateComponent.left().value();
-
- if (shouldLockComp) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT);
- if (lockComponent.isRight()) {
- result = Either.right(lockComponent.right().value());
- return result;
- }
- }
-
- Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
- if (canWork.isRight()) {
- result = Either.right(canWork.right().value());
- return result;
- }
-
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- result = Either.right(allDataTypes.right().value());
- return result;
- }
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst();
- if(!op.isPresent()){
- ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
- log.debug("Failed to found input {} under component {}, error: {}", input.getUniqueId(), componentId, actionStatus.name());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
- return result;
- }
- InputDefinition currentInput = op.get();
-
- String innerType = null;
- String propertyType = currentInput.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = currentInput.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
- }
- innerType = propDef.getType();
- }
- // Specific Update Logic
-
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, input.getDefaultValue(), true, innerType, allDataTypes.left().value());
-
- String newValue = currentInput.getDefaultValue();
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- currentInput.setDefaultValue(newValue);
- currentInput.setOwnerId(userId);
-
- Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currentInput);
-
- if(status.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
- return result;
- }
-
-
- result = Either.left(status.left().value());
-
- 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<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- String parentId = componentId;
- org.openecomp.sdc.be.model.Component component = null;
- ComponentParametersView filters = new ComponentParametersView();
- filters.disableAll();
- filters.setIgnoreComponentInstances(false);
- filters.setIgnoreInputs(false);
- filters.setIgnoreComponentInstancesInputs(false);
- filters.setIgnoreProperties(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
- if(getComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", parentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- component = getComponentEither.left().value();
-
- Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
- if(!op.isPresent()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
-
- return Either.left(getComponentInstanceInputsByInputId(component, inputId));
-
- }
-
- public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) {
-
- Either<List<InputDefinition>, ResponseFormat> result = null;
- org.openecomp.sdc.be.model.Component component = null;
-
- Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap = new HashMap<>();
- Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap = new HashMap<>();
- Map<String, InputDefinition> inputsToCreate = new HashMap<>();
-
- try {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
-
- if (resp.isRight()) {
- result = Either.right(resp.right().value());
- return result;
- }
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreInputs(false);
- componentParametersView.setIgnoreComponentInstancesInputs(false);
- componentParametersView.setIgnoreComponentInstances(false);
- componentParametersView.setIgnoreComponentInstancesProperties(false);
- componentParametersView.setIgnoreUsers(false);
+ private static final String CREATE_INPUT = "CreateInput";
+ private static final String UPDATE_INPUT = "UpdateInput";
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
+ private static final Logger log = LoggerFactory.getLogger(InputsBusinessLogic.class);
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- component = validateComponent.left().value();
+ @Inject
+ private PropertyDecelerationOrchestrator propertyDecelerationOrchestrator;
+ @Inject
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
- if (shouldLockComp) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT);
- if (lockComponent.isRight()) {
- result = Either.right(lockComponent.right().value());
- return result;
- }
- }
+ /**
+ * associate inputs to a given component with paging
+ *
+ * @param userId
+ * @param componentId
+ * @return
+ */
+ public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) {
- Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
- if (canWork.isRight()) {
- result = Either.right(canWork.right().value());
- return result;
- }
-
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- result = Either.right(allDataTypes.right().value());
- return result;
- }
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
- Map<String, org.openecomp.sdc.be.model.Component> origComponentMap = new HashMap<>();
-
-
- //////////////////////////////////////////////////////////////////////////////////////////////////////
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
- List<InputDefinition> resList = new ArrayList<InputDefinition>();
- Map<String, List<ComponentInstancePropInput>> newInputsMap = componentInstInputsMapUi.getComponentInstanceInputsMap();
- List<ComponentInstance> ciList = component.getComponentInstances();
- if (newInputsMap != null && !newInputsMap.isEmpty()) {
-
- result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsMap, true);
-
- if (result.isRight()) {
- log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value());
- return result;
- }
- resList = result.left().value();
-
-
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
- }
- Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInstInputsMapUi.getComponentInstanceProperties();
- if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) {
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreInputs(false);
- result = createInputsFromProperty(component, origComponentMap, inputsToCreate, propertiesToCreateMap, inputsValueToCreateMap, dataTypes, resList, newInputsPropsMap, false);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", componentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
- if (result.isRight()) {
- log.debug("Failed to create inputs of resource for id {} error {}", component.getUniqueId(), result.right().value());
- return result;
- }
- resList = result.left().value();
+ }
+ org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
+ List<InputDefinition> inputs = component.getInputs();
- }
+ return Either.left(inputs);
- assignOwnerIdToInputs(userId, inputsToCreate);
+ }
- Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.addInputsToComponent(inputsToCreate, component.getUniqueId());
- if(assotiateInputsEither.isRight()){
- log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
- return result;
- }
+ public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) {
- Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> assotiatePropsEither = toscaOperationFacade.addComponentInstancePropertiesToComponent(component, propertiesToCreateMap, component.getUniqueId());
- if(assotiatePropsEither.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())));
- return result;
- }
-
- Either<Map<String, List<ComponentInstanceInput>>, 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())));
- return result;
- }
-
-
-
-
- result = Either.left(resList);
- 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());
- }
-
- }
-
- }
-
- private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) {
- inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId));
- }
-
- private StorageOperationStatus addInputsToComponent(String componentId, Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap, Map<String, DataTypeDefinition> allDataTypes, List<InputDefinition> resList, int index,
- String compInstId, String compInstname, org.openecomp.sdc.be.model.Component origComponent, InputDefinition input) {
-
-
- Either<List<InputDefinition>, ResponseFormat> result;
- String innerType = null;
- InputDefinition oldInput = origComponent.getInputs().stream().filter(ciIn -> ciIn.getUniqueId().equals(input.getUniqueId())).findAny().get();
- String serviceInputName = compInstname + "_" + input.getName();
- input.setName(serviceInputName);
-
- JSONObject jobject = new JSONObject();
- jobject.put(GET_INPUT, input.getName());
-
- ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null);
-
- Either<String, StorageOperationStatus> validatevalueEiter = validateInputValueBeforeCreate(inputValue, jobject.toJSONString(), false, innerType, allDataTypes);
- if (validatevalueEiter.isRight()) {
-
- return validatevalueEiter.right().value();
- }
-
- String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(compInstId, index++);
- inputValue.setUniqueId(uniqueId);
- inputValue.setValue(validatevalueEiter.left().value());
-
-
- input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName()));
- input.setSchema(oldInput.getSchema());
- input.setDefaultValue(oldInput.getDefaultValue());
- input.setConstraints(oldInput.getConstraints());
- input.setDescription(oldInput.getDescription());
- input.setHidden(oldInput.isHidden());
- input.setImmutable(oldInput.isImmutable());
- input.setDefinition(oldInput.isDefinition());
- input.setRequired(oldInput.isRequired());
- input.setOwnerId(null);
- input.setParentUniqueId(null);
- input.setInstanceUniqueId(compInstId);
- inputsToCreate.put(input.getName(), input);
-
-
-
- List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
- GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
- getInputValueDataDefinition.setInputId(input.getUniqueId());
- getInputValueDataDefinition.setInputName(input.getName());
- getInputValues.add(getInputValueDataDefinition);
- inputValue.setGetInputValues(getInputValues);
-
- List<ComponentInstanceInput> inputsValueToCreate = null;
-
- if(inputsValueToCreateMap.containsKey(compInstId)){
- inputsValueToCreate = inputsValueToCreateMap.get(compInstId);
- }else{
- inputsValueToCreate = new ArrayList<>();
- }
- inputsValueToCreate.add(inputValue);
- inputsValueToCreateMap.put(compInstId, inputsValueToCreate);
-
-
- inputsValueToCreate.add(inputValue);
- List<ComponentInstanceInput> inputsValue = input.getInputs();
- if(inputsValue == null)
- inputsValue = new ArrayList<>();
- inputsValue.add(inputValue);
- input.setInputs(inputsValue);
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Inputs", false);
- resList.add(input);
- return StorageOperationStatus.OK;
- }
-
- public Either<List<InputDefinition>, ResponseFormat> createInputs(String componentId, String userId, ComponentTypeEnum componentType, List<InputDefinition> inputsDefinitions, boolean shouldLockComp, boolean inTransaction) {
-
- Either<List<InputDefinition>, ResponseFormat> result = null;
-
- org.openecomp.sdc.be.model.Component component = null;
- try {
-
- if (inputsDefinitions != null && false == inputsDefinitions.isEmpty()) {
-
- if (shouldLockComp == true && inTransaction == true) {
- 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<User, ResponseFormat> validateUserExists = validateUserExists(userId, CREATE_INPUT, true);
- if (validateUserExists.isRight()) {
- result = Either.right(validateUserExists.right().value());
- return result;
- }
-
- User user = validateUserExists.left().value();
-
- Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, null);
- if (validateComponent.isRight()) {
- result = Either.right(validateComponent.right().value());
- return result;
- }
- component = validateComponent.left().value();
-
- if (shouldLockComp) {
- Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT);
- if (lockComponent.isRight()) {
- return Either.right(lockComponent.right().value());
- }
- }
-
- Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
- if (canWork.isRight()) {
- result = Either.right(canWork.right().value());
- return result;
- }
- Map<String, InputDefinition> inputs = inputsDefinitions.stream().collect(Collectors.toMap( o -> o.getName(), o -> o));
-
- result = createInputsInGraph(inputs, component);
- }
-
- 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<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) {
-
- List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList());
- Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
- List<InputDefinition> resourceProperties = component.getInputs();
-
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- return Either.right(allDataTypes.right().value());
- }
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
- String inputName = inputDefinition.getKey();
- inputDefinition.getValue().setName(inputName);
-
- Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
- if(preparedInputEither.isRight()){
- return Either.right(preparedInputEither.right().value());
- }
-
- }
- if (resourceProperties != null) {
- Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
- Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
- if(mergeEither.isRight()){
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
- }
- inputs = mergeEither.left().value();
- }
-
- Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
- if(assotiateInputsEither.isRight()){
- log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
- }
- result = Either.left(assotiateInputsEither.left().value());
-
- return result;
- }
-
-
- /* Mutates the object
- * Tail recurse -> traverse the tosca elements and remove nested empty map properties
- * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected
- *
- * @param toscaElement - expected map of tosca values
- * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
- **/
- private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){
- //region - Stop if map is empty
- if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof Map))
- return toscaElement;
- //endregion
- //region - Remove empty map entries & return null iff empty map
- if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) {
- Object ret;
- Set<Object> keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException
- for( Object key : ((Map)toscaElement).keySet() ) {
- Object value = ((Map) toscaElement).get(key);
- ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel );
- if ( ret == null )
- keysToRemove.add(key);
- }
- Collection set = ((Map) toscaElement).keySet();
- if (CollectionUtils.isNotEmpty(set))
- set.removeAll(keysToRemove);
-
- if ( isEmptyNestedMap(toscaElement) ) // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check
- return null;
- }
- //endregion
- else
- return null;
- return toscaElement;
- }
-
- //@returns true iff map nested maps are all empty
- //ignores other collection objects
- private boolean isEmptyNestedMap(Object element){
- boolean isEmpty = true;
- if (element != null){
- if ( element instanceof Map ){
- if (MapUtils.isEmpty((Map)element))
- isEmpty = true;
- else
- {
- for( Object key : ((Map)(element)).keySet() ){
- Object value = ((Map)(element)).get(key);
- isEmpty &= isEmptyNestedMap( value );
- }
- }
- } else {
- isEmpty = false;
- }
- }
- return isEmpty;
- }
-
- public Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone ){
- if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){
- if (deepClone){
- if (!(mappedToscaTemplate instanceof HashMap))
- return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() );
- else
- mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone();
- }
- return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , InputsBusinessLogic.LOOP_PROTECTION_LEVEL ) );
- }
- else {
- log.debug("mappedToscaTemplate is empty ");
- return Either.right("mappedToscaTemplate is empty ");
- }
- }
-
-
-
- /**
- * Delete input from service
- *
- * @param componentType
- * @param inputId
- * @param component
- * @param user
- *
- * @return
- */
- public Either<InputDefinition, ResponseFormat> deleteInput(String componentType, String componentId, String userId, String inputId) {
-
- Either<InputDefinition, ResponseFormat> deleteEither = null;
- if (log.isDebugEnabled())
- log.debug("Going to delete input id: {}", inputId);
-
- // Validate user (exists)
- Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true);
- if (userEither.isRight()) {
- deleteEither = Either.right(userEither.right().value());
- return deleteEither;
- }
-
- // Get component using componentType, componentId
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreInputs(false);
- componentParametersView.setIgnoreComponentInstances(false);
- componentParametersView.setIgnoreComponentInstancesInputs(false);
- componentParametersView.setIgnoreComponentInstancesProperties(false);
- componentParametersView.setIgnoreUsers(false);
-
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
- if (componentEither.isRight()) {
- deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value())));
- return deleteEither;
- }
- org.openecomp.sdc.be.model.Component component = componentEither.left().value();
-
- // Validate inputId is child of the component
- Optional<InputDefinition> optionalInput = component.getInputs().stream().
- // filter by ID
- filter(input -> input.getUniqueId().equals(inputId)).
- // Get the input
- findAny();
- if (!optionalInput.isPresent()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId));
- }
-
- InputDefinition inputForDelete = optionalInput.get();
-
- // Lock component
- Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput");
- if (lockResultEither.isRight()) {
- ResponseFormat responseFormat = lockResultEither.right().value();
- deleteEither = Either.right(responseFormat);
- return deleteEither;
- }
-
- // Delete input operations
- try {
- StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
- if(status != StorageOperationStatus.OK){
- log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
- deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
- return deleteEither;
- }
-
- List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId);
-
- if(inputsValue != null && !inputsValue.isEmpty()){
- for(ComponentInstanceInput inputValue: inputsValue){
- String compInstId = inputValue.getComponentInstanceId();
- prepareValueBeforeDelete(compInstId, inputForDelete, inputValue, inputValue.getPath());
-
- status = toscaOperationFacade.updateComponentInstanceInput(component, compInstId, inputValue);
- if(status != StorageOperationStatus.OK){
- log.debug("Component id: {} update component instance property {} id: {} failed", componentId, inputValue.getUniqueId(), inputId);
- deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
- return deleteEither;
- }
-
- }
-
-
- }
-
- // US848813 delete service input that relates to VL / CP property
-
- List<ComponentInstanceProperty> propertiesValue = getComponentInstancePropertiesByInputId(component, inputId);
- if(propertiesValue != null && !propertiesValue.isEmpty()){
- //propertyList = propertyValueStatus.left().value();
- for(ComponentInstanceProperty propertyValue: propertiesValue){
-
- String compInstId = propertyValue.getComponentInstanceId();
- prepareValueBeforeDelete(compInstId, inputForDelete, propertyValue, propertyValue.getPath());
-
- status = toscaOperationFacade.updateComponentInstanceProperty(component, compInstId, propertyValue);
- if(status != StorageOperationStatus.OK){
- log.debug("Component id: {} update component instance property {} id: {} failed", componentId, propertyValue.getUniqueId(), inputId);
- deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
- return deleteEither;
- }
-
- }
- }
-
-
- deleteEither = Either.left(inputForDelete);
- return deleteEither;
- } finally {
- if (deleteEither == null || deleteEither.isRight()) {
- log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
- titanDao.rollback();
- } else {
- log.debug("Component id: {} delete input id: {} success", componentId, inputId);
- titanDao.commit();
- }
- unlockComponent(deleteEither, component);
- }
- }
-
- private Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(String compInstId, InputDefinition inputForDelete, PropertyDefinition inputValue, List<String> pathOfComponentInstances) {
- Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete);
- String value = inputValue.getValue();
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
-
- resetInputName(mappedToscaTemplate, inputForDelete.getName());
-
- value = "";
- if(!mappedToscaTemplate.isEmpty()){
- Either result = cleanNestedMap(mappedToscaTemplate , true);
- Map modifiedMappedToscaTemplate = mappedToscaTemplate;
- if (result.isLeft())
- modifiedMappedToscaTemplate = (Map)result.left().value();
- else
- Log.warn("Map cleanup failed -> " +result.right().value().toString()); //continue, don't break operation
- value = gson.toJson(modifiedMappedToscaTemplate);
- }
- inputValue.setValue(value);
-
-
- List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues();
- if(getInputsValues != null && !getInputsValues.isEmpty()){
- Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny();
- if(op.isPresent()){
- getInputsValues.remove(op.get());
- }
- }
- inputValue.setGetInputValues(getInputsValues);
-
- Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue());
- if (findDefaultValue.isRight()) {
- deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()))));
- return deleteEither;
-
- }
- String defaultValue = findDefaultValue.left().value();
- inputValue.setDefaultValue(defaultValue);
- log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
- return deleteEither;
- }
-
- private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
-
- // validate input default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
- if (defaultValuesValidation.isRight()) {
- return Either.right(defaultValuesValidation.right().value());
- }
- // convert property
- ToscaPropertyType type = getType(newInputDefinition.getType());
- if (type != null) {
- PropertyValueConverter converter = type.getConverter();
- // get inner type
- String innerType = null;
- if (newInputDefinition != null) {
- SchemaDefinition schema = newInputDefinition.getSchema();
- if (schema != null) {
- PropertyDataDefinition prop = schema.getProperty();
- if (prop != null) {
- innerType = prop.getType();
- }
- }
- String convertedValue = null;
- if (newInputDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
- newInputDefinition.setDefaultValue(convertedValue);
- }
- }
- }
- return Either.left(newInputDefinition);
- }
-
- public boolean isInputExist(List<InputDefinition> inputs, String resourceUid, String inputName) {
-
- if (inputs == null) {
- return false;
- }
-
- for (InputDefinition propertyDefinition : inputs) {
- String parentUniqueId = propertyDefinition.getParentUniqueId();
- String name = propertyDefinition.getName();
-
- if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) {
- return true;
- }
- }
-
- return false;
-
- }
-
-
- public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) {
- Either<InputDefinition, ResponseFormat> result = null;
- try {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<List<ComponentInstanceProperty>, StorageOperationStatus> propertiesEitherRes = null;
-
- ComponentParametersView filters = new ComponentParametersView();
- filters.disableAll();
- filters.setIgnoreComponentInstances(false);
- filters.setIgnoreInputs(false);
- filters.setIgnoreComponentInstancesInputs(false);
- filters.setIgnoreComponentInstancesProperties(false);
- filters.setIgnoreProperties(false);
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
- if(getComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found component {}, error: {}", componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
- Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
- if(!op.isPresent()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
- log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
-
- InputDefinition resObj = op.get();
-
- List<ComponentInstanceInput> inputCIInput = getComponentInstanceInputsByInputId(component, inputId) ;
-
- resObj.setInputs(inputCIInput);
-
-
- List<ComponentInstanceProperty> inputProps = getComponentInstancePropertiesByInputId(component, inputId) ;
-
- resObj.setProperties(inputProps);
-
-
- result = Either.left(resObj);
-
- 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 List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
- List<ComponentInstanceProperty> resList = new ArrayList<>();
- Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
- if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
- ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
- @Override
- public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
- String ciName = "";
- Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
- if(ciOp.isPresent())
- ciName = ciOp.get().getName();
- if (ciPropList != null && !ciPropList.isEmpty()) {
- for(ComponentInstanceProperty prop: ciPropList){
- List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
- if(inputsValues != null && !inputsValues.isEmpty()){
- for(GetInputValueDataDefinition inputData: inputsValues){
- if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){
- prop.setComponentInstanceId(s);
- prop.setComponentInstanceName(ciName);
- resList.add(prop);
- break;
- }
- }
- }
-
- }
- }
- }
- });
- }
- return resList;
-
- }
-
- private List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
- List<ComponentInstanceInput> resList = new ArrayList<>();
- Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
- if(ciInputsMap != null && !ciInputsMap.isEmpty()){
- ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
- @Override
- public void accept(String s, List<ComponentInstanceInput> ciPropList) {
- String ciName = "";
- Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
- if(ciOp.isPresent())
- ciName = ciOp.get().getName();
- if (ciPropList != null && !ciPropList.isEmpty()) {
- for(ComponentInstanceInput prop: ciPropList){
- List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
- if(inputsValues != null && !inputsValues.isEmpty()){
- for(GetInputValueDataDefinition inputData: inputsValues){
- if(inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId))){
- prop.setComponentInstanceId(s);
- prop.setComponentInstanceName(ciName);
- resList.add(prop);
- break;
- }
- }
- }
-
- }
- }
- }
- });
- }
- return resList;
-
- }
-
- private Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getOriginComponent(ComponentInstance ci, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap){
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> result = null;
- String compInstname = ci.getNormalizedName();
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreInputs(false);
- org.openecomp.sdc.be.model.Component origComponent = null;
- if(!origComponentMap.containsKey(ci.getComponentUid())){
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentFound = toscaOperationFacade.getToscaElement(ci.getComponentUid(), componentParametersView);
-
- if (componentFound.isRight()) {
- result = Either.right(componentFound.right().value());
- return result;
- }
- origComponent = componentFound.left().value();
- origComponentMap.put(origComponent.getUniqueId(), origComponent);
- }else{
- origComponent = origComponentMap.get(ci.getComponentUid());
- }
- result = Either.left(origComponent);
- return result;
- }
-
-
-
- private Either<List<InputDefinition>, ResponseFormat> createInputsFromProperty(org.openecomp.sdc.be.model.Component component, Map<String, org.openecomp.sdc.be.model.Component> origComponentMap, Map<String, InputDefinition> inputsToCreate, Map<String, List<ComponentInstanceProperty>> propertiesToCreateMap, Map<String, List<ComponentInstanceInput>> inputsValueToCreateMap, Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap, boolean isInputValue) {
- List<ComponentInstance> ciList = component.getComponentInstances();
- String componentId = component.getUniqueId();
- for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) {
- String compInstId = entry.getKey();
- List<ComponentInstanceProperty> propertiesToCreate = null;
- if(propertiesToCreateMap.containsKey(compInstId)){
- propertiesToCreate = propertiesToCreateMap.get(compInstId);
- }else{
- propertiesToCreate = new ArrayList<>();
- }
-
- List<ComponentInstanceInput> inputsValueToCreate = null;
- if(propertiesToCreateMap.containsKey(compInstId)){
- inputsValueToCreate = inputsValueToCreateMap.get(compInstId);
- }else{
- inputsValueToCreate = new ArrayList<>();
- }
-
- List<ComponentInstancePropInput> properties = entry.getValue();
-
- Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny();
- if(!op.isPresent()){
- ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
- log.debug("Failed to find component instance {} under component {}", compInstId, componentId);
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- ComponentInstance ci = op.get();
- String compInstname = ci.getNormalizedName();
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap);
- if(origComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value());
- log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
- }
- org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value();
-
-
- //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
-
- String inputName = compInstname;
-
- if (properties != null && !properties.isEmpty()) {
- for (ComponentInstancePropInput propInput : properties) {
- propInput.setOwnerId(null);
- propInput.setParentUniqueId(null);
-
- Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(component, ci, inputsToCreate, propertiesToCreate, inputsValueToCreate, inputName, propInput, isInputValue);
-
- if (createInputRes.isRight()) {
- log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createInputRes.right().value())));
-
- }
-
- resList.add(createInputRes.left().value());
-
- }
- if(! isInputValue){
- propertiesToCreateMap.put(compInstId, propertiesToCreate);
- }
- else{
- inputsValueToCreateMap.put(compInstId, inputsValueToCreate);
- }
- }
-
- }
- return Either.left(resList);
- }
-
- private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance ci, Map<String, InputDefinition> inputsToCreate, List<ComponentInstanceProperty> propertiesToCreate, List<ComponentInstanceInput> inputsValueToCreate, String inputName, ComponentInstancePropInput propInput, boolean isInputValue) {
- String propertiesName = propInput.getPropertiesName() ;
- PropertyDefinition selectedProp = propInput.getInput();
- String[] parsedPropNames = propInput.getParsedPropNames();
-
- if(parsedPropNames != null){
- for(String str: parsedPropNames){
- inputName += "_" + str;
- }
- } else {
- inputName += "_" + propInput.getName();
- }
-
- InputDefinition input = null;
- PropertyDefinition prop = propInput;
-
- if(CollectionUtils.isNotEmpty(propertiesToCreate) && !isInputValue){
- Optional<ComponentInstanceProperty> propOpt = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
- if(propOpt.isPresent()){
- prop = propOpt.get();
- }
- }else{
- if(CollectionUtils.isNotEmpty(inputsValueToCreate) && isInputValue){
- Optional<ComponentInstanceInput> propOpt = inputsValueToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
- if(propOpt.isPresent()){
- prop = propOpt.get();
- }
- }
- }
-
- boolean complexProperty = false;
- if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
- complexProperty = true;
- input = new InputDefinition(selectedProp);
- }else{
- input = new InputDefinition(prop);
- input.setName(inputName + "_" + prop.getName());
-
- }
- input.setDefaultValue(prop.getValue());
- input.setName(inputName);
- input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName()));
- input.setInputPath(propertiesName);
- input.setInstanceUniqueId(ci.getUniqueId());
- input.setPropertyId(propInput.getUniqueId());
-
- JSONObject jobject = new JSONObject();
-
-
- if(prop.getValue() == null || prop.getValue().isEmpty()){
- if(complexProperty){
-
- jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
- prop.setValue(jobject.toJSONString());
-
- }else{
-
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
-
- }
-
- }else{
-
- String value = prop.getValue();
- Object objValue = new Yaml().load(value);
- if( objValue instanceof Map || objValue instanceof List ){
- if(!complexProperty){
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
-
-
- }else{
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
- createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
-
- String json = gson.toJson(mappedToscaTemplate);
- prop.setValue(json);
-
- }
-
- }else{
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
-
- }
-
- }
-
- ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(ci.getUniqueId());
- ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(ci.getName());
-
- if(CollectionUtils.isEmpty(prop.getGetInputValues())){
- prop.setGetInputValues(new ArrayList<>());
- }
- List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues();
-
- GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
- getInputValueDataDefinition.setInputId(input.getUniqueId());
- getInputValueDataDefinition.setInputName(input.getName());
- getInputValues.add(getInputValueDataDefinition);
-
- if(!isInputValue){
- if(!propertiesToCreate.contains(prop)){
- propertiesToCreate.add((ComponentInstanceProperty)prop);
- }
-
- inputsToCreate.put(input.getName(), input);
- List<ComponentInstanceProperty> propertiesList = input.getProperties();
- if(propertiesList == null)
- propertiesList = new ArrayList<>(); // adding the property with the new value for UI
- propertiesList.add((ComponentInstanceProperty)prop);
- input.setProperties(propertiesList);
- }else{
- ComponentInstanceInput inputValue = new ComponentInstanceInput(prop);
- if(!inputsValueToCreate.contains(inputValue)){
- inputsValueToCreate.add(inputValue);;
- }
-
- inputsToCreate.put(input.getName(), input);
- List<ComponentInstanceInput> inputsValueList = input.getInputs();
- if(inputsValueList == null)
- inputsValueList = new ArrayList<>(); // adding the property with the new value for UI
- inputsValueList.add(inputValue);
- input.setInputs(inputsValueList);
- }
-
- return Either.left(input);
-
- }
-
- private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
-
- while(i >= 1){
- if( i == parsedPropNames.length -1){
- JSONObject jobProp = new JSONObject();
- jobProp.put(GET_INPUT, inputName);
- ooj.put(parsedPropNames[i], jobProp);
- i--;
- return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
- }else{
- JSONObject res = new JSONObject();
- res.put(parsedPropNames[i], ooj);
- i --;
- res = createJSONValueForProperty (i, parsedPropNames, res, inputName);
- return res;
- }
- }
-
- return ooj;
- }
-
- public void resetInputName(Map<String, Object> lhm1, String inputName){
- for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
- value = "";
- lhm1.remove(key);
- } else if (value instanceof Map) {
- Map<String, Object> subMap = (Map<String, Object>)value;
- resetInputName(subMap, inputName);
- } else {
- continue;
- }
-
- }
- }
-
- private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
- while(index < inputNames.length){
- if(lhm1.containsKey(inputNames[index])){
- Object value = lhm1.get(inputNames[index]);
- if (value instanceof Map){
- if(index == inputNames.length -1){
- ((Map) value).put(GET_INPUT, inputName);
- return ((Map) value);
-
- }else{
- index++;
- return createInputValue((Map)value, index, inputNames, inputName);
- }
- }else{
- Map<String, Object> jobProp = new HashMap<>();
- if(index == inputNames.length -1){
- jobProp.put(GET_INPUT, inputName);
- lhm1.put(inputNames[index], jobProp);
- return lhm1;
- }else{
- lhm1.put(inputNames[index], jobProp);
- index++;
- return createInputValue(jobProp, index, inputNames, inputName);
- }
- }
- }else{
- Map<String, Object> jobProp = new HashMap<>();
- lhm1.put(inputNames[index], jobProp);
- if(index == inputNames.length -1){
- jobProp.put(GET_INPUT, inputName);
- return jobProp;
- }else{
- index++;
- return createInputValue(jobProp, index, inputNames, inputName);
- }
- }
- }
- return lhm1;
- }
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreInputs(false);
+ filters.setIgnoreComponentInstances(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", componentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
+
+ if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){
+ ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
+ log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+ Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap());
+ return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList()));
+ }
+
+ /**
+ * associate properties to a given component instance input
+ *
+ * @param instanceId
+ * @param userId
+ * @param inputId
+ * @return
+ */
+
+ public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ String parentId = componentId;
+ org.openecomp.sdc.be.model.Component component = null;
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreComponentInstances(false);
+
+ if(!instanceId.equals(inputId)){
+
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", parentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ component = getComponentEither.left().value();
+ Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny();
+ if(ciOp.isPresent()){
+ parentId = ciOp.get().getComponentUid();
+ }
+
+ }
+
+ filters.setIgnoreInputs(false);
+
+ filters.setIgnoreComponentInstancesProperties(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+ filters.setIgnoreProperties(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", parentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ component = getComponentEither.left().value();
+
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ return Either.left(componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId));
+
+ }
+
+ private Either<String,ResponseFormat> updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) {
+ String innerType = null;
+ String propertyType = currentInput.getType();
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
+
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+ SchemaDefinition def = currentInput.getSchema();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+ }
+ innerType = propDef.getType();
+ }
+ // Specific Update Logic
+
+ Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes);
+
+ String newValue = currentInput.getDefaultValue();
+ if (isValid.isRight()) {
+ Boolean res = isValid.right().value();
+ if (Boolean.FALSE.equals(res)) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT))));
+ }
+ } else {
+ Object object = isValid.left().value();
+ if (object != null) {
+ newValue = object.toString();
+ }
+ }
+ return Either.left(newValue);
+ }
+
+ private InputDefinition getInputFromInputsListById(List<InputDefinition> componentsOldInputs, InputDefinition input) {
+ Optional<InputDefinition> foundInput = componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst();
+ return foundInput.isPresent() ? foundInput.get() : null;
+ }
+
+ public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List<InputDefinition> inputs, String userId, boolean shouldLockComp, boolean inTransaction) {
+
+ List<InputDefinition> returnInputs = new ArrayList<>();
+ Either<List<InputDefinition>, ResponseFormat> result = null;
+ org.openecomp.sdc.be.model.Component component = null;
+
+ try {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get input", false);
+
+ if (resp.isRight()) {
+ result = Either.right(resp.right().value());
+ return result;
+ }
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreInputs(false);
+ componentParametersView.setIgnoreUsers(false);
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
+
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ component = validateComponent.left().value();
+
+ if (shouldLockComp) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_INPUT);
+ if (lockComponent.isRight()) {
+ result = Either.right(lockComponent.right().value());
+ return result;
+ }
+ }
+
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
+ if (canWork.isRight()) {
+ result = Either.right(canWork.right().value());
+ return result;
+ }
+
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ result = Either.right(allDataTypes.right().value());
+ return result;
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+ List<InputDefinition> componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList());
+ for (InputDefinition newInput: inputs) {
+ InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput);
+ if (currInput == null) {
+ ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
+ log.debug("Failed to found newInput {} under component {}, error: {}", newInput.getUniqueId(), componentId, actionStatus.name());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus));
+ return result;
+ }
+ Either<String, ResponseFormat> updateInputObjectValue = updateInputObjectValue(currInput, newInput, dataTypes);
+ if ( updateInputObjectValue.isRight()) {
+ return Either.right(updateInputObjectValue.right().value());
+ }
+ String newValue = updateInputObjectValue.left().value();
+ currInput.setDefaultValue(newValue);
+ currInput.setOwnerId(userId);
+ Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currInput);
+ if(status.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
+ return result;
+ } else {
+ returnInputs.add(status.left().value());
+ }
+ }
+ result = Either.left(returnInputs);
+ 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<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ String parentId = componentId;
+ org.openecomp.sdc.be.model.Component component = null;
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreComponentInstances(false);
+ filters.setIgnoreInputs(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+ filters.setIgnoreProperties(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
+
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", parentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ component = getComponentEither.left().value();
+
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found input {} under component {}, error: {}", inputId, parentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId));
+
+ }
+
+ public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) {
+
+ Either<List<InputDefinition>, ResponseFormat> result = null;
+ org.openecomp.sdc.be.model.Component component = null;
+
+ try {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
+
+ if (resp.isRight()) {
+ result = Either.right(resp.right().value());
+ return result;
+ }
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreInputs(false);
+ componentParametersView.setIgnoreComponentInstancesInputs(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+ componentParametersView.setIgnoreComponentInstancesProperties(false);
+ componentParametersView.setIgnoreUsers(false);
+
+ Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentType, componentParametersView);
+
+ if (validateComponent.isRight()) {
+ result = Either.right(validateComponent.right().value());
+ return result;
+ }
+ component = validateComponent.left().value();
+
+ if (shouldLockComp) {
+ Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, CREATE_INPUT);
+ if (lockComponent.isRight()) {
+ result = Either.right(lockComponent.right().value());
+ return result;
+ }
+ }
+
+ Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
+ if (canWork.isRight()) {
+ result = Either.right(canWork.right().value());
+ return result;
+ }
+
+ result = propertyDecelerationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi)
+ .left()
+ .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate))
+ .right()
+ .map(err -> componentsUtils.getResponseFormat(err));
+
+ return result;
+
+ } finally {
+
+ if (!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());
+ }
+
+ }
+ }
+
+ private Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, List<InputDefinition> inputsToCreate) {
+ Map<String, InputDefinition> inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName);
+ assignOwnerIdToInputs(userId, inputsToPersist);
+ return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId)
+ .left()
+ .map(persistedInputs -> inputsToCreate);
+ }
+
+ private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) {
+ inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId));
+ }
+
+ public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) {
+
+ List<InputDefinition> resList = inputs.values().stream().collect(Collectors.toList());
+ Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
+ List<InputDefinition> resourceProperties = component.getInputs();
+
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+
+ for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
+ String inputName = inputDefinition.getKey();
+ inputDefinition.getValue().setName(inputName);
+
+ Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
+ if(preparedInputEither.isRight()){
+ return Either.right(preparedInputEither.right().value());
+ }
+
+ }
+ if (resourceProperties != null) {
+ Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
+ Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
+ if(mergeEither.isRight()){
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
+ }
+ inputs = mergeEither.left().value();
+ }
+
+ Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
+ if(assotiateInputsEither.isRight()){
+ log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
+ }
+ result = Either.left(assotiateInputsEither.left().value());
+
+ return result;
+ }
+
+ /**
+ * Delete input from service
+ *
+ * @param componentId
+ * @param userId
+ *
+ * @param inputId
+ * @return
+ */
+ public Either<InputDefinition, ResponseFormat> deleteInput(String componentId, String userId, String inputId) {
+
+ Either<InputDefinition, ResponseFormat> deleteEither = null;
+ if (log.isDebugEnabled())
+ log.debug("Going to delete input id: {}", inputId);
+
+ // Validate user (exists)
+ Either<User, ResponseFormat> userEither = validateUserExists(userId, "Delete input", true);
+ if (userEither.isRight()) {
+ deleteEither = Either.right(userEither.right().value());
+ return deleteEither;
+ }
+
+ // Get component using componentType, componentId
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreInputs(false);
+ componentParametersView.setIgnoreComponentInstances(false);
+ componentParametersView.setIgnoreComponentInstancesInputs(false);
+ componentParametersView.setIgnoreComponentInstancesProperties(false);
+ componentParametersView.setIgnorePolicies(false);
+ componentParametersView.setIgnoreUsers(false);
+
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+ if (componentEither.isRight()) {
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentEither.right().value())));
+ return deleteEither;
+ }
+ org.openecomp.sdc.be.model.Component component = componentEither.left().value();
+
+ // Validate inputId is child of the component
+ Optional<InputDefinition> optionalInput = component.getInputs().stream().
+ // filter by ID
+ filter(input -> input.getUniqueId().equals(inputId)).
+ // Get the input
+ findAny();
+ if (!optionalInput.isPresent()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId));
+ }
+
+ InputDefinition inputForDelete = optionalInput.get();
+
+ // Lock component
+ Either<Boolean, ResponseFormat> lockResultEither = lockComponent(componentId, component, "deleteInput");
+ if (lockResultEither.isRight()) {
+ ResponseFormat responseFormat = lockResultEither.right().value();
+ deleteEither = Either.right(responseFormat);
+ return deleteEither;
+ }
+
+ // Delete input operations
+ try {
+ StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
+ if (status != StorageOperationStatus.OK) {
+ log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
+ }
+ StorageOperationStatus storageOperationStatus = propertyDecelerationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
+ if (storageOperationStatus != StorageOperationStatus.OK) {
+ log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
+ return deleteEither;
+ }
+ deleteEither = Either.left(inputForDelete);
+ return deleteEither;
+ } finally {
+ if (deleteEither == null || deleteEither.isRight()) {
+ log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
+ titanDao.rollback();
+ } else {
+ log.debug("Component id: {} delete input id: {} success", componentId, inputId);
+ titanDao.commit();
+ }
+ unlockComponent(deleteEither, component);
+ }
+ }
+
+ private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+
+ // validate input default values
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
+ if (defaultValuesValidation.isRight()) {
+ return Either.right(defaultValuesValidation.right().value());
+ }
+ // convert property
+ ToscaPropertyType type = getType(newInputDefinition.getType());
+ if (type != null) {
+ PropertyValueConverter converter = type.getConverter();
+ // get inner type
+ String innerType = null;
+ if (newInputDefinition != null) {
+ SchemaDefinition schema = newInputDefinition.getSchema();
+ if (schema != null) {
+ PropertyDataDefinition prop = schema.getProperty();
+ if (prop != null) {
+ innerType = prop.getType();
+ }
+ }
+ String convertedValue = null;
+ if (newInputDefinition.getDefaultValue() != null) {
+ convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes);
+ newInputDefinition.setDefaultValue(convertedValue);
+ }
+ }
+ }
+ return Either.left(newInputDefinition);
+ }
+
+ public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) {
+ Either<InputDefinition, ResponseFormat> result = null;
+ try {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Properties by input", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.disableAll();
+ filters.setIgnoreComponentInstances(false);
+ filters.setIgnoreInputs(false);
+ filters.setIgnoreComponentInstancesInputs(false);
+ filters.setIgnoreComponentInstancesProperties(false);
+ filters.setIgnoreProperties(false);
+ Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
+ if(getComponentEither.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found component {}, error: {}", componentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+
+ }
+ org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
+ Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
+ if(!op.isPresent()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
+ log.debug("Failed to found input {} under component {}, error: {}", inputId, componentId, actionStatus);
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ InputDefinition resObj = op.get();
+
+ List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId) ;
+
+ resObj.setInputs(inputCIInput);
+
+
+ List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId) ;
+
+ resObj.setProperties(inputProps);
+
+
+ result = Either.left(resObj);
+
+ 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();
+ }
+
+ }
+
+ }
+
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
index e7d051290f..cfc2505942 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.InterfaceDefinition;
@@ -39,86 +32,86 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
@Component("interfaceLifecycleTypeImportManager")
public class InterfaceLifecycleTypeImportManager {
- @Resource
- private IInterfaceLifecycleOperation interfaceLifecycleOperation;
-
- @Resource
- private ComponentsUtils componentsUtils;
- @Resource
- private CommonImportManager commonImportManager;
-
- private static Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class.getName());
-
- public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) {
-
- Either<List<InterfaceDefinition>, ActionStatus> interfaces = createLifecyclyTypeFromYml(interfaceLifecycleTypesYml);
- if (interfaces.isRight()) {
- ActionStatus status = interfaces.right().value();
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null);
- return Either.right(responseFormat);
- }
- return createInterfacesByDao(interfaces.left().value());
-
- }
-
- private Either<List<InterfaceDefinition>, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) {
- return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData));
-
- }
-
- private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) {
- List<InterfaceDefinition> createdInterfaces = new ArrayList<>();
- Either<List<InterfaceDefinition>, ResponseFormat> eitherResult = Either.left(createdInterfaces);
- Iterator<InterfaceDefinition> interfaceItr = interfacesToCreate.iterator();
- boolean stopDao = false;
- while (interfaceItr.hasNext() && !stopDao) {
- InterfaceDefinition interfaceDef = interfaceItr.next();
-
- log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType());
-
- Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef);
- if (dataModelResponse.isRight()) {
- log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name());
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType());
- eitherResult = Either.right(responseFormat);
- stopDao = true;
- }
-
- } else {
- createdInterfaces.add(dataModelResponse.left().value());
- }
- if (!interfaceItr.hasNext()) {
- log.info("lifecycle types were created successfully!!!");
- }
- }
- return eitherResult;
- }
-
- private InterfaceDefinition createLifecycleType(String interfaceDefinition, Map<String, Object> toscaJson) {
- InterfaceDefinition interfaceDef = new InterfaceDefinition();
- interfaceDef.setType(interfaceDefinition);
-
- Map<String, Operation> operations = new HashMap<String, Operation>();
-
- for (Map.Entry<String, Object> entry : toscaJson.entrySet()) {
- Operation operation = new Operation();
- Map<String, Object> opProp = (Map<String, Object>) entry.getValue();
-
- operation.setDescription((String) opProp.get("description"));
- operations.put(entry.getKey(), operation);
- }
- interfaceDef.setOperationsMap(operations);
- return interfaceDef;
- }
-
- public static void setLog(Logger log) {
- InterfaceLifecycleTypeImportManager.log = log;
- }
-
+ @Resource
+ private IInterfaceLifecycleOperation interfaceLifecycleOperation;
+
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Resource
+ private CommonImportManager commonImportManager;
+
+ private static final Logger log = LoggerFactory.getLogger(InterfaceLifecycleTypeImportManager.class);
+
+ public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) {
+
+ Either<List<InterfaceDefinition>, ActionStatus> interfaces = createLifecyclyTypeFromYml(interfaceLifecycleTypesYml);
+ if (interfaces.isRight()) {
+ ActionStatus status = interfaces.right().value();
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null);
+ return Either.right(responseFormat);
+ }
+ return createInterfacesByDao(interfaces.left().value());
+
+ }
+
+ private Either<List<InterfaceDefinition>, ActionStatus> createLifecyclyTypeFromYml(String interfaceLifecycleTypesYml) {
+ return commonImportManager.createElementTypesFromYml(interfaceLifecycleTypesYml, (lifecycleTypeName, lifecycleTypeJsonData) -> createLifecycleType(lifecycleTypeName, lifecycleTypeJsonData));
+
+ }
+
+ private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) {
+ List<InterfaceDefinition> createdInterfaces = new ArrayList<>();
+ Either<List<InterfaceDefinition>, ResponseFormat> eitherResult = Either.left(createdInterfaces);
+ Iterator<InterfaceDefinition> interfaceItr = interfacesToCreate.iterator();
+ boolean stopDao = false;
+ while (interfaceItr.hasNext() && !stopDao) {
+ InterfaceDefinition interfaceDef = interfaceItr.next();
+
+ log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType());
+
+ Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef);
+ if (dataModelResponse.isRight()) {
+ log.info("failed to create interface : {} error: {}", interfaceDef.getType(), dataModelResponse.right().value().name());
+ if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType());
+ eitherResult = Either.right(responseFormat);
+ stopDao = true;
+ }
+
+ } else {
+ createdInterfaces.add(dataModelResponse.left().value());
+ }
+ if (!interfaceItr.hasNext()) {
+ log.info("lifecycle types were created successfully!!!");
+ }
+ }
+ return eitherResult;
+ }
+
+ private InterfaceDefinition createLifecycleType(String interfaceDefinition, Map<String, Object> toscaJson) {
+ InterfaceDefinition interfaceDef = new InterfaceDefinition();
+ interfaceDef.setType(interfaceDefinition);
+
+ Map<String, Operation> operations = new HashMap<String, Operation>();
+
+ for (Map.Entry<String, Object> entry : toscaJson.entrySet()) {
+ Operation operation = new Operation();
+ Map<String, Object> opProp = (Map<String, Object>) entry.getValue();
+
+ operation.setDescription((String) opProp.get("description"));
+ operations.put(entry.getKey(), operation);
+ }
+ interfaceDef.setOperationsMap(operations);
+ return interfaceDef;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java
index e9708f50d5..43cf9bdec8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/MonitoringBusinessLogic.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.be.components.impl;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.impl.MonitoringDao;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -29,43 +30,41 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
-
@Component("monitoringBusinessLogic")
public class MonitoringBusinessLogic {
- private static Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(MonitoringBusinessLogic.class);
- @javax.annotation.Resource
- private MonitoringDao monitoringDao;
+ @javax.annotation.Resource
+ private MonitoringDao monitoringDao;
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
- public Either<Boolean, ResponseFormat> logMonitoringEvent(MonitoringEvent monitoringEvent) {
- if (monitoringDao == null) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- ActionStatus status = monitoringDao.addRecord(monitoringEvent);
- if (!status.equals(ActionStatus.OK)) {
- log.warn("Failed to persist monitoring event: {}", status.name());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return Either.left(true);
- }
+ public Either<Boolean, ResponseFormat> logMonitoringEvent(MonitoringEvent monitoringEvent) {
+ if (monitoringDao == null) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ ActionStatus status = monitoringDao.addRecord(monitoringEvent);
+ if (!status.equals(ActionStatus.OK)) {
+ log.warn("Failed to persist monitoring event: {}", status);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return Either.left(true);
+ }
- public String getEsHost() {
+ public String getEsHost() {
- String res = monitoringDao.getEsHost();
- res = res.replaceAll("[\\[\\]]", "");
- res = res.split(",")[0];
- res = res.replaceAll("[']", "");
- res = res.split(":")[0];
- return res;
- }
+ String res = monitoringDao.getEsHost();
+ res = res.replaceAll("[\\[\\]]", "");
+ res = res.split(",")[0];
+ res = res.replaceAll("[']", "");
+ res = res.split(":")[0];
+ return res;
+ }
- public String getEsPort() {
- return monitoringDao.getEsPort();
- }
+ public String getEsPort() {
+ return monitoringDao.getEsPort();
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
new file mode 100644
index 0000000000..37a853ccdd
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
@@ -0,0 +1,451 @@
+package org.openecomp.sdc.be.components.impl;
+
+import static java.util.stream.Collectors.toMap;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+/**
+ * Provides specified business logic to create, retrieve, update, delete a policy
+ */
+@org.springframework.stereotype.Component("policyBusinessLogic")
+public class PolicyBusinessLogic extends BaseBusinessLogic {
+
+ private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. ";
+ private static final Logger log = LoggerFactory.getLogger(PolicyBusinessLogic.class);
+
+ /**
+ * Adds the newly created policy of the specified type to the component
+ *
+ * @param componentType the type of the component
+ * @param componentId the id of the component which the policy resides under
+ * @param policyTypeName the name of the policy type
+ * @param userId the user creator id
+ * @param shouldLock the flag defining if the component should be locked
+ * @return a policy or an error in a response format
+ */
+
+ public Either<PolicyDefinition, ResponseFormat> createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) {
+
+ Either<PolicyDefinition, ResponseFormat> result = null;
+ log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId);
+ Wrapper<Component> component = new Wrapper<>();
+ try {
+ result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock)
+ .left()
+ .bind(c -> {
+ component.setInnerElement(c);
+ return createPolicy(policyTypeName, c);
+ });
+ } catch (Exception e) {
+ log.error("#createPolicy - the exception occurred upon creation of a policy of the type {} for the component {}: ", policyTypeName, componentId, e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+
+ unlockComponent(shouldLock, result, component);
+ }
+ return result;
+ }
+
+ /**
+ * Retrieves the policy of the component by UniqueId
+ *
+ * @param componentType
+ * @param componentId
+ * @param policyId
+ * @param userId
+ * @return
+ */
+ public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
+ Either<PolicyDefinition, ResponseFormat> result = null;
+ log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId);
+ try {
+ result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
+ .left()
+ .bind(c -> getPolicyById(c, policyId));
+ } catch (Exception e) {
+ log.error("#getPolicy - the exception occurred upon retrieving the policy {} of the component {}: ", policyId, componentId, e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return result;
+ }
+
+ /**
+ * Updates the policy of the component
+ *
+ * @param componentType the type of the component
+ * @param componentId the id of the component which the policy resides under
+ * @param policy
+ * @param userId the user modifier id
+ * @param shouldLock the flag defining if the component should be locked
+ * @return a policy or an error in a response format
+ */
+ public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) {
+ Either<PolicyDefinition, ResponseFormat> result = null;
+ log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId);
+ Wrapper<Component> component = new Wrapper<>();
+ try {
+ result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock)
+ .left()
+ .bind(c -> {
+ component.setInnerElement(c);
+ return validateAndUpdatePolicy(c, policy);
+ });
+ } catch (Exception e) {
+ log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ unlockComponent(shouldLock, result, component);
+ }
+ return result;
+ }
+
+ /**
+ * Deletes the policy from the component
+ *
+ * @param componentType the type of the component
+ * @param componentId the id of the component which the policy resides under
+ * @param policyId the id of the policy which its properties to return
+ * @param userId the user modifier id
+ * @param shouldLock the flag defining if the component should be locked
+ * @return a policy or an error in a response format
+ */
+ public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) {
+ Either<PolicyDefinition, ResponseFormat> result = null;
+ log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId);
+ Wrapper<Component> component = new Wrapper<>();
+ try {
+ result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock)
+ .left()
+ .bind(c -> {
+ component.setInnerElement(c);
+ return deletePolicy(c, policyId);
+ });
+ } catch (Exception e) {
+ log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e);
+ } finally {
+ unlockComponent(shouldLock, result, component);
+ }
+ return result;
+ }
+
+ public Either<PolicyDefinition, ResponseFormat> updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) {
+
+ Either<PolicyDefinition, ResponseFormat> result = null;
+ log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId);
+ Component component = null;
+
+ try {
+ //not right error response
+ result = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true)
+ .left()
+ .bind(cmpt -> validateAndUpdatePolicyTargets(cmpt, policyId, targets));
+
+ return result;
+ } finally {
+
+ unlockComponentById(result, componentId);
+
+ }
+
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyTargets(Component component, String policyId, Map<PolicyTargetType, List<String>> targets) {
+ if (!validateTargetsExistAndTypesCorrect(component.getUniqueId(), targets)) {
+ log.debug("Error finding all the targets: {} .", targets);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, StringUtils.join(targets.values())));
+ }
+ return updateTargets(component.getUniqueId(), component.getPolicyById(policyId), targets, policyId);
+
+ }
+
+ private boolean validateTargetsExistAndTypesCorrect(String componentId, Map<PolicyTargetType, List<String>> targets) {
+ Either<Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaFullElement(componentId);
+ Component parentComponent = componentEither.left().value();
+
+ return targets.entrySet().stream().noneMatch(t -> checkTargetNotExistOnComponentByType(parentComponent, t));
+ }
+
+ private boolean checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) {
+
+ return targetEntry.getValue().stream()
+ .anyMatch(id -> checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().toString()));
+ }
+
+ private boolean checkNotPresenceInComponentByType(Component parentComponent, String uniqueId, String type) {
+ if (type.equalsIgnoreCase(PolicyTargetType.GROUPS.getName()) && parentComponent.getGroups() != null) {
+ return !parentComponent.getGroupById(uniqueId).isPresent();
+ } else if (type.equalsIgnoreCase(PolicyTargetType.COMPONENT_INSTANCES.getName()) && parentComponent.getComponentInstances() != null) {
+ return !parentComponent.getComponentInstanceById(uniqueId).isPresent();
+ }
+ return true;
+ }
+
+ private PolicyDefinition setPolicyTargets(PolicyDefinition policyDefinition, Map<PolicyTargetType, List<String>> targets) {
+ policyDefinition.setTargets(targets);
+ return policyDefinition;
+ }
+
+
+ /**
+ * @param componentType the type of the component
+ * @param componentId the id of the component which the policy resides under
+ * @param policyId the id of the policy which its properties to return
+ * @param userId the user id
+ * @return a list of policy properties or an error in a response format
+ */
+ public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
+ log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId);
+ try {
+ return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
+ .left()
+ .bind(cmpt -> getPolicyById(cmpt, policyId)).left().map(PolicyDataDefinition::getProperties);
+ } finally {
+ titanDao.commit();
+ }
+ }
+
+ /**
+ * Updates the policy properties of the component
+ *
+ * @param componentType the type of the component
+ * @param componentId the id of the component which the policy resides under
+ * @param policyId the id of the policy which its properties to return
+ * @param properties a list of policy properties containing updated values
+ * @param userId the user modifier id
+ * @param shouldLock the flag defining if the component should be locked
+ * @return a list of policy properties or anerrorin a response format
+ */
+ public Either<List<PropertyDataDefinition>, ResponseFormat> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) {
+ Either<List<PropertyDataDefinition>, ResponseFormat> result = null;
+ log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId);
+ Wrapper<Component> component = new Wrapper<>();
+ try {
+ result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock).left().bind(c -> setComponentValidateUpdatePolicyProperties(policyId, properties, component, c));
+ } catch (Exception e) {
+ log.error("#updatePolicyProperties - the exception {} occurred upon update properties of the policy {} for the component {}: ", policyId, componentId, e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ if (shouldLock && !component.isEmpty()) {
+ unlockComponent(result, component.getInnerElement());
+ }
+ }
+ return result;
+ }
+
+ private Either<List<PropertyDataDefinition>, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper<Component> component, Component c) {
+ component.setInnerElement(c);
+ return validateAndUpdatePolicyProperties(c, policyId, properties)
+ .left()
+ .map(PolicyDefinition::getProperties);
+ }
+
+ private void unlockComponent(boolean shouldLock, Either<PolicyDefinition, ResponseFormat> result, Wrapper<Component> component) {
+ if (shouldLock && !component.isEmpty()) {
+ unlockComponent(result, component.getInnerElement());
+ }
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> getPolicyById(Component component, String policyId) {
+ PolicyDefinition policyById = component.getPolicyById(policyId);
+ if (policyById == null) {
+ String cmptId = component.getUniqueId();
+ log.debug("#getPolicyById - policy with id {} does not exist on component with id {}", policyId, cmptId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, cmptId));
+ }
+ return Either.left(policyById);
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) {
+ return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component));
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> addPolicyToComponent(PolicyTypeDefinition policyType, Component component) {
+ return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()))
+ .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
+ }
+
+ private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) {
+ return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
+ .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
+ }
+
+ private Either<PolicyTypeDefinition, ResponseFormat> validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) {
+ if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component)));
+ }
+ return Either.left(policyType);
+ }
+
+ private String getComponentOrResourceTypeName(Component component) {
+ return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name();
+ }
+
+ private Either<Component, ResponseFormat> validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) {
+ Wrapper<Component> component = new Wrapper<>();
+ return validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId)
+ .left()
+ .bind(this::validateComponentIsTopologyTemplate)
+ .left()
+ .bind(c -> {
+ component.setInnerElement(c);
+ return validateCanWorkOnComponent(c, userId);
+ })
+ .left()
+ .bind(l -> lockComponent(component.getInnerElement(), shouldLock, "policyWritingOperation"))
+ .either(l -> Either.left(component.getInnerElement()), r -> {
+ log.error(FAILED_TO_VALIDATE_COMPONENT, componentId);
+ return Either.right(r);
+ });
+ }
+
+ private Either<Component, ResponseFormat> validateComponentIsTopologyTemplate(Component component) {
+ if (!component.isTopologyTemplate()) {
+ log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ", component.getToscaType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES, "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType()));
+ }
+ return Either.left(component);
+ }
+
+ private Either<Component, ResponseFormat> validateContainerComponentAndUserBeforeReadOperation(ComponentTypeEnum componentType, String componentId, String userId) {
+ Either<Component, ResponseFormat> result = null;
+ log.trace("#validateContainerComponentAndUserBeforeReadOperation - starting to validate the user {} before policy processing. ", userId);
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Policy", false);
+ if (resp.isRight()) {
+ log.error("#validateContainerComponentAndUserBeforeReadOperation - failed to validate the user {} before policy processing. ", userId);
+ result = Either.right(resp.right().value());
+ } else {
+ result = validateComponentExists(componentType, componentId);
+ if (result.isRight()) {
+ log.error(FAILED_TO_VALIDATE_COMPONENT, "#validateContainerComponentAndUserBeforeReadOperation", componentId);
+ }
+ return result;
+ }
+ return result;
+ }
+
+ private Either<Component, ResponseFormat> validateComponentExists(ComponentTypeEnum componentType, String componentId) {
+
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnorePolicies(false);
+ filter.setIgnoreUsers(false);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreGroups(false);
+ return validateComponentExists(componentId, componentType, filter);
+ }
+
+
+ private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicy(Component component, PolicyDefinition policy) {
+ return getPolicyById(component, policy.getUniqueId())
+ .left()
+ .bind(np -> validateUpdatePolicyBeforeUpdate(policy, np, component.getPolicies()))
+ .left()
+ .bind(p -> updatePolicyOfComponent(component, p));
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) {
+ return getPolicyById(component, policyId)
+ .left()
+ .bind(p -> validateUpdatePolicyPropertiesBeforeUpdate(p, properties))
+ .left().bind(l -> updatePolicyOfComponent(component.getUniqueId(), l));
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(String componentId, PolicyDefinition policy) {
+ return toscaOperationFacade.updatePolicyOfComponent(componentId, policy)
+ .right()
+ .bind(r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
+ if (CollectionUtils.isEmpty(policy.getProperties())) {
+ log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. ");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
+ }
+ return updatePropertyValues(policy, newProperties);
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
+
+ Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity()));
+ for (PropertyDataDefinition newProperty : newProperties) {
+ if (!oldProperties.containsKey(newProperty.getName())) {
+ log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName()));
+ }
+ Either<String, ResponseFormat> newPropertyValueEither = updatePropertyObjectValue(newProperty, true);
+ if (newPropertyValueEither.isRight()) {
+ return Either.right(newPropertyValueEither.right().value());
+ }
+ oldProperties.get(newProperty.getName()).setValue(newPropertyValueEither.left().value());
+ }
+ return Either.left(policy);
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> deletePolicy(Component component, String policyId) {
+ return getPolicyById(component, policyId)
+ .left()
+ .bind(p -> removePolicyFromComponent(component, p));
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> updatePolicyOfComponent(Component component, PolicyDefinition policy) {
+ Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy);
+ if (updatePolicyRes.isRight()) {
+ log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value())));
+ } else {
+ log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName());
+ return Either.left(updatePolicyRes.left().value());
+ }
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> removePolicyFromComponent(Component component, PolicyDefinition policy) {
+ StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId());
+ if (updatePolicyStatus != StorageOperationStatus.OK) {
+ log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updatePolicyStatus)));
+ } else {
+ log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus);
+ return Either.left(policy);
+ }
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) {
+ return validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies)
+ .right()
+ .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName())));
+ }
+
+ private Either<PolicyDefinition, ResponseFormat> updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) {
+ if(policy == null){
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId));
+ }
+ PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets);
+ return updatePolicyOfComponent(componentId, updatedPolicy);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
new file mode 100644
index 0000000000..fee8ba187c
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
@@ -0,0 +1,56 @@
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+import java.util.Set;
+
+@Component
+public class PolicyTypeBusinessLogic {
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyTypeBusinessLogic.class);
+ private PolicyTypeOperation policyTypeOperation;
+ private TitanDao titanDao;
+ private ComponentsUtils componentsUtils;
+ private UserValidations userValidations;
+
+ public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, TitanDao titanDao, ComponentsUtils componentsUtils, UserValidations userValidations) {
+ this.policyTypeOperation = policyTypeOperation;
+ this.titanDao = titanDao;
+ this.componentsUtils = componentsUtils;
+ this.userValidations = userValidations;
+ }
+
+ public Either<List<PolicyTypeDefinition>, ResponseFormat> getAllPolicyTypes(String userId, String internalComponentType) {
+ try {
+ Set<String> excludedPolicyTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping().get(internalComponentType);
+ return userValidations.validateUserExists(userId, "get policy types", true)
+ .left()
+ .bind(user -> getPolicyTypes(excludedPolicyTypes));
+ } finally {
+ titanDao.commit();
+ }
+ }
+
+ private Either<List<PolicyTypeDefinition>, ResponseFormat> getPolicyTypes(Set<String> excludedTypes) {
+ return policyTypeOperation.getAllPolicyTypes(excludedTypes)
+ .right()
+ .bind(this::convertToResponseFormatOrNotFoundErrorToEmptyList);
+ }
+
+ private Either<List<PolicyTypeDefinition>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus err) {
+ log.debug("error when trying to fetch policy types: {}", err);
+ return componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(err);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
index 4a07120994..fed588ff9c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
@@ -20,109 +20,120 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
+import org.openecomp.sdc.be.components.impl.utils.PolicyTypeImportUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
@Component("policyTypeImportManager")
public class PolicyTypeImportManager {
- @Resource
- private IPolicyTypeOperation policyTypeOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Autowired
- protected IGroupOperation groupOperation;
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
-
- @Resource
- private CommonImportManager commonImportManager;
-
- public Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypes(String groupTypesYml) {
- return commonImportManager.createElementTypes(groupTypesYml, elementTypeYml -> createPolicyTypesFromYml(elementTypeYml), groupTypesList -> createPolicyTypesByDao(groupTypesList), ElementTypeEnum.PolicyType);
- }
-
- private Either<List<PolicyTypeDefinition>, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) {
-
- return commonImportManager.createElementTypesFromYml(policyTypesYml, (policyTypeName, groupTypeJsonData) -> createPolicyType(policyTypeName, groupTypeJsonData));
- }
-
- private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) {
- return commonImportManager.createElementTypesByDao(policyTypesToCreate, policyType -> validatePolicyType(policyType), policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()),
- policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), null);
- }
-
- private Either<ActionStatus, ResponseFormat> validatePolicyType(PolicyTypeDefinition policyType) {
- Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK);
- if (policyType.getTargets() != null) {
- if (policyType.getTargets().isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_EMPTY, policyType.getType());
- result = Either.right(responseFormat);
- }
- if (result.isLeft()) {
- for (String targetName : policyType.getTargets()) {
-
- boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetName).isLeft();;
- if (!isValid) {
- isValid = groupOperation.isGroupExist(targetName, false);
- }
- if (!isValid) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetName);
- result = Either.right(responseFormat);
- break;
- }
- }
- }
- }
-
- return result;
- }
-
- private PolicyTypeDefinition createPolicyType(String groupTypeName, Map<String, Object> toscaJson) {
-
- PolicyTypeDefinition policyType = new PolicyTypeDefinition();
-
- if (toscaJson != null) {
- // Description
- final Consumer<String> descriptionSetter = description -> policyType.setDescription(description);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
- // Derived From
- final Consumer<String> derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
- // Properties
- commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values));
- // Metadata
- final Consumer<Map<String, String>> metadataSetter = metadata -> policyType.setMetadata(metadata);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
- // Targets
- final Consumer<List<String>> targetsSetter = targets -> policyType.setTargets(targets);
- commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter);
-
- policyType.setType(groupTypeName);
-
- policyType.setHighestVersion(true);
-
- policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
- }
- return policyType;
- }
+ @Resource
+ private IPolicyTypeOperation policyTypeOperation;
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Autowired
+ protected IGroupOperation groupOperation;
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Resource
+ private CommonImportManager commonImportManager;
+
+ public Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> createPolicyTypes(String policyTypesYml) {
+ return commonImportManager.createElementTypes(policyTypesYml, this::createPolicyTypesFromYml, this::upsertPolicyTypesByDao, ElementTypeEnum.PolicyType);
+ }
+
+ private Either<List<PolicyTypeDefinition>, ActionStatus> createPolicyTypesFromYml(String policyTypesYml) {
+
+ return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType);
+ }
+
+ private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) {
+ return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.PolicyType, policyType.getType()),
+ policyTypeName -> policyTypeOperation.getLatestPolicyTypeByType(policyTypeName), policyType -> policyTypeOperation.addPolicyType(policyType), this::updatePolicyType);
+ }
+
+ private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) {
+ if (PolicyTypeImportUtils.isPolicyTypesEquals(newPolicyType, oldPolicyType)) {
+ return policyTypeAlreadyExists();
+ }
+ return policyTypeOperation.updatePolicyType(newPolicyType, oldPolicyType);
+ }
+
+ private Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeAlreadyExists() {
+ return Either.right(StorageOperationStatus.OK);
+ }
+
+ private Either<ActionStatus, ResponseFormat> validatePolicyType(PolicyTypeDefinition policyType) {
+ Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK);
+ if (policyType.getTargets() != null) {
+ if (policyType.getTargets().isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_EMPTY, policyType.getType());
+ result = Either.right(responseFormat);
+ }
+ if (result.isLeft()) {
+ for (String targetId : policyType.getTargets()) {
+ boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft();
+ if (!isValid) {
+ isValid = groupOperation.isGroupExist(targetId, false);
+ }
+ if (!isValid) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId);
+ result = Either.right(responseFormat);
+ break;
+ }
+ }
+ }
+ }
+
+
+ return result;
+ }
+
+ private PolicyTypeDefinition createPolicyType(String groupTypeName, Map<String, Object> toscaJson) {
+
+ PolicyTypeDefinition policyType = new PolicyTypeDefinition();
+
+ if (toscaJson != null) {
+ // Description
+ final Consumer<String> descriptionSetter = description -> policyType.setDescription(description);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DESCRIPTION.getElementName(), descriptionSetter);
+ // Derived From
+ final Consumer<String> derivedFromSetter = derivedFrom -> policyType.setDerivedFrom(derivedFrom);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.DERIVED_FROM.getElementName(), derivedFromSetter);
+ // Properties
+ commonImportManager.setProperties(toscaJson, (values) -> policyType.setProperties(values));
+ // Metadata
+ final Consumer<Map<String, String>> metadataSetter = metadata -> policyType.setMetadata(metadata);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
+ // Targets
+ final Consumer <List<String>> targetsSetter = targets -> policyType.setTargets(targets);
+ commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter);
+
+ policyType.setType(groupTypeName);
+
+ policyType.setHighestVersion(true);
+
+ policyType.setVersion(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION);
+ }
+ return policyType;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
index da64f3f5b7..ab6ff24676 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -48,846 +41,848 @@ import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("productBusinessLogic")
public class ProductBusinessLogic extends ComponentBusinessLogic {
- private static final String PRODUCT_FULL_NAME = "full";
- private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated";
- private static Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class.getName());
- private static final String INITIAL_VERSION = "0.1";
- private static List<Role> creationRoles;
- private static List<Role> updateRoles;
- private static List<Role> contactsRoles;
-
- public ProductBusinessLogic() {
- creationRoles = new ArrayList<>();
- updateRoles = new ArrayList<>();
- contactsRoles = new ArrayList<>();
-
- // only PM is allowed to create/update products
- creationRoles.add(Role.PRODUCT_MANAGER);
- updateRoles.add(Role.PRODUCT_MANAGER);
- // Only PM is allowed to be product contacts
- contactsRoles.add(Role.PRODUCT_MANAGER);
- }
-
- @Autowired
- private IElementOperation elementDao;
-
- @Autowired
- private ProductComponentInstanceBusinessLogic productComponentInstanceBusinessLogic;
-
- @Autowired
- private ICacheMangerOperation cacheManagerOperation;
-
- @Autowired
- ToscaOperationFacade toscaOperationFacade;
-
- public Either<Product, ResponseFormat> createProduct(Product product, User user) {
- AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
- ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
-
- // validate user - should be first to get the maximum auditing info in
- // case of subsequent failures
- log.debug("get user from DB");
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Product", product, actionEnum, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- // validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, product, creationRoles, actionEnum, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
-
- if (product == null) {
- log.debug("Invalid product json. Check product servlet log for createProduct entry params");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum);
- return Either.right(responseFormat);
- }
-
- // warn about non-updatable fields
- checkUnupdatableProductFields(product);
-
- Either<Product, ResponseFormat> validateProductResponse = validateProductBeforeCreate(product, user, actionEnum);
- if (validateProductResponse.isRight()) {
- return Either.right(validateProductResponse.right().value());
- }
-
- log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, "Create Product");
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult);
-
- try {
- Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product);
-
- if (createProductEither.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum);
- return Either.right(responseFormat);
- }
-
- log.debug("Product created successfully");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, Constants.EMPTY_STRING, Constants.EMPTY_STRING, actionEnum, typeEnum);
-
- // //Add product to cache
- Product createdProduct = createProductEither.left().value();
- // cacheManagerOperation.updateComponentInCache(createdProduct.getUniqueId(),
- // createdProduct.getLastUpdateDate(), NodeTypeEnum.Product);
-
- return Either.left(createdProduct);
-
- } finally {
- graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product);
- }
-
- }
-
- private void checkUnupdatableProductFields(Product product) {
- checkComponentFieldsForOverrideAttempt(product);
- if (product.getNormalizedName() != null) {
- log.info("NormalizedName cannot be defined by user. This field will be overridden by the application");
- }
- }
-
- private Either<Product, ResponseFormat> validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) {
-
- Either<Boolean, ResponseFormat> validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum);
- if (validateProductFields.isRight()) {
- return Either.right(validateProductFields.right().value());
- }
-
- if (product.getIsActive() == null) {
- log.debug("no isActive value was provided, setting to default: false");
- product.setIsActive(false);
- }
-
- product.setCreatorUserId(user.getUserId());
-
- // enrich object
- log.debug("enrich product with version and state");
- product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- product.setVersion(INITIAL_VERSION);
-
- // Generate invariant UUID - must be here and not in operation since it
- // should stay constant during clone
- String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
- product.setInvariantUUID(invariantUUID);
-
- return Either.left(product);
- }
-
- private Either<Boolean, ResponseFormat> validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) {
-
- // To be removed in 1607
- // See below
- String oldName = product.getName();
-
- Either<Boolean, ResponseFormat> componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum);
- if (componentNameValidation.isRight()) {
- return componentNameValidation;
- }
-
- Either<Boolean, ResponseFormat> componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum);
- if (componentNameUniquenessValidation.isRight()) {
- return componentNameUniquenessValidation;
- }
-
- // To be removed in 1607 and replaced with generic
- // validateTagsListAndRemoveDuplicates()
- // See comments on the validateTagsListAndRemoveDuplicates(user,
- // product, oldName, actionEnum) function
- Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum);
- if (tagsValidation.isRight()) {
- return tagsValidation;
- }
-
- Either<Boolean, ResponseFormat> validateIconResponse = validateIcon(user, product, actionEnum);
- if (validateIconResponse.isRight()) {
- return validateIconResponse;
- }
-
- Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, product, actionEnum);
- if (projectCodeValidation.isRight()) {
- return projectCodeValidation;
- }
- Either<Boolean, ResponseFormat> categoryValidation = validateGrouping(user, product, actionEnum);
- if (categoryValidation.isRight()) {
- return categoryValidation;
- }
-
- Either<Boolean, ResponseFormat> contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum);
- if (contactsListValidation.isRight()) {
- return contactsListValidation;
- }
-
- Either<Boolean, ResponseFormat> productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum);
- if (productFullNameValidation.isRight()) {
- return productFullNameValidation;
- }
-
- Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, product, actionEnum);
- if (descValidation.isRight()) {
- return descValidation;
- }
-
- return Either.left(true);
- }
-
- public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Product Name Exists", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
- // DE242223
- titanDao.commit();
-
- if (dataModelResponse.isLeft()) {
- Map<String, Boolean> result = new HashMap<>();
- result.put("isValid", dataModelResponse.left().value());
- log.debug("validation was successfully performed.");
- return Either.left(result);
- }
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
- return Either.right(responseFormat);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateProductContactsList(User user, Product product, AuditingActionEnum actionEnum) {
- List<String> contacts = product.getContacts();
- if (!ValidationUtils.validateListNotEmpty(contacts)) {
- log.debug("Contacts list cannot be empty for product {}", product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.EMPTY_PRODUCT_CONTACTS_LIST);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- boolean isProductCreatorInContacts = false;
- String modifierUserId = user.getUserId();
- for (String contact : contacts) {
- if (contact.equals(modifierUserId)) {
- log.trace("modifier userId found in product contacts");
- isProductCreatorInContacts = true;
- // No need to validate for this userId - it's modifier's
- continue;
- }
- if (!ValidationUtils.validateContactId(contact)) {
- log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue());
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- User contactUser = new User();
- contactUser.setUserId(contact);
- Either<User, ResponseFormat> validateUser = validateUserExists(contact, "Create Product", false);
- if (validateUser.isRight()) {
- log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- contactUser = validateUser.left().value();
-
- Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(contactUser, contactsRoles);
- if (validateUserRole.isRight()) {
- log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- }
-
- if (!isProductCreatorInContacts) {
- log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId);
- contacts.add(modifierUserId);
- }
-
- // passed - setting all contacts userIds to lowercase
- List<String> tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList());
- ValidationUtils.removeDuplicateFromList(tempContacts);
- product.setContacts(tempContacts);
-
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateGrouping(User user, Product product, AuditingActionEnum actionEnum) {
- List<CategoryDefinition> categories = product.getCategories();
- if (categories == null || categories.isEmpty()) {
- log.debug("Grouping list is empty for product: {}", product.getName());
- return Either.left(true);
- }
- Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<String, Map<String, Set<String>>>();
- // remove duplicated entries
- for (CategoryDefinition cat : categories) {
- String catName = cat.getName();
- if (ValidationUtils.validateStringNotEmpty(catName) == false) {
- // error missing cat name
- log.debug("Missing category name for product: {}", product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- Map<String, Set<String>> catEntry = nonDuplicatedCategories.get(catName);
- if (catEntry == null) {
- catEntry = new HashMap<String, Set<String>>();
- nonDuplicatedCategories.put(catName, catEntry);
- }
- List<SubCategoryDefinition> subcategories = cat.getSubcategories();
- if (subcategories == null || subcategories.isEmpty()) {
- // error missing subcat for cat
- log.debug("Missing sub-categories for category {} in product {}", catName, product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- for (SubCategoryDefinition subcat : subcategories) {
- String subCatName = subcat.getName();
- if (ValidationUtils.validateStringNotEmpty(subCatName) == false) {
- // error missing sub cat name for cat
- log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- Set<String> subcatEntry = catEntry.get(subCatName);
- if (subcatEntry == null) {
- subcatEntry = new HashSet<String>();
- catEntry.put(subCatName, subcatEntry);
- }
- List<GroupingDefinition> groupings = subcat.getGroupings();
- for (GroupingDefinition group : groupings) {
- String groupName = group.getName();
- if (ValidationUtils.validateStringNotEmpty(groupName) == false) {
- // error missing grouping for sub cat name and cat
- log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- if (!subcatEntry.contains(groupName)) {
- subcatEntry.add(groupName);
- } else {
- log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName);
- }
- }
- }
- } // for end of checking duplicated
- // validate existence
- Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories();
-
- if (allProductCategories.isRight()) {
- log.debug("No product categories {}", allProductCategories.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value());
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- boolean catExist;
- // convert non-duplicated to data modeling format and update in the
- // input object
- List<CategoryDefinition> newCatList = new ArrayList<CategoryDefinition>();
-
- // over all categories from request
- for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) {
- catExist = false;
- CategoryDefinition categoryDefinition = null;
- // over all categories from Titan
- List<CategoryDefinition> categoriesList = allProductCategories.left().value();
- if (categoriesList != null) {
- for (CategoryDefinition catInDb : categoriesList) {
- if (entry.getKey().equals(catInDb.getName())) {
- catExist = true;
- boolean subcatExist;
- // copy data
- categoryDefinition = new CategoryDefinition(catInDb);
- SubCategoryDefinition subCategory = null;
-
- Map<String, Set<String>> subcats = entry.getValue();
- for (Map.Entry<String, Set<String>> subcat : subcats.entrySet()) {
- subcatExist = false;
- List<SubCategoryDefinition> subcategoriesList = catInDb.getSubcategories();
- if (subcategoriesList != null) {
- for (SubCategoryDefinition subcatInDb : subcategoriesList) {
- if (subcatInDb.getName().equals(subcat.getKey())) {
- // copy data
- subCategory = new SubCategoryDefinition(subcatInDb);
- subcatExist = true;
- Set<String> grouping = subcat.getValue();
- boolean groupExist;
- GroupingDefinition groupingDefinition = null;
- for (String group : grouping) {
- groupExist = false;
- List<GroupingDefinition> groupings = subcatInDb.getGroupings();
- if (groupings != null) {
- for (GroupingDefinition groupInDb : groupings) {
- if (groupInDb.getName().equals(group)) {
- groupExist = true;
- groupingDefinition = new GroupingDefinition(groupInDb);
- }
- }
- }
- if (!groupExist) {
- // error grouping isn't defined
- // in Titan
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- subCategory.addGrouping(groupingDefinition);
- }
- }
- }
- }
- if (!subcatExist) {
- // error sub category isn't defined in Titan
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey());
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- categoryDefinition.addSubCategory(subCategory);
- }
- }
- }
- }
- if (!catExist) {
- // error category isn't defined in Titan
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey());
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- newCatList.add(categoryDefinition);
- }
- product.setCategories(newCatList);
- return Either.left(true);
- }
-
- public Either<Product, ResponseFormat> getProduct(String productId, User user) {
- String ecompErrorContext = "Get product";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return Either.right(validateEmptyResult.right().value());
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
-
- Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
-
- if (storageStatus.isRight()) {
- log.debug("failed to get resource by id {}", productId);
- if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- // TODO check error
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue()));
- } else {
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
- }
- }
- return Either.left(storageStatus.left().value());
- }
-
- public Either<Product, ResponseFormat> deleteProduct(String productId, User user) {
- String ecompErrorContext = "Delete product";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return Either.right(validateEmptyResult.right().value());
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
-
- Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
-
- if (storageStatus.isRight()) {
- log.debug("failed to delete resource by id {}", productId);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
- }
- return Either.left(storageStatus.left().value());
- }
-
- private Either<Boolean, ResponseFormat> validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
- String fullName = product.getFullName();
- if (!ValidationUtils.validateStringNotEmpty(fullName)) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
- componentsUtils.auditComponentAdmin(errorResponse, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(errorResponse);
- }
-
- fullName = ValidationUtils.removeNoneUtf8Chars(fullName);
- fullName = ValidationUtils.removeHtmlTags(fullName);
- fullName = ValidationUtils.normaliseWhitespace(fullName);
- fullName = ValidationUtils.stripOctets(fullName);
-
- if (!ValidationUtils.validateProductFullNameLength(fullName)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- if (!ValidationUtils.validateIsEnglish(fullName)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- product.setFullName(fullName);
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
- String name = product.getName();
- if (!ValidationUtils.validateStringNotEmpty(name)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- // Product name is required to have same validation and normalization as
- // category
- if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name);
-
- if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
-
- product.setName(normalizedName4Display);
- String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display);
- product.setNormalizedName(normalizedName4Uniqueness);
-
- return Either.left(true);
- }
-
- // This is a workaround for a current tag--->product name behaviour, which
- // will be changed in 1607.
- // It was agreed with Ella on 23/2/16 that the tag validation of product
- // will be made against the old product name (before normalization),
- // and in 1607 US will be defined where UI will no longer pass tag of
- // component name, and BE will add it by itself after all needed
- // normalizations.
- private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) {
- List<String> tagsList = product.getTags();
-
- Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT);
- if (validateTags.isRight()) {
- ResponseFormat responseFormat = validateTags.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, product, "", "", actionEnum, ComponentTypeEnum.PRODUCT);
- return Either.right(responseFormat);
- }
- ValidationUtils.removeDuplicateFromList(tagsList);
- return Either.left(true);
- }
-
- @Override
- public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) {
-
- }
-
- public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) {
- ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- // validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
-
- if (updatedProduct == null) {
- log.debug("Invalid product json. Check product servlet log for updateProduct entry params");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
- }
-
- Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
- if (storageStatus.isRight()) {
- if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
- }
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), ""));
- }
-
- Product currentProduct = storageStatus.left().value();
-
- if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) {
- log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- Either<Product, ResponseFormat> validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct);
- if (validationRsponse.isRight()) {
- log.info("product update metadata: validations field.");
- return validationRsponse;
- }
-
- Product productToUpdate = validationRsponse.left().value();
- // lock resource
- Either<Boolean, ResponseFormat> lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
- }
- try {
- Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate);
- if (updateResponse.isRight()) {
- toscaOperationFacade.rollback();
- log.debug("failed to update product {}", productToUpdate.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- toscaOperationFacade.commit();
- return Either.left(updateResponse.left().value());
- } finally {
- graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product);
- }
- }
-
- private Either<Product, ResponseFormat> validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) {
-
- boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion());
- Either<Boolean, ResponseFormat> response = validateAndUpdateProductName(user, currentProduct, updatedProduct);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateFullName(user, currentProduct, updatedProduct);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateCategory(user, currentProduct, updatedProduct);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateContactList(user, currentProduct, updatedProduct);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateTags(user, currentProduct, updatedProduct);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- if (updatedProduct.getIsActive() != null) {
- currentProduct.setIsActive(updatedProduct.getIsActive());
- }
-
- response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- String currentInvariantUuid = currentProduct.getInvariantUUID();
- String updatedInvariantUuid = updatedProduct.getInvariantUUID();
-
- if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
- log.warn("Product invariant UUID is automatically set and cannot be updated");
- updatedProduct.setInvariantUUID(currentInvariantUuid);
- }
- return Either.left(currentProduct);
-
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) {
- String updatedProductName = updatedProduct.getName();
- String tags = "";
- String currentProductName = currentProduct.getName();
- if (updatedProductName != null) {
- Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null);
- if (validatProductNameResponse.isRight()) {
- ResponseFormat errorRespons = validatProductNameResponse.right().value();
- return Either.right(errorRespons);
- }
- updatedProductName = updatedProduct.getName();
- if (!currentProductName.equals(updatedProductName)) {
- Either<Boolean, ResponseFormat> productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null);
- if (productNameUniquenessValidation.isRight()) {
- return productNameUniquenessValidation;
- }
- currentProduct.setName(updatedProductName);
- tags = updatedProductName;
- updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName);
- currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName));
- List<String> updatedTags = updatedProduct.getTags();
- // As discussed with Ella currently (1604) we are not removing
- // the old name from tags.
- if (updatedTags == null) {
- updatedTags = currentProduct.getTags();
- }
- updatedTags.add(tags);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateFullName(User user, Product currentProduct, Product updatedProduct) {
- String updatedProductName = updatedProduct.getFullName();
- String currentProductName = currentProduct.getFullName();
- if (updatedProductName != null && !currentProductName.equals(updatedProductName)) {
- Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductFullNameAndCleanup(user, updatedProduct, null);
- if (validatProductNameResponse.isRight()) {
- ResponseFormat errorRespons = validatProductNameResponse.right().value();
- return Either.right(errorRespons);
- }
- currentProduct.setFullName(updatedProduct.getFullName());
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
- List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
-
- Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null);
- if (validatCategoryResponse.isRight()) {
- ResponseFormat errorResponse = validatCategoryResponse.right().value();
- return Either.right(errorResponse);
- }
-
- categoryUpdated = updatedProduct.getCategories();
- if (categoryUpdated != null) {
- currentProduct.setCategories(categoryUpdated);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateContactList(User user, Product currentProduct, Product updatedProduct) {
- List<String> updatedContacts = updatedProduct.getContacts();
- List<String> currentContacts = currentProduct.getContacts();
- if (updatedContacts != null) {
- if (!(currentContacts.containsAll(updatedContacts) && updatedContacts.containsAll(currentContacts))) {
- Either<Boolean, ResponseFormat> validatResponse = validateAndUpdateProductContactsList(user, updatedProduct, null);
- if (validatResponse.isRight()) {
- ResponseFormat errorRespons = validatResponse.right().value();
- return Either.right(errorRespons);
- }
- currentProduct.setContacts(updatedProduct.getContacts());
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Product currentProduct, Product updatedProduct) {
- List<String> tagsUpdated = updatedProduct.getTags();
- List<String> tagsCurrent = currentProduct.getTags();
- if (tagsUpdated != null) {
- if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
- Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null);
- if (validatResponse.isRight()) {
- ResponseFormat errorRespons = validatResponse.right().value();
- return Either.right(errorRespons);
- }
- currentProduct.setTags(updatedProduct.getTags());
- }
- }
- return Either.left(true);
- }
-
- @Override
- public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
- // markAsDeleted isnt implemented yet
- return Either.left(new ArrayList<>());
- }
-
- @Override
- protected boolean validateTagPattern(String tag) {
- return ValidationUtils.validateCategoryDisplayNameFormat(tag);
- }
-
- public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
- if (storageStatus.isRight()) {
- log.debug("failed to get service by name {} and version {}", productName, productVersion);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName));
- }
- Product product = storageStatus.left().value();
- return Either.left(product);
- }
-
- @Override
- public ComponentInstanceBusinessLogic getComponentInstanceBL() {
- return productComponentInstanceBusinessLogic;
- }
-
- @Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
- return null;
- }
-
- public ICacheMangerOperation getCacheManagerOperation() {
- return cacheManagerOperation;
- }
-
- public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
- this.cacheManagerOperation = cacheManagerOperation;
- }
-
- @Override
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
- List<String> dataParamsToReturn) {
- // TODO Auto-generated method stub
- return null;
- }
+ private static final String PRODUCT_FULL_NAME = "full";
+ private static final String PRODUCT_ABBREVIATED_NAME = "abbreviated";
+ private static final Logger log = LoggerFactory.getLogger(ProductBusinessLogic.class);
+ private static final String INITIAL_VERSION = "0.1";
+ private static List<Role> creationRoles;
+ private static List<Role> updateRoles;
+ private static List<Role> contactsRoles;
+
+ public ProductBusinessLogic() {
+ creationRoles = new ArrayList<>();
+ updateRoles = new ArrayList<>();
+ contactsRoles = new ArrayList<>();
+
+ // only PM is allowed to create/update products
+ creationRoles.add(Role.PRODUCT_MANAGER);
+ updateRoles.add(Role.PRODUCT_MANAGER);
+ // Only PM is allowed to be product contacts
+ contactsRoles.add(Role.PRODUCT_MANAGER);
+ }
+
+ @Autowired
+ private IElementOperation elementDao;
+
+ @Autowired
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+ @Autowired
+ private ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
+
+ public Either<Product, ResponseFormat> createProduct(Product product, User user) {
+ AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
+ ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
+
+ // validate user - should be first to get the maximum auditing info in
+ // case of subsequent failures
+ log.debug("get user from DB");
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Product", product, actionEnum, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, product, creationRoles, actionEnum, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+
+ if (product == null) {
+ log.debug("Invalid product json. Check product servlet log for createProduct entry params");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
+ return Either.right(responseFormat);
+ }
+
+ // warn about non-updatable fields
+ checkUnupdatableProductFields(product);
+
+ Either<Product, ResponseFormat> validateProductResponse = validateProductBeforeCreate(product, user, actionEnum);
+ if (validateProductResponse.isRight()) {
+ return Either.right(validateProductResponse.right().value());
+ }
+
+ log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, "Create Product");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult);
+
+ try {
+ Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product);
+
+ if (createProductEither.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("Product created successfully");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
+
+ Product createdProduct = createProductEither.left().value();
+
+ return Either.left(createdProduct);
+
+ } finally {
+ graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product);
+ }
+
+ }
+
+ private void checkUnupdatableProductFields(Product product) {
+ checkComponentFieldsForOverrideAttempt(product);
+ if (product.getNormalizedName() != null) {
+ log.info("NormalizedName cannot be defined by user. This field will be overridden by the application");
+ }
+ }
+
+ private Either<Product, ResponseFormat> validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) {
+
+ Either<Boolean, ResponseFormat> validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum);
+ if (validateProductFields.isRight()) {
+ return Either.right(validateProductFields.right().value());
+ }
+
+ if (product.getIsActive() == null) {
+ log.debug("no isActive value was provided, setting to default: false");
+ product.setIsActive(false);
+ }
+
+ product.setCreatorUserId(user.getUserId());
+
+ // enrich object
+ log.debug("enrich product with version and state");
+ product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ product.setVersion(INITIAL_VERSION);
+
+ // Generate invariant UUID - must be here and not in operation since it
+ // should stay constant during clone
+ String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
+ product.setInvariantUUID(invariantUUID);
+
+ return Either.left(product);
+ }
+
+ private Either<Boolean, ResponseFormat> validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) {
+
+ // To be removed in 1607
+ // See below
+ String oldName = product.getName();
+
+ Either<Boolean, ResponseFormat> componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum);
+ if (componentNameValidation.isRight()) {
+ return componentNameValidation;
+ }
+
+ Either<Boolean, ResponseFormat> componentNameUniquenessValidation = validateComponentNameUnique(user, product, actionEnum);
+ if (componentNameUniquenessValidation.isRight()) {
+ return componentNameUniquenessValidation;
+ }
+
+ // To be removed in 1607 and replaced with generic
+ // validateTagsListAndRemoveDuplicates()
+ // See comments on the validateTagsListAndRemoveDuplicates(user,
+ // product, oldName, actionEnum) function
+ Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum);
+ if (tagsValidation.isRight()) {
+ return tagsValidation;
+ }
+
+ Either<Boolean, ResponseFormat> validateIconResponse = validateIcon(user, product, actionEnum);
+ if (validateIconResponse.isRight()) {
+ return validateIconResponse;
+ }
+
+ Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, product, actionEnum);
+ if (projectCodeValidation.isRight()) {
+ return projectCodeValidation;
+ }
+ Either<Boolean, ResponseFormat> categoryValidation = validateGrouping(user, product, actionEnum);
+ if (categoryValidation.isRight()) {
+ return categoryValidation;
+ }
+
+ Either<Boolean, ResponseFormat> contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum);
+ if (contactsListValidation.isRight()) {
+ return contactsListValidation;
+ }
+
+ Either<Boolean, ResponseFormat> productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum);
+ if (productFullNameValidation.isRight()) {
+ return productFullNameValidation;
+ }
+
+ Either<Boolean, ResponseFormat> descValidation = validateDescriptionAndCleanup(user, product, actionEnum);
+ if (descValidation.isRight()) {
+ return descValidation;
+ }
+
+ return Either.left(true);
+ }
+
+ public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Product Name Exists", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
+ // DE242223
+ titanDao.commit();
+
+ if (dataModelResponse.isLeft()) {
+ Map<String, Boolean> result = new HashMap<>();
+ result.put("isValid", dataModelResponse.left().value());
+ log.debug("validation was successfully performed.");
+ return Either.left(result);
+ }
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+
+ return Either.right(responseFormat);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateProductContactsList(User user, Product product, AuditingActionEnum actionEnum) {
+ List<String> contacts = product.getContacts();
+ if (!ValidationUtils.validateListNotEmpty(contacts)) {
+ log.debug("Contacts list cannot be empty for product {}", product.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.EMPTY_PRODUCT_CONTACTS_LIST);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ boolean isProductCreatorInContacts = false;
+ String modifierUserId = user.getUserId();
+ for (String contact : contacts) {
+ if (contact.equals(modifierUserId)) {
+ log.trace("modifier userId found in product contacts");
+ isProductCreatorInContacts = true;
+ // No need to validate for this userId - it's modifier's
+ continue;
+ }
+ if (!ValidationUtils.validateContactId(contact)) {
+ log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue());
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ User contactUser = new User();
+ contactUser.setUserId(contact);
+ Either<User, ResponseFormat> validateUser = validateUserExists(contact, "Create Product", false);
+ if (validateUser.isRight()) {
+ log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUser.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ contactUser = validateUser.left().value();
+
+ Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(contactUser, contactsRoles);
+ if (validateUserRole.isRight()) {
+ log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, validateUserRole.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ }
+
+ if (!isProductCreatorInContacts) {
+ log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId);
+ contacts.add(modifierUserId);
+ }
+
+ // passed - setting all contacts userIds to lowercase
+ List<String> tempContacts = contacts.stream().map(e -> e.toLowerCase()).collect(Collectors.toList());
+ ValidationUtils.removeDuplicateFromList(tempContacts);
+ product.setContacts(tempContacts);
+
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateGrouping(User user, Product product, AuditingActionEnum actionEnum) {
+ List<CategoryDefinition> categories = product.getCategories();
+ if (categories == null || categories.isEmpty()) {
+ log.debug("Grouping list is empty for product: {}", product.getName());
+ return Either.left(true);
+ }
+ Map<String, Map<String, Set<String>>> nonDuplicatedCategories = new HashMap<String, Map<String, Set<String>>>();
+ // remove duplicated entries
+ for (CategoryDefinition cat : categories) {
+ String catName = cat.getName();
+ if (ValidationUtils.validateStringNotEmpty(catName) == false) {
+ // error missing cat name
+ log.debug("Missing category name for product: {}", product.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ Map<String, Set<String>> catEntry = nonDuplicatedCategories.get(catName);
+ if (catEntry == null) {
+ catEntry = new HashMap<String, Set<String>>();
+ nonDuplicatedCategories.put(catName, catEntry);
+ }
+ List<SubCategoryDefinition> subcategories = cat.getSubcategories();
+ if (subcategories == null || subcategories.isEmpty()) {
+ // error missing subcat for cat
+ log.debug("Missing sub-categories for category {} in product {}", catName, product.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ for (SubCategoryDefinition subcat : subcategories) {
+ String subCatName = subcat.getName();
+ if (ValidationUtils.validateStringNotEmpty(subCatName) == false) {
+ // error missing sub cat name for cat
+ log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ Set<String> subcatEntry = catEntry.get(subCatName);
+ if (subcatEntry == null) {
+ subcatEntry = new HashSet<String>();
+ catEntry.put(subCatName, subcatEntry);
+ }
+ List<GroupingDefinition> groupings = subcat.getGroupings();
+ for (GroupingDefinition group : groupings) {
+ String groupName = group.getName();
+ if (ValidationUtils.validateStringNotEmpty(groupName) == false) {
+ // error missing grouping for sub cat name and cat
+ log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ if (!subcatEntry.contains(groupName)) {
+ subcatEntry.add(groupName);
+ } else {
+ log.debug("Grouping: {}, already exist for category: {} and subcategory: {}", groupName, catName, subCatName);
+ }
+ }
+ }
+ } // for end of checking duplicated
+ // validate existence
+ Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories();
+
+ if (allProductCategories.isRight()) {
+ log.debug("No product categories {}", allProductCategories.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value());
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ boolean catExist;
+ // convert non-duplicated to data modeling format and update in the
+ // input object
+ List<CategoryDefinition> newCatList = new ArrayList<CategoryDefinition>();
+
+ // over all categories from request
+ for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) {
+ catExist = false;
+ CategoryDefinition categoryDefinition = null;
+ // over all categories from Titan
+ List<CategoryDefinition> categoriesList = allProductCategories.left().value();
+ if (categoriesList != null) {
+ for (CategoryDefinition catInDb : categoriesList) {
+ if (entry.getKey().equals(catInDb.getName())) {
+ catExist = true;
+ boolean subcatExist;
+ // copy data
+ categoryDefinition = new CategoryDefinition(catInDb);
+ SubCategoryDefinition subCategory = null;
+
+ Map<String, Set<String>> subcats = entry.getValue();
+ for (Map.Entry<String, Set<String>> subcat : subcats.entrySet()) {
+ subcatExist = false;
+ List<SubCategoryDefinition> subcategoriesList = catInDb.getSubcategories();
+ if (subcategoriesList != null) {
+ for (SubCategoryDefinition subcatInDb : subcategoriesList) {
+ if (subcatInDb.getName().equals(subcat.getKey())) {
+ // copy data
+ subCategory = new SubCategoryDefinition(subcatInDb);
+ subcatExist = true;
+ Set<String> grouping = subcat.getValue();
+ boolean groupExist;
+ GroupingDefinition groupingDefinition = null;
+ for (String group : grouping) {
+ groupExist = false;
+ List<GroupingDefinition> groupings = subcatInDb.getGroupings();
+ if (groupings != null) {
+ for (GroupingDefinition groupInDb : groupings) {
+ if (groupInDb.getName().equals(group)) {
+ groupExist = true;
+ groupingDefinition = new GroupingDefinition(groupInDb);
+ }
+ }
+ }
+ if (!groupExist) {
+ // error grouping isn't defined
+ // in Titan
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ subCategory.addGrouping(groupingDefinition);
+ }
+ }
+ }
+ }
+ if (!subcatExist) {
+ // error sub category isn't defined in Titan
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey());
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ categoryDefinition.addSubCategory(subCategory);
+ }
+ }
+ }
+ }
+ if (!catExist) {
+ // error category isn't defined in Titan
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey());
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ newCatList.add(categoryDefinition);
+ }
+ product.setCategories(newCatList);
+ return Either.left(true);
+ }
+
+ public Either<Product, ResponseFormat> getProduct(String productId, User user) {
+ String ecompErrorContext = "Get product";
+ Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
+ if (validateEmptyResult.isRight()) {
+ return Either.right(validateEmptyResult.right().value());
+ }
+
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
+
+ if (storageStatus.isRight()) {
+ log.debug("failed to get resource by id {}", productId);
+ if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ // TODO check error
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue()));
+ } else {
+ return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ }
+ }
+ return Either.left(storageStatus.left().value());
+ }
+
+ public Either<Product, ResponseFormat> deleteProduct(String productId, User user) {
+ String ecompErrorContext = "Delete product";
+ Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
+ if (validateEmptyResult.isRight()) {
+ return Either.right(validateEmptyResult.right().value());
+ }
+
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
+
+ if (storageStatus.isRight()) {
+ log.debug("failed to delete resource by id {}", productId);
+ return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ }
+ return Either.left(storageStatus.left().value());
+ }
+
+ private Either<Boolean, ResponseFormat> validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
+ String fullName = product.getFullName();
+ if (!ValidationUtils.validateStringNotEmpty(fullName)) {
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+ componentsUtils.auditComponentAdmin(errorResponse, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(errorResponse);
+ }
+
+ fullName = ValidationUtils.removeNoneUtf8Chars(fullName);
+ fullName = ValidationUtils.removeHtmlTags(fullName);
+ fullName = ValidationUtils.normaliseWhitespace(fullName);
+ fullName = ValidationUtils.stripOctets(fullName);
+
+ if (!ValidationUtils.validateProductFullNameLength(fullName)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(fullName)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ product.setFullName(fullName);
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
+ String name = product.getName();
+ if (!ValidationUtils.validateStringNotEmpty(name)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ // Product name is required to have same validation and normalization as
+ // category
+ if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name);
+
+ if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+
+ product.setName(normalizedName4Display);
+ String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display);
+ product.setNormalizedName(normalizedName4Uniqueness);
+
+ return Either.left(true);
+ }
+
+ // This is a workaround for a current tag--->product name behaviour, which
+ // will be changed in 1607.
+ // It was agreed with Ella on 23/2/16 that the tag validation of product
+ // will be made against the old product name (before normalization),
+ // and in 1607 US will be defined where UI will no longer pass tag of
+ // component name, and BE will add it by itself after all needed
+ // normalizations.
+ private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) {
+ List<String> tagsList = product.getTags();
+
+ Either<Boolean, ResponseFormat> validateTags = validateComponentTags(tagsList, oldProductName, ComponentTypeEnum.PRODUCT);
+ if (validateTags.isRight()) {
+ ResponseFormat responseFormat = validateTags.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+ return Either.right(responseFormat);
+ }
+ ValidationUtils.removeDuplicateFromList(tagsList);
+ return Either.left(true);
+ }
+
+ @Override
+ public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) {
+
+ }
+
+ public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) {
+ ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "Update Product", updatedProduct, null, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, updatedProduct, updateRoles, null, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+
+ if (updatedProduct == null) {
+ log.debug("Invalid product json. Check product servlet log for updateProduct entry params");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(responseFormat);
+ }
+
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
+ if (storageStatus.isRight()) {
+ if (storageStatus.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
+ }
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), ""));
+ }
+
+ Product currentProduct = storageStatus.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) {
+ log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ Either<Product, ResponseFormat> validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct);
+ if (validationRsponse.isRight()) {
+ log.info("product update metadata: validations field.");
+ return validationRsponse;
+ }
+
+ Product productToUpdate = validationRsponse.left().value();
+ // lock resource
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata");
+ if (lockResult.isRight()) {
+ return Either.right(lockResult.right().value());
+ }
+ try {
+ Either<Product, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(productToUpdate);
+ if (updateResponse.isRight()) {
+ toscaOperationFacade.rollback();
+ log.debug("failed to update product {}", productToUpdate.getUniqueId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ toscaOperationFacade.commit();
+ return Either.left(updateResponse.left().value());
+ } finally {
+ graphLockOperation.unlockComponent(productId, NodeTypeEnum.Product);
+ }
+ }
+
+ private Either<Product, ResponseFormat> validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) {
+
+ boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion());
+ Either<Boolean, ResponseFormat> response = validateAndUpdateProductName(user, currentProduct, updatedProduct);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateFullName(user, currentProduct, updatedProduct);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateCategory(user, currentProduct, updatedProduct);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateContactList(user, currentProduct, updatedProduct);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateTags(user, currentProduct, updatedProduct);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ if (updatedProduct.getIsActive() != null) {
+ currentProduct.setIsActive(updatedProduct.getIsActive());
+ }
+
+ response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ String currentInvariantUuid = currentProduct.getInvariantUUID();
+ String updatedInvariantUuid = updatedProduct.getInvariantUUID();
+
+ if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
+ log.warn("Product invariant UUID is automatically set and cannot be updated");
+ updatedProduct.setInvariantUUID(currentInvariantUuid);
+ }
+ return Either.left(currentProduct);
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) {
+ String updatedProductName = updatedProduct.getName();
+ String tags = "";
+ String currentProductName = currentProduct.getName();
+ if (updatedProductName != null) {
+ Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductNameAndCleanup(user, updatedProduct, null);
+ if (validatProductNameResponse.isRight()) {
+ ResponseFormat errorRespons = validatProductNameResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ updatedProductName = updatedProduct.getName();
+ if (!currentProductName.equals(updatedProductName)) {
+ Either<Boolean, ResponseFormat> productNameUniquenessValidation = validateComponentNameUnique(user, updatedProduct, null);
+ if (productNameUniquenessValidation.isRight()) {
+ return productNameUniquenessValidation;
+ }
+ currentProduct.setName(updatedProductName);
+ tags = updatedProductName;
+ updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName);
+ currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName));
+ List<String> updatedTags = updatedProduct.getTags();
+ // As discussed with Ella currently (1604) we are not removing
+ // the old name from tags.
+ if (updatedTags == null) {
+ updatedTags = currentProduct.getTags();
+ }
+ updatedTags.add(tags);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateFullName(User user, Product currentProduct, Product updatedProduct) {
+ String updatedProductName = updatedProduct.getFullName();
+ String currentProductName = currentProduct.getFullName();
+ if (updatedProductName != null && !currentProductName.equals(updatedProductName)) {
+ Either<Boolean, ResponseFormat> validatProductNameResponse = validateProductFullNameAndCleanup(user, updatedProduct, null);
+ if (validatProductNameResponse.isRight()) {
+ ResponseFormat errorRespons = validatProductNameResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentProduct.setFullName(updatedProduct.getFullName());
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
+ List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
+
+ Either<Boolean, ResponseFormat> validatCategoryResponse = validateGrouping(user, updatedProduct, null);
+ if (validatCategoryResponse.isRight()) {
+ ResponseFormat errorResponse = validatCategoryResponse.right().value();
+ return Either.right(errorResponse);
+ }
+
+ categoryUpdated = updatedProduct.getCategories();
+ if (categoryUpdated != null) {
+ currentProduct.setCategories(categoryUpdated);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateContactList(User user, Product currentProduct, Product updatedProduct) {
+ List<String> updatedContacts = updatedProduct.getContacts();
+ List<String> currentContacts = currentProduct.getContacts();
+ if (updatedContacts != null) {
+ if (!(currentContacts.containsAll(updatedContacts) && updatedContacts.containsAll(currentContacts))) {
+ Either<Boolean, ResponseFormat> validatResponse = validateAndUpdateProductContactsList(user, updatedProduct, null);
+ if (validatResponse.isRight()) {
+ ResponseFormat errorRespons = validatResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentProduct.setContacts(updatedProduct.getContacts());
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Product currentProduct, Product updatedProduct) {
+ List<String> tagsUpdated = updatedProduct.getTags();
+ List<String> tagsCurrent = currentProduct.getTags();
+ if (tagsUpdated != null) {
+ if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
+ Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null);
+ if (validatResponse.isRight()) {
+ ResponseFormat errorRespons = validatResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentProduct.setTags(updatedProduct.getTags());
+ }
+ }
+ return Either.left(true);
+ }
+
+ @Override
+ public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
+ // markAsDeleted isnt implemented yet
+ return Either.left(new ArrayList<>());
+ }
+
+ @Override
+ protected boolean validateTagPattern(String tag) {
+ return ValidationUtils.validateCategoryDisplayNameFormat(tag);
+ }
+
+ public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
+ if (storageStatus.isRight()) {
+ log.debug("failed to get service by name {} and version {}", productName, productVersion);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName));
+ }
+ Product product = storageStatus.left().value();
+ return Either.left(product);
+ }
+
+ @Override
+ public ComponentInstanceBusinessLogic getComponentInstanceBL() {
+ return componentInstanceBusinessLogic;
+ }
+
+ @Override
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+ return null;
+ }
+
+ public ICacheMangerOperation getCacheManagerOperation() {
+ return cacheManagerOperation;
+ }
+
+ public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
+ this.cacheManagerOperation = cacheManagerOperation;
+ }
+
+ @Override
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
+ List<String> dataParamsToReturn) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
deleted file mode 100644
index 73f72216d2..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.components.impl;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.springframework.stereotype.Component;
-
-@Component("productComponentInstanceBusinessLogic")
-public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
-
-
- @Override
- protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
- // TODO Pavel this might be also a resource?
- return NodeTypeEnum.Service;
- }
-
- @Override
- protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
- // TODO Auto-generated method stub
- return ComponentTypeEnum.SERVICE_INSTANCE;
- }
-
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
index ff26ced5c9..9cc4b9cd3e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
@@ -20,16 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.Supplier;
-
-import javax.servlet.ServletContext;
-
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -41,20 +33,17 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
-import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
import org.openecomp.sdc.be.resources.data.EntryData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -62,513 +51,479 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.Supplier;
@Component("propertyBusinessLogic")
public class PropertyBusinessLogic extends BaseBusinessLogic {
- private static final String CREATE_PROPERTY = "CreateProperty";
-
- private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class.getName());
-
- private static final String EMPTY_VALUE = null;
-
- private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
-
- protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-
- return webApplicationContext.getBean(class1);
- }
-
- public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes() {
- Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
- return eitherAllDataTypes;
- }
-
- /**
- * Create new property on resource in graph
- *
- * @param resourceId
- * @param propertyName
- * @param newPropertyDefinition
- * @param userId
- * @return Either<PropertyDefinition, ActionStatus>
- */
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) {
-
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Property", false);
- if (resp.isRight()) {
- result = Either.right(resp.right().value());
- return result;
- }
-
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
- }
-
- try {
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
- if (status.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- return result;
- }
- Resource resource = status.left().value();
-
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return result;
- }
-
- // verify property not exist in resource
- List<PropertyDefinition> resourceProperties = resource.getProperties();
-
- if (resourceProperties != null) {
- if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
- return result;
- }
- }
-
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- result = Either.right(allDataTypes.right().value());
- return result;
- }
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- // validate property default values
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes);
- if (defaultValuesValidation.isRight()) {
- result = Either.right(defaultValuesValidation.right().value());
- return result;
- }
- // convert property
- ToscaPropertyType type = getType(newPropertyDefinition.getType());
- if (type != null) {
- PropertyValueConverter converter = type.getConverter();
- // get inner type
- String innerType = null;
- if (newPropertyDefinition != null) {
- SchemaDefinition schema = newPropertyDefinition.getSchema();
- if (schema != null) {
- PropertyDataDefinition prop = schema.getProperty();
- if (prop != null) {
- innerType = prop.getType();
- }
- }
- String convertedValue = null;
- if (newPropertyDefinition.getDefaultValue() != null) {
- convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value());
- newPropertyDefinition.setDefaultValue(convertedValue);
- }
- }
- }
-
- // add the new property to resource on graph
- // need to get StorageOpaerationStatus and convert to ActionStatus
- // from componentsUtils
- Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource);
- if (either.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
- return result;
- }
-
- PropertyDefinition createdPropertyDefinition = either.left().value();
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
- result = Either.left(property);
- return result;
-
- } finally {
- commitOrRollback(result);
- // unlock component
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
-
- }
-
- /**
- * Get property of resource
- *
- * @param resourceId
- * @param propertyId
- * @param userId
- * @return
- */
- public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
- if (status.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
- Resource resource = status.left().value();
-
- // verify property exist in resource
- List<PropertyDefinition> properties = resource.getProperties();
- if (properties == null) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
- }
- for (PropertyDefinition property : properties) {
- if (property.getUniqueId().equals(propertyId) ) {
- Map<String, PropertyDefinition> propMap = new HashMap<>();
- propMap.put(property.getName(), property);
- return Either.left(propMap.entrySet().iterator().next());
- }
- }
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
- }
-
- private boolean isPropertyBelongsToResource(PropertyDataDefinition property, String resourceId) {
- return property.getOwnerId() == null || property.getOwnerId().equals(resourceId);
- }
-
- /**
- * delete property of resource from graph
- *
- * @param resourceId
- * @param propertyId
- * @param userId
- * @return
- */
- public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
-
- Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null;
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
- }
-
- try {
-
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(resourceId);
- if (getResourceRes.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- return result;
- }
- Resource resource = getResourceRes.left().value();
-
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- return result;
- }
-
- // verify property exist in resource
- Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId);
- if (statusGetProperty.isRight()) {
- result = Either.right(statusGetProperty.right().value());
- return result;
- }
-
- StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey());
- if (status != StorageOperationStatus.OK) {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName()));
- return result;
- }
- // propertyOperation.getTitanGenericDao().commit();
- result = Either.left(statusGetProperty.left().value());
- return result;
-
- } finally {
- commitOrRollback(result);
- // unlock component
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
- }
-
- /**
- * update property
- *
- * @param resourceId
- * @param propertyId
- * @param newPropertyDefinition
- * @param userId
- * @return
- */
- public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) {
-
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
-
- Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
- if (status.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
- }
- Resource resource = status.left().value();
-
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- return result;
- }
-
- try {
- Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId);
- if (statusGetProperty.isRight()) {
- result = Either.right(statusGetProperty.right().value());
- return result;
- }
- String propertyName = statusGetProperty.left().value().getKey();
-
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- result = Either.right(allDataTypes.right().value());
- return result;
- }
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
-
- Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes);
- if (defaultValuesValidation.isRight()) {
- result = Either.right(defaultValuesValidation.right().value());
- return result;
- }
-
- Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(propertyId, newPropertyDefinition, dataTypes);
- if (either.isRight()) {
- log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value());
- result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
- return result;
- }
-
-
- either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition);
- if (either.isRight()) {
- result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
- return result;
- }
-
- EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, either.left().value());
- result = Either.left(property);
- return result;
-
- } finally {
- commitOrRollback(result);
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
-
- }
-
- private boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
- boolean result = false;
- if (!CollectionUtils.isEmpty(properties)) {
- for (PropertyDefinition propertyDefinition : properties) {
-
- if ( propertyDefinition.getName().equals(propertyName) &&
- (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) {
- result = true;
- break;
- }
- }
- }
- return result;
- }
-
- private PropertyDefinition convertPropertyDataToPropertyDefinition(PropertyData propertyDataResult, String propertyName, String resourceId) {
- log.debug("The object returned after create property is {}", propertyDataResult);
- PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition());
- propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints()));
- propertyDefResult.setName(propertyName);
- propertyDefResult.setParentUniqueId(resourceId);
- return propertyDefResult;
- }
-
- private List<PropertyConstraint> convertConstraints(List<String> constraints) {
-
- if (constraints == null || constraints.size() == 0) {
- return null;
- }
-
- List<PropertyConstraint> list = new ArrayList<PropertyConstraint>();
- Type constraintType = new TypeToken<PropertyConstraint>() {
- }.getType();
-
- Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
-
- for (String constraintJson : constraints) {
- PropertyConstraint propertyConstraint = gson.fromJson(constraintJson, constraintType);
- list.add(propertyConstraint);
- }
-
- return list;
- }
-
- private Either<PropertyDefinition, StorageOperationStatus> handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
- StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
- if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- return Either.right(validateAndUpdateProperty);
- }
-
- return Either.left(newPropertyDefinition);
- }
-
- private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
- log.trace("Going to validate property type and value. {}", propertyDefinition);
-
- String propertyType = propertyDefinition.getType();
- String value = propertyDefinition.getDefaultValue();
-
- ToscaPropertyType type = getType(propertyType);
-
- if (type == null) {
-
- DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- if (dataTypeDefinition == null) {
- log.debug("The type {} of property cannot be found.", propertyType);
- return StorageOperationStatus.INVALID_TYPE;
- }
-
- StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
-
- return status;
-
- }
- String innerType = null;
-
- Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema());
- if (checkInnerType.isRight()) {
- return StorageOperationStatus.INVALID_TYPE;
- }
- innerType = checkInnerType.left().value();
-
- log.trace("After validating property type {}", propertyType);
-
- boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
- if (false == isValidProperty) {
- log.info("The value {} of property from type {} is invalid", value, type);
- return StorageOperationStatus.INVALID_VALUE;
- }
-
- PropertyValueConverter converter = type.getConverter();
-
- if (isEmptyValue(value)) {
- log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
- propertyDefinition.setDefaultValue(EMPTY_VALUE);
- } else if (false == isEmptyValue(value)) {
- String convertedValue = converter.convert(value, innerType, dataTypes);
- propertyDefinition.setDefaultValue(convertedValue);
- }
- return StorageOperationStatus.OK;
- }
-
- protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
-
- String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
- ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
-
- if (validateResult.right.booleanValue() == false) {
- log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
- return StorageOperationStatus.INVALID_VALUE;
- }
-
- JsonElement jsonElement = validateResult.left;
-
- log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null));
-
- updateValue(propertyDefinition, jsonElement);
-
- return StorageOperationStatus.OK;
- }
-
- protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
-
- propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
-
- }
-
- protected String getValueFromJsonElement(JsonElement jsonElement) {
- String value = null;
-
- if (jsonElement == null || jsonElement.isJsonNull()) {
- value = EMPTY_VALUE;
- } else {
- if (jsonElement.toString().isEmpty()) {
- value = "";
- } else {
- value = jsonElement.toString();
- }
- }
-
- return value;
- }
-
- protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
- String innerType = null;
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
-
- SchemaDefinition def = schemeGen.get();// propDataDef.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
- return Either.left(innerType);
- }
- protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- if (isEmptyValue(value)) {
- return true;
- }
-
- PropertyTypeValidator validator = type.getValidator();
-
- boolean isValid = validator.isValid(value, innerType, dataTypes);
- if (true == isValid) {
- return true;
- } else {
- return false;
- }
-
- }
-
- public boolean isEmptyValue(String value) {
- if (value == null) {
- return true;
- }
- return false;
- }
+ private static final String CREATE_PROPERTY = "CreateProperty";
+
+ private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogic.class);
+
+ private static final String EMPTY_VALUE = null;
+
+ private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
+
+ protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+
+ return webApplicationContext.getBean(class1);
+ }
+
+ public Either<Map<String, DataTypeDefinition>, ResponseFormat> getAllDataTypes() {
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
+ return eitherAllDataTypes;
+ }
+
+ /**
+ * Create new property on resource in graph
+ *
+ * @param resourceId
+ * @param propertyName
+ * @param newPropertyDefinition
+ * @param userId
+ * @return Either<PropertyDefinition, ActionStatus>
+ */
+ public Either<EntryData<String, PropertyDefinition>, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) {
+
+ Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Property", false);
+ if (resp.isRight()) {
+ result = Either.right(resp.right().value());
+ return result;
+ }
+
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ log.info("Failed to lock component {}. Error - {}", resourceId, lockResult);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+
+ try {
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
+ if (status.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ return result;
+ }
+ Resource resource = status.left().value();
+
+ // verify that resource is checked-out and the user is the last
+ // updater
+ if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return result;
+ }
+
+ // verify property not exist in resource
+ List<PropertyDefinition> resourceProperties = resource.getProperties();
+
+ if (resourceProperties != null) {
+ if (isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
+ return result;
+ }
+ }
+
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ result = Either.right(allDataTypes.right().value());
+ return result;
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+
+ // validate property default values
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes);
+ if (defaultValuesValidation.isRight()) {
+ result = Either.right(defaultValuesValidation.right().value());
+ return result;
+ }
+ // convert property
+ ToscaPropertyType type = getType(newPropertyDefinition.getType());
+ if (type != null) {
+ PropertyValueConverter converter = type.getConverter();
+ // get inner type
+ String innerType = null;
+ if (newPropertyDefinition != null) {
+ SchemaDefinition schema = newPropertyDefinition.getSchema();
+ if (schema != null) {
+ PropertyDataDefinition prop = schema.getProperty();
+ if (prop != null) {
+ innerType = prop.getType();
+ }
+ }
+ String convertedValue = null;
+ if (newPropertyDefinition.getDefaultValue() != null) {
+ convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value());
+ newPropertyDefinition.setDefaultValue(convertedValue);
+ }
+ }
+ }
+
+ // add the new property to resource on graph
+ // need to get StorageOpaerationStatus and convert to ActionStatus
+ // from componentsUtils
+ Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource);
+ if (either.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ return result;
+ }
+
+ PropertyDefinition createdPropertyDefinition = either.left().value();
+ EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, createdPropertyDefinition);
+ result = Either.left(property);
+ return result;
+
+ } finally {
+ commitOrRollback(result);
+ // unlock component
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+
+ }
+
+ /**
+ * Get property of resource
+ *
+ * @param resourceId
+ * @param propertyId
+ * @param userId
+ * @return
+ */
+ public Either<Entry<String, PropertyDefinition>, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "create Component Instance", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
+ if (status.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ }
+ Resource resource = status.left().value();
+
+ // verify property exist in resource
+ List<PropertyDefinition> properties = resource.getProperties();
+ if (properties == null) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
+ }
+ for (PropertyDefinition property : properties) {
+ if (property.getUniqueId().equals(propertyId) ) {
+ Map<String, PropertyDefinition> propMap = new HashMap<>();
+ propMap.put(property.getName(), property);
+ return Either.left(propMap.entrySet().iterator().next());
+ }
+ }
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
+ }
+
+ /**
+ * delete property of resource from graph
+ *
+ * @param resourceId
+ * @param propertyId
+ * @param userId
+ * @return
+ */
+ public Either<Entry<String, PropertyDefinition>, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) {
+
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> result = null;
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "delete Property", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+
+ try {
+
+ // Get the resource from DB
+ Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(resourceId);
+ if (getResourceRes.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ return result;
+ }
+ Resource resource = getResourceRes.left().value();
+
+ // verify that resource is checked-out and the user is the last
+ // updater
+ if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ return result;
+ }
+
+ // verify property exist in resource
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId);
+ if (statusGetProperty.isRight()) {
+ result = Either.right(statusGetProperty.right().value());
+ return result;
+ }
+
+ StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey());
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName()));
+ return result;
+ }
+ result = Either.left(statusGetProperty.left().value());
+ return result;
+
+ } finally {
+ commitOrRollback(result);
+ // unlock component
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+ }
+
+ /**
+ * update property
+ *
+ * @param resourceId
+ * @param propertyId
+ * @param newPropertyDefinition
+ * @param userId
+ * @return
+ */
+ public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) {
+
+ Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
+
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
+ if (status.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
+ }
+ Resource resource = status.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return result;
+ }
+
+ try {
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId);
+ if (statusGetProperty.isRight()) {
+ result = Either.right(statusGetProperty.right().value());
+ return result;
+ }
+ String propertyName = statusGetProperty.left().value().getKey();
+
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ result = Either.right(allDataTypes.right().value());
+ return result;
+ }
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+
+ Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes);
+ if (defaultValuesValidation.isRight()) {
+ result = Either.right(defaultValuesValidation.right().value());
+ return result;
+ }
+
+ Either<PropertyDefinition, StorageOperationStatus> either = handleProperty(propertyId, newPropertyDefinition, dataTypes);
+ if (either.isRight()) {
+ log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value());
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ return result;
+ }
+
+
+ either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition);
+ if (either.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
+ return result;
+ }
+
+ EntryData<String, PropertyDefinition> property = new EntryData<String, PropertyDefinition>(propertyName, either.left().value());
+ result = Either.left(property);
+ return result;
+
+ } finally {
+ commitOrRollback(result);
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+
+ }
+
+ private boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) {
+ boolean result = false;
+ if (!CollectionUtils.isEmpty(properties)) {
+ for (PropertyDefinition propertyDefinition : properties) {
+
+ if ( propertyDefinition.getName().equals(propertyName) &&
+ (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) {
+ result = true;
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ private Either<PropertyDefinition, StorageOperationStatus> handleProperty(String propertyId, PropertyDefinition newPropertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+ StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(newPropertyDefinition, dataTypes);
+ if (validateAndUpdateProperty != StorageOperationStatus.OK) {
+ return Either.right(validateAndUpdateProperty);
+ }
+
+ return Either.left(newPropertyDefinition);
+ }
+
+ private StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+ log.trace("Going to validate property type and value. {}", propertyDefinition);
+
+ String propertyType = propertyDefinition.getType();
+ String value = propertyDefinition.getDefaultValue();
+
+ ToscaPropertyType type = getType(propertyType);
+
+ if (type == null) {
+
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ if (dataTypeDefinition == null) {
+ log.debug("The type {} of property cannot be found.", propertyType);
+ return StorageOperationStatus.INVALID_TYPE;
+ }
+
+ StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes);
+
+ return status;
+
+ }
+ String innerType = null;
+
+ Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema());
+ if (checkInnerType.isRight()) {
+ return StorageOperationStatus.INVALID_TYPE;
+ }
+ innerType = checkInnerType.left().value();
+
+ log.trace("After validating property type {}", propertyType);
+
+ boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
+ if (false == isValidProperty) {
+ log.info("The value {} of property from type {} is invalid", value, type);
+ return StorageOperationStatus.INVALID_VALUE;
+ }
+
+ PropertyValueConverter converter = type.getConverter();
+
+ if (isEmptyValue(value)) {
+ log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE);
+ propertyDefinition.setDefaultValue(EMPTY_VALUE);
+ } else if (false == isEmptyValue(value)) {
+ String convertedValue = converter.convert(value, innerType, dataTypes);
+ propertyDefinition.setDefaultValue(convertedValue);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType,
+
+ String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) {
+
+ ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
+
+ if (validateResult.right.booleanValue() == false) {
+ log.debug("The value {} of property from type {} is invalid", propertyType, propertyType);
+ return StorageOperationStatus.INVALID_VALUE;
+ }
+
+ JsonElement jsonElement = validateResult.left;
+
+ log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , jsonElement);
+
+ updateValue(propertyDefinition, jsonElement);
+
+ return StorageOperationStatus.OK;
+ }
+
+ protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) {
+
+ propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement));
+
+ }
+
+ protected String getValueFromJsonElement(JsonElement jsonElement) {
+ String value = null;
+
+ if (jsonElement == null || jsonElement.isJsonNull()) {
+ value = EMPTY_VALUE;
+ } else {
+ if (jsonElement.toString().isEmpty()) {
+ value = "";
+ } else {
+ value = jsonElement.toString();
+ }
+ }
+
+ return value;
+ }
+
+ protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
+ String innerType = null;
+ if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
+
+ SchemaDefinition def = schemeGen.get();
+ if (def == null) {
+ log.debug("Schema doesn't exists for property of type {}", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ PropertyDataDefinition propDef = def.getProperty();
+ if (propDef == null) {
+ log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
+ return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
+ }
+ innerType = propDef.getType();
+ }
+ return Either.left(innerType);
+ }
+ protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ if (isEmptyValue(value)) {
+ return true;
+ }
+
+ PropertyTypeValidator validator = type.getValidator();
+
+ boolean isValid = validator.isValid(value, innerType, dataTypes);
+ if (true == isValid) {
+ return true;
+ } else {
+ return false;
+ }
+
+ }
+
+ public boolean isEmptyValue(String value) {
+ if (value == null) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
index bd7e810066..6454379af8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
@@ -27,13 +27,13 @@ import org.springframework.stereotype.Component;
@Component("requirementsBusinessLogic")
public class RequirementsBusinessLogic {
- private static Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class);
- @javax.annotation.Resource
- private ComponentsUtils componentsUtils;
+ @javax.annotation.Resource
+ private ComponentsUtils componentsUtils;
- @javax.annotation.Resource
- private ResourceBusinessLogic resourceBusinessLogic;
+ @javax.annotation.Resource
+ private ResourceBusinessLogic resourceBusinessLogic;
}
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 4924bd25a7..f6cb50c5c2 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
@@ -20,33 +20,15 @@
package org.openecomp.sdc.be.components.impl;
-import static org.openecomp.sdc.be.tosca.CsarUtils.ARTIFACTS_PATH;
-import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
+import com.google.gson.Gson;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
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.csar.CsarArtifactsAndGroupsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationInfo;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
@@ -59,7 +41,6 @@ import org.openecomp.sdc.be.components.merge.resource.MergeResourceBLFactory;
import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
@@ -74,8 +55,7 @@ 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.info.ArtifactTemplateInfo;
-import org.openecomp.sdc.be.info.MergedArtifactInfo;
+import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
@@ -90,7 +70,6 @@ import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
@@ -113,7 +92,6 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
@@ -127,7 +105,7 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
@@ -138,7 +116,6 @@ import org.openecomp.sdc.be.utils.CommonBeUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
@@ -153,7288 +130,6634 @@ import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.parser.ParserException;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
+import javax.servlet.ServletContext;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.Function;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
-import fj.data.Either;
+import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
@org.springframework.stereotype.Component("resourceBusinessLogic")
public class ResourceBusinessLogic extends ComponentBusinessLogic {
- private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
- public static final String INITIAL_VERSION = "0.1";
+ private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
+ public static final String INITIAL_VERSION = "0.1";
+
+ private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
+ private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
+ private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
+ private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
+ private Pattern GET_ATTRIBUTE_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_attribute" + "=");
- private Pattern STR_REPLACE_PATTERN = Pattern.compile("^[ ]*\\{[ ]*" + "str_replace" + "=");
- private Pattern TOKEN_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "token" + "=");
- private Pattern GET_PROPERTY_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "get_property" + "=");
- private Pattern CONCAT_PATTERN = Pattern.compile("[ ]*\\{[ ]*" + "concat" + "=");
+ private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class);
- private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class.getName());
+ private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
- private static Pattern pattern = Pattern.compile("\\..(.*?)\\..");
+ /**
+ * Default constructor
+ */
+ public ResourceBusinessLogic() {
+ log.debug("ResourceBusinessLogic started");
+ }
- /**
- * Default constructor
- */
- public ResourceBusinessLogic() {
- log.debug("ResourceBusinessLogic started");
- }
+ @Autowired
+ private ICapabilityTypeOperation capabilityTypeOperation = null;
- @Autowired
- private ICapabilityTypeOperation capabilityTypeOperation = null;
+ @Autowired
+ private IInterfaceLifecycleOperation interfaceTypeOperation = null;
- @Autowired
- private IInterfaceLifecycleOperation interfaceTypeOperation = null;
+ @Autowired
+ private LifecycleBusinessLogic lifecycleBusinessLogic;
- @Autowired
- private LifecycleBusinessLogic lifecycleBusinessLogic;
+ @Autowired
+ private IPropertyOperation propertyOperation;
- @Autowired
- private IPropertyOperation propertyOperation;
+ @Autowired
+ private CsarOperation csarOperation;
- @Autowired
- private CsarOperation csarOperation;
+ @Autowired
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
- @Autowired
- private VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic;
+ @Autowired
+ private ResourceImportManager resourceImportManager;
- @Autowired
- private ResourceImportManager resourceImportManager;
- @Autowired
- private GroupBusinessLogic groupBusinessLogic;
-
- @Autowired
- private InputsBusinessLogic inputsBusinessLogic;
-
- @Autowired
- private CompositionBusinessLogic compositionBusinessLogic;
-
- @Autowired
- private ICacheMangerOperation cacheManagerOperation;
-
- @Autowired
- private ApplicationDataTypeCache dataTypeCache;
-
- @Autowired
- private MergeResourceBLFactory mergeResourceBLFactory;
+ @Autowired
+ private InputsBusinessLogic inputsBusinessLogic;
- private Gson gson = new Gson();
-
- public CsarOperation getCsarOperation() {
- return csarOperation;
- }
-
- public void setCsarOperation(CsarOperation csarOperation) {
- this.csarOperation = csarOperation;
- }
-
- public LifecycleBusinessLogic getLifecycleBusinessLogic() {
- return lifecycleBusinessLogic;
- }
-
- public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
- this.lifecycleBusinessLogic = lifecycleBusinessLogic;
- }
-
- public IElementOperation getElementDao() {
- return elementDao;
- }
-
- public void setElementDao(IElementOperation elementDao) {
- this.elementDao = elementDao;
- }
-
- public IUserBusinessLogic getUserAdmin() {
- return this.userAdmin;
- }
-
- public void setUserAdmin(UserBusinessLogic userAdmin) {
- this.userAdmin = userAdmin;
- }
-
- public ComponentsUtils getComponentsUtils() {
- return this.componentsUtils;
- }
-
- public void setComponentsUtils(ComponentsUtils componentsUtils) {
- this.componentsUtils = componentsUtils;
- }
-
- public ArtifactsBusinessLogic getArtifactsManager() {
- return artifactsBusinessLogic;
- }
-
- public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
- this.artifactsBusinessLogic = artifactsManager;
- }
-
- public void setPropertyOperation(IPropertyOperation propertyOperation) {
- this.propertyOperation = propertyOperation;
- }
-
- public ApplicationDataTypeCache getApplicationDataTypeCache() {
- return applicationDataTypeCache;
- }
-
- public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
- this.applicationDataTypeCache = applicationDataTypeCache;
- }
-
- /**
- * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param
- *
- * @param getAbstract
- * @param userId TODO
- * @return
- */
- public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Boolean isHighest = null;
- switch (highestFilter) {
- case ALL:
- break;
- case HIGHEST_ONLY:
- isHighest = true;
- break;
- case NON_HIGHEST_ONLY:
- isHighest = false;
- break;
- default:
- break;
- }
- Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
-
- if (getResponse.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
- }
-
- return Either.left(getResponse.left().value());
- }
-
- public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
- // DE242223
- titanDao.commit();
-
- if (dataModelResponse.isLeft()) {
- Map<String, Boolean> result = new HashMap<>();
- result.put("isValid", dataModelResponse.left().value());
- log.debug("validation was successfully performed.");
- return Either.left(result);
- }
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
- return Either.right(responseFormat);
- }
-
- public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload, String payloadName) {
- Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
- if (createResourceResponse.isRight()) {
- return createResourceResponse;
- }
-
- // Creating resource either by DAO or from CSAR
- String csarUUID = null;
- if (payloadName == null) {
- csarUUID = resource.getCsarUUID();
- } else {
- csarUUID = payloadName;
- }
- if (csarUUID != null && !csarUUID.isEmpty()) {
- // check if VF with the same Csar UUID or with he same name already
- // exists
- Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
- if (validateCsarUuidUniquenessRes.isRight()) {
- log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
- }
-
- Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
- if (existingResourceRes.intValue() > 0) {
- log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", auditingAction, null);
- return Either.right(errorResponse);
- }
-
- log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
- createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
- return createResourceResponse;
- }
-
- return createResourceByDao(resource, user, auditingAction, false, false, null);
- }
-
- public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
- Either<Resource, ResponseFormat> updateResourceResponse = null;
- Either<Resource, ResponseFormat> validateResourceResponse = null;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
- String csarUUID = null;
- String csarVersion = null;
- if (payloadName == null) {
- csarUUID = resource.getCsarUUID();
- csarVersion = resource.getCsarVersion();
- } else {
- csarUUID = payloadName;
- }
- if (csarUUID != null && !csarUUID.isEmpty()) {
- Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
- if (responseWrapper.isEmpty()) {
- validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
- }
- if (responseWrapper.isEmpty()) {
- validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
- }
- if (responseWrapper.isEmpty()) {
- if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
- overrideImmutableMetadata(oldResource, resource);
- }
- validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
- if (validateResourceResponse.isRight()) {
- responseWrapper.setInnerElement(validateResourceResponse.right().value());
- }
- }
- if (responseWrapper.isEmpty()) {
- String oldCsarVersion = oldResource.getCsarVersion();
- log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
- // (on boarding flow): If the update includes same csarUUID and
- // same csarVersion as already in the VF - no need to import the
- // csar (do only metadata changes if there are).
- if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
- updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
- } else {
- updateResourceResponse = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
- }
- }
- } else {
- log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
- componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
- responseWrapper.setInnerElement(errorResponse);
- }
- if (responseWrapper.isEmpty()) {
- return updateResourceResponse;
- }
- return Either.right(responseWrapper.getInnerElement());
- }
-
- private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource, Resource resource, String csarUUID, User user) {
- // (on boarding flow): If the update includes a csarUUID: verify this
- // csarUUID is not in use by another VF, If it is - use same error as
- // above:
- // "Error: The VSP with UUID %1 was already imported for VF %2. Please
- // select another or update the existing VF." %1 - csarUUID, %2 - VF
- // name
- Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
- if (resourceLinkedToCsarRes.isRight()) {
- if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
- log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
- }
- } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
- componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
- responseWrapper.setInnerElement(errorResponse);
- }
- }
-
- private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
- // (on boarding flow): If the update includes csarUUID which is
- // different from the csarUUID of the VF - fail with
- // error: "Error: Resource %1 cannot be updated using since it is linked
- // to a different VSP" %1 - VF name
- String oldCsarUUID = oldResource.getCsarUUID();
- if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
- log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}", resourceUniqueId, csarUUID, oldCsarUUID);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", AuditingActionEnum.UPDATE_RESOURCE_METADATA, null);
- responseWrapper.setInnerElement(errorResponse);
- }
- }
-
- private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
- Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaElement(resourceUniqueId);
- if (oldResourceRes.isRight()) {
- log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
- responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
- return null;
- }
- return oldResourceRes.left().value();
- }
-
- private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
- resource.setName(oldRresource.getName());
- resource.setIcon(oldRresource.getIcon());
- resource.setTags(oldRresource.getTags());
- resource.setVendorName(oldRresource.getVendorName());
- resource.setCategories(oldRresource.getCategories());
- resource.setDerivedFrom(oldRresource.getDerivedFrom());
- }
-
- private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
- String csarUUID) {
-
- // check state
- if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
- if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
- log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", oldRresource.getLastUpdaterUserId(), user.getUserId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- }
- String lockedResourceId = oldRresource.getUniqueId();
- List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
-
- Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
- if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
- csar = csarUIPayload;
- } else {
- csar = csarOperation.getCsar(csarUUID, user);
- }
- if (csar.isRight()) {
- log.debug("Failed to get csar for casrUUID{} ", csarUUID);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource, user, csarUUID, csar);
- if (toscaYamlCsarStatus.isRight()) {
- return Either.right(toscaYamlCsarStatus.right().value());
- }
- Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
- if (checksum.isRight()) {
- log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
- return Either.right(checksum.right().value());
- }
- boolean isUpdateYaml = true;
- if (checksum.left().value().equals(oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
- log.debug("The checksums are equals for csarUUID {}, existing checsum is {}, new one is {} ", csarUUID, oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum.left().value());
- if (oldRresource.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT))
- isUpdateYaml = false;
- } else {
- oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum.left().value());
- }
-
- Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource, "update Resource From Csar");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
- }
-
- String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
- String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
- CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, true);
- Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
- Either<Resource, ResponseFormat> result = null;
-
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, oldRresource);
- if (findNodeTypesArtifactsToHandleRes.isRight()) {
- log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
- result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
- return result;
- }
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left().value();
- try{
- result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, isUpdateYaml, yamlFileName, yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
-
- } finally {
- if (result == null || result.isRight()) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- log.debug("unlock resource {}", lockedResourceId);
- graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
- }
- return result;
-
- }
-
- private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts,
- boolean isUpdateYaml, String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, String nodeName, boolean isNested) {
- Either<Resource, ResponseFormat> result;
- Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither;
- boolean inTransaction = true;
- boolean shouldLock = false;
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate;
- Resource preparedResource;
- Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
- if (uploadComponentInstanceInfoMap.isRight()) {
- ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, "", "", updateResource, null);
- result = Either.right(responseFormat);
- return result;
- }
-
- Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
-
- if (isUpdateYaml || !nodeTypesArtifactsToHandle.isEmpty()) {
-
- prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock, isNested);
- if (prepareForUpdate.isRight()) {
- log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
- result = Either.right(prepareForUpdate.right().value());
- return result;
- }
- preparedResource = prepareForUpdate.left().value().left;
-
- log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
-
- Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(preparedResource);
- if (genericResourceEither.isRight()) {
- log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value());
- ResponseFormat responseFormat = genericResourceEither.right().value();
- componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
- return Either.right(responseFormat);
- }
-
- parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
- if (parseNodeTypeInfoYamlEither.isRight()) {
- ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
- result = Either.right(responseFormat);
- return result;
- }
-
- Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource, csarInfo.getModifier(), inputs, inTransaction);
- if (createInputsOnResource.isRight()) {
- log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
- ResponseFormat responseFormat = createInputsOnResource.right().value();
- componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
- result = Either.right(responseFormat);
- return result;
- }
- preparedResource = createInputsOnResource.left().value();
-
- Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock, csarInfo.getCreatedNodes());
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
- ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
- componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(), preparedResource, "", "", updateResource, null);
- result = Either.right(responseFormat);
- return result;
- }
- preparedResource = createResourcesInstancesEither.left().value();
-
- createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
- result = Either.right(createResourcesInstancesEither.right().value());
- return result;
- }
-
- preparedResource = createResourcesInstancesEither.left().value();
-
- Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(), preparedResource.getSystemName());
- if (validateUpdateVfGroupNamesRes.isRight()) {
-
- return Either.right(validateUpdateVfGroupNamesRes.right().value());
- }
- // add groups to resource
- Map<String, GroupDefinition> groups;
-
- if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
- groups = validateUpdateVfGroupNamesRes.left().value();
- } else {
- groups = uploadComponentInstanceInfoMap.left().value().getGroups();
- }
- Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource, csarInfo.getModifier(), groups);
- if (updatedGroupsOnResource.isRight()) {
-
- return updatedGroupsOnResource;
- }
- preparedResource = updatedGroupsOnResource.left().value();
-
- } else {
- Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(oldRresource.getUniqueId(), newRresource, csarInfo.getModifier(), oldRresource, shouldLock, inTransaction);
- if (dataModelResponse.isRight()) {
- log.debug("failed to update resource metadata {}", dataModelResponse.right().value());
- result = Either.right(dataModelResponse.right().value());
- return result;
- }
- preparedResource = dataModelResponse.left().value();
- }
-
- if(preparedResource.getResourceType() == ResourceTypeEnum.CVFC){
- if(nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()){
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
- handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
- if(handleNodeTypeArtifactsRes.isRight()){
- return Either.right(handleNodeTypeArtifactsRes.right().value());
- }
- }
- } else {
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
- artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), shouldLock, inTransaction);
- log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
- if (createdCsarArtifactsEither.isRight()) {
- return createdCsarArtifactsEither;
- }
- preparedResource = createdCsarArtifactsEither.left().value();
- }
-
- ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource);
- if (mergingPropsAndInputsStatus != ActionStatus.OK) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
- return Either.right(responseFormat);
- }
-
- Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
- result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(preparedResource);
-
- return result;
-
- }
-
- private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) {
- Either<MergeResourceBusinessLogic, ActionStatus> mergeResourceBLEither = mergeResourceBLFactory.getInstance(oldResource, newResource);
- if (mergeResourceBLEither.isRight()) {
- return mergeResourceBLEither.right().value();
- }
- MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value();
- return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource);
- }
-
- private Either<Resource, ResponseFormat> handleResourceGenericType(Resource resource) {
- Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
- if (genericResourceEither.isRight()) {
- return genericResourceEither;
- }
- if (resource.shouldGenerateInputs()) {
- generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
- }
- return genericResourceEither;
- }
-
- private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
-
- Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
-
- try {
- nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
- Map<String, ImmutablePair<String,String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
- Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
- log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarInfo.getCsarUUID());
-
- for (Entry<String, ImmutablePair<String,String>> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) {
- String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft();
- String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight();
- String currNamespace = currVfcToscaNameEntry.getKey();
- log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
-
- Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
- Resource curNodeType = null;
- if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
- curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName);
- }
- if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
- log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, curVfcRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(curVfcRes.right().value()), csarInfo.getCsarUUID());
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
- nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
- break;
- } else if (curVfcRes.isLeft()) {
- curNodeType = curVfcRes.left().value();
- }
- if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
- List<ArtifactDefinition> currArtifacts = new ArrayList<>();
- if (extractedVfcsArtifacts.containsKey(currNamespace)) {
- handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
- }
- curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
- if (curNodeTypeArtifactsToHandleRes.isRight()) {
- nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
- break;
- }
- curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
-
- } else if (curNodeType != null) {
- // delete all artifacts if have not received artifacts from csar
- curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
- // delete all informational artifacts
- artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toList()));
- // delete all deployment artifacts
- artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
- if (!artifactsToDelete.isEmpty()) {
- curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
- }
- }
- if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
- nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
- }
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
- log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
- }
- return nodeTypesArtifactsToHandleRes;
- }
-
- private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
-
- Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
- try {
- List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
- List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
- List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
- if (curNodeType != null) {
- Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
- if (curNodeType.getDeploymentArtifacts() != null) {
- existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
- }
- if (curNodeType.getArtifacts() != null) {
- existingArtifacts.putAll(curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
- }
- for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
- ArtifactDefinition foundArtifact;
-
- if (!existingArtifacts.isEmpty()) {
- foundArtifact = existingArtifacts.values().stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
- if (foundArtifact != null) {
- if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
- if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
- foundArtifact.setPayload(currNewArtifact.getPayloadData());
- foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
- foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
- artifactsToUpdate.add(foundArtifact);
- }
- existingArtifacts.remove(foundArtifact.getArtifactLabel());
- artifactsToUpload.remove(currNewArtifact);
- } else {
- log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
- foundArtifact.getArtifactType());
- responseWrapper.setInnerElement(responseFormat);
- break;
- }
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- artifactsToDelete.addAll(existingArtifacts.values());
- }
- }
- if (responseWrapper.isEmpty()) {
- if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
- nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- if (!artifactsToUpload.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
- if (!artifactsToUpdate.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
- if (!artifactsToDelete.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
- }
- nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
- }
- if (!responseWrapper.isEmpty()) {
- nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- responseWrapper.setInnerElement(responseFormat);
- log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
- }
- return nodeTypeArtifactsToHandleRes;
- }
-
- /**
- * Changes resource life cycle state to checked out
- *
- * @param resource
- * @param user
- * @param inTransaction
- * @return
- */
- private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
- Either<Resource, ResponseFormat> checkoutResourceRes;
- try {
- if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
- Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
- new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
- if (checkoutRes.isRight()) {
- log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
- checkoutResourceRes = Either.right(checkoutRes.right().value());
- } else {
- checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
- }
- } else {
- checkoutResourceRes = Either.left(resource);
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- checkoutResourceRes = Either.right(responseFormat);
- log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
- }
- return checkoutResourceRes;
- }
-
- /**
- * Handles Artifacts of NodeType
- *
- * @param nodeTypeResource
- * @param nodeTypeArtifactsToHandle
- * @param vfcsNewCreatedArtifacts
- * @param user
- * @param inTransaction
- * @return
- */
- public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
- User user, boolean inTransaction, boolean ignoreLifecycleState) {
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
- Either<Resource, ResponseFormat> changeStateResponse;
- try {
- changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
- if (changeStateResponse.isRight()) {
- return Either.right(changeStateResponse.right().value());
- }
- nodeTypeResource = changeStateResponse.left().value();
-
- List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
- log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
- for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
- ArtifactOperationEnum curOperation = curOperationEntry.getKey();
- List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
- if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
- log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
- handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic.handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
- artifactsBusinessLogic.new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
- if (handleNodeTypeArtifactsRequestRes.isRight()) {
- handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
- break;
- }
- if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
- createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
- }
- handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
- }
- }
- if (handleNodeTypeArtifactsRes == null) {
- handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- handleNodeTypeArtifactsRes = Either.right(responseFormat);
- log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
- }
- return handleNodeTypeArtifactsRes;
- }
-
- private Map<String, ImmutablePair<String,String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName, CsarInfo csarInfo) {
- Map<String, ImmutablePair<String,String>> vfcToscaNames = new HashMap<>();
-
- Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
- if (!nodes.isEmpty()) {
- Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
- while (nodesNameEntry.hasNext()) {
- Entry<String, Object> nodeType = nodesNameEntry.next();
- ImmutablePair<String,String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
- vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
- }
- }
- for(NodeTypeInfo cvfc : nodeTypesInfo.values()){
- vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
- }
- return vfcToscaNames;
- }
-
- private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
- Map<String, Object> nodes = new HashMap<>();
- for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
- extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
- }
- extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
- return nodes;
- }
-
- private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
- Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
- if (eitherNodeTypes.isLeft()) {
- nodes.putAll(eitherNodeTypes.left().value());
- }
- }
-
- public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
- log.trace("************* created successfully from YAML, resource TOSCA ");
-
- Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
- if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
- csar = csarUIPayload;
- } else {
- csar = csarOperation.getCsar(csarUUID, user);
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csarUUID, csar);
- if (toscaYamlCsarStatus.isRight()) {
- return Either.right(toscaYamlCsarStatus.right().value());
- }
- Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(), csarUUID, componentsUtils);
- if (toscaYamlChecksum.isRight()) {
- log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID, toscaYamlChecksum.right().value());
- return Either.right(toscaYamlChecksum.right().value());
- }
- resource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(toscaYamlChecksum.left().value());
-
- String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
- String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
- log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
-
- CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents, false);
- Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, resource);
- if (findNodeTypesArtifactsToHandleRes.isRight()) {
- log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
- return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
- }
- Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
- if (createResourceFromYaml.isRight()) {
- log.debug("Couldn't create resource from YAML");
- return Either.right(createResourceFromYaml.right().value());
- }
-
- Resource vfResource = createResourceFromYaml.left().value();
- log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
- return Either.left(vfResource);
- }
-
- private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
- Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
- List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
- for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
- extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
- }
- if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
- setDerivedFrom(nodeTypesInfo, globalSubstitutes);
- }
- markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
- return nodeTypesInfo;
- }
-
- @SuppressWarnings("unchecked")
- private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, List<Entry<String, byte[]>> globalSubstitutes) {
- for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
- String yamlFileContents = new String(entry.getValue());
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
- Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
- if (nodeTypesEither.isLeft()) {
- Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
- for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
- Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
- if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
- if (nodeTypesInfo.containsKey(nodeType.getKey())) {
- NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
- List<String> derivedFrom = new ArrayList<>();
- derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
- nodeTypeInfo.setDerivedFrom(derivedFrom);
- }
- }
- }
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
- List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
- if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
- if (!isGlobalSubstitute(entry.getKey())) {
- String yamlFileContents = new String(entry.getValue());
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
- Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
- if (substitutionMappingsEither.isLeft()) {
- Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
- if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
- NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
- nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
- nodeTypeInfo.setTemplateFileName(entry.getKey());
- nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
- nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
- }
- }
- } else {
- globalSubstitutes.add(entry);
- }
- }
- }
-
-
- @SuppressWarnings("unchecked")
- private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
- Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
- if (nodeTemplatesEither.isLeft()) {
- Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
- for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
- Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
- if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
- if (nodeTypesInfo.containsKey(type)) {
- NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
- nodeTypeInfo.setNested(true);
- }
- }
- }
- }
- }
-
- private boolean isGlobalSubstitute(String fileName) {
- return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
- }
-
- private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
- if (csar.isRight()) {
- StorageOperationStatus value = csar.right().value();
- log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(), csarUUID, componentsUtils);
- if (validateCsarStatus.isRight()) {
- ResponseFormat responseFormat = validateCsarStatus.right().value();
- log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
- return Either.right(responseFormat);
- }
-
- Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
-
- if (toscaYamlCsarStatus.isRight()) {
- ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
- log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
- return Either.right(responseFormat);
- }
- return toscaYamlCsarStatus;
- }
-
- private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
- log.trace("validating resource before create");
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource, AuditingActionEnum.CREATE_RESOURCE, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user.copyData(eitherCreator.left().value());
-
- // validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
- // VF / PNF "derivedFrom" should be null (or ignored)
- if (ModelConverter.isAtomicComponent(resource)) {
- Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
- if (validateDerivedFromNotEmpty.isRight()) {
- return Either.right(validateDerivedFromNotEmpty.right().value());
- }
- }
- return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
-
- }
-//resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo, nodeTypesArtifactsToCreate, true, false, null
- private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- boolean shouldLock, boolean inTransaction, String nodeName) {
-
- List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
- log.trace("************* createResourceFromYaml before parse yaml ");
- Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName);
- if (parseResourceInfoFromYamlEither.isRight()) {
- ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
- }
- log.trace("************* createResourceFromYaml after parse yaml ");
- ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
- log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
- log.trace("************* createResourceFromYaml before create ");
- Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
- AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
- nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
- log.trace("************* createResourceFromYaml after create ");
- if (createdResourceResponse.isRight()) {
- ResponseFormat responseFormat = createdResourceResponse.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
- }
-
- return createdResourceResponse;
-
- }
-
- public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
-
- Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
- if (tosca_version.isRight()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
- return Either.right(responseFormat);
- }
- Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
- Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
- Map<String, Object> mapToConvert = new HashMap<String, Object>();
- mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
- Resource vfcCreated = null;
- if (eitherNodeTypes.isLeft()) {
- Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
- while (nodesNameValue.hasNext()) {
- Entry<String, Object> nodeType = nodesNameValue.next();
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
- if (nodeTypesInfo.containsKey(nodeType.getKey())) {
- log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
- Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeType.getKey());
- log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
- if (handleNeatedVfcYaml.isRight()) {
- return Either.right(handleNeatedVfcYaml.right().value());
- }
- vfcCreated = handleNeatedVfcYaml.left().value();
- } else if(csarInfo.getCreatedNodesToscaResourceNames()!= null && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
- log.trace("************* Going to create node {}", nodeType.getKey());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
- log.debug("************* Finished to create node {}", nodeType.getKey());
-
- if (resourceCreated.isRight()) {
- return Either.right(resourceCreated.right().value());
- }
- vfcCreated = resourceCreated.left().value().getLeft();
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
- }
- if (vfcCreated != null) {
- csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
- }
- mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
- }
- }
- return result;
- }
-
- private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
- List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName) {
-
- Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
- String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
- Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
-
- log.debug("************* Going to create node types from yaml {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(yamlName, resource,
- nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
- if (createNodeTypesRes.isRight()) {
- log.debug("Failed to create node types from yaml {}. Status is {}", yamlName, createNodeTypesRes.right().value());
- return Either.right(createNodeTypesRes.right().value());
- }
- log.debug("************* Finished to create node types from yaml {}", yamlName);
-
- if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
- log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
- handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
- }
- return handleNestedVfcRes;
- }
-
- private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts,
- Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
-
- Either<Resource, ResponseFormat> result = null;
- Resource oldComplexVfc = null;
- Resource newComplexVfc = null;
-
- Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
- if(buildCvfcRes.isRight()){
- log.debug("Failed to validate complex VFC for node {}. ", nodeName);
- result = buildCvfcRes;
- }
- if(result == null){
- newComplexVfc = buildCvfcRes.left().value();
- Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
- if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND){
- oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
- }
- if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){
- log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } else if(oldComplexVfcRes.isLeft()){
- log.debug("validate derived before update");
- Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
- if (eitherValidation.isLeft()) {
- oldComplexVfc = oldComplexVfcRes.left().value();
- }
- }
- }
- if(result == null){
- result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc, newComplexVfc);
- }
- if(result.isLeft()){
- newComplexVfc = result.left().value();
- csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
- log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
- result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
- if (result.isRight()) {
- log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
- }
- }
- if(result.isLeft()){
- csarInfo.getCreatedNodes().put(nodeName, result.left().value());
- csarInfo.getCvfcToCreateQueue().remove();
- }
- return result;
- }
-
- private Either<Resource, ResponseFormat> handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle, List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo,
- CsarInfo csarInfo, String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
-
- Either<Resource, ResponseFormat> handleComplexVfcRes;
- Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
- String yamlContent = new String(csarInfo.getCsar().get(yamlName));
- Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
- markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
- if(oldComplexVfc == null){
- handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle, false, true, nodeName);
- if (handleComplexVfcRes.isRight()) {
- log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
- }
- } else {
- handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, true, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
- if (handleComplexVfcRes.isRight()) {
- log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
- }
- }
- return handleComplexVfcRes;
- }
-
- private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
-
- Either<Resource, ResponseFormat> result = null;
- Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
- log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
-
- if(!csarInfo.getCvfcToCreateQueue().contains(nodeName)){
- csarInfo.getCvfcToCreateQueue().add(nodeName);
- } else {
- log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(), csarInfo.getVfResourceName());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, csarInfo.getVfResourceName(), complexVfc.getName()));
- }
- if(result == null){
- result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
- if(result.isRight()){
- log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
- }
- }
- return result;
- }
-
- private String getNodeTypeActualName(String fullName) {
- String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
- String[] findTypes = nameWithouNamespacePrefix.split("\\.");
- String resourceType = findTypes[0];
- return nameWithouNamespacePrefix.substring(resourceType.length());
- }
-
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, boolean isNested) {
-
- Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
- if (resourceMetaData.isRight()) {
- return Either.right(resourceMetaData.right().value());
- }
- String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarInfo);
-
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
- }
-
- private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, CsarInfo csarInfo) {
- // We need to create a Yaml from each node_types in order to create
- // resource from each node type using import normative flow.
- DumperOptions options = new DumperOptions();
- options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
- Yaml yaml = new Yaml(options);
-
- Map<String, Object> node = new HashMap<>();
- node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(), nodeNameValue.getValue());
- mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
-
- return yaml.dumpAsMap(mapToConvert);
- }
-
- public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
-
- Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
- if (validateDerivedFromNotEmpty.isRight()) {
- return Either.right(validateDerivedFromNotEmpty.right().value());
- }
- return Either.left(true);
- }
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) {
-
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
- Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
- return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
- }
-
- private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
- UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
- // validate nodetype name prefix
- if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
- log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
- return Either.right(responseFormat);
- }
-
- String actualName = this.getNodeTypeActualName(nodeName);
- String namePrefix = nodeName.replace(actualName, "");
- String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
-
- // if we import from csar, the node_type name can be
- // org.openecomp.resource.abstract.node_name - in this case we always
- // create a vfc
- if (resourceType.equals(Constants.ABSTRACT)) {
- resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
- }
- // validating type
- if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
- log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
- return Either.right(responseFormat);
- }
-
- // Setting name
- resourceMetaData.setName(resourceVf.getSystemName() + actualName);
-
- // Setting type from name
- String type = resourceType.toUpperCase();
- resourceMetaData.setResourceType(type);
-
- resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
- resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
- resourceMetaData.setContactId(user.getUserId());
- resourceMetaData.setVendorName(resourceVf.getVendorName());
- resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
-
- // Setting tag
- List<String> tags = new ArrayList<>();
- tags.add(resourceMetaData.getName());
- resourceMetaData.setTags(tags);
-
- // Setting category
- CategoryDefinition category = new CategoryDefinition();
- category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
- SubCategoryDefinition subCategory = new SubCategoryDefinition();
- subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
- category.addSubCategory(subCategory);
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- resourceMetaData.setCategories(categories);
-
- return Either.left(resourceMetaData);
- }
-
- private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
- Resource cvfc = new Resource();
- NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
- cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
- cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
- cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
- cvfc.setResourceType(ResourceTypeEnum.CVFC);
- cvfc.setAbstract(true);
- cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
- cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
- cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
- cvfc.setContactId(csarInfo.getModifier().getUserId());
- cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
- cvfc.setVendorName(resourceVf.getVendorName());
- cvfc.setVendorRelease(resourceVf.getVendorRelease());
- cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
- cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
- cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
- List<String> tags = new ArrayList<>();
- tags.add(cvfc.getName());
- cvfc.setTags(tags);
-
- CategoryDefinition category = new CategoryDefinition();
- category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
- SubCategoryDefinition subCategory = new SubCategoryDefinition();
- subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
- category.addSubCategory(subCategory);
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- cvfc.setCategories(categories);
-
- cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
- cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
- cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
- return cvfc;
- }
-
- private String buildCvfcName(String resourceVfName, String nodeName) {
- String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
- String[] findTypes = nameWithouNamespacePrefix.split("\\.");
- String resourceType = findTypes[0];
- String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
- return addCvfcSuffixToResourceName(resourceName);
- }
-
- private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
- List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
- CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- boolean shouldLock, boolean inTransaction, String nodeName) {
-
- boolean result = true;
- List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
-
- if (shouldLock) {
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- return Either.right(responseFormat);
- }
- log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
- }
- try {
- log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
- Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
- if (genericResourceEither.isRight()) {
- result = false;
- return genericResourceEither;
- }
- Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, csarInfo.getModifier(), isNormative, inTransaction);
- log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
- if (createResourcesEither.isRight()) {
- result = false;
- return createResourcesEither;
- }
- resource = createResourcesEither.left().value();
- // add groups to resource
- log.trace("************* Going to add inputs from yaml {}", yamlName);
- if (resource.shouldGenerateInputs())
- generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
-
- Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, csarInfo.getModifier(), inputs, inTransaction);
- if (createInputsOnResource.isRight()) {
- result = false;
- return createInputsOnResource;
- }
- resource = createInputsOnResource.left().value();
- log.trace("************* Finish to add inputs from yaml {}", yamlName);
-
- Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
- log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
-
- createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
- log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
- if (createResourcesEither.isRight()) {
- result = false;
- return createResourcesEither;
- }
-
- resource = createResourcesEither.left().value();
- // validate update vf module group names
- Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
- if (validateUpdateVfGroupNamesRes.isRight()) {
- result = false;
- return Either.right(validateUpdateVfGroupNamesRes.right().value());
- }
- // add groups to resource
- Map<String, GroupDefinition> groups;
- log.trace("************* Going to add groups from yaml {}", yamlName);
-
- if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
- groups = validateUpdateVfGroupNamesRes.left().value();
- } else {
- groups = parsedToscaYamlInfo.getGroups();
- }
- Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, csarInfo.getModifier(), groups);
- if (createGroupsOnResource.isRight()) {
- result = false;
- return createGroupsOnResource;
- }
- resource = createGroupsOnResource.left().value();
- log.trace("************* Finished to add groups from yaml {}", yamlName);
-
- log.trace("************* Going to add artifacts from yaml {}", yamlName);
-
- if(resource.getResourceType() == ResourceTypeEnum.CVFC){
- if(nodeTypesArtifactsToCreate.containsKey(nodeName) && nodeTypesArtifactsToCreate.get(nodeName) !=null && !nodeTypesArtifactsToCreate.get(nodeName).isEmpty()){
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
- handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeName), nodeTypesNewCreatedArtifacts, csarInfo.getModifier(), true, false);
- if(handleNodeTypeArtifactsRes.isRight()){
- return Either.right(handleNodeTypeArtifactsRes.right().value());
- }
- }
- } else {
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, csarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
- inTransaction);
- log.trace("************* Finished to add artifacts from yaml {}", yamlName);
- if (createdCsarArtifactsEither.isRight()) {
- result = false;
- return createdCsarArtifactsEither;
- }
- resource = createdCsarArtifactsEither.left().value();
- }
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", actionEnum, null);
- ASDCKpiApi.countCreatedResourcesKPI();
- return Either.left(resource);
-
- } finally {
- if (!inTransaction) {
- if (!result) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
- createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
- log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
- }
-
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- if (shouldLock) {
- graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
- }
- }
- }
-
- private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
- if (groups != null && !groups.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
-
- if (mergeGroupsUsingResource.isRight()) {
- log.debug("Failed to prepare groups for creation");
- return Either.right(mergeGroupsUsingResource.right().value());
- }
- List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsAsList);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right().value());
- }
- } else {
- return Either.left(resource);
- }
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
- return Either.right(responseFormat);
- }
- return Either.left(updatedResource.left().value());
- }
-
- private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
- if (groups != null && false == groups.isEmpty()) {
- List<GroupDefinition> groupsFromResource = resource.getGroups();
- Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(groups, resource);
-
- if (mergeGroupsUsingResource.isRight()) {
- log.debug("Failed to prepare groups for creation");
- return Either.right(mergeGroupsUsingResource.right().value());
- }
- List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
- List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
- List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
- List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
- if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
- for (GroupDefinition group : groupsAsList) {
- Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
- if (op.isPresent()) {
- GroupDefinition groupToUpdate = op.get();
- groupToUpdate.setMembers(group.getMembers());
- groupsToUpdate.add(groupToUpdate);
- } else {
- groupsToCreate.add(group);
- }
- }
- for (GroupDefinition group : groupsFromResource) {
- Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
- if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
-
- groupsToDelete.add(group);
- }
-
- }
- } else
- groupsToCreate.addAll(groupsAsList);
- Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
- if (!groupsToCreate.isEmpty()) {
-
- if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
- prepareGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
- } else {
- prepareGroups = groupBusinessLogic.createGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToCreate);
- }
-
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
- }
- }
-
- if (!groupsToDelete.isEmpty()) {
- prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupsToDelete);
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
- }
- }
-
- if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
- prepareGroups = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsToUpdate);
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
- }
- }
-
- } else {
- return Either.left(resource);
- }
-
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
- return Either.right(responseFormat);
- }
- return Either.left(updatedResource.left().value());
- }
-
- private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
- List<InputDefinition> resourceProperties = resource.getInputs();
- if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
-
- Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
- if (createInputs.isRight()) {
- return Either.right(createInputs.right().value());
- }
- } else {
- return Either.left(resource);
- }
-
- Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- if (updatedResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
- return Either.right(responseFormat);
- }
- return Either.left(updatedResource.left().value());
- }
-
- private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
-
- List<GroupDefinition> result = new ArrayList<>();
-
- List<ComponentInstance> componentInstances = component.getComponentInstances();
-
- if (groups != null) {
- Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
- if (validateCyclicGroupsDependencies.isRight()) {
- return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
- }
- for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
- String groupName = entry.getKey();
-
- GroupDefinition groupDefinition = entry.getValue();
-
- GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
- updatedGroupDefinition.setMembers(null);
-
- // get the members of the group
- Map<String, String> members = groupDefinition.getMembers();
- if (members != null) {
- Set<String> compInstancesNames = members.keySet();
-
- if (componentInstances == null || true == componentInstances.isEmpty()) {
- String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString, groupName, component.getNormalizedName());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
- }
- // Find all component instances with the member names
- Map<String, String> memberNames = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
- memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
- Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey())).collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
-
- if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
-
- List<String> foundMembers = new ArrayList<>();
- if (relevantInstances != null) {
- foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
- }
- compInstancesNames.removeAll(foundMembers);
- String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
- log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(), getComponentTypeForResponse(component)));
- }
-
- updatedGroupDefinition.setMembers(relevantInstances);
- }
-
- result.add(updatedGroupDefinition);
- }
- }
- return Either.left(result);
- }
-
- /**
- * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
- *
- * @param allGroups
- * @return
- */
- private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
-
- Either<Boolean, ResponseFormat> result = Either.left(true);
- try {
- Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
- while (allGroupsItr.hasNext() && result.isLeft()) {
- Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
- // Fetches a group member A
- String groupAName = groupAEntry.getKey();
- // Finds all group members in group A
- Set<String> allGroupAMembersNames = new HashSet<>();
- fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
- // If A is a group member of itself found cyclic dependency
- if (allGroupAMembersNames.contains(groupAName)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
- result = Either.right(responseFormat);
- }
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- result = Either.right(responseFormat);
- log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
- }
- return result;
- }
-
- /**
- * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
- *
- * @param groupName
- * @param allGroups
- * @param allGroupMembers
- * @return
- */
- private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
-
- // Found Cyclic dependency
- if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
- return;
- }
- GroupDefinition groupDefinition = allGroups.get(groupName);
- // All Members Of Current Group Resource Instances & Other Groups
- Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
- // Filtered Members Of Current Group containing only members which
- // are groups
- List<String> currGroupFilteredMembers = currGroupMembers.stream().
- // Keep Only Elements of type group and not Resource Instances
- filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
- // Add Filtered Elements to main Set
- peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
- // Collect results
- collect(Collectors.toList());
-
- // Recursively call the method for all the filtered group members
- for (String innerGroupName : currGroupFilteredMembers) {
- fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
- }
-
- }
-
- private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
-
- boolean stop = false;
- // In Case Not Group Stop
- if (!allGroups.containsKey(groupName)) {
- stop = true;
- }
- // In Case Group Has no members stop
- if (!stop) {
- GroupDefinition groupDefinition = allGroups.get(groupName);
- stop = MapUtils.isEmpty(groupDefinition.getMembers());
-
- }
- // In Case all group members already contained stop
- if (!stop) {
- final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
- Set<String> membersOfTypeGroup = allMembers.stream().
- // Filter In Only Group members
- filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
- // Collect
- collect(Collectors.toSet());
- stop = allGroupMembers.containsAll(membersOfTypeGroup);
- }
- return stop;
- }
-
- private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
- String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
- String nodeName) {
-
- Either<Resource, ResponseFormat> result;
- Either<Resource, ResponseFormat> createResourcesInstancesEither;
-
- log.debug("************* Going to create all nodes {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
- log.debug("************* Finished to create all nodes {}", yamlName);
- if (createdResourcesFromdNodeTypeMap.isRight()) {
- log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
- return Either.right(createdResourcesFromdNodeTypeMap.right().value());
- }
-
- log.debug("************* Going to create all resource instances {}", yamlName);
- createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
-
- log.debug("************* Finished to create all resource instances {}", yamlName);
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create resource instances status is {}", createResourcesInstancesEither.right().value());
- result = createResourcesInstancesEither;
- return createResourcesInstancesEither;
- }
- resource = createResourcesInstancesEither.left().value();
- log.debug("************* Going to create all relations {}", yamlName);
- createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
-
- log.debug("************* Finished to create all relations {}", yamlName);
-
- if (createResourcesInstancesEither.isRight()) {
- log.debug("failed to create relation between resource instances status is {}", createResourcesInstancesEither.right().value());
- result = createResourcesInstancesEither;
- return result;
- } else {
- resource = createResourcesInstancesEither.left().value();
- }
-
- log.debug("************* Going to create positions {}", yamlName);
- Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
- log.debug("************* Finished to set positions {}", yamlName);
- result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
-
- return result;
- }
-
- private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
- List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
- artifactsToAdd.stream().forEach(a -> {
- if (!vfcArtifactNames.contains(a.getArtifactName())) {
- vfcArtifacts.add(a);
- } else {
- log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
- }
- });
-
- }
-
- @SuppressWarnings("unchecked")
- private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, String nodeName) {
-
- Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
- for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
- if (nodeTypeEntry.getValue().isNested()) {
-
- Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
- log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
- if (createResourceFromYaml.isRight()) {
- return Either.right(createResourceFromYaml.right().value());
- }
- }
- }
-
- Map<String, Object> mappedToscaTemplate = null;
- if(StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)){
- mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
- }
- if(MapUtils.isEmpty(mappedToscaTemplate)){
- mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
- }
-
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
- if (createdNodeTypeFromMainTemplateEither.isRight()) {
- ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
- }
-
- // add the created node types to the cache although they are not in the
- // graph.
- csarInfo.getCreatedNodes().values().stream().forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
-
- return result;
- }
-
- private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
- boolean inTransaction) {
-
- if (csarInfo.getCsar() != null) {
- String vendorLicenseModelId = null;
- String vfLicenseModelId = null;
-
- if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Update) {
- Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
- if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
- for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
- if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
- vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
- if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
- vfLicenseModelId = artifactEntry.getValue().getUniqueId();
- }
- }
-
- }
- // Specific Behavior for license artifacts
- createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
- Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
- createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
- Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
-
- Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
- if (eitherCreateResult.isRight()) {
- return Either.right(eitherCreateResult.right().value());
- }
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
- resource = eitherGerResource.left().value();
-
- Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
- if (artifacsMetaCsarStatus.isLeft()) {
-
- String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
- String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
- Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
- if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum()))
- createArtifactsFromCsar = createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
- else
- createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
- if (createArtifactsFromCsar.isRight()) {
- log.debug("Couldn't create artifacts from artifacts.meta");
- return Either.right(createArtifactsFromCsar.right().value());
- }
-
- resource = createArtifactsFromCsar.left().value();
- } else {
- List<GroupDefinition> groupsToDelete = resource.getGroups();
-
- if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
- Set<String> artifactsToDelete = new HashSet<String>();
-
- for (String artifactId : artifactsToDelete) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
- resource, null, null, shouldLock, inTransaction);
- if (handleDelete.isRight()) {
- log.debug("Couldn't delete artifact {}", artifactId);
- return Either.right(handleDelete.right().value());
- }
- }
- Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
- resource = eitherGetResource.left().value();
- }
- }
- }
- return Either.left(resource);
- }
-
- private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath, String artifactFileName, String artifactType,
- ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
- boolean inTransaction) {
- byte[] artifactFileBytes = null;
-
- if (csarInfo.getCsar().containsKey(artifactPath)) {
- artifactFileBytes = csarInfo.getCsar().get(artifactPath);
- }
- Either<Boolean, ResponseFormat> result = Either.left(true);
- if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
- if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
- null, shouldLock, inTransaction);
- if (handleDelete.isRight()) {
- result = Either.right(handleDelete.right().value());
- }
- return result;
- }
-
- if ((artifactId == null || artifactId.isEmpty()) && artifactFileBytes != null) {
- operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create);
- }
-
- }
- if (artifactFileBytes != null) {
- Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction);
- addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
- if (eitherNonMetaArtifacts.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
- return Either.right(eitherNonMetaArtifacts.right().value());
- }
- }
- return result;
- }
-
- private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
- if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
- Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
- if (eitherResult.isLeft()) {
- createdArtifacts.add(eitherResult.left().value());
- }
- }
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Resource resource, User user, Map<String, Object> json, ArtifactOperationInfo operation, boolean shoudLock, boolean inTransaction) {
-
- String jsonStr = gson.toJson(json);
-
- String origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(jsonStr);
- ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class);
- String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.validateAndHandleArtifact(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, operation, artifactUniqueId,
- artifactDefinitionFromJson, origMd5, jsonStr, null, null, null, user, resource, false, true, false);
- if (uploadArtifactToService.isRight())
- return Either.right(uploadArtifactToService.right().value());
-
- return Either.left(uploadArtifactToService.left().value());
- }
-
- public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
- boolean shouldLock, boolean inTransaction) {
-
- Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
- if (parseResourceInfoFromYamlEither.isRight()) {
- ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
- }
-
- List<GroupDefinition> groups = resource.getGroups();
- Map<String, ArtifactDefinition> deplymentArtifact = resource.getDeploymentArtifacts();
- List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete = new ArrayList<ArtifactDefinition>();
- if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
- for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
- createdDeplymentArtifactsAfterDelete.add(entry.getValue());
- }
- }
- int labelCounter = createdDeplymentArtifactsAfterDelete.size();
-
- if (deplymentArtifact == null || deplymentArtifact.isEmpty()) {
- if (groups != null && !groups.isEmpty()) {
- for (GroupDefinition group : groups) {
- if (group.getArtifacts() != null && !group.getArtifacts().isEmpty()) {
- log.debug("failed to update artifacts from csar. List of emty but group not empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
- }
- }
- }
- return createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
- }
-
- // find master in group
- Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deplymentArtifact);
-
- ////////////////////////////////////// create set parsed
- ////////////////////////////////////// artifacts///////////////////////////////////////////
- Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
-
- Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>();
- List<ArtifactTemplateInfo> artifactsWithoutGroups = null;
- if(parsedArtifactsMap.containsKey(ArtifactTemplateInfo.CSAR_ARTIFACT)){
- artifactsWithoutGroups = parsedArtifactsMap.get(ArtifactTemplateInfo.CSAR_ARTIFACT);
- parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT);
- }
- Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
- for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
-
- for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
- if(parsedGroupTemplate.getGroupName() != null){
- parsedGroupTemplate.setGroupName("");
- Set<ArtifactTemplateInfo> parsedArtifactsNames = new HashSet<ArtifactTemplateInfo>();
- parsedArtifactsNames.add(parsedGroupTemplate);
- List<ArtifactTemplateInfo> relatedGroupTemplateList = parsedGroupTemplate.getRelatedArtifactsInfo();
- if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
- createArtifactsGroupSet(parsedGroupTemplateList, parsedArtifactsNames);
- }
- parsedGroup.put(parsedGroupTemplate, parsedArtifactsNames);
- }else{
- List<ArtifactTemplateInfo> arrtifacts = new ArrayList<ArtifactTemplateInfo>();
- arrtifacts.add(parsedGroupTemplate);
- Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
-
- }
- }
-
- }
-
- ///////////////////////////////// find artifacts to
- ///////////////////////////////// delete////////////////////////////////////////////////////
-
- Set<ArtifactDefinition> artifactsToDelete = new HashSet<ArtifactDefinition>();
- Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<String, List<ArtifactDefinition>>();
-
- Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
- Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
-
- // Set<String> deletedArtifactsName = new HashSet<String>();
- Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
- if (deletedArtifactsEither.isRight()) {
- log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
-
- return Either.right(deletedArtifactsEither.right().value());
-
- }
- List<ArtifactDefinition> deletedArtifacts = deletedArtifactsEither.left().value();
-
- // need to update resource if we updated artifacts
- if (deletedArtifacts != null && !deletedArtifacts.isEmpty()) {
- for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
- ArtifactDefinition artToRemove = null;
- for (ArtifactDefinition artFromResource : createdDeplymentArtifactsAfterDelete) {
- if (deletedArtifact.getUniqueId().equalsIgnoreCase(artFromResource.getUniqueId())) {
- artToRemove = artFromResource;
- break;
- }
- }
- if (artToRemove != null)
- createdDeplymentArtifactsAfterDelete.remove(artToRemove);
-
- }
- }
-
- ////////////// dissociate, associate or create
- ////////////// artifacts////////////////////////////
- Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
- mergedgroup, deletedArtifacts);
- groups = resource.getGroups();
- if (assDissotiateEither.isRight()) {
- log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
-
- return Either.right(assDissotiateEither.right().value());
-
- }
- resource = assDissotiateEither.left().value();
- deplymentArtifact = resource.getDeploymentArtifacts();
- createdDeplymentArtifactsAfterDelete.clear();
- if (deplymentArtifact != null && !deplymentArtifact.isEmpty()) {
- for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
- createdDeplymentArtifactsAfterDelete.add(entry.getValue());
- }
- }
-
-
-
- // update vfModule names
- Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
- if (groups != null && !groups.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic.validateUpdateVfGroupNamesOnGraph(groups, resource, inTransaction);
- if (validateUpdateVfGroupNamesRes.isRight()) {
- return Either.right(validateUpdateVfGroupNamesRes.right().value());
- }
- List<GroupDefinition> heatGroups = null;
-
- heatGroups = groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
- ;
-
- for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
-
- if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
- updatedGroupDef.getMembers().clear();
- }
- Map<String, String> members = new HashMap<String, String>();
- Set<String> artifactsGroup = new HashSet<String>();
- artifactsGroup.addAll(updatedGroupDef.getArtifacts());
- associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
- if (!members.isEmpty()) {
- updatedGroupDef.setMembers(members);
-
- }
-
-
- }
-
-
- }
-
- //////////////// create new artifacts in update
- //////////////// flow////////////////////////////
- List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<ArtifactTemplateInfo>();
-
- for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
- ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
- boolean isNewGroup = true;
- for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
- Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
- Set<ArtifactDefinition> group = groupArtifacts.keySet();
- for (ArtifactDefinition artifactInfo : group) {
- if (parsedArtifactMaster.getFileName().equalsIgnoreCase(artifactInfo.getArtifactName())) {
- parsedArtifactMaster.setGroupName(groupListEntry.getKey().getName());
- isNewGroup = false;
- }
- }
- }
- if (isNewGroup)
- newArtifactsGroup.add(parsedArtifactMaster);
-
- }
- if (!newArtifactsGroup.isEmpty()) {
- Collections.sort(newArtifactsGroup, (art1, art2) -> ArtifactTemplateInfo.compareByGroupName(art1, art2));
- int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
- Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(newArtifactsGroup, resource.getSystemName(), startGroupCounter);
- if (validateGroupNamesRes.isRight()) {
- return Either.right(validateGroupNamesRes.right().value());
- }
- Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
- }
-
- // updatedGroup
- if (!groupForAssociateWithMembers.isEmpty()) {
-
- List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().map(e -> e).collect(Collectors.toList());
-
- Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(resource, ComponentTypeEnum.RESOURCE, groupsId);
- if (updateVersionEither.isRight()) {
- log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
-
- return Either.right(updateVersionEither.right().value());
-
- }
- }
- if(artifactsWithoutGroups != null && !artifactsWithoutGroups.isEmpty()){
- for(ArtifactTemplateInfo t: artifactsWithoutGroups){
- List<ArtifactTemplateInfo> arrtifacts = new ArrayList<ArtifactTemplateInfo>();
- arrtifacts.add(t);
- Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
- };
- }
-
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
- return Either.left(eitherGerResource.left().value());
-
- }
-
- private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
- Map<String, List<ArtifactDefinition>> groupToDelete) {
- List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
- String resourceId = resource.getUniqueId();
- if (!artifactsToDelete.isEmpty()) {
- for (ArtifactDefinition artifact : artifactsToDelete) {
- String artifactType = artifact.getArtifactType();
- ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
- if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
- null, null, shouldLock, inTransaction);
- if (handleDelete.isRight()) {
- return Either.right(handleDelete.right().value());
- }
-
- deletedArtifacts.add(handleDelete.left().value().left().value());
- }
-
- }
- }
- if (!groupToDelete.isEmpty()) {
- log.debug("try to delete group");
- List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
- List<GroupDefinition> groups = resource.getGroups();
- for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
- Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
- if (op.isPresent()) {
- groupDefinitionstoDelete.add(op.get());
- }
-
- }
- if (!groupDefinitionstoDelete.isEmpty()) {
- Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, user, ComponentTypeEnum.RESOURCE, groupDefinitionstoDelete);
- if (prepareGroups.isRight()) {
- return Either.right(prepareGroups.right().value());
- }
- }
- }
- return Either.left(deletedArtifacts);
- }
-
- private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
- boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
- Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
- Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
- Either<Resource, ResponseFormat> resEither = Either.left(resource);
- for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
- List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
- GroupDefinition grDef = entry.getKey();
- if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
- for (ArtifactDefinition art : dissArtifactsInGroup) {
- grDef.getArtifacts().remove(art.getUniqueId());
- grDef.getArtifactsUuid().remove(art.getArtifactUUID());
- }
- }
-
- List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
- if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
- artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
-
- List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
- if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
- artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
- }
-
- if (!artifactsToUpdateMap.isEmpty()) {
- List<ArtifactDefinition> updatedArtifacts = new ArrayList<ArtifactDefinition>();
- for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
- List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
- GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
-
- for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
- String prevUUID = artifact.getKey().getArtifactUUID();
- String prevId = artifact.getKey().getUniqueId();
- String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey());
- Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
- artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
- if (updateArtifactEither.isRight()) {
- log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
- resEither = Either.right(updateArtifactEither.right().value());
- return resEither;
- }
- ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
- if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
- groupToUpdate.getArtifacts().remove(prevId);
- groupToUpdate.getArtifactsUuid().remove(prevUUID);
- groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
- groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
- }
- Optional<ArtifactDefinition> op = updatedArtifacts.stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())).findAny();
- if (op.isPresent()) {
- ArtifactDefinition artifactInfoHeatEnv = op.get();
- groupToUpdate.getArtifacts().remove(prevHeatEnvId);
- groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId());
- }
-
- }
- }
- }
-
- for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
- List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
- Set<String> arifactsUids = new HashSet<String>();
- Set<String> arifactsUuids = new HashSet<String>();
- for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
- // to
- // find
- // artifact
- // in
- // resource
- boolean isCreate = true;
- for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
- if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
- arifactsUids.add(createdArtifact.getUniqueId());
- arifactsUuids.add(createdArtifact.getArtifactUUID());
- isCreate = false;
- String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
- if (!heatEnvId.isEmpty()) {
- arifactsUids.add(heatEnvId);
- Optional<ArtifactDefinition> op = createdDeplymentArtifactsAfterDelete.stream().filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
- if (op.isPresent()) {
- this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource.getUniqueId(), resource.getComponentType().getNodeType());
-
- }
- }
-
- break;
- }
-
- }
- if (isCreate) { // check if already created
- for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
- if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
- arifactsUids.add(createdNewArtifact.getUniqueId());
- arifactsUuids.add(createdNewArtifact.getArtifactUUID());
- isCreate = false;
- String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
- if (!heatEnvId.isEmpty()) {
- arifactsUids.add(heatEnvId);
- }
- break;
- }
- }
- }
-
- if (isCreate) {
- Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
- if (createArtifactEither.isRight()) {
- resEither = Either.right(createArtifactEither.right().value());
- return resEither;
- }
- ArtifactDefinition createdArtifact = createArtifactEither.left().value();
- arifactsUids.add(createdArtifact.getUniqueId());
- arifactsUuids.add(createdArtifact.getArtifactUUID());
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
- if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
- Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
- resource.getName(), csarInfo.getModifier(), resource, null);
- if (createHeatEnvPlaceHolder.isRight()) {
- return Either.right(createHeatEnvPlaceHolder.right().value());
- }
- String heatEnvId = createHeatEnvPlaceHolder.left().value().getUniqueId();
- arifactsUids.add(heatEnvId);
- }
- }
-
- }
- if (arifactsUids.size() > 0) {
- List<String> artifactsToAssociate = new ArrayList<String>();
- artifactsToAssociate.addAll(arifactsUids);
- GroupDefinition assotiateGroup = associateEntry.getKey();
- assotiateGroup.getArtifacts().addAll(arifactsUids);
- assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
- }
- }
-
-
-
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreUsers(false);
- parametersView.setIgnoreArtifacts(false);
- parametersView.setIgnoreGroups(false);
-
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
-
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- resEither = Either.right(responseFormat);
- return resEither;
-
- }
- resEither = Either.left(eitherGerResource.left().value());
- return resEither;
- }
-
- private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
- Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
- Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
- for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
- Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
- boolean isNeedToDeleteGroup = true;
- List<ArtifactDefinition> listToDelete = null;
- for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
- listToDelete = createdArtifactMap.get(maserArtifact);
- for (ArtifactDefinition artToDelete : listToDelete) {
- findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
- }
- if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
- GroupDefinition group = groupListEntry.getKey();
- for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
- if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
- group.getArtifacts().remove(artifactDefinition.getUniqueId());
-
- }
- if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
- group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
-
- }
- }
-
- }
-
- for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
- if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
- MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
- mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
- mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
- mergedgroup.put(groupListEntry.getKey(), mergedGroup);
- isNeedToDeleteGroup = false;
-
- }
- }
-
- }
- if (isNeedToDeleteGroup) {
- groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
- }
-
- }
- return mergedgroup;
- }
-
- private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
- List<ArtifactDefinition> createdDeplymentArtifacts) {
- boolean isNeedToDeleteArtifact = true;
- String artifactType = artifact.getArtifactType();
- ArtifactDefinition generatedFromArt = null;
- if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
- Optional<ArtifactDefinition> op = createdDeplymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
- if (op.isPresent())
- generatedFromArt = op.get();
-
- }
-
- for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
- Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
- for (ArtifactTemplateInfo template : artifactsNames) {
- if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
- isNeedToDeleteArtifact = false;
- break;
-
- } else {
- if (generatedFromArt != null) {
- if (generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
- isNeedToDeleteArtifact = false;
- break;
- }
- }
- }
- }
-
- }
- if (isNeedToDeleteArtifact) {
- artifactsToDelete.add(artifact);
-
- }
- }
-
- private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups, Map<String, ArtifactDefinition> deplymentArtifact) {
- Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>>();
-
- for (GroupDefinition group : groups) {
- Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<ArtifactDefinition, List<ArtifactDefinition>>();
- List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
- List<String> artifactsList = group.getArtifacts();
- if (artifactsList != null && !artifactsList.isEmpty()) {
-
- ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deplymentArtifact, artifacts, artifactsList);
- if (masterArtifact != null)
- gupsMap.put(masterArtifact, artifacts);
- groupArtifact.put(group, gupsMap);
-
- }
- }
- return groupArtifact;
- }
-
- private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
-
- for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
- parsedArtifactsName.add(parsedGroupTemplate);
- List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
- if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
- createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
- }
- }
- }
-
- public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
- boolean shouldLock, boolean inTransaction) {
-
- log.debug("parseResourceArtifactsInfoFromFile start");
- Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, csarInfo.getModifier());
- if (parseResourceInfoFromYamlEither.isRight()) {
- ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
- }
- log.debug("parseResourceArtifactsInfoFromFile end");
-
- log.debug("createResourceArtifacts start");
- Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
- if (respStatus.isRight()) {
- return respStatus;
- }
- log.debug("createResourceArtifacts end");
- log.debug("getResource start");
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- log.debug("getResource end");
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
- return Either.left(eitherGerResource.left().value());
-
- }
-
- private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
- List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
- Either<Resource, ResponseFormat> resStatus = Either.left(resource);
- List<GroupDefinition> createdGroups = resource.getGroups();
- List<GroupDefinition> heatGroups = null;
- if (createdGroups != null && !createdGroups.isEmpty()) {
- heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
- }
-
- List<GroupDefinition> needToAdd = new ArrayList<>();
- for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
- String groupName = groupTemplateInfo.getGroupName();
- Set<String> artifactsGroup = new HashSet<String>();
- Set<String> artifactsUUIDGroup = new HashSet<String>();
-
- resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
- if(groupName != null && !groupName.isEmpty()){
- Map<String, String> members = new HashMap<String, String>();
- associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
-
- List<String> artifactsList = new ArrayList<String>(artifactsGroup);
- List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
-
- GroupDefinition groupDefinition = new GroupDefinition();
- groupDefinition.setName(groupName);
- groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
- groupDefinition.setArtifacts(artifactsList);
- groupDefinition.setArtifactsUuid(artifactsUUIDList);
-
- if (!members.isEmpty())
- groupDefinition.setMembers(members);
-
- List<GroupProperty> properties = new ArrayList<GroupProperty>();
- GroupProperty prop = new GroupProperty();
- prop.setName(Constants.IS_BASE);
- prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
- properties.add(prop);
-
- List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
- createdArtifacts.addAll(createdNewArtifacts);
- createdArtifacts.addAll(artifactsFromResource);
- Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
- if (getLatestGroupTypeRes.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
- }
- properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
- groupDefinition.convertFromGroupProperties(properties);
-
- needToAdd.add(groupDefinition);
- }
- }
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreArtifacts(false);
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreComponentInstances(false);
-
- Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
- if (component.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- resource = component.left().value();
-
- Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd);
- if (addGroups.isRight())
- return Either.right(addGroups.right().value());
-
- return resStatus;
- }
-
- private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
- ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
- Either<Resource, ResponseFormat> resStatus = Either.left(resource);
- String artifactFileName = artifactTemplateInfo.getFileName();
- String artifactUid = "";
- String artifactUUID = "";
- String artifactEnvUid = "";
- boolean alreadyExist = false;
-
- // check if artifacts already exist
- if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
- for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
- if (artifactFromResource.getArtifactName().equals(artifactFileName)) {
- artifactUid = artifactFromResource.getUniqueId();
- artifactUUID = artifactFromResource.getArtifactUUID();
- if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
- log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
- }
- alreadyExist = true;
- artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
- break;
- }
-
- }
-
- }
- if (!alreadyExist) {
- for (ArtifactDefinition createdArtifact : createdArtifacts) {
- if (createdArtifact.getArtifactName().equals(artifactFileName)) {
- artifactUid = createdArtifact.getUniqueId();
- artifactUUID = createdArtifact.getArtifactUUID();
-
- if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
- log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
- }
- alreadyExist = true;
- artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
- break;
- }
-
- }
- }
- // if not exist need to create
- if (!alreadyExist) {
-
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
- if (newArtifactEither.isRight()) {
- resStatus = Either.right(newArtifactEither.right().value());
- return resStatus;
- }
- ArtifactDefinition newArtifact = newArtifactEither.left().value();
- artifactUid = newArtifact.getUniqueId();
- artifactUUID = newArtifact.getArtifactUUID();
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
- if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
- Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
- resource.getName(), csarInfo.getModifier(), resource, null);
- if (createHeatEnvPlaceHolder.isRight()) {
- return Either.right(createHeatEnvPlaceHolder.right().value());
- }
- artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
- }
- }
-
- artifactsGroup.add(artifactUid);
- artifactsUUIDGroup.add(artifactUUID);
- if (!artifactEnvUid.isEmpty()) {
- artifactsGroup.add(artifactEnvUid);
- }
-
- List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
- if (relatedArtifacts != null) {
- for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
- }
- }
- return resStatus;
- }
-
- private Either<Resource, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
- List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
-
- Either<Resource, ResponseFormat> resStatus = Either.left(resource);
-
- Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
-
- for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
- if (groupTemplateList != null) {
- resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
- }
- }
-
- return resStatus;
-
- }
-
- private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) {
-
- Either<Resource, ResponseFormat> resStatus = null;
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
-
- try {
- List<NonMetaArtifactInfo> artifactPathAndNameList =
- // Stream of file paths contained in csar
- csarInfo.getCsar().entrySet().stream()
- // Filter in only VF artifact path location
- .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
- // Validate and add warnings
- .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
- // Filter in Non Warnings
- .filter(e -> e.isLeft())
- // Convert from Either to NonMetaArtifactInfo
- .map(e -> e.left().value())
- // collect to List
- .collect(Collectors.toList());
-
- Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
- if (responseFormatEither.isRight()) {
- return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
- }
-
-
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
-
- if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
- vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
- } else {
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, csarInfo.getModifier());
-
- if (findVfCsarArtifactsToHandleRes.isRight()) {
- resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
- }
- if (resStatus == null) {
- vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
- }
- }
- if (resStatus == null && vfCsarArtifactsToHandle != null) {
- for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
-
- Optional<ResponseFormat> optionalCreateInDBError =
- // Stream of artifacts to be created
- currArtifactOperationPair.getValue().stream()
- // create each artifact
- .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
- CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
- inTransaction))
- // filter in only error
- .filter(e -> e.isRight()).
- // Convert the error from either to ResponseFormat
- map(e -> e.right().value()).
- // Check if an error occurred
- findAny();
- // Error found on artifact Creation
- if (optionalCreateInDBError.isPresent()) {
- resStatus = Either.right(optionalCreateInDBError.get());
- break;
- }
- }
- }
- if (resStatus == null) {
- resStatus = Either.left(resource);
- }
- } catch (Exception e) {
- resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
- } finally {
- CsarUtils.handleWarningMessages(collectedWarningMessages);
- }
- return resStatus;
- }
-
- private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
- Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
- for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
- if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
- return Either.right(nonMetaArtifactInfo.getArtifactName());
- }
- }
- return Either.left(true);
- }
-
-
- private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
-
- List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
- // collect all Deployment and Informational artifacts of VF
- if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
- existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
- }
- if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
- existingArtifacts.addAll(resource.getArtifacts().values());
- }
- existingArtifacts = existingArtifacts.stream()
- // filter MANDATORY artifacts, LICENSE artifacts and artifacts was created from HEAT.meta
- .filter(this::isNonMetaArtifact).collect(Collectors.toList());
-
- List<String> artifactsToIgnore = new ArrayList<>();
- // collect IDs of Artifacts of VF which belongs to any group
- if (resource.getGroups() != null) {
- resource.getGroups().stream().forEach(g -> {
- if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
- artifactsToIgnore.addAll(g.getArtifacts());
- });
- }
- existingArtifacts = existingArtifacts.stream()
- // filter artifacts which belongs to any group
- .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
- return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
- }
-
- private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
- boolean result = true;
- if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
- result = false;
- }
- return result;
- }
-
- private boolean isValidArtifactType(ArtifactDefinition artifact) {
- boolean result = true;
- if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
- result = false;
- }
- return result;
- }
-
- private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
- int labelCounter, boolean shouldLock, boolean inTransaction) {
- Either<Resource, ResponseFormat> resStatus = Either.left(resource);
- List<GroupDefinition> createdGroups = resource.getGroups();
- List<GroupDefinition> heatGroups = null;
- if (createdGroups != null && !createdGroups.isEmpty()) {
-
- // List<IArtifactInfo> collect = resources.stream().flatMap( e ->
- // e.getArtifacts().stream()).filter(p ->
- // relevantArtifactTypes.contains(p.getArtifactType()
- // )).collect(Collectors.toList());
- // List<GroupDefinition> heatGroups = createdGroups.stream().filter(
- // e -> e.getProperties().stream().filter(p ->
- // p.getName().contains(Constants.HEAT_FILE_PROPS))).collect(Collectors.toList());
- heatGroups = createdGroups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
- ;
- }
- List<GroupDefinition> needToCreate = new ArrayList<>();
- for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
- String groupName = groupTemplateInfo.getGroupName();
- Set<String> artifactsGroup = new HashSet<String>();
- Set<String> artifactsUUIDGroup = new HashSet<String>();
-
- log.debug("createDeploymentArtifactsFromCsar start");
- resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
- log.debug("createDeploymentArtifactsFromCsar end");
- if (resStatus.isRight())
- return resStatus;
- if(groupName != null && !groupName.isEmpty()){
- Map<String, String> members = new HashMap<String, String>();
- associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
-
- List<String> artifactsList = new ArrayList<String>(artifactsGroup);
- List<String> artifactsUUIDList = new ArrayList<String>(artifactsUUIDGroup);
-
- GroupDefinition groupDefinition = new GroupDefinition();
- groupDefinition.setName(groupName);
- groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
- groupDefinition.setArtifacts(artifactsList);
- groupDefinition.setArtifactsUuid(artifactsUUIDList);
-
- if (!members.isEmpty())
- groupDefinition.setMembers(members);
- List<GroupProperty> properties = new ArrayList<GroupProperty>();
- GroupProperty prop = new GroupProperty();
- prop.setName(Constants.IS_BASE);
- prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
- properties.add(prop);
- Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation.getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
- if (getLatestGroupTypeRes.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
- }
- properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
- groupDefinition.convertFromGroupProperties(properties);
- log.debug("createGroup start");
-
- needToCreate.add(groupDefinition);
- }
- }
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreArtifacts(false);
- componentParametersView.setIgnoreGroups(false);
-
- componentParametersView.setIgnoreComponentInstances(false);
-
- Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(resource.getUniqueId(), componentParametersView);
- if (component.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), csarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right().value());
- }
-
- return resStatus;
- }
-
- public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup, GroupTypeDefinition groupType) {
- Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
- vfModuleProperties.entrySet().forEach(p -> {
- GroupProperty prop = new GroupProperty();
- prop.setName(p.getKey());
- if (isBase) {
- prop.setValue(p.getValue().getForBaseModule());
- prop.setDefaultValue(p.getValue().getForBaseModule());
- } else {
- prop.setValue(p.getValue().getForNonBaseModule());
- prop.setDefaultValue(p.getValue().getForNonBaseModule());
- }
- properties.add(prop);
-
- });
- GroupProperty proplabel = new GroupProperty();
- proplabel.setName("vf_module_label");
-
- Matcher matcher = pattern.matcher(moduleName);
-
- if (matcher.find()) {
- proplabel.setValue(matcher.group(1));
- proplabel.setDefaultValue(matcher.group(1));
- } else {
- proplabel.setValue(moduleName);
- proplabel.setDefaultValue(moduleName);
- }
- properties.add(proplabel);
-
- GroupProperty propvolume = new GroupProperty();
- propvolume.setName("volume_group");
- boolean isVolume = false;
- for (String artifactId : artifactsInGroup) {
- ArtifactDefinition artifactDef = null;
- artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
- if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
- isVolume = true;
- break;
- }
- }
- propvolume.setValue(String.valueOf(isVolume));
- propvolume.setDefaultValue(String.valueOf(isVolume));
- properties.add(propvolume);
- mergeWithGroupTypeProperties(properties, groupType.getProperties());
- return properties;
- }
-
- private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
-
- Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
- for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
- if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
- properties.add(new GroupProperty(groupTypeProperty));
- }
- }
- }
-
- private ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
- for (ArtifactDefinition artifact : createdArtifacts) {
- if (artifact.getUniqueId().equals(artifactId)) {
- return artifact;
- }
- }
- return null;
- }
-
- private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
- if (heatGroups != null && !heatGroups.isEmpty()) {
- for (GroupDefinition heatGroup : heatGroups) {
- List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
- if (grpoupProps != null) {
- Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
- if (op.isPresent()) {
- GroupProperty prop = op.get();
- String heatFileNAme = prop.getValue();
- if (null == heatFileNAme || heatFileNAme.isEmpty())
- continue;
- List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
- for (String artifactId : artifactsGroup) {
- Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
- if (opArt.isPresent()) {
- artifacts.add(opArt.get());
- }
- if (artifactsFromResource != null) {
- opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
- if (opArt.isPresent()) {
- artifacts.add(opArt.get());
- }
- }
- }
- Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
- if (resOp.isPresent()) {
- members.putAll(heatGroup.getMembers());
- }
- }
- }
- }
-
- }
- }
-
- private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
- ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
- Either<Resource, ResponseFormat> resStatus = Either.left(resource);
- String artifactFileName = artifactTemplateInfo.getFileName();
- String artifactUid = "";
- String artifactEnvUid = "";
- String artifactUUID = "";
- boolean alreadyExist = false;
-
- // check if artifacts already exist
- for (ArtifactDefinition createdArtifact : createdArtifacts) {
- if (createdArtifact.getArtifactName().equals(artifactFileName)) {
- artifactUid = createdArtifact.getUniqueId();
- artifactUUID = createdArtifact.getArtifactUUID();
- if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
- log.debug("Artifact with name {} and type {} already exist with type {}", artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
- }
- alreadyExist = true;
- artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
- break;
- }
- }
- // if not exist need to create
- if (!alreadyExist) {
-
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
- if (newArtifactEither.isRight()) {
- resStatus = Either.right(newArtifactEither.right().value());
- return resStatus;
- }
- ArtifactDefinition newArtifact = newArtifactEither.left().value();
- artifactUid = newArtifact.getUniqueId();
- artifactUUID = newArtifact.getArtifactUUID();
-
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
- if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
- Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
- resource.getName(), csarInfo.getModifier(), resource, null);
- if (createHeatEnvPlaceHolder.isRight()) {
- return Either.right(createHeatEnvPlaceHolder.right().value());
- }
- artifactEnvUid = createHeatEnvPlaceHolder.left().value().getUniqueId();
- }
- }
-
- artifactsGroup.add(artifactUid);
- artifactsUUIDGroup.add(artifactUUID);
- if (!artifactEnvUid.isEmpty()) {
- artifactsGroup.add(artifactEnvUid);
- }
-
- List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
- if (relatedArtifacts != null) {
- for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
- if (resStatus.isRight())
- return resStatus;
- }
- }
- return resStatus;
- }
-
- private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
- String artifactEnvUid = "";
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
- if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
- artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
- }
- return artifactEnvUid;
- }
-
- private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
- final String artifactFileName = artifactTemplateInfo.getFileName();
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
- if (artifactContententStatus.isRight()) {
- return Either.right(artifactContententStatus.right().value());
- }
- labelCounter += createdArtifacts.size();
-
- Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
- shoudLock, inTransaction);
-
- if (uploadArtifactToService.isRight())
- return Either.right(uploadArtifactToService.right().value());
-
- ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
- if (currentInfo.getHeatParameters() != null) {
-
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, false);
- if (updateEnvEither.isRight()) {
- log.debug("failed to update parameters to artifact {}", artifactFileName);
- return Either.right(updateEnvEither.right().value());
-
- }
- currentInfo = updateEnvEither.left().value();
-
- }
-
- createdArtifacts.add(currentInfo);
-
- return Either.left(currentInfo);
-
- }
-
- private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
-
- Either<ArtifactDefinition, ResponseFormat> resStatus = null;
- String artifactFileName = artifactTemplateInfo.getFileName();
-
- // check if artifacts already exist
- for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
- if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
- if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
- log.debug("Artifact with name {} and type {} already updated with type {}", artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName, artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
- return resStatus;
- }
- resStatus = Either.left(updatedArtifact);
- return resStatus;
- }
-
- }
-
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
- if (artifactContententStatus.isRight()) {
- resStatus = Either.right(artifactContententStatus.right().value());
- return resStatus;
- }
-
- Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
- oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
- shouldLock, inTransaction);
-
- if (uploadArtifactToService.isRight()) {
- resStatus = Either.right(uploadArtifactToService.right().value());
- return resStatus;
- }
- ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
- updatedArtifacts.add(currentInfo);
-
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo, true);
- if (updateEnvEither.isRight()) {
- log.debug("failed to update parameters to artifact {}", artifactFileName);
- resStatus = Either.right(updateEnvEither.right().value());
- return resStatus;
- }
- // TODO evg update env time ( must be separate US for this!!!!)
-
- updatedArtifacts.add(updateEnvEither.left().value());
- resStatus = Either.left(currentInfo);
-
- return resStatus;
-
- }
-
- private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, CsarInfo csarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
- Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
- if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
-
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
- componentsUtils);
- if (artifactparamsStatus.isRight()) {
- resStatus = Either.right(artifactparamsStatus.right().value());
- return resStatus;
- }
- Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(), artifactparamsStatus.left().value().getValue(), false);
-
- if (propsStatus.isLeft()) {
- List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
- List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
- // List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
-
- if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
-
- String paramName;
- for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
-
- paramName = heatEnvParam.getName();
- for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
- if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
- String updatedParamValue = heatEnvParam.getCurrentValue();
- if (updatedParamValue == null)
- updatedParamValue = heatEnvParam.getDefaultValue();
- HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
- if (!paramType.getValidator().isValid(updatedParamValue, null)) {
- ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
- resStatus = Either.right(responseFormat);
- return resStatus;
- }
- currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
- // newHeatEnvParams.add(currHeatParam);
- break;
- }
- }
- }
- currentInfo.setListHeatParameters(currentHeatEnvParams);
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(currentInfo, resource.getUniqueId(), currentInfo.getUniqueId(), null, null);
- if (updateArifactOnResource.isRight()) {
- log.debug("Failed to update heat paratemers of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
- }
- resStatus = Either.left(updateArifactOnResource.left().value());
- }
- }
- }
- if (isUpdateEnv) {
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreUsers(false);
- parametersView.setIgnoreArtifacts(false);
- parametersView.setIgnoreGroups(false);
-
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
-
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- resStatus = Either.right(responseFormat);
- return resStatus;
-
- }
- resource = eitherGerResource.left().value();
- Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
- Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
- if (op.isPresent()) {
- ArtifactDefinition artifactInfoHeatEnv = op.get();
- Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource = artifactToscaOperation.updateArifactOnResource(artifactInfoHeatEnv, resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), null, null);
- if (updateArifactOnResource.isRight()) {
- log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactOnResource.right().value())));
- }
- resStatus = Either.left(updateArifactOnResource.left().value());
- }
- }
- return resStatus;
- }
-
- private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content, boolean is64Encoded) {
- // extract heat parameters
- String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
- Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
- if (heatParameters.isRight()) {
- log.debug("File {} is not in expected key-value form in csar ", fileName);
- BeEcompErrorManager.getInstance().logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
-
- }
- return Either.left(heatParameters.left().value());
-
- }
-
- private Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent, int atrifactLabelCounter) {
-
- Map<String, Object> json = new HashMap<String, Object>();
- String artifactName = artifactTemplateInfo.getFileName();
-
- json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
- json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
- json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
-
- // DE250204: There is no need to check if base64 encoding.
-
- // String encodedPayload = new String(artifactContentent);
- // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
- // if (!isEncoded) {
- String encodedPayload = Base64.encodeBase64String(artifactContentent);
- // }
- json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
- String displayName = artifactName;
- if (artifactName.lastIndexOf(".") > 0)
- displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
- json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
- String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
- json.put(Constants.ARTIFACT_LABEL, label);
- json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
- List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
- json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
- : requiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
- return json;
- }
-
- private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
- List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
-
- Map<String, Object> json = new HashMap<String, Object>();
- if (artifactId != null && !artifactId.isEmpty())
- json.put(Constants.ARTIFACT_ID, artifactId);
-
- json.put(Constants.ARTIFACT_NAME, artifactName);
- json.put(Constants.ARTIFACT_TYPE, artifactType);
- json.put(Constants.ARTIFACT_DESCRIPTION, description);
-
- String encodedPayload = new String(artifactContentent);
-
- // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
- // if (!isEncoded) {
- log.debug("payload is encoded. perform decode");
- encodedPayload = Base64.encodeBase64String(artifactContentent);
- // }
-
- json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
- json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
- json.put(Constants.ARTIFACT_LABEL, label);
- json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
- json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
- : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
- return json;
- }
-
- @SuppressWarnings({ "unchecked", "static-access" })
- private Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Resource resource, String artifactsMetaFile, String artifactFileName, User user) {
-
- try {
- JsonObject jsonElement = new JsonObject();
- jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
-
- JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
- if (importStructureElement == null || importStructureElement.isJsonNull()) {
- log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
- }
-
- Map<String, List<Map<String, Object>>> artifactTemplateMap = new HashMap<String, List<Map<String, Object>>>();
- artifactTemplateMap = componentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
- if (artifactTemplateMap.isEmpty()) {
- log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected formatr, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
- }
-
- Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
- Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<String, List<ArtifactTemplateInfo>>();
- List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
- for (String artifactsTypeKey : artifactsTypeKeys) {
-
- List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
- Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
- if (artifactTemplateInfoListPairStatus.isRight()) {
- log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(artifactTemplateInfoListPairStatus.right().value());
- }
- List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
- if (artifactTemplateInfoList == null) {
- log.debug("Artifact file is not in expected formatr, fileName {}", artifactFileName);
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
-
- }
- if(!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT))
- allGroups.addAll(artifactTemplateInfoList);
- artifactsMap.put(artifactsTypeKey, artifactTemplateInfoList);
- }
- int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
- Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic.validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
- if (validateGroupNamesRes.isRight()) {
- return Either.right(validateGroupNamesRes.right().value());
- }
- return Either.left(artifactsMap);
- } catch (Exception e) {
- log.debug("Artifact file is not in expected format, fileName {}", artifactFileName);
- log.debug("failed with exception.", e);
- BeEcompErrorManager.getInstance().logInternalDataError("Artifact file is not in expected format, fileName " + artifactFileName, "Artifact internals are invalid", ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
- }
-
- }
-
- private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey, List<Map<String, Object>> jsonObject) {
- List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<ArtifactTemplateInfo>();
- for (Map<String, Object> o : jsonObject) {
- Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
- if (artifacttemplateInfoStatus.isRight()) {
- return Either.right(artifacttemplateInfoStatus.right().value());
- }
-
- ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
- if (artifacttemplateInfo != null) {
- artifactTemplateInfoList.add(artifacttemplateInfo);
- }
-
- }
- return Either.left(artifactTemplateInfoList);
- }
-
- private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
- log.debug("createResourceInstancesRelations try to create relations ");
- List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
- if (uploadResInstancesMap == null) {
- log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
- BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}", yamlName, ErrorSeverity.ERROR);
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
-
- if (componentInstancesList == null || componentInstancesList.isEmpty()) {
- log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
-
- log.debug("Before validateAndUpdatePropertyValue");
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
-
- }
-
- Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
- Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
- Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
- Map<String, Resource> originCompMap = new HashMap<>();
- List<RequirementCapabilityRelDef> relations = new ArrayList<>();
-
- Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
- for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
- log.trace("Processing entry: {}", entry);
- UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
- ComponentInstance currentCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- log.trace("Processing component instance: {}", compInstance);
- if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
- currentCompInstance = compInstance;
- break;
- }
-
- }
- if (currentCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
- String resourceInstanceId = currentCompInstance.getUniqueId();
- Resource originResource;
- if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
- Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade.getToscaFullElement(currentCompInstance.getComponentUid());
- if (getOriginResourceRes.isRight()) {
- log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(), getOriginResourceRes);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
- return Either.right(responseFormat);
- }
- originResource = getOriginResourceRes.left().value();
- originCompMap.put(originResource.getUniqueId(), originResource);
- } else {
- originResource = originCompMap.get(currentCompInstance.getComponentUid());
- }
- if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
- instRequirements.put(currentCompInstance, originResource.getRequirements());
- if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
- Map<String, List<CapabilityDefinition>> originCapabilities ;
- if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
- originCapabilities = new HashMap<>();
- originResource.getCapabilities().entrySet().stream().forEach(e ->{
- List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l)).collect(Collectors.toList());
- originCapabilities.put(e.getKey(), list);
- });
- Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
- for(List<UploadCapInfo> capabilities : uploadComponentInstanceInfo.getCapabilities().values()){
- for(UploadCapInfo capability :capabilities){
- if(CollectionUtils.isNotEmpty(capability.getProperties())){
- newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(Collectors.toMap(p->p.getName(), p->p)));
- }
- }
- }
- for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
- List<CapabilityDefinition> filteredCapabilities = capabilities.stream().filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList());
- for(CapabilityDefinition cap : filteredCapabilities){
- Either<Boolean, ResponseFormat> updateRes = updatePropertyValues(cap.getProperties(),newPropertiesMap.get(cap.getName()), allDataTypes.left().value());
- if(updateRes.isRight()){
- log.debug("Failed to update capability properties of capability {} . Status is {}. ", cap.getName(), updateRes.right().value());
- return Either.right(updateRes.right().value());
- }
- }
- }
- }
- else{
- originCapabilities = originResource.getCapabilities();
- }
- instCapabilties.put(currentCompInstance, originCapabilities);
- }
- if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
- instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
- if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
- instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
- if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
- instAttributes.put(resourceInstanceId, originResource.getAttributes());
- if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
- if (addPropertiesValueToRiRes.getStatus() != 200) {
- return Either.right(addPropertiesValueToRiRes);
- }
- } else {
- ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
- if (addInputValueToRiRes.getStatus() != 200) {
- return Either.right(addInputValueToRiRes);
- }
- }
- }
-
- Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
- if (addPropToInst.isRight()) {
- log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
- return Either.right(responseFormat);
- }
- if (instInputs != null && !instInputs.isEmpty()) {
- Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
- if (addInputToInst.isRight()) {
- log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
- return Either.right(responseFormat);
- }
- }
- StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
- }
-
- addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
- }
-
- addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements, resource.getUniqueId());
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
- }
-
- addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource.getUniqueId());
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
- }
-
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreComponentInstancesProperties(false);
- parametersView.setIgnoreCapabilities(false);
- parametersView.setIgnoreRequirements(false);
-
- Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
-
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
-
- resource = eitherGetResource.left().value();
-
- for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
- UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
- ComponentInstance currentCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
-
- if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
- currentCompInstance = compInstance;
- break;
- }
-
- }
- if (currentCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return Either.right(responseFormat);
- }
-
- ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
- if (addRelationToRiRes.getStatus() != 200) {
- return Either.right(addRelationToRiRes);
- }
- }
-
- addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
- if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
- log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), addArtToInst);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
- return Either.right(responseFormat);
- }
-
- if(resource.getResourceType() == ResourceTypeEnum.CVFC){
- eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
- return Either.right(responseFormat);
- }
- eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(), uploadResInstancesMap);
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
- return Either.right(responseFormat);
- }
- }
-
- log.debug("************* in create relations, getResource start");
- eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
- log.debug("************* in create relations, getResource end");
- if (eitherGetResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
- return Either.right(responseFormat);
- }
- return Either.left(eitherGetResource.left().value());
- }
-
- private Either<Boolean, ResponseFormat> updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
- for(ComponentInstanceProperty property : properties){
- Either<String, StorageOperationStatus> updateRes = updatePropertyValue(property ,newProperties.get(property.getName()), allDataTypes);
- if(updateRes.isRight()){
- log.debug("Failed to update capability property {} . Status is {}. ", property.getName(), updateRes.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value())));
- }
- }
- return Either.left(true);
- }
-
- private Either<String, StorageOperationStatus> updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, Map<String, DataTypeDefinition> allDataTypes) {
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- property.setValue(value);
- return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
- }
-
- private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
- Either<Resource, StorageOperationStatus> updateRes = null;
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
- Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
- StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements( resource.getUniqueId());
- if(status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND){
- log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", resource.getUniqueId(), status);
- updateRes = Either.right(status);
- }
- if(updateRes == null){
- fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities, updatedInstRequirements);
- status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource.getUniqueId());
- if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
- log.debug("Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}", resource.getUniqueId(), status);
- updateRes = Either.right(status);
- }
- }
- if(updateRes == null){
- updateRes = Either.left(resource);
- }
- return updateRes;
- }
-
-
- private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
- Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
-
- componentInstances.stream().forEach( i -> {
- fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
- fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
- });
- }
-
- private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements, ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
- Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
- Set<String> updatedReqNames = new HashSet<>();
- if(MapUtils.isNotEmpty(requirementsNamesToUpdate)){
- for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
- updatedRequirements.put(requirements.getKey(), requirements.getValue().stream()
- .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
- .map(r ->{r.setParentName(r.getName()); r.setName(requirementsNamesToUpdate.get(r.getName())); updatedReqNames.add(r.getName()); return r;})
- .collect(Collectors.toList()));
- }
- }
- if(MapUtils.isNotEmpty(updatedRequirements)){
- updatedInstRequirements.put(instance, updatedRequirements);
- }
- }
-
- private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties, ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
- Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
- Set<String> updatedCapNames = new HashSet<>();
- if(MapUtils.isNotEmpty(capabilitiesNamesToUpdate)){
- for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
- updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream()
- .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
- .map(c -> {c.setParentName(c.getName()); c.setName(capabilitiesNamesToUpdate.get(c.getName())); updatedCapNames.add(c.getName()); return c;})
- .collect(Collectors.toList()));
- }
- }
- if(MapUtils.isNotEmpty(updatedCapabilities)){
- updatedInstCapabilties.put(instance, updatedCapabilities);
- }
- }
-
- private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
- List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
-
- UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
-
- ComponentInstance currentCompInstance = null;
-
- for (ComponentInstance compInstance : componentInstancesList) {
-
- if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
- currentCompInstance = compInstance;
- break;
- }
-
- }
-
- if (currentCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return responseFormat;
- }
- String resourceInstanceId = currentCompInstance.getUniqueId();
-
- Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
-
- if (regMap != null) {
- Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
-
- while (nodesRegValue.hasNext()) {
- Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
-
- List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
- for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
- log.debug("Going to create relation {}", uploadRegInfo.getName());
- String regName = uploadRegInfo.getName();
- RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
- regCapRelDef.setFromNode(resourceInstanceId);
- log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
- if (eitherReqStatus.isRight()) {
- log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
- return eitherReqStatus.right().value();
- }
-
- RequirementDefinition validReq = eitherReqStatus.left().value();
- List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
- if (reqAndRelationshipPairList == null)
- reqAndRelationshipPairList = new ArrayList<>();
- RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
- reqAndRelationshipPair.setRequirement(regName);
- reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
- reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
- RelationshipImpl relationship = new RelationshipImpl();
- relationship.setType(validReq.getCapability());
- reqAndRelationshipPair.setRelationships(relationship);
-
- ComponentInstance currentCapCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- if (compInstance.getName().equals(uploadRegInfo.getNode())) {
- currentCapCompInstance = compInstance;
- break;
- }
- }
-
- if (currentCapCompInstance == null) {
- log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return responseFormat;
- }
- regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
- log.debug("try to find aviable Capability req name is {} ", validReq.getName());
- CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
- if (aviableCapForRel == null) {
- log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
- ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return responseFormat;
- }
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- capReqRel.setRelation(reqAndRelationshipPair);
- reqAndRelationshipPairList.add(capReqRel);
- regCapRelDef.setRelationships(reqAndRelationshipPairList);
- relations.add(regCapRelDef);
- }
- }
- } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
- return responseFormat;
- }
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
-
- private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
- Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
- Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
- if (propMap != null && propMap.size() > 0) {
- Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
-
- List<InputDefinition> listFromMap = originResource.getInputs();
- if (listFromMap == null || listFromMap.isEmpty()) {
- log.debug("failed to find properties ");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
- return responseFormat;
- }
- for (InputDefinition prop : listFromMap) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
- }
- List<ComponentInstanceInput> instPropList = new ArrayList<>();
- for (List<UploadPropInfo> propertyList : propMap.values()) {
-
- UploadPropInfo propertyInfo = propertyList.get(0);
- String propName = propertyInfo.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- log.debug("failed to find property {} ", propName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
- return responseFormat;
- }
- InputDefinition curPropertyDef = currPropertiesMap.get(propName);
- ComponentInstanceInput property = null;
-
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- String innerType = null;
- property = new ComponentInstanceInput(curPropertyDef, value, null);
-
- Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
- if (validatevalueEiter.isRight()) {
- return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
- }
-
- // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
- // property.setUniqueId(uniqueId);
- property.setValue(validatevalueEiter.left().value());
-
- if (getInputs != null && !getInputs.isEmpty()) {
- List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
- for (GetInputValueDataDefinition getInput : getInputs) {
- List<InputDefinition> inputs = resource.getInputs();
- if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
-
- Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInput.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition input = optional.get();
- getInput.setInputId(input.getUniqueId());
- getInputValues.add(getInput);
-
- GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
- if (getInputIndex != null) {
- optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInputIndex.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition inputIndex = optional.get();
- getInputIndex.setInputId(inputIndex.getUniqueId());
- getInputValues.add(getInputIndex);
- }
- }
- property.setGetInputValues(getInputValues);
- }
- instPropList.add(property);
- // delete overriden property
- currPropertiesMap.remove(property.getName());
- }
- // add rest of properties
- if (!currPropertiesMap.isEmpty()) {
- for (InputDefinition value : currPropertiesMap.values()) {
- instPropList.add(new ComponentInstanceInput(value));
- }
- }
- instInputs.put(currentCompInstance.getUniqueId(), instPropList);
- }
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
-
- private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
- Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
-
- Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
- Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
-
- List<PropertyDefinition> listFromMap = originResource.getProperties();
- if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
- log.debug("failed to find properties ");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
- return responseFormat;
- }
- if(listFromMap == null || listFromMap.isEmpty()){
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
- for (PropertyDefinition prop : listFromMap) {
- String propName = prop.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- currPropertiesMap.put(propName, prop);
- }
- }
- List<ComponentInstanceProperty> instPropList = new ArrayList<>();
- if (propMap != null && propMap.size() > 0) {
- for (List<UploadPropInfo> propertyList : propMap.values()) {
-
- UploadPropInfo propertyInfo = propertyList.get(0);
- String propName = propertyInfo.getName();
- if (!currPropertiesMap.containsKey(propName)) {
- log.debug("failed to find property {} ", propName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
- return responseFormat;
- }
- PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
- ComponentInstanceProperty property = null;
-
- String value = null;
- List<GetInputValueDataDefinition> getInputs = null;
- boolean isValidate = true;
- if (propertyInfo.getValue() != null) {
- getInputs = propertyInfo.getGet_input();
- isValidate = getInputs == null || getInputs.isEmpty();
- if (isValidate) {
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
- } else
- value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
- String innerType = null;
- property = new ComponentInstanceProperty(curPropertyDef, value, null);
-
- Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
- if (validatevalueEiter.isRight()) {
- return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
- }
-
- property.setValue(validatevalueEiter.left().value());
-
- if (getInputs != null && !getInputs.isEmpty()) {
- List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
- for (GetInputValueDataDefinition getInput : getInputs) {
- List<InputDefinition> inputs = resource.getInputs();
- if (inputs == null || inputs.isEmpty()) {
- log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
-
- Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInput.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition input = optional.get();
- getInput.setInputId(input.getUniqueId());
- getInputValues.add(getInput);
-
- GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
- if (getInputIndex != null) {
- optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
- if (!optional.isPresent()) {
- log.debug("Failed to find input {} ", getInputIndex.getInputName());
- // @@TODO error message
- return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- }
- InputDefinition inputIndex = optional.get();
- getInputIndex.setInputId(inputIndex.getUniqueId());
- getInputValues.add(getInputIndex);
-
- }
-
- }
- property.setGetInputValues(getInputValues);
- }
- instPropList.add(property);
- // delete overriden property
- currPropertiesMap.remove(property.getName());
- }
- }
- // add rest of properties
- if (!currPropertiesMap.isEmpty()) {
- for (PropertyDefinition value : currPropertiesMap.values()) {
- instPropList.add(new ComponentInstanceProperty(value));
- }
- }
- instProperties.put(currentCompInstance.getUniqueId(), instPropList);
- return componentsUtils.getResponseFormat(ActionStatus.OK);
- }
-
- // US740820 Relate RIs according to capability name
- private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
- if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
- // by
- // capability
- // type
- return findAviableCapability(validReq, currentCapCompInstance);
- }
- return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
- }
-
- private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
- CapabilityDefinition cap = null;
- Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
- if (!capMap.containsKey(validReq.getCapability())) {
- return null;
- }
- Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream().filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
- if (!capByName.isPresent()) {
- return null;
- }
- cap = capByName.get();
-
- if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = cap.getLeftOccurrences();
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- cap.setLeftOccurrences(String.valueOf(left));
-
- }
-
- }
- return cap;
- }
-
- private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
- CapabilityDefinition aviableCapForRel = null;
- Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
- if (capMap.containsKey(validReq.getCapability())) {
- List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
-
- for (CapabilityDefinition cap : capList) {
- if (cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = cap.getLeftOccurrences();
- if (leftOccurrences == null) {
- leftOccurrences = cap.getMaxOccurrences();
- }
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- cap.setLeftOccurrences(String.valueOf(left));
- aviableCapForRel = cap;
- break;
- } else {
- continue;
- }
- } else {
- aviableCapForRel = cap;
- break;
- }
- }
- }
- return aviableCapForRel;
- }
-
- private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, String capName) {
- Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
- List<RequirementDefinition> list = comInstRegDefMap.get(capName);
- RequirementDefinition validRegDef = null;
- if (list == null) {
- for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
- for (RequirementDefinition reqDef : entry.getValue()) {
- if (reqDef.getName().equals(regName)) {
- if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = reqDef.getLeftOccurrences();
- if (leftOccurrences == null) {
- leftOccurrences = reqDef.getMaxOccurrences();
- }
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- reqDef.setLeftOccurrences(String.valueOf(left));
- validRegDef = reqDef;
- break;
- } else {
- continue;
- }
- } else {
- validRegDef = reqDef;
- break;
- }
-
- }
- }
- if (validRegDef != null) {
- break;
- }
- }
- } else {
- for (RequirementDefinition reqDef : list) {
- if (reqDef.getName().equals(regName)) {
- if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- String leftOccurrences = reqDef.getLeftOccurrences();
- if (leftOccurrences == null) {
- leftOccurrences = reqDef.getMaxOccurrences();
- }
- int left = Integer.parseInt(leftOccurrences);
- if (left > 0) {
- --left;
- reqDef.setLeftOccurrences(String.valueOf(left));
- validRegDef = reqDef;
- break;
- } else {
- continue;
- }
- } else {
- validRegDef = reqDef;
- break;
- }
- }
- }
- }
- if (validRegDef == null) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- return Either.left(validRegDef);
- }
-
- @SuppressWarnings("unchecked")
- public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
-
- Map<String, Object> mappedToscaTemplate;
- if(nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)){
- mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
- }
- else {
- try {
- //DE154502 Fail if duplicate key found in file
- mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
-
- } catch(ParserException e) {
- log.error("Failed to load yaml file {}", yamlFileName, e);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage());
- return Either.right(responseFormat);
- }
- }
- Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
- if (toscaElementEither.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
- return Either.right(responseFormat);
- }
-
- Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName, mappedToscaTemplate, resource);
- if (createInputsEither.isRight()) {
- ResponseFormat responseFormat = createInputsEither.right().value();
- return Either.right(responseFormat);
- }
-
- Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
- if (uploadResInstancesEither.isRight()) {
- ResponseFormat responseFormat = uploadResInstancesEither.right().value();
- return Either.right(responseFormat);
- }
-
- Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName, mappedToscaTemplate, resource);
- if (createGroupsFromYaml.isRight()) {
- ResponseFormat responseFormat = createGroupsFromYaml.right().value();
- return Either.right(responseFormat);
- }
-
- ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
- parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
- parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
- parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
-
- return Either.left(parsedToscaYamlInfo);
- }
-
- private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
- Map<String, Resource> nodeNamespaceMap) {
-
- Either<Resource, ResponseFormat> eitherResource = null;
- log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
- if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
-
- return Either.right(responseFormat);
-
- }
- Map<String, Resource> existingnodeTypeMap = new HashMap<>();
- if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
- nodeNamespaceMap.entrySet().stream().forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
- }
-
- Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet().iterator();
- Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
- while (nodesInfoValue.hasNext()) {
- log.debug("*************Going to create resource instances {}", yamlName);
- Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
- UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
-
- // updating type if the type is node type name - we need to take the
- // updated name
- log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
- if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
- uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
- }
-
- eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
- if (eitherResource.isRight()) {
- return eitherResource;
- }
- Resource refResource = eitherResource.left().value();
-
- ComponentInstance componentInstance = new ComponentInstance();
-
- componentInstance.setComponentUid(refResource.getUniqueId());
-
- ComponentTypeEnum containerComponentType = resource.getComponentType();
- NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
-
- if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils.isNotEmpty(refResource.getCapabilities())) {
- setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
- Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
- if (getValidComponentInstanceCapabilitiesRes.isRight()) {
- return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
- } else {
- componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
- }
- }
- if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
- log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
- componentInstance.setName(uploadComponentInstanceInfo.getName());
- componentInstance.setIcon(origResource.getIcon());
-
- resourcesInstancesMap.put(componentInstance, origResource);
-
- }
- if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
-
- StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false);
- if (status != null && status != StorageOperationStatus.OK) {
- log.debug("Failed to add component instances to container component {}", resource.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status));
- eitherResource = Either.right(responseFormat);
- return eitherResource;
- }
-
- }
-
- log.debug("*************Going to get resource {}", resource.getUniqueId());
- ComponentParametersView parametersView = new ComponentParametersView();
- parametersView.disableAll();
- parametersView.setIgnoreComponentInstances(false);
- parametersView.setIgnoreUsers(false);
- parametersView.setIgnoreInputs(false); // inputs are read when creating
- // property values on instances
- Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
- log.debug("*************finished to get resource {}", resource.getUniqueId());
- if (eitherGerResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
-
- return Either.right(responseFormat);
-
- }
-
- if (eitherGerResource.left().value().getComponentInstances() == null || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
-
- log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource inctanse from csar. ComponentInstances list empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
- return Either.right(responseFormat);
-
- }
-
- return Either.left(eitherGerResource.left().value());
- }
-
- private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
- for(Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()){
- if(originCapabilities.containsKey(currEntry.getKey())){
- currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
- }
- }
- for(Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()){
- capabilities.getValue().stream().forEach(cap -> {if(uploadedCapabilities.containsKey(cap.getName())){uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {c.setName(cap.getName());c.setType(cap.getType());});};});
- }
-
- }
-
- private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
- log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- Resource refResource = null;
- if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
- refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
- } else {
- Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
- if (findResourceEither.isRight()) {
- log.debug("validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ", uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
- return Either.right(responseFormat);
- }
- refResource = findResourceEither.left().value();
- nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
- }
- String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
- if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
- log.debug("validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.", refResource.getName(), componentState);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
- return Either.right(responseFormat);
- }
-
- if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
- log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
- return Either.right(responseFormat);
- }
- return Either.left(refResource);
- }
-
- private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
- Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
- Map<String, Object> substitutionMappings = null;
- Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
- Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
- Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
- if (eitherSubstitutionMappings.isLeft()) {
- substitutionMappings = eitherSubstitutionMappings.left().value();
- }
- if (eitherNodesTemlates.isLeft()) {
- Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
-
- Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
- while (nodesNameValue.hasNext()) {
- Entry<String, Object> nodeNameValue = nodesNameValue.next();
- Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
- if (eitherNode.isRight()) {
- log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
- return Either.right(eitherNode.right().value());
- } else {
- UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
- moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
- }
-
- }
-
- }
- if (moduleComponentInstances.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
- return Either.right(responseFormat);
- }
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
-
- UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
- Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
- nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
- try {
- if (nodeTemplateJsonEntry.getValue() instanceof String) {
- String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
- nodeTemplateInfo.setType(nodeTemplateJsonString);
- } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
- // Type
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
- if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
- toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
- }
- nodeTemplateInfo.setType(toscaResourceType);
- }
-
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
- Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (regResponse.left().value().size() > 0) {
- nodeTemplateInfo.setRequirements(regResponse.left().value());
- }
- }
-
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
- Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(nodeTemplateInfo, nodeTemplateJsonMap);
- if (eitherCapRes.isRight())
- return Either.right(eitherCapRes.right().value());
- if (eitherCapRes.left().value().size() > 0) {
- nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
- }
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (regResponse.left().value().size() > 0) {
- nodeTemplateInfo.setProperties(regResponse.left().value());
- }
- }
- if (substitutionMappings != null) {
- if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
- Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
- if (getCapNamesToUpdateRes.isRight())
- return Either.right(getCapNamesToUpdateRes.right().value());
- if (getCapNamesToUpdateRes.left().value().size() > 0) {
- nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
- }
- }
- if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
- Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
- if (getReqNamesToUpdateRes.isRight())
- return Either.right(getReqNamesToUpdateRes.right().value());
- if (getReqNamesToUpdateRes.left().value().size() > 0) {
- nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
- }
- }
- }
- } else {
-
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
-
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
- log.debug("error when creating capability, message:{}", e.getMessage(), e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- return result;
- }
-
- private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
- Either<Map<String, String>, ResponseFormat> response;
- try {
- Map<String, String> namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
- response = Either.left(namesToUpdate);
- } catch (Exception e) {
- log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
- response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return response;
- }
-
- @SuppressWarnings("unchecked")
- private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
- Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
- Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
- Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
- if (toscaProperties.isLeft()) {
- Map<String, Object> jsonProperties = toscaProperties.left().value();
- for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
- // Property
- String propName = jsonPropObj.getKey();
- Object propValue = jsonPropObj.getValue();
-
- if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
- if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
- log.trace("Ignore property value {}.", propName);
- continue;
- }
-
- UploadPropInfo propertyDef = new UploadPropInfo();
- propertyDef.setValue(propValue);
- propertyDef.setName(propName);
- if (propValue instanceof Map) {
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- propertyDef.setType(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
- }
-
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
- || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType()).contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
- createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
- }
-
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- propertyDef.setDescription(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
- }
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
- propertyDef.setValue(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
- }
- if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
- propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
- } else {
- propertyDef.setValue(propValue);
- }
- } else if (propValue instanceof List) {
- List<Object> propValueList = (List<Object>) propValue;
-
- createInputPropList(propertyDef, propValueList);
- propertyDef.setValue(propValue);
- }
-
- if (moduleProp.containsKey(propName)) {
- moduleProp.get(propName).add(propertyDef);
- } else {
- List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
- list.add(propertyDef);
- moduleProp.put(propName, list);
- }
- }
- }
- return response;
- }
-
- @SuppressWarnings("unchecked")
- private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
- for (Object objValue : propValueList) {
-
- if (objValue instanceof Map) {
- Map<String, Object> objMap = (Map<String, Object>) objValue;
- if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
- createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
- else {
- Set<String> keys = objMap.keySet();
- for (String key : keys) {
- Object value = objMap.get(key);
- if (value instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
-
- } else if (value instanceof List) {
- List<Object> propSubValueList = (List<Object>) value;
-
- createInputPropList(propertyDef, propSubValueList);
- }
-
- }
- }
-
- } else if (objValue instanceof List) {
- List<Object> propSubValueList = (List<Object>) objValue;
-
- createInputPropList(propertyDef, propSubValueList);
-
- }
-
- }
- }
-
- @SuppressWarnings("unchecked")
- private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
-
- if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
- Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
- List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
- if (getInputs == null) {
- getInputs = new ArrayList<GetInputValueDataDefinition>();
- }
- if (getInput instanceof String) {
-
- getInputInfo.setInputName((String) getInput);
- getInputInfo.setPropName(propName);
-
- } else if (getInput instanceof List) {
- List<Object> getInputList = (List<Object>) getInput;
- getInputInfo.setPropName(propName);
- getInputInfo.setInputName((String) getInputList.get(0));
- if (getInputList.size() > 1) {
- Object indexObj = getInputList.get(1);
- if (indexObj instanceof Integer) {
- getInputInfo.setIndexValue((Integer) indexObj);
- } else if (indexObj instanceof Float) {
- int index = ((Float) indexObj).intValue();
- getInputInfo.setIndexValue(index);
- } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
- Object index = ((Map<String, Object>) indexObj).get(ToscaTagNamesEnum.GET_INPUT.getElementName());
- GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
- getInputInfoIndex.setInputName((String) index);
- getInputInfoIndex.setPropName(propName);
- getInputInfo.setGetInputIndex(getInputInfoIndex);
- }
- getInputInfo.setList(true);
- }
-
- }
- getInputs.add(getInputInfo);
- propertyDef.setGet_input(getInputs);
- propertyDef.setValue(propValue);
- } else {
- Set<String> keys = propValue.keySet();
- for (String key : keys) {
- Object value = propValue.get(key);
- if (value instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
-
- } else if (value instanceof List) {
- List<Object> valueList = (List<Object>) value;
- for (Object o : valueList) {
- if (o instanceof Map) {
- createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
-
- }
- }
-
- }
-
- }
-
- }
- }
-
- /*
- * private boolean valueContainsStrReplace(Object propValue) {
- *
- * log.debug("valueContainsStrReplace value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsStrReplace value is {}", propValue.getClass()); Matcher matcher =
- * STR_REPLACE_PATTERN.matcher(propValue.toString()); result = matcher.find(); }
- *
- * return result; }
- *
- * private boolean valueContainsToken(Object propValue) {
- *
- * log.debug("valueContainsToken value is {}", propValue); boolean result = false; if (propValue != null) { log.debug("valueContainsToken value is {}", propValue.getClass()); Matcher matcher = TOKEN_PATTERN.matcher(propValue.toString()); result =
- * matcher.find(); }
- *
- * return result; }
- */
-
- private boolean valueContainsPattern(Pattern pattern, Object propValue) {
-
- log.debug("valueContainsToken value is {}", propValue);
- boolean result = false;
- if (propValue != null) {
- log.trace("valueContainspattern value is {}", propValue.getClass());
- Matcher matcher = pattern.matcher(propValue.toString());
- result = matcher.find();
- }
-
- return result;
-
- }
- @SuppressWarnings("unchecked")
- private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
- Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
- Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
- Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
-
- if (requirementsListRes.isLeft()) {
- for (Object jsonReqObj : requirementsListRes.left().value()) {
- String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
- Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
- Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- } else {
- Either<Map<String,Object>, ResultStatusEnum> requirementsMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
- if (requirementsMapRes.isLeft()) {
- for (Map.Entry<String, Object> entry: requirementsMapRes.left().value().entrySet()) {
- String reqName = entry.getKey();
- Object reqJson = entry.getValue();
- Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo, moduleRequirements, reqJson, reqName);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- }
- }
- return response;
- }
-
- private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo,Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
-
- Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson);
- if (eitherRequirement.isRight()) {
- log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
- return Either.right(eitherRequirement.right().value());
- } else {
- UploadReqInfo requirementDef = eitherRequirement.left().value();
- requirementDef.setName(requirementName);
- if (moduleRequirements.containsKey(requirementName)) {
- moduleRequirements.get(requirementName).add(requirementDef);
- } else {
- List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
- list.add(requirementDef);
- moduleRequirements.put(requirementName, list);
- }
- }
- return Either.left(eitherRequirement.left().value());
- }
-
- @SuppressWarnings("unchecked")
- private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
- Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
- Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
- Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
- if (capabilitiesListRes.isLeft()) {
- for (Object jsonCapObj : capabilitiesListRes.left().value()) {
- String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
- Object capJson = ((Map<String, Object>) jsonCapObj).get(key);
- Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, key);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- } else {
- Either<Map<String,Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils.findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
- if (capabilitiesMapRes.isLeft()) {
- for (Map.Entry<String, Object> entry: capabilitiesMapRes.left().value().entrySet()) {
- String capName = entry.getKey();
- Object capJson = entry.getValue();
- Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap, capJson, capName);
- if (eitherCap.isRight()) {
- return Either.right(eitherCap.right().value());
- }
- }
- }
- }
- return response;
- }
-
- private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
-
- Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson);
- if (eitherCap.isRight()) {
- log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo);
- return Either.right(eitherCap.right().value());
- } else {
- UploadCapInfo capabilityDef = eitherCap.left().value();
- capabilityDef.setKey(key);
- if (moduleCap.containsKey(key)) {
- moduleCap.get(key).add(capabilityDef);
- } else {
- List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
- list.add(capabilityDef);
- moduleCap.put(key, list);
- }
- }
- return Either.left( eitherCap.left().value());
- }
-
- @SuppressWarnings("unchecked")
- private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
- UploadCapInfo capTemplateInfo = new UploadCapInfo();
- Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
-
- if (capObject instanceof String) {
- String nodeTemplateJsonString = (String) capObject;
- capTemplateInfo.setNode(nodeTemplateJsonString);
- } else if (capObject instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
- // Type
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
- capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
- Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils.findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
- if (validSourceTypesRes.isLeft()) {
- capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(o -> o.toString()).collect(Collectors.toList()));
- }
- }
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(nodeTemplateJsonMap);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (!regResponse.left().value().isEmpty()) {
- List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
- regResponse.left().value().values().forEach(list -> properties.addAll(list));
- if (!properties.isEmpty())
- capTemplateInfo.setProperties(properties);
- }
- }
- }
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
-
- UploadReqInfo regTemplateInfo = new UploadReqInfo();
- Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
-
- if (regObject instanceof String) {
- String nodeTemplateJsonString = (String) regObject;
- regTemplateInfo.setNode(nodeTemplateJsonString);
- } else if (regObject instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
- // Type
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
- regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
- }
- // US740820 Relate RIs according to capability name
- if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
- regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
- }
- }
- return result;
- }
-
- public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
-
- Either<Resource, ResponseFormat> result = null;
- try {
- if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())){
- result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
- if(result.isRight()){
- return result;
- }
- resource = result.left().value();
- }
- if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
- result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
- return result;
- }
- return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
- } catch (Exception e) {
- log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
- if (inTransaction == false) {
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- }
- } else if (inTransaction == false) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- }
-
- private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
- if (result.isLeft()) {
- result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
- }
- if (result.isLeft()) {
- result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
- }
- return result;
- }
-
- private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
- }
-
- /*
- * /**
- *
- * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
- */
- /*
- * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
- * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
- */
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock, CsarInfo csarInfo, String nodeName, boolean isNested) {
-
- // check if resource already exist
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
-
- // create
- if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
-
- Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
- if (csarInfo!= null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){
- latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
- // update
- if (latestByToscaName.isLeft()) {
- log.debug("validate derived before update");
- Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(latestByToscaName.left().value(), resource, ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion()));
- if (eitherValidation.isRight()) {
- result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- } else {
- result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user, isNormative, needLock, isNested);
- }
- }
- }
- if (result == null && latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)){
- result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
- } else if (result == null){
- StorageOperationStatus status = latestByName.right().value();
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- log.debug("resource already exist {}. status={}", resource.getName(), status);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- result = Either.right(responseFormat);
- }
-
- }
-
- // update
- else if (latestByName.isLeft()) {
- result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock, isNested);
- }
-
- // error
- else {
- StorageOperationStatus status = latestByName.right().value();
- log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- result = Either.right(responseFormat);
- }
- return result;
-
- }
-
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
- log.debug("resource with name {} does not exist. create new resource", resource.getName());
- Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
- if (response.isRight()) {
- return Either.right(response.right().value());
- }
- Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
- if (createResponse.isRight()) {
- return Either.right(createResponse.right().value());
- } else {
- ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
- ASDCKpiApi.countImportResourcesKPI();
- return Either.left(resourcePair);
-
- }
- }
-
- public boolean isResourceExist(String resourceName) {
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
- return latestByName.isLeft();
- }
-
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
- String lockedResourceId = oldResource.getUniqueId();
- log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(), oldResource.getLifecycleState());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
- try {
- if (needLock) {
- Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource, "Update Resource by Import");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
- }
- }
-
- Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user, inTransaction, false);
- if (prepareResourceForUpdate.isRight()) {
- ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
- log.info("resource {} cannot be updated. reason={}", lockedResourceId, responseFormat.getFormattedMessage());
- componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
- result = Either.right(prepareResourceForUpdate.right().value());
- return result;
- }
- oldResource = prepareResourceForUpdate.left().value();
-
- mergeOldResourceMetadataWithNew(oldResource, newResource);
-
- Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
- if (validateFieldsResponse.isRight()) {
- result = Either.right(validateFieldsResponse.right().value());
- return result;
- }
-
- validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
- if (validateFieldsResponse.isRight()) {
- return Either.right(validateFieldsResponse.right().value());
- }
-
- // contact info normalization
- newResource.setContactId(newResource.getContactId().toLowerCase());
- // non-updatable fields
- newResource.setCreatorUserId(user.getUserId());
- newResource.setCreatorFullName(user.getFullName());
- newResource.setLastUpdaterUserId(user.getUserId());
- newResource.setLastUpdaterFullName(user.getFullName());
- newResource.setUniqueId(oldResource.getUniqueId());
- newResource.setVersion(oldResource.getVersion());
- newResource.setInvariantUUID(oldResource.getInvariantUUID());
- newResource.setLifecycleState(oldResource.getLifecycleState());
- newResource.setUUID(oldResource.getUUID());
- newResource.setNormalizedName(oldResource.getNormalizedName());
- newResource.setSystemName(oldResource.getSystemName());
- if (oldResource.getCsarUUID() != null) {
- newResource.setCsarUUID(oldResource.getCsarUUID());
- }
- if (oldResource.getImportedToscaChecksum() != null) {
- newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
- }
- newResource.setAbstract(oldResource.isAbstract());
-
- if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
- newResource.setDerivedFrom(oldResource.getDerivedFrom());
- }
- // TODO rhalili: handle artifacts here (delete from old resource and
- // add for new)
- // TODO rbetzer: remove after migration - in case of resources
- // created without tosca artifacts - add the placeholders
- if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
- setToscaArtifactsPlaceHolders(newResource, user);
- }
- Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
-
- if (overrideResource.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
- componentsUtils.auditResource(responseFormat, user, newResource, newResource.getLifecycleState().name(), newResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
- result = Either.right(responseFormat);
- return result;
- }
-
- log.debug("Resource updated successfully!!!");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- componentsUtils.auditResource(responseFormat, user, newResource, oldResource.getLifecycleState().name(), oldResource.getVersion(), AuditingActionEnum.IMPORT_RESOURCE, null);
-
- ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
- result = Either.left(resourcePair);
- return result;
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- } else if (inTransaction == false) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- if (needLock == true) {
- log.debug("unlock resource {}", lockedResourceId);
- graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
- }
- }
-
- }
-
- /**
- * Merge old resource with new. Keep old category and vendor name without change
- *
- * @param oldResource
- * @param newResource
- */
- private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
-
- // keep old category and vendor name without change
- // merge the rest of the resource metadata
- if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
- newResource.setTags(oldResource.getTags());
- }
-
- if (newResource.getDescription() == null) {
- newResource.setDescription(oldResource.getDescription());
- }
-
- if (newResource.getVendorRelease() == null) {
- newResource.setVendorRelease(oldResource.getVendorRelease());
- }
-
- if (newResource.getResourceVendorModelNumber() == null) {
- newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
- }
-
- if (newResource.getContactId() == null) {
- newResource.setContactId(oldResource.getContactId());
- }
-
- newResource.setCategories(oldResource.getCategories());
- newResource.setVendorName(oldResource.getVendorName());
- }
-
- private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user, boolean inTransaction, boolean needLock) {
-
- Either<Resource, ResponseFormat> result = Either.left(latestResource);
- // check if user can edit resource
- if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
- // checkout
- Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
- result = changeState;
- }
-
- return result;
- }
-
- public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
-
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
-
- eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
- eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
- eitherValidation = validateResourceType(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
-
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setContactId(resource.getContactId().toLowerCase());
- if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
- String resourceSystemName;
- if(csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())){
- resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
- } else {
- resourceSystemName = resource.getSystemName();
- }
- resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
- }
-
- // Generate invariant UUID - must be here and not in operation since it
- // should stay constant during clone
- // TODO
- String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
- resource.setInvariantUUID(invariantUUID);
-
- return Either.left(resource);
- }
-
- private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (resource.getResourceType() == null) {
- log.debug("Invalid resource type for resource");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
- log.debug("validate interface lifecycle Types Exist");
- Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
- while (intItr.hasNext() && eitherResult.isLeft()) {
- InterfaceDefinition interfaceDefinition = intItr.next();
- String intType = interfaceDefinition.getUniqueId();
- Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
- if (eitherCapTypeFound.isRight()) {
- if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
- log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
- log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
- }
-
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
- }
-
- }
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
-
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
- log.debug("validate capability Types Exist - capabilities section");
-
- for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
-
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry, inTransaction);
- if (eitherResult.isRight()) {
- return Either.right(eitherResult.right().value());
- }
- }
- }
-
- if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
- log.debug("validate capability Types Exist - requirements section");
- for (String type : resource.getRequirements().keySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
- if (eitherResult.isRight()) {
- return Either.right(eitherResult.right().value());
- }
- }
- }
-
- return eitherResult;
- }
-
- // @param typeObject- the object to which the validation is done
- private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
- boolean inTransaction) {
- Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
- if (eitherCapTypeFound.isRight()) {
- if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
- log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
- }
- log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
- ResponseFormat errorResponse = null;
- if (type != null)
- errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
- else
- errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
- }
- return eitherResult;
- }
-
- private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
- Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
- Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
- if (eitherCapTypeFound.isRight()) {
- if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
- log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
- }
- log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
- eitherResult = Either.right(errorResponse);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
- }
- CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
- if (capabilityTypeDefinition.getProperties() != null) {
- for (CapabilityDefinition capDef : typeEntry.getValue()) {
- List<ComponentInstanceProperty> properties = capDef.getProperties();
- if (properties == null || properties.isEmpty()) {
- properties = new ArrayList<ComponentInstanceProperty>();
- for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
- ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
- properties.add(newProp);
- }
- } else {
- for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
- PropertyDefinition porpFromDef = prop.getValue();
- List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
- for (ComponentInstanceProperty cip : properties) {
- if (!cip.getName().equals(porpFromDef.getName())) {
- ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
- propsToAdd.add(newProp);
- }
- }
- if (!propsToAdd.isEmpty()) {
- properties.addAll(propsToAdd);
- }
- }
- }
- capDef.setProperties(properties);
- }
- }
- return eitherResult;
- }
-
- public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- // create resource
-
- // lock new resource name in order to avoid creation resource with same
- // name
- if (inTransaction == false) {
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
- return Either.right(responseFormat);
- }
-
- log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
- }
- try {
- if (resource.deriveFromGeneric()) {
- Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(resource);
- if (genericResourceEither.isRight())
- return genericResourceEither;
- }
-
- Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
- if (respStatus.isLeft()) {
- auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
- ASDCKpiApi.countCreatedResourcesKPI();
- } else
- componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
- return respStatus;
-
- } finally {
- if (inTransaction == false) {
- graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
- }
- }
- }
-
- private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
- }
-
- private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
- // validate resource name uniqueness
- log.debug("validate resource name");
- Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
- if (eitherValidation.isRight()) {
- log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
- return Either.right(errorResponse);
- }
- if (eitherValidation.left().value()) {
- log.debug("resource with name: {}, already exists", resource.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- return Either.right(errorResponse);
- }
-
- log.debug("send resource {} to dao for create", resource.getName());
-
- createArtifactsPlaceHolderData(resource, user);
-
- //
-
- // enrich object
- if (!isNormative) {
- log.debug("enrich resource with creator, version and state");
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- resource.setVersion(INITIAL_VERSION);
- resource.setHighestVersion(true);
- if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
- resource.setAbstract(false);
- }
-
- Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
- if (createToscaElement.isLeft()) {
- return Either.left(createToscaElement.left().value());
- }
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
-
- return Either.right(responseFormat);
- }
-
- private void createArtifactsPlaceHolderData(Resource resource, User user) {
- // create mandatory artifacts
-
- // TODO it must be removed after that artifact uniqueId creation will be
- // moved to ArtifactOperation
- // String resourceUniqueId =
- // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
- // resource.getResourceVersion());
-
- setInformationalArtifactsPlaceHolder(resource, user);
- setDeploymentArtifactsPlaceHolder(resource, user);
- setToscaArtifactsPlaceHolders(resource, user);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
- Resource resource = (Resource) component;
- Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
- if (artifactMap == null) {
- artifactMap = new HashMap<String, ArtifactDefinition>();
- }
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceArtifacts();
- if (deploymentResourceArtifacts != null) {
- Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
- while (iterator.hasNext()) {
- Entry<String, Object> currEntry = iterator.next();
- boolean shouldCreateArtifact = true;
- Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
- Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
- if (object != null) {
- List<String> artifactTypes = (List<String>) object;
- if (!artifactTypes.contains(resource.getResourceType().name())) {
- shouldCreateArtifact = false;
- continue;
- }
- } else {
- log.info("resource types for artifact placeholder {} were not defined. default is all resources", currEntry.getKey());
- }
- if (shouldCreateArtifact) {
- if (artifactsBusinessLogic != null) {
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(), user, ArtifactGroupTypeEnum.DEPLOYMENT);
- if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
- }
- }
- }
- }
- resource.setDeploymentArtifacts(artifactMap);
- }
-
- @SuppressWarnings("unchecked")
- private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
- Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
- if (artifactMap == null) {
- artifactMap = new HashMap<String, ArtifactDefinition>();
- }
- String resourceUniqueId = resource.getUniqueId();
- List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
- List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
- Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
- List<CategoryDefinition> categories = resource.getCategories();
- boolean isCreateArtifact = true;
- if (exludeResourceCategory != null) {
- String category = categories.get(0).getName();
- for (String exlude : exludeResourceCategory) {
- if (exlude.equalsIgnoreCase(category)) {
- isCreateArtifact = false;
- break;
- }
- }
-
- }
- if (isCreateArtifact && exludeResourceType != null) {
- String resourceType = resource.getResourceType().name();
- for (String type : exludeResourceType) {
- if (type.equalsIgnoreCase(resourceType)) {
- isCreateArtifact = false;
- break;
- }
- }
-
- }
-
- if (informationalResourceArtifacts != null && isCreateArtifact) {
- Set<String> keys = informationalResourceArtifacts.keySet();
- for (String informationalResourceArtifactName : keys) {
- Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
- ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
- }
- }
- resource.setArtifacts(artifactMap);
- }
-
- /**
- * deleteResource
- *
- * @param resourceId
- * @param user
- * @return
- */
- public ResponseFormat deleteResource(String resourceId, User user) {
- ResponseFormat responseFormat;
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
-
- Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
- if (resourceStatus.isRight()) {
- log.debug("failed to get resource {}", resourceId);
- return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
- }
-
- Resource resource = resourceStatus.left().value();
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
- if (lockResult.isRight()) {
- result = StorageOperationStatus.GENERAL_ERROR;
- return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- }
-
- try {
-
- result = markComponentToDelete(resource);
- if (result.equals(StorageOperationStatus.OK)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- } else {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
- }
- return responseFormat;
-
- } finally {
- if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
- }
-
- }
-
- public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
-
- // Resource resource = null;
- Resource resource = null;
- StorageOperationStatus result = StorageOperationStatus.OK;
- try {
-
- Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
- if (resourceStatus.isRight()) {
- log.debug("failed to get resource {} version {}", resourceName, version);
- return componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
- }
-
- resource = resourceStatus.left().value();
-
- } finally {
- if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- if (resource != null) {
- Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource, "Delete Resource");
- if (lockResult.isRight()) {
- result = StorageOperationStatus.GENERAL_ERROR;
- return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- }
- try {
- result = markComponentToDelete(resource);
- if (!result.equals(StorageOperationStatus.OK)) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
- return responseFormat;
- }
-
- } finally {
- if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
- }
- }
- return responseFormat;
- }
-
- public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
-
- if (user != null) {
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- }
-
- // IResourceOperation dataModel = getResourceOperation();
- Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
- if (storageStatus.isRight()) {
- log.debug("failed to get resource by id {}", resourceId);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
- }
- if(!(storageStatus.left().value() instanceof Resource)){
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
- }
- return Either.left(storageStatus.left().value());
-
- }
-
- public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
- if (getResource.isRight()) {
- log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
- }
- return Either.left(getResource.left().value());
- }
-
- /**
- * updateResourceMetadata
- *
- * @param user - modifier data (userId)
- * @param inTransaction TODO
- * @param resourceIdToUpdate - the resource identifier
- * @param newResource
- * @return Either<Resource, responseFormat>
- */
- public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
-
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- // IResourceOperation dataModel = getResourceOperation();
- log.debug("Get resource with id {}", resourceIdToUpdate);
- boolean needToUnlock = false;
- boolean rollbackNeeded = true;
-
- try {
- // Either<Resource, StorageOperationStatus> storageStatus =
- // dataModel.getResource_tx(resourceIdToUpdate, false);
- if (currentResource == null) {
- Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
- if (storageStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
- }
-
- currentResource = storageStatus.left().value();
- }
- // verify that resource is checked-out and the user is the last
- // updater
- if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- // lock resource
- StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
- if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
- log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
- return Either.right(responseFormat);
- }
-
- needToUnlock = true;
-
- // critical section starts here
- // convert json to object
-
- // Update and updated resource must have a non-empty "derivedFrom"
- // list
- // This code is not called from import resources, because of root
- // VF "derivedFrom" should be null (or ignored)
- if (ModelConverter.isAtomicComponent(currentResource)) {
- Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
- if (derivedFromNotEmptyEither.isRight()) {
- log.debug("for updated resource {}, derived from field is empty", newResource.getName());
- return Either.right(derivedFromNotEmptyEither.right().value());
- }
-
- derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
- if (derivedFromNotEmptyEither.isRight()) {
- log.debug("for current resource {}, derived from field is empty", currentResource.getName());
- return Either.right(derivedFromNotEmptyEither.right().value());
- }
- } else {
- newResource.setDerivedFrom(null);
- }
-
- Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true);
- if (dataModelResponse.isRight()) {
- log.debug("failed to update resource metadata!!!");
- rollbackNeeded = true;
- return Either.right(dataModelResponse.right().value());
- }
-
- log.debug("Resource metadata updated successfully!!!");
- rollbackNeeded = false;
- return Either.left(dataModelResponse.left().value());
-
- } finally {
- if (!inTransaction) {
- if (rollbackNeeded) {
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- }
-
- if (needToUnlock) {
- graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
- }
- }
- }
-
- private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
- if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
- if (log.isInfoEnabled())
- log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
- return Either.right(false);
- }
- List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
- for ( GroupDefinition group : list) {
- if ( group!=null && group.isSamePrefix( replacePattern ) ){
- String prefix = group.getName().substring( 0, replacePattern.length() );
- String newGroupName = group.getName().replaceFirst(prefix , with);
- group.setName(newGroupName);
- //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
- //group.setUniqueId(newUid);
- }
- }
- return Either.left(list);
- }
-
- private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
- if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional
- String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- return !oldName.equals(futureName);
- }
- return false;
- }
-
- private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
- //region -> Update groups name for newResource
- if ( isComponentNameChanged( currentResource , newResource) ){
- String replacePattern = Optional.ofNullable( //get currentResource name from metadata
- Optional.ofNullable( Optional.ofNullable( currentResource )
- .orElse(null).getComponentMetadataDefinition() )
- .orElse(null).getMetadataDataDefinition() )
- .orElse(null).getName();
- String with = Optional.ofNullable( //get newResource name from metadata
- Optional.ofNullable( Optional.ofNullable( newResource )
- .orElse(null).getComponentMetadataDefinition() )
- .orElse(null).getMetadataDataDefinition() )
- .orElse(null).getName();
- if ( with != null && replacePattern != null ){
- Either<List<GroupDefinition>,Boolean> result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups());
- if (result.isLeft())
- newResource.setGroups( (List<GroupDefinition>)result.left().value() );
- }
- }
- //endregion
-
- Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
- if (validateResourceFields.isRight()) {
- return Either.right(validateResourceFields.right().value());
- }
- // Setting last updater and uniqueId
- newResource.setContactId(newResource.getContactId().toLowerCase());
- newResource.setLastUpdaterUserId(user.getUserId());
- newResource.setUniqueId(resourceIdToUpdate);
- // Cannot set highest version through UI
- newResource.setHighestVersion(currentResource.isHighestVersion());
- newResource.setCreationDate(currentResource.getCreationDate());
-
- Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(), shouldLock, inTransaction);
-
- if (processUpdateOfDerivedFrom.isRight()) {
- log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
- return Either.right(processUpdateOfDerivedFrom.right().value());
- }
-
- log.debug("send resource {} to dao for update", newResource.getUniqueId());
- if (newResource!=null && newResource.getGroups()!=null){
- for ( GroupDefinition group : newResource.getGroups() ){
- if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
- groupBusinessLogic.validateAndUpdateGroupMetadata(
- newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
- user,
- ComponentTypeEnum.RESOURCE_INSTANCE,
- group,
- true ,
- false) ;
- }
- }
- Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
-
- if (dataModelResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
- return Either.right(responseFormat);
- } else if (dataModelResponse.left().value() == null) {
- log.debug("No response from updateResource");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return Either.left(dataModelResponse.left().value());
- }
-
- /**
- * validateResourceFieldsBeforeCreate
- *
- * @param user - modifier data (userId)
- * @param dataModel - IResourceOperation for resource crud
- * @param resource - Resource object to validate
- * @return Either<Boolean, ErrorResponse>
- */
- private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
- Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource, actionEnum);
- if (componentsFieldsValidation.isRight()) {
- return componentsFieldsValidation;
- }
-
- // validate name
-
- /*
- * log.debug("validate resource name"); Either<Boolean, ResponseFormat> eitherValidation = validateComponentName(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
- *
- * // validate description log.debug("validate description"); eitherValidation = validateDescriptionAndCleanup(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
- */
-
- // validate icon
- /*
- * log.debug("validate icon"); eitherValidation = validateIcon(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
- */
-
- // validate tags
- /*
- * log.debug("validate tags"); eitherValidation = validateTagsListAndRemoveDuplicates(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
- */
-
- // validate category
- log.debug("validate category");
- Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // validate vendor name & release & model number
- log.debug("validate vendor name");
- eitherValidation = validateVendorName(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate vendor release");
- eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate resource vendor model number");
- eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // validate contact info
- /*
- * log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
- */
-
- // validate cost
- log.debug("validate cost");
- eitherValidation = validateCost(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // validate licenseType
- log.debug("validate licenseType");
- eitherValidation = validateLicenseType(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // validate template (derived from)
- log.debug("validate derived from");
- if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
- resource.setDerivedFrom(null);
- }
- eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
- if (eitherValidation.isRight()) {
- return Either.right(eitherValidation.right().value());
- }
-
- // warn about non-updatable fields
- checkComponentFieldsForOverrideAttempt(resource);
- String currentCreatorFullName = resource.getCreatorFullName();
- if (currentCreatorFullName != null) {
- log.warn("Resource Creator fullname is automatically set and cannot be updated");
- }
-
- String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
- if (currentLastUpdaterFullName != null) {
- log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
- }
-
- Long currentLastUpdateDate = resource.getLastUpdateDate();
- if (currentLastUpdateDate != null) {
- log.warn("Resource last update date is automatically set and cannot be updated");
- }
-
- Boolean currentAbstract = resource.isAbstract();
- if (currentAbstract != null) {
- log.warn("Resource abstract is automatically set and cannot be updated");
- }
-
- return Either.left(true);
- }
-
- /**
- * validateResourceFieldsBeforeUpdate
- *
- * @param currentResource - Resource object to validate
- * @param isNested
- * @return Either<Boolean, ErrorResponse>
- */
- private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
-
- boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
-
- // validate resource name
- log.debug("validate resource name before update");
- Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // validate description
- log.debug("validate description before update");
- eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate icon before update");
- eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate tags before update");
- eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate vendor name before update");
- eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate resource vendor model number before update");
- eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
-
- log.debug("validate vendor release before update");
- eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate contact info before update");
- eitherValidation = validateContactId(null, updateInfoResource, null);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate derived before update");
- eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- log.debug("validate category before update");
- eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
- if (eitherValidation.isRight()) {
- return eitherValidation;
- }
-
- // warn about non-updatable fields
- String currentResourceVersion = currentResource.getVersion();
- String updatedResourceVersion = updateInfoResource.getVersion();
-
- if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
- log.warn("Resource version is automatically set and cannot be updated");
- }
-
- String currentCreatorUserId = currentResource.getCreatorUserId();
- String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
-
- if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
- log.warn("Resource Creator UserId is automatically set and cannot be updated");
- }
-
- String currentCreatorFullName = currentResource.getCreatorFullName();
- String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
-
- if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
- log.warn("Resource Creator fullname is automatically set and cannot be updated");
- }
-
- String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
- String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
-
- if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
- log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
- }
-
- String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
- String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
-
- if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
- log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
- }
-
- Long currentCreationDate = currentResource.getCreationDate();
- Long updatedCreationDate = updateInfoResource.getCreationDate();
-
- if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
- log.warn("Resource Creation date is automatically set and cannot be updated");
- }
-
- Long currentLastUpdateDate = currentResource.getLastUpdateDate();
- Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
-
- if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
- log.warn("Resource last update date is automatically set and cannot be updated");
- }
-
- LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
- LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
-
- if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
- log.warn("Resource lifecycle state date is automatically set and cannot be updated");
- }
-
- Boolean currentAbstract = currentResource.isAbstract();
- Boolean updatedAbstract = updateInfoResource.isAbstract();
-
- if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
- log.warn("Resource abstract is automatically set and cannot be updated");
- }
-
- Boolean currentHighestVersion = currentResource.isHighestVersion();
- Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
-
- if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
- log.warn("Resource highest version is automatically set and cannot be updated");
- }
-
- String currentUuid = currentResource.getUUID();
- String updatedUuid = updateInfoResource.getUUID();
-
- if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
- log.warn("Resource UUID is automatically set and cannot be updated");
- }
-
- ResourceTypeEnum currentResourceType = currentResource.getResourceType();
- ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
-
- if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
- log.warn("Resource Type cannot be updated");
-
- }
- updateInfoResource.setResourceType(currentResource.getResourceType());
-
- String currentInvariantUuid = currentResource.getInvariantUUID();
- String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
-
- if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
- log.warn("Resource invariant UUID is automatically set and cannot be updated");
- updateInfoResource.setInvariantUUID(currentInvariantUuid);
- }
- return Either.left(true);
- }
-
- /*
- * private Either<Boolean, ResponseFormat> validateResourceName(User user, Resource resource, AuditingActionEnum actionEnum) { log.debug("validate resource name is not empty"); String resourceName = resource.getResourceName();
- *
- * if (!ValidationUtils.validateStringNotEmpty(resourceName)) { log.debug("Resource name is empty"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
- * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); }
- *
- * if (!ValidationUtils.validateResourceNameLength(resourceName)) { log.debug("Resource name is exceeds max length {} ", ValidationUtils.RESOURCE_NAME_MAX_LENGTH); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.
- * COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.RESOURCE_NAME_MAX_LENGTH); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat);
- * }
- *
- * if (!ValidationUtils.validateResourceName(resourceName)) { log.debug("Resource name {} has invalid format", resourceName); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPONENT_NAME,
- * ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setNormalizedName(ValidationUtils.normaliseComponentName(
- * resourceName)); resource.setSystemName(ValidationUtils.convertToSystemName(resourceName)) ;
- *
- * return Either.left(true); }
- */
-
- private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
- String resourceNameUpdated = updateInfoResource.getName();
- String resourceNameCurrent = currentResource.getName();
- if (resourceNameCurrent.equals(resourceNameUpdated))
- return true;
- // In case of CVFC type we should support the case of old VF with CVFC instances that were created without the "Cvfc" suffix
- return (currentResource.getResourceType().equals(ResourceTypeEnum.CVFC)
- && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent)));
- }
-
- private String addCvfcSuffixToResourceName(String resourceName) {
- return resourceName+"Cvfc";
- }
-
- private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
- String resourceNameUpdated = updateInfoResource.getName();
- if (!isResourceNameEquals(currentResource, updateInfoResource)) {
- if (isNested || !hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null, updateInfoResource, null);
- if (validateResourceNameResponse.isRight()) {
- ResponseFormat errorResponse = validateResourceNameResponse.right().value();
- return Either.right(errorResponse);
- }
- validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
- if (validateResourceNameResponse.isRight()) {
- ResponseFormat errorResponse = validateResourceNameResponse.right().value();
- return Either.right(errorResponse);
- }
- currentResource.setName(resourceNameUpdated);
- currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
- currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
-
- } else {
- log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
- String iconUpdated = updateInfoResource.getIcon();
- String iconCurrent = currentResource.getIcon();
- if (!iconCurrent.equals(iconUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
- if (validateIcon.isRight()) {
- ResponseFormat errorResponse = validateIcon.right().value();
- return Either.right(errorResponse);
- }
- } else {
- log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
- String vendorNameUpdated = updateInfoResource.getVendorName();
- String vendorNameCurrent = currentResource.getVendorName();
- if (!vendorNameCurrent.equals(vendorNameUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
- if (validateVendorName.isRight()) {
- ResponseFormat errorResponse = validateVendorName.right().value();
- return Either.right(errorResponse);
- }
- } else {
- log.info("Vendor name {} cannot be updated once the resource has been certified once.", vendorNameUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
- String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
- String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
- if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
- Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
- if (validateResourceVendorModelNumber.isRight()) {
- ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
- Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
- if (validateCategoryName.isRight()) {
- ResponseFormat errorResponse = validateCategoryName.right().value();
- return Either.right(errorResponse);
- }
- if (hasBeenCertified) {
- CategoryDefinition currentCategory = currentResource.getCategories().get(0);
- SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
- CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
- SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
- if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
- log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
-
- List<String> currentDerivedFrom = currentResource.getDerivedFrom();
- List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
- if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
- log.trace("Update normative types");
- return Either.left(true);
- }
-
- String derivedFromCurrent = currentDerivedFrom.get(0);
- String derivedFromUpdated = updatedDerivedFrom.get(0);
-
- if (!derivedFromCurrent.equals(derivedFromUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
- if (validateDerivedFromExistsEither.isRight()) {
- return validateDerivedFromExistsEither;
- }
- } else {
- Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
-
- if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
- log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
- return validateDerivedFromExtending;
- }
- }
- } else {
- // For derived from, we must know whether it was actually changed,
- // otherwise we must do no action.
- // Due to changes it inflicts on data model (remove artifacts,
- // properties...), it's not like a flat field which can be
- // overwritten if not changed.
- // So we must indicate that derived from is not changed
- updateInfoResource.setDerivedFrom(null);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
-
- List<String> currentDerivedFrom = currentResource.getDerivedFrom();
- List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
- if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
- log.trace("Update normative types");
- return Either.left(true);
- }
-
- String derivedFromCurrent = currentDerivedFrom.get(0);
- String derivedFromUpdated = updatedDerivedFrom.get(0);
-
- if (!derivedFromCurrent.equals(derivedFromUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null, updateInfoResource, null);
- if (validateDerivedFromExistsEither.isRight()) {
- return validateDerivedFromExistsEither;
- }
- } else {
- Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource, null);
-
- if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
- log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
- return validateDerivedFromExtending;
- }
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
-
- if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
- return Either.left(true);
- }
-
- // IResourceOperation resourceOperation = getResourceOperation();
-
- String templateName = resource.getDerivedFrom().get(0);
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
- if (dataModelResponse.isRight()) {
- StorageOperationStatus storageStatus = dataModelResponse.right().value();
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
- log.debug("request to data model failed with error: {}", storageStatus.name());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
- log.trace("audit before sending response");
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- return Either.right(responseFormat);
- } else if (!dataModelResponse.left().value()) {
- log.info("resource template with name: {}, does not exists", templateName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
-
- return Either.right(responseFormat);
-
- }
- return Either.left(true);
- }
-
- // Tal G for extending inheritance US815447
- private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource, AuditingActionEnum actionEnum) {
- // If updated resource is not deriving, should fail validation
- /*
- * if (currentResource.getDerivedFrom() == null || currentResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
- */
- // If current resource is deriving from certain type and it is updated to not deriving, should fail validation
- /*
- * if (updateInfoResource.getDerivedFrom() == null || updateInfoResource.getDerivedFrom().isEmpty()) { return Either.left(false); }
- */
- String currentTemplateName = currentResource.getDerivedFrom().get(0);
- String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
- if (dataModelResponse.isRight()) {
- StorageOperationStatus storageStatus = dataModelResponse.right().value();
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
- log.debug("request to data model failed with error: {}", storageStatus.name());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
- log.trace("audit before sending response");
- componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
- return Either.right(responseFormat);
- }
-
- if (!dataModelResponse.left().value()) {
- log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
- componentsUtils.auditResource(responseFormat, user, currentResource, "", "", actionEnum, null);
-
- return Either.right(responseFormat);
-
- }
- return Either.left(true);
- }
-
- public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
- log.debug("validate resource derivedFrom field");
- if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
- log.info("derived from (template) field is missing for the resource");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
-
- return Either.right(responseFormat);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
-
- Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade.validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
- if (resourceOperationResponse.isLeft()) {
- if (!resourceOperationResponse.left().value()) {
- return Either.left(false);
- } else {
- log.debug("resource with name: {}, already exists", resource.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- return Either.right(errorResponse);
- }
- }
- log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
- return Either.right(errorResponse);
- }
-
- /*
- * private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Resource resource, AuditingActionEnum actionEnum) { List<String> tagsList = resource.getTags();
- *
- * Either<Boolean, ResponseFormat> validateTags = validateResourceTags(tagsList, resource.getResourceName()); if (validateTags.isRight()) { ResponseFormat responseFormat = validateTags.right().value();
- * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } ValidationUtils.removeDuplicateFromList(tagsList); return Either.left(true);
- *
- * }
- *
- * private Either<Boolean, ResponseFormat> validateResourceTags(List<String> tags, String resourceName) { log.debug("validate resource tags"); boolean includesResourceName = false; int tagListSize = 0; if (tags != null && !tags.isEmpty()) { for
- * (String tag : tags) { if (!ValidationUtils.validateTagLength(tag)) { log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
- * COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH)); } if (ValidationUtils.validateComponentNamePattern(tag)) { if (!includesResourceName) { includesResourceName = resourceName.equals(tag); } } else {
- * log.debug("invalid tag {}", tag); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAG)); } tagListSize += tag.length() + 1; } if (!includesResourceName) { log.debug( "tags must include resource name");
- * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_TAGS_NO_COMP_NAME)); } if (!ValidationUtils.validateTagListLength(tagListSize)) { log.debug( "overall tags length {}, exceeds limit {}", tagListSize,
- * ValidationUtils.TAG_LIST_MAX_LENGTH); return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH)); } return Either.left(true); }
- *
- * return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_TAGS)); }
- */
-
- private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
-
- List<CategoryDefinition> categories = resource.getCategories();
- if (categories == null || categories.size() == 0) {
- log.debug("Resource category is empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- return Either.right(responseFormat);
- }
- if (categories.size() > 1) {
- log.debug("Must be only one category for resource");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
- return Either.right(responseFormat);
- }
- CategoryDefinition category = categories.get(0);
- List<SubCategoryDefinition> subcategories = category.getSubcategories();
- if (subcategories == null || subcategories.size() == 0) {
- log.debug("Missinig subcategory for resource");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
- return Either.right(responseFormat);
- }
- if (subcategories.size() > 1) {
- log.debug("Must be only one sub category for resource");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
- return Either.right(responseFormat);
- }
-
- SubCategoryDefinition subcategory = subcategories.get(0);
-
- if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
- log.debug("Resource category is empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- return Either.right(responseFormat);
- }
- if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
- log.debug("Resource category is empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- return Either.right(responseFormat);
- }
-
- Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
- if (validateCategory.isRight()) {
- ResponseFormat responseFormat = validateCategory.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- return Either.right(responseFormat);
- }
-
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, boolean inTransaction) {
- if (category != null && subcategory != null) {
- log.debug("validating resource category {} against valid categories list", category);
- Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
- if (categories.isRight()) {
- log.debug("failed to retrive resource categories from Titan");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
- return Either.right(responseFormat);
- }
- List<CategoryDefinition> categoryList = categories.left().value();
- for (CategoryDefinition cat : categoryList) {
- if (cat.getName().equals(category.getName())) {
- for (SubCategoryDefinition subcat : cat.getSubcategories()) {
- if (subcat.getName().equals(subcategory.getName())) {
- return Either.left(true);
- }
- }
- log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory, cat.getSubcategories());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
- }
- }
- log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
- }
- return Either.left(false);
- }
-
- public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
- String vendorRelease = resource.getVendorRelease();
-
- log.debug("validate vendor relese name");
- if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
- log.info("vendor relese name is missing.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
- if (validateVendorReleaseResponse.isRight()) {
- ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- }
- return validateVendorReleaseResponse;
- }
-
- public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
- if (vendorRelease != null) {
- if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
- log.info("vendor release exceds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- return Either.right(errorResponse);
- }
-
- if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
- log.info("vendor release is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- return Either.left(false);
-
- }
-
- private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
- String vendorName = resource.getVendorName();
- if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
- log.info("vendor name is missing.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
- componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
- if (validateVendorNameResponse.isRight()) {
- ResponseFormat responseFormat = validateVendorNameResponse.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- }
- return validateVendorNameResponse;
-
- }
-
- private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
- String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
- Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
- if (validateResourceVendorModelNumber.isRight()) {
- ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- }
- return validateResourceVendorModelNumber;
-
- }
-
-
- private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
- if (vendorName != null) {
- if (!ValidationUtils.validateVendorNameLength(vendorName)) {
- log.info("vendor name exceds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
- return Either.right(errorResponse);
- }
-
- if (!ValidationUtils.validateVendorName(vendorName)) {
- log.info("vendor name is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
- return Either.right(errorResponse);
- }
- return Either.left(true);
-
- }
- return Either.left(false);
-
- }
-
- private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
- if (resourceVendorModelNumber.equals("")) {
- return Either.left(true);
- } else {
- if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
- log.info("resource vendor model number exceeds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
- return Either.right(errorResponse);
- }
- // resource vendor model number is currently validated as vendor name
- if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
- log.info("resource vendor model number is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- }
-
-
- /*
- * private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
- * log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
- * user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
- *
- * description = ValidationUtils.removeNoneUtf8Chars(description); description = ValidationUtils.removeHtmlTags(description); description = ValidationUtils.normaliseWhitespace(description); description = ValidationUtils.stripOctets(description);
- *
- * Either<Boolean, ResponseFormat> validatDescription = validateResourceDescription(description); if (validatDescription.isRight()) { ResponseFormat responseFormat = validatDescription.right().value();
- * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); return Either.right(responseFormat); } resource.setDescription(description); return Either.left(true); }
- *
- * private Either<Boolean, ResponseFormat> validateResourceDescription(String description) { if (description != null) { if (!ValidationUtils.validateDescriptionLength(description)) { return
- * Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH)); }
- *
- * if (!ValidationUtils.validateIsEnglish(description)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue())); } return Either.left(true); } return
- * Either.left(false); }
- */
-
- /*
- * private Either<Boolean, ResponseFormat> validateContactId(User user, Resource resource, AuditingActionEnum actionEnum) { String contactId = resource.getContactId();
- *
- * if (!ValidationUtils.validateStringNotEmpty(contactId)) { log.info("contact info is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
- *
- * Either<Boolean, ResponseFormat> validateContactIdResponse = validateContactId(contactId); if (validateContactIdResponse.isRight()) { ResponseFormat responseFormat = validateContactIdResponse.right().value();
- * componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null); } return validateContactIdResponse; }
- *
- * private Either<Boolean, ResponseFormat> validateContactId(String contactId) { if (contactId != null) { if (!ValidationUtils.validateContactId(contactId)) { log.debug("contact {} is invalid.", contactId); ResponseFormat errorResponse =
- * componentsUtils.getResponseFormat(ActionStatus. COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
- *
- * }
- */
-
- /*
- * private Either<Boolean, ResponseFormat> validateIcon(User user, Resource resource, AuditingActionEnum actionEnum) { String icon = resource.getIcon();
- *
- * if (!ValidationUtils.validateStringNotEmpty(icon)) { log.debug("icon is missing."); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
- * componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null); return Either.right(errorResponse); }
- *
- * Either<Boolean, ResponseFormat> validateIcon = validateIcon(icon); if (validateIcon.isRight()) { ResponseFormat responseFormat = validateIcon.right().value(); componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum,
- * null); } return validateIcon;
- *
- * }
- *
- * public Either<Boolean, ResponseFormat> validateIcon(String icon) { if (icon != null) { if (!ValidationUtils.validateIconLength(icon)) { log.debug("icon exceeds max length"); return Either.right(componentsUtils.getResponseFormat(ActionStatus.
- * COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH)); } if (!ValidationUtils.validateIcon(icon)) { log.debug("icon is invalid." ); ResponseFormat errorResponse =
- * componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue()); return Either.right(errorResponse); } return Either.left(true); } return Either.left(false);
- *
- * }
- */
-
- private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
- String cost = resource.getCost();
- if (cost != null) {
-
- if (!ValidationUtils.validateCost(cost)) {
- log.debug("resource cost is invalid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
- log.debug("validate licenseType");
- String licenseType = resource.getLicenseType();
- if (licenseType != null) {
- List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
- if (!licenseTypes.contains(licenseType)) {
- log.debug("License type {} isn't configured");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- if (actionEnum != null) {
- // In update case, no audit is required
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
- }
- return Either.right(responseFormat);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
- Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
- if (updatedResource.getDerivedFrom() != null) {
- log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
- log.debug("1. Removing interface artifacts from graph");
- // Remove all interface artifacts of resource
- String resourceId = updatedResource.getUniqueId();
- Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
-
- if (interfaces != null) {
- Collection<InterfaceDefinition> values = interfaces.values();
- for (InterfaceDefinition interfaceDefinition : values) {
- String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
-
- log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
- Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
- if (operations != null) {
- for (Entry<String, Operation> operationEntry : operations.entrySet()) {
- Operation operation = operationEntry.getValue();
- ArtifactDefinition implementation = operation.getImplementationArtifact();
- if (implementation != null) {
- String uniqueId = implementation.getUniqueId();
- log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId, operationEntry.getKey(), interfaceType);
- // only thing that transacts and locks here
- deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId, interfaceType, operationEntry.getKey(), userId, uniqueId, null, shouldLock, true);
- if (deleteArtifactByInterface.isRight()) {
- log.debug("Couldn't remove artifact definition with id {}", uniqueId);
- if (!inTransaction) {
- titanDao.rollback();
- }
- return Either.right(deleteArtifactByInterface.right().value());
- }
- } else {
- log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
- }
- }
- } else {
- log.trace("No operations found for interface type {}", interfaceType);
- }
- }
- }
- log.debug("2. Removing properties");
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
-
- if (findPropertiesOfNode.isRight() && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
- log.debug("Failed to remove all properties of resource");
- if (!inTransaction)
- titanDao.rollback();
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
- }
-
- } else {
- log.debug("Derived from wasn't changed during update");
- }
-
- if (!inTransaction)
- titanDao.commit();
- return Either.left(true);
-
- }
-
- /**** Auditing *******************/
-
- protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-
- return webApplicationContext.getBean(class1);
- }
-
- public ICapabilityTypeOperation getCapabilityTypeOperation() {
- return capabilityTypeOperation;
- }
-
- public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
- this.capabilityTypeOperation = capabilityTypeOperation;
- }
-
- public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
- log.debug("validate resource properties default values");
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- List<PropertyDefinition> properties = resource.getProperties();
- String type = null;
- String innerType = null;
- if (properties != null) {
- for (PropertyDefinition property : properties) {
- if (!propertyOperation.isPropertyTypeValid(property)) {
- log.info("Invalid type for property");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
- eitherResult = Either.right(responseFormat);
- break;
- }
-
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- return Either.right(allDataTypes.right().value());
- }
-
- type = property.getType();
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes.left().value());
- innerType = propertyInnerTypeValid.getLeft();
- if (!propertyInnerTypeValid.getRight().booleanValue()) {
- log.info("Invalid inner type for property");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
- eitherResult = Either.right(responseFormat);
- break;
- }
- }
-
- if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
- log.info("Invalid default value for property");
- ResponseFormat responseFormat;
- if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
- } else {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
- }
- eitherResult = Either.right(responseFormat);
- break;
-
- }
- }
- }
- return eitherResult;
- }
-
- @Override
- public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
- return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
- }
-
- @Override
- public ComponentInstanceBusinessLogic getComponentInstanceBL() {
- return vfComponentInstanceBusinessLogic;
- }
-
- private String getComponentTypeForResponse(Component component) {
- String componentTypeForResponse = "SERVICE";
- if (component instanceof Resource) {
- componentTypeForResponse = ((Resource) component).getResourceType().name();
- }
- return componentTypeForResponse;
- }
-
- private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
-
- Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
- Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
-
- Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
- if (eitherNodesTemlates.isLeft()) {
- Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
-
- if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
- Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
- while (nodesNameValue.hasNext()) {
- Entry<String, Object> groupNameValue = nodesNameValue.next();
-
- String groupName = groupNameValue.getKey();
- Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName, groupNameValue.getValue());
- if (eitherNode.isRight()) {
- String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:" + resource.getName();
- BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
- return Either.right(eitherNode.right().value());
- } else {
- GroupDefinition groupDefinition = eitherNode.left().value();
- groups.put(groupName, groupDefinition);
- }
- }
- }
- }
-
- return result;
- }
-
- private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
-
- Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
- if (inputs.isRight()) {
- String message = "Failed when creating inputs: for resource:" + resource.getName();
- BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
- Map<String, InputDefinition> resultMap = new HashMap<>();
- return Either.left(resultMap);
-
- }
-
- Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
-
- GroupDefinition groupInfo = new GroupDefinition();
- groupInfo.setName(groupName);
- Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
-
- try {
- if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
- Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
- String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
- if (!StringUtils.isEmpty(groupType)) {
- groupInfo.setType(groupType);
- } else {
- log.debug("The 'type' member is not found under group {}", groupName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
- }
-
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- groupInfo.setDescription((String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
- }
-
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
- Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
- if (members != null) {
- if (members instanceof List) {
- Map<String, String> membersLoaded = new HashMap<>();
- List<?> membersAsList = (List<?>) members;
- for (Object member : membersAsList) {
- membersLoaded.put(member.toString(), "");
- }
- groupInfo.setMembers(membersLoaded);
- } else {
- log.debug("The 'members' member is not of type list under group {}", groupName);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
- }
- }
- }
-
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
-
- Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(properties, groupName, groupType);
- if (regResponse.isRight())
- return Either.right(regResponse.right().value());
- if (regResponse.left().value().size() > 0) {
- groupInfo.convertFromGroupProperties(regResponse.left().value());
- }
- }
-
- } else {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
- log.debug("error when creating group, message:{}", e.getMessage(), e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties, String groupName, String groupType) {
-
- List<GroupProperty> result = new ArrayList<>();
-
- if (properties == null) {
- return Either.left(result);
- }
-
- Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
-
- if (groupTypeRes.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
- }
-
- Map<String, PropertyDefinition> gtProperties = new HashMap<>();
- GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
-
- List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
-
- if (propertiesDef != null) {
- gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
- }
-
- if (properties != null) {
-
- if (properties instanceof Map) {
-
- Map<String, Object> props = (Map<String, Object>) properties;
- for (Entry<String, Object> entry : props.entrySet()) {
-
- String propName = entry.getKey();
- Object value = entry.getValue();
-
- PropertyDefinition gtDefinition = gtProperties.get(propName);
- if (gtDefinition == null) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND, propName, groupName, groupType));
- }
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
-
- String convertedValue = null;
- if (value != null) {
- if (type == null || value instanceof Map || value instanceof List) {
- convertedValue = gson.toJson(value);
- } else {
- convertedValue = value.toString();
- }
- }
-
- GroupProperty groupProperty = new GroupProperty();
- groupProperty.setValue(convertedValue);
- groupProperty.setName(propName);
-
- log.trace("After building group property {}", groupProperty);
-
- result.add(groupProperty);
- }
-
- }
-
- }
-
- return Either.left(result);
- }
-
- public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
-
- // validate user
- if (user != null) {
- Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID", false);
- if (userValidation.isRight()) {
- return Either.right(userValidation.right().value());
- }
- }
-
- // get resource from csar uuid
- Either<Resource, StorageOperationStatus> either = toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
- if (either.isRight()) {
- ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
- return Either.right(resp);
- }
-
- return Either.left(either.left().value());
- }
-
- @Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
- return null;
- }
-
- private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities, Map<String, List<UploadCapInfo>> uploadedCapabilities) {
- ResponseFormat responseFormat;
- Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
-
- for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
- String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
- if (!defaultCapabilities.containsKey(capabilityType)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
- return Either.right(responseFormat);
- } else {
- CapabilityDefinition defaultCapability;
- if(CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())){
- defaultCapability = defaultCapabilities.get(capabilityType).get(0);
- } else {
- Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
- if(getFullComponentRes.isRight()){
- log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
- return Either.right(responseFormat);
- }
- defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
- }
- if(CollectionUtils.isEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){
- log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
- log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
- return Either.right(responseFormat);
- }
- if(CollectionUtils.isNotEmpty(defaultCapability.getProperties()) && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())){
- Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
- if (validationRes.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, validationRes.right().value());
- return Either.right(responseFormat);
- }
- }
- List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
- validCapabilityList.add(defaultCapability);
- validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
- }
- }
- return Either.left(validCapabilitiesMap);
- }
-
- private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
- List<ComponentInstanceProperty> validProperties = new ArrayList<>();
- Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
- List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
- for (UploadPropInfo property : uploadedProperties) {
- String propertyName = property.getName().toLowerCase();
- String propertyType = property.getType();
- ComponentInstanceProperty validProperty;
- if (defaultProperties.containsKey(propertyName)) {
- if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
- return Either.right(propertyName);
- }
- }
- validProperty = new ComponentInstanceProperty();
- validProperty.setName(propertyName);
- if (property.getValue() != null)
- validProperty.setValue(property.getValue().toString());
- validProperty.setDescription(property.getDescription());
- validProperty.setPassword(property.isPassword());
- validProperties.add(validProperty);
- }
- defaultCapability.setProperties(validProperties);
- return Either.left(true);
- }
-
- private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
- Resource resource, User user) {
-
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
- ;
- try {
- // add all found Csar artifacts to list to upload
- List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
- List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
- List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
- for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
- ArtifactDefinition foundArtifact;
-
- if (!existingArtifactsToHandle.isEmpty()) {
- foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst().orElse(null);
- if (foundArtifact != null) {
- if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact.getArtifactType()) {
- if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
- currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
- // if current artifact already exists, but has different content, add him to the list to update
- artifactsToUpdate.add(currNewArtifact);
- }
- // remove found artifact from the list of existing artifacts to handle, because it was already handled
- existingArtifactsToHandle.remove(foundArtifact);
- // and remove found artifact from the list to upload, because it should either be updated or be ignored
- artifactsToUpload.remove(currNewArtifact);
- } else {
- log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
- ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
- currNewArtifact.getArtifactType().name(), foundArtifact.getArtifactType());
- AuditingActionEnum auditingAction = artifactsBusinessLogic.detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), foundArtifact.getArtifactChecksum());
- artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(), responseFormat, resource.getComponentType(), null);
- responseWrapper.setInnerElement(responseFormat);
- break;
- }
- }
- }
- }
- if (responseWrapper.isEmpty()) {
- existingArtifactsToHandle.stream()
- // add all artifacts which was not detected as artifact to update or to ignore to the list to delete
- .forEach(a -> artifactsToDelete.add(new NonMetaArtifactInfo(a.getArtifactName(), null, ArtifactTypeEnum.findType(a.getArtifactType()), a.getArtifactGroupType(), null, a.getUniqueId())));
- }
- if (responseWrapper.isEmpty()) {
- if (!artifactsToUpload.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Create, artifactsToUpload);
- if (!artifactsToUpdate.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Update, artifactsToUpdate);
- if (!artifactsToDelete.isEmpty())
- nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.Delete, artifactsToDelete);
- }
- if (!responseWrapper.isEmpty()) {
- nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
- }
- } catch (Exception e) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- responseWrapper.setInnerElement(responseFormat);
- log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
- }
- return nodeTypeArtifactsToHandleRes;
- }
-
-
- private ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
- String actualType;
- String actualVfName;
- String actualPreviousVfName;
- if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){
- actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
- actualType = ResourceTypeEnum.VFC.name();
- } else {
- actualVfName = vfResourceName;
- actualType = nodeResourceType;
- }
-
- StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
- String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
- String[] findTypes = nameWithouNamespacePrefix.split("\\.");
- String resourceType = findTypes[0];
- String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
-
- if (actualName.startsWith(Constants.ABSTRACT)) {
- toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
- } else {
- toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
- }
- StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
- return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(), previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
- }
-
- public ICacheMangerOperation getCacheManagerOperation() {
- return cacheManagerOperation;
- }
-
- public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
- this.cacheManagerOperation = cacheManagerOperation;
- }
-
- ///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
- @Override
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
-
- ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
- Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
-
- if (resourceResultEither.isRight()) {
- if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- 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()), ""));
- }
-
- Resource resource = resourceResultEither.left().value();
- UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
- return Either.left(dataTransfer);
- }
- @Override
- public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
- Resource resource = (Resource) clonedComponent;
- if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
- Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade.shouldUpgradeToLatestDerived(resource);
- if (shouldUpgradeToLatestDerived.isRight()) {
- return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
- }
- return Either.left(shouldUpgradeToLatestDerived.left().value());
- } else {
- return super.shouldUpgradeToLatestDerived(clonedComponent);
- }
- }
-
-
-
-}
+ @Autowired
+ private CompositionBusinessLogic compositionBusinessLogic;
+
+ @Autowired
+ private ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
+ @Autowired
+ private MergeResourceBLFactory mergeResourceBLFactory;
+
+ @Autowired
+ private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
+
+ private Gson gson = new Gson();
+
+ public CsarOperation getCsarOperation() {
+ return csarOperation;
+ }
+
+ public void setCsarOperation(CsarOperation csarOperation) {
+ this.csarOperation = csarOperation;
+ }
+
+ public LifecycleBusinessLogic getLifecycleBusinessLogic() {
+ return lifecycleBusinessLogic;
+ }
+
+ public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
+ this.lifecycleBusinessLogic = lifecycleBusinessLogic;
+ }
+
+ public IElementOperation getElementDao() {
+ return elementDao;
+ }
+
+ public void setElementDao(IElementOperation elementDao) {
+ this.elementDao = elementDao;
+ }
+
+ public IUserBusinessLogic getUserAdmin() {
+ return this.userAdmin;
+ }
+
+ public void setUserAdmin(UserBusinessLogic userAdmin) {
+ this.userAdmin = userAdmin;
+ }
+
+ public ComponentsUtils getComponentsUtils() {
+ return this.componentsUtils;
+ }
+
+ public void setComponentsUtils(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
+
+ public ArtifactsBusinessLogic getArtifactsManager() {
+ return artifactsBusinessLogic;
+ }
+
+ public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
+ this.artifactsBusinessLogic = artifactsManager;
+ }
+
+ public void setPropertyOperation(IPropertyOperation propertyOperation) {
+ this.propertyOperation = propertyOperation;
+ }
+
+ public ApplicationDataTypeCache getApplicationDataTypeCache() {
+ return applicationDataTypeCache;
+ }
+
+ public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
+ this.applicationDataTypeCache = applicationDataTypeCache;
+ }
+
+ /**
+ * the method returns a list of all the resources that are certified, the
+ * returned resources are only abstract or only none abstract according to
+ * the given param
+ *
+ * @param getAbstract
+ * @param userId TODO
+ * @return
+ */
+ public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract,
+ HighestFilterEnum highestFilter, String userId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get All Certified Resources", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Boolean isHighest = null;
+ switch (highestFilter) {
+ case ALL:
+ break;
+ case HIGHEST_ONLY:
+ isHighest = true;
+ break;
+ case NON_HIGHEST_ONLY:
+ isHighest = false;
+ break;
+ default:
+ break;
+ }
+ Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
+ .getAllCertifiedResources(getAbstract, isHighest);
+
+ if (getResponse.isRight()) {
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(getResponse.right().value())));
+ }
+
+ return Either.left(getResponse.left().value());
+ }
+
+ public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
+ ResourceTypeEnum resourceTypeEnum, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Resource Name Exists", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
+ // DE242223
+ titanDao.commit();
+
+ if (dataModelResponse.isLeft()) {
+ Map<String, Boolean> result = new HashMap<>();
+ result.put("isValid", dataModelResponse.left().value());
+ log.debug("validation was successfully performed.");
+ return Either.left(result);
+ }
+
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+
+ return Either.right(responseFormat);
+ }
+
+ public Either<Resource, ResponseFormat> createResource(Resource resource, AuditingActionEnum auditingAction,
+ User user, Map<String, byte[]> csarUIPayload, String payloadName) {
+ Either<Resource, ResponseFormat> createResourceResponse = validateResourceBeforeCreate(resource, user, false);
+ if (createResourceResponse.isRight()) {
+ return createResourceResponse;
+ }
+
+ // Creating resource either by DAO or from CSAR
+ String csarUUID = null;
+ if (payloadName == null) {
+ csarUUID = resource.getCsarUUID();
+ } else {
+ csarUUID = payloadName;
+ }
+ if (csarUUID != null && !csarUUID.isEmpty()) {
+ // check if VF with the same Csar UUID or with he same name already
+ // exists
+ Either<Integer, StorageOperationStatus> validateCsarUuidUniquenessRes = toscaOperationFacade
+ .validateCsarUuidUniqueness(csarUUID);
+ if (validateCsarUuidUniquenessRes.isRight()) {
+ log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID,
+ resource.getSystemName());
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(validateCsarUuidUniquenessRes.right().value())));
+ }
+
+ Integer existingResourceRes = validateCsarUuidUniquenessRes.left().value();
+ if (existingResourceRes.intValue() > 0) {
+ log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ",
+ resource.getSystemName(), csarUUID);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS,
+ csarUUID);
+ componentsUtils.auditResource(errorResponse, user, resource, auditingAction);
+ return Either.right(errorResponse);
+ }
+
+ log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
+ createResourceResponse = createResourceFromCsar(resource, user, Either.left(csarUIPayload), csarUUID);
+ return createResourceResponse;
+ }
+
+ return createResourceByDao(resource, user, auditingAction, false, false);
+ }
+
+ public Either<Resource, ResponseFormat> validateAndUpdateResourceFromCsar(Resource resource, User user,
+ Map<String, byte[]> csarUIPayload, String payloadName, String resourceUniqueId) {
+ Either<Resource, ResponseFormat> updateResourceResponse = null;
+ Either<Resource, ResponseFormat> validateResourceResponse = null;
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
+ String csarUUID = null;
+ String csarVersion = null;
+ if (payloadName == null) {
+ csarUUID = resource.getCsarUUID();
+ csarVersion = resource.getCsarVersion();
+ } else {
+ csarUUID = payloadName;
+ }
+ if (csarUUID != null && !csarUUID.isEmpty()) {
+ Resource oldResource = getResourceByUniqueId(responseWrapper, resourceUniqueId);
+ if (responseWrapper.isEmpty()) {
+ validateCsarUuidMatching(responseWrapper, oldResource, resource, csarUUID, resourceUniqueId, user);
+ }
+ if (responseWrapper.isEmpty()) {
+ validateCsarIsNotAlreadyUsed(responseWrapper, oldResource, resource, csarUUID, user);
+ }
+ if (responseWrapper.isEmpty()) {
+ if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
+ overrideImmutableMetadata(oldResource, resource);
+ }
+ validateResourceResponse = validateResourceBeforeCreate(resource, user, false);
+ if (validateResourceResponse.isRight()) {
+ responseWrapper.setInnerElement(validateResourceResponse.right().value());
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ String oldCsarVersion = oldResource.getCsarVersion();
+ log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
+ resourceUniqueId);
+ // (on boarding flow): If the update includes same csarUUID and
+ // same csarVersion as already in the VF - no need to import the
+ // csar (do only metadata changes if there are).
+ if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
+ updateResourceResponse = updateResourceMetadata(resourceUniqueId, resource, oldResource, user,
+ false);
+ } else {
+ updateResourceResponse = updateResourceFromCsar(oldResource, resource, user,
+ AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, Either.left(csarUIPayload), csarUUID);
+ }
+ }
+ } else {
+ log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
+ resource.getName());
+ componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ if (responseWrapper.isEmpty()) {
+ return updateResourceResponse;
+ }
+ return Either.right(responseWrapper.getInnerElement());
+ }
+
+ private void validateCsarIsNotAlreadyUsed(Wrapper<ResponseFormat> responseWrapper, Resource oldResource,
+ Resource resource, String csarUUID, User user) {
+ // (on boarding flow): If the update includes a csarUUID: verify this
+ // csarUUID is not in use by another VF, If it is - use same error as
+ // above:
+ // "Error: The VSP with UUID %1 was already imported for VF %2. Please
+ // select another or update the existing VF." %1 - csarUUID, %2 - VF
+ // name
+ Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
+ .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
+ if (resourceLinkedToCsarRes.isRight()) {
+ if (!StorageOperationStatus.NOT_FOUND.equals(resourceLinkedToCsarRes.right().value())) {
+ log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
+ resource.getSystemName());
+ responseWrapper.setInnerElement(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(resourceLinkedToCsarRes.right().value())));
+ }
+ } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId())
+ && !resourceLinkedToCsarRes.left().value().getName().equals(oldResource.getName())) {
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
+ resourceLinkedToCsarRes.left().value().getName());
+ componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ }
+
+ private void validateCsarUuidMatching(Wrapper<ResponseFormat> responseWrapper, Resource resource,
+ Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
+ // (on boarding flow): If the update includes csarUUID which is
+ // different from the csarUUID of the VF - fail with
+ // error: "Error: Resource %1 cannot be updated using since it is linked
+ // to a different VSP" %1 - VF name
+ String oldCsarUUID = oldResource.getCsarUUID();
+ if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
+ log.debug(
+ "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
+ resourceUniqueId, csarUUID, oldCsarUUID);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(
+ ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
+ componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ }
+
+ private Resource getResourceByUniqueId(Wrapper<ResponseFormat> responseWrapper, String resourceUniqueId) {
+ Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
+ if (oldResourceRes.isRight()) {
+ log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
+ oldResourceRes.right().value());
+ responseWrapper.setInnerElement(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(oldResourceRes.right().value())));
+ return null;
+ }
+ return oldResourceRes.left().value();
+ }
+
+ private void overrideImmutableMetadata(Resource oldRresource, Resource resource) {
+ resource.setName(oldRresource.getName());
+ resource.setIcon(oldRresource.getIcon());
+ resource.setTags(oldRresource.getTags());
+ resource.setVendorName(oldRresource.getVendorName());
+ resource.setCategories(oldRresource.getCategories());
+ resource.setDerivedFrom(oldRresource.getDerivedFrom());
+ }
+
+ private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource,
+ User user, AuditingActionEnum updateResource, boolean inTransaction,
+ Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
+
+ // check state
+ if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
+ if (!oldRresource.getLastUpdaterUserId().equals(user.getUserId())) {
+ log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}",
+ oldRresource.getLastUpdaterUserId(), user.getUserId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+ String lockedResourceId = oldRresource.getUniqueId();
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+
+ Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
+ if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
+ csar = csarUIPayload;
+ } else {
+ csar = csarOperation.getCsar(csarUUID, user);
+ }
+ if (csar.isRight()) {
+ log.debug("Failed to get csar for casrUUID{} ", csarUUID);
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(csar.right().value())));
+ }
+
+ Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(newRresource,
+ user, csarUUID, csar);
+ if (toscaYamlCsarStatus.isRight()) {
+ return Either.right(toscaYamlCsarStatus.right().value());
+ }
+ Either<String, ResponseFormat> checksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(),
+ csarUUID, componentsUtils);
+ if (checksum.isRight()) {
+ log.debug("Failed to calculate checksum for casrUUID{} error {} ", csarUUID, checksum.right().value());
+ return Either.right(checksum.right().value());
+ }
+ if (!checksum.left().value().equals(
+ oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
+ log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID,
+ oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition()
+ .getImportedToscaChecksum(),
+ checksum.left().value());
+ oldRresource.getComponentMetadataDefinition().getMetadataDataDefinition()
+ .setImportedToscaChecksum(checksum.left().value());
+ }
+
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldRresource,
+ "update Resource From Csar");
+ if (lockResult.isRight()) {
+ return Either.right(lockResult.right().value());
+ }
+
+ String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+ String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
+ CsarInfo csarInfo = new CsarInfo(newRresource.getName(), user, csarUUID, csar.left().value(), yamlFileContents,
+ true);
+ Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
+ Either<Resource, ResponseFormat> result = null;
+
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
+ nodeTypesInfo, csarInfo, oldRresource);
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ",
+ csarInfo.getCsarUUID());
+ result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
+ return result;
+ }
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
+ .left().value();
+ try {
+ result = updateResourceFromYaml(oldRresource, newRresource, updateResource, createdArtifacts, yamlFileName,
+ yamlFileContents, csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
+
+ } finally {
+ if (result == null || result.isRight()) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ log.debug("unlock resource {}", lockedResourceId);
+ graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
+ }
+ return result;
+
+ }
+
+ private Either<Resource, ResponseFormat> updateResourceFromYaml(Resource oldRresource, Resource newRresource,
+ AuditingActionEnum updateResource, List<ArtifactDefinition> createdArtifacts,
+ String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ String nodeName, boolean isNested) {
+ Either<Resource, ResponseFormat> result;
+ Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither;
+ boolean inTransaction = true;
+ boolean shouldLock = false;
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate;
+ Resource preparedResource;
+ Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(
+ yamlFileName, newRresource, yamlFileContent, csarInfo.getCreatedNodesToscaResourceNames(),
+ nodeTypesInfo, nodeName);
+ if (uploadComponentInstanceInfoMap.isRight()) {
+ ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), newRresource, updateResource);
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value()
+ .getInstances();
+
+ prepareForUpdate = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
+ inTransaction, shouldLock, isNested);
+ if (prepareForUpdate.isRight()) {
+ log.debug("Failed to prepare resource for update : {}", prepareForUpdate.right().value());
+ result = Either.right(prepareForUpdate.right().value());
+ return result;
+ }
+ preparedResource = prepareForUpdate.left().value().left;
+
+ log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
+
+ Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(preparedResource);
+ if (genericResourceEither.isRight()) {
+ log.debug("failed to get resource generic type. status is {}", genericResourceEither.right().value());
+ ResponseFormat responseFormat = genericResourceEither.right().value();
+ componentsUtils.auditResource(genericResourceEither.right().value(), csarInfo.getModifier(),
+ preparedResource, updateResource);
+ return Either.right(responseFormat);
+ }
+
+ parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
+ shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
+ if (parseNodeTypeInfoYamlEither.isRight()) {
+ ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource, updateResource);
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ Map<String, InputDefinition> inputs = uploadComponentInstanceInfoMap.left().value().getInputs();
+ Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(preparedResource,
+ csarInfo.getModifier(), inputs, inTransaction);
+ if (createInputsOnResource.isRight()) {
+ log.debug("failed to create resource inputs status is {}", createInputsOnResource.right().value());
+ ResponseFormat responseFormat = createInputsOnResource.right().value();
+ componentsUtils.auditResource(createInputsOnResource.right().value(), csarInfo.getModifier(),
+ preparedResource, updateResource);
+ result = Either.right(responseFormat);
+ return result;
+ }
+ preparedResource = createInputsOnResource.left().value();
+
+ Either<Resource, ResponseFormat> createResourcesInstancesEither = createResourceInstances(
+ csarInfo.getModifier(), yamlFileName, preparedResource, instances, inTransaction, shouldLock,
+ csarInfo.getCreatedNodes());
+ if (createResourcesInstancesEither.isRight()) {
+ log.debug("failed to create resource instances status is {}",
+ createResourcesInstancesEither.right().value());
+ ResponseFormat responseFormat = createResourcesInstancesEither.right().value();
+ componentsUtils.auditResource(createResourcesInstancesEither.right().value(), csarInfo.getModifier(),
+ preparedResource, updateResource);
+ result = Either.right(responseFormat);
+ return result;
+ }
+ preparedResource = createResourcesInstancesEither.left().value();
+
+ createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName,
+ preparedResource, instances);
+ if (createResourcesInstancesEither.isRight()) {
+ log.debug("failed to create relation between resource instances status is {}",
+ createResourcesInstancesEither.right().value());
+ result = Either.right(createResourcesInstancesEither.right().value());
+ return result;
+ }
+
+ preparedResource = createResourcesInstancesEither.left().value();
+
+ Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
+ .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.left().value().getGroups(),
+ preparedResource.getSystemName());
+ if (validateUpdateVfGroupNamesRes.isRight()) {
+
+ return Either.right(validateUpdateVfGroupNamesRes.right().value());
+ }
+ // add groups to resource
+ Map<String, GroupDefinition> groups;
+
+ if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
+ groups = validateUpdateVfGroupNamesRes.left().value();
+ } else {
+ groups = uploadComponentInstanceInfoMap.left().value().getGroups();
+ }
+ Either<Resource, ResponseFormat> updatedGroupsOnResource = updateGroupsOnResource(preparedResource,
+ csarInfo.getModifier(), groups);
+ if (updatedGroupsOnResource.isRight()) {
+
+ return updatedGroupsOnResource;
+ }
+ preparedResource = updatedGroupsOnResource.left().value();
+
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
+ nodeTypesArtifactsToHandle);
+
+ Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
+ csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ if (updateArtifactsEither.isRight()) {
+ log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
+ result = Either.right(updateArtifactsEither.right().value());
+ return result;
+ }
+ preparedResource = updateArtifactsEither.left().value();
+
+ ActionStatus mergingPropsAndInputsStatus = mergeResourceEntities(oldRresource, preparedResource);
+ if (mergingPropsAndInputsStatus != ActionStatus.OK) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
+ preparedResource);
+ return Either.right(responseFormat);
+ }
+
+ Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic
+ .setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
+ result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value())
+ : Either.left(preparedResource);
+
+ return result;
+
+ }
+
+ private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
+ String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
+
+ String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
+ Resource resource = preparedResource;
+
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
+ .getNodeTypesArtifactsToHandle();
+ if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
+ if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
+ handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
+ if (handleNodeTypeArtifactsRes.isRight()) {
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
+ } else {
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
+ log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
+ if (createdCsarArtifactsEither.isRight()) {
+ return createdCsarArtifactsEither;
+
+ }
+ resource = createdCsarArtifactsEither.left().value();
+ }
+ return Either.left(resource);
+ }
+
+ private ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) {
+ Either<MergeResourceBusinessLogic, ActionStatus> mergeResourceBLEither = mergeResourceBLFactory
+ .getInstance(oldResource, newResource);
+ if (mergeResourceBLEither.isRight()) {
+ return mergeResourceBLEither.right().value();
+ }
+ MergeResourceBusinessLogic mergeResourceBusinessLogic = mergeResourceBLEither.left().value();
+ return mergeResourceBusinessLogic.mergeResourceEntities(oldResource, newResource);
+ }
+
+ private Either<Resource, ResponseFormat> handleResourceGenericType(Resource resource) {
+ Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
+ if (genericResourceEither.isRight()) {
+ return genericResourceEither;
+ }
+ if (resource.shouldGenerateInputs()) {
+ generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
+ }
+ return genericResourceEither;
+ }
+
+ private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Resource oldResource) {
+
+ Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
+ .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes;
+
+ try {
+ nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
+ Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo,
+ oldResource.getName(), csarInfo);
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+ log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
+ oldResource.getName(), csarInfo.getCsarUUID());
+
+ for (Entry<String, ImmutablePair<String, String>> currVfcToscaNameEntry : extractedVfcToscaNames
+ .entrySet()) {
+ String currVfcToscaName = currVfcToscaNameEntry.getValue().getLeft();
+ String previousVfcToscaName = currVfcToscaNameEntry.getValue().getRight();
+ String currNamespace = currVfcToscaNameEntry.getKey();
+ log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
+
+ Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade
+ .getLatestByToscaResourceName(currVfcToscaName);
+ Resource curNodeType = null;
+ if (curVfcRes.isRight() && curVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
+ curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(previousVfcToscaName);
+ }
+ if (curVfcRes.isRight() && curVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName,
+ curVfcRes.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(curVfcRes.right().value()),
+ csarInfo.getCsarUUID());
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), oldResource, AuditingActionEnum.CREATE_RESOURCE);
+ nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
+ break;
+ } else if (curVfcRes.isLeft()) {
+ curNodeType = curVfcRes.left().value();
+ }
+ if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
+ List<ArtifactDefinition> currArtifacts = new ArrayList<>();
+ if (extractedVfcsArtifacts.containsKey(currNamespace)) {
+ handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
+ }
+ curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
+ if (curNodeTypeArtifactsToHandleRes.isRight()) {
+ nodeTypesArtifactsToHandleRes = Either.right(curNodeTypeArtifactsToHandleRes.right().value());
+ break;
+ }
+ curNodeTypeArtifactsToHandle = curNodeTypeArtifactsToHandleRes.left().value();
+
+ } else if (curNodeType != null) {
+ // delete all artifacts if have not received artifacts from
+ // csar
+ curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ // delete all informational artifacts
+ artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
+ .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(Collectors.toList()));
+ // delete all deployment artifacts
+ artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
+ if (!artifactsToDelete.isEmpty()) {
+ curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ }
+ if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
+ nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
+ }
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
+ log.debug("Exception occured when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypesArtifactsToHandleRes;
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(
+ Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
+
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
+ EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ try {
+ List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
+ List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
+ List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+ if (curNodeType != null) {
+ Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
+ if (curNodeType.getDeploymentArtifacts() != null) {
+ existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
+ }
+ if (curNodeType.getArtifacts() != null) {
+ existingArtifacts
+ .putAll(curNodeType.getArtifacts().entrySet().stream()
+ .filter(e -> e.getValue()
+ .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
+ }
+ for (ArtifactDefinition currNewArtifact : extractedArtifacts) {
+ ArtifactDefinition foundArtifact;
+
+ if (!existingArtifacts.isEmpty()) {
+ foundArtifact = existingArtifacts.values().stream()
+ .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
+ .orElse(null);
+ if (foundArtifact != null) {
+ if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
+ if (!foundArtifact.getArtifactChecksum()
+ .equals(currNewArtifact.getArtifactChecksum())) {
+ foundArtifact.setPayload(currNewArtifact.getPayloadData());
+ foundArtifact.setPayloadData(
+ Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+ foundArtifact.setArtifactChecksum(GeneralUtility
+ .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
+ artifactsToUpdate.add(foundArtifact);
+ }
+ existingArtifacts.remove(foundArtifact.getArtifactLabel());
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.",
+ currNewArtifact.getArtifactName());
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
+ ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
+ currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
+ foundArtifact.getArtifactType());
+ responseWrapper.setInnerElement(responseFormat);
+ break;
+ }
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ artifactsToDelete.addAll(existingArtifacts.values());
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
+ nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ if (!artifactsToUpload.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
+ if (!artifactsToUpdate.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
+ if (!artifactsToDelete.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ nodeTypeArtifactsToHandleRes = Either.left(nodeTypeArtifactsToHandle);
+ }
+ if (!responseWrapper.isEmpty()) {
+ nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypeArtifactsToHandleRes;
+ }
+
+ /**
+ * Changes resource life cycle state to checked out
+ *
+ * @param resource
+ * @param user
+ * @param inTransaction
+ * @return
+ */
+ private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
+ Either<Resource, ResponseFormat> checkoutResourceRes;
+ try {
+ if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
+ .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ log.debug(
+ "************* Going to change life cycle state of resource {} to not certified checked out. ",
+ resource.getName());
+ Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
+ resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction("certification on import",
+ LifecycleChanceActionEnum.CREATE_FROM_CSAR),
+ inTransaction, true);
+ if (checkoutRes.isRight()) {
+ log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
+ resource.getComponentType().getNodeType(), resource.getUniqueId(),
+ checkoutRes.right().value().getStatus());
+ checkoutResourceRes = Either.right(checkoutRes.right().value());
+ } else {
+ checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
+ }
+ } else {
+ checkoutResourceRes = Either.left(resource);
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ checkoutResourceRes = Either.right(responseFormat);
+ log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
+ e);
+ }
+ return checkoutResourceRes;
+ }
+
+ /**
+ * Handles Artifacts of NodeType
+ *
+ * @param nodeTypeResource
+ * @param nodeTypeArtifactsToHandle
+ * @param user
+ * @param inTransaction
+ * @return
+ */
+ public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
+ Either<Resource, ResponseFormat> changeStateResponse;
+ try {
+ changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
+ if (changeStateResponse.isRight()) {
+ return Either.right(changeStateResponse.right().value());
+ }
+ nodeTypeResource = changeStateResponse.left().value();
+
+ List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
+ log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
+ for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
+ .entrySet()) {
+ ArtifactOperationEnum curOperation = curOperationEntry.getKey();
+ List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
+ if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
+ log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
+ nodeTypeResource.getName());
+ handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
+ .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
+ createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false,
+ ignoreLifecycleState, curOperation),
+ false, inTransaction);
+ if (handleNodeTypeArtifactsRequestRes.isRight()) {
+ handleNodeTypeArtifactsRes = Either.right(handleNodeTypeArtifactsRequestRes.right().value());
+ break;
+ }
+ if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
+ createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
+ }
+ handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes.left().value());
+ }
+ }
+ if (handleNodeTypeArtifactsRes == null) {
+ handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ handleNodeTypeArtifactsRes = Either.right(responseFormat);
+ log.debug("Exception occured when handleVfcArtifacts, error is:{}", e.getMessage(), e);
+ }
+ return handleNodeTypeArtifactsRes;
+ }
+
+ private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
+ String vfResourceName, CsarInfo csarInfo) {
+ Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
+
+ Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
+ if (!nodes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
+ ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
+ vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
+ }
+ }
+ for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
+ vfcToscaNames.put(cvfc.getType(),
+ buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
+ }
+ return vfcToscaNames;
+ }
+
+ private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
+ Map<String, Object> nodes = new HashMap<>();
+ for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
+ extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
+ }
+ extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
+ return nodes;
+ }
+
+ private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
+ .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
+ if (eitherNodeTypes.isLeft()) {
+ nodes.putAll(eitherNodeTypes.left().value());
+ }
+ }
+
+ public Either<Resource, ResponseFormat> createResourceFromCsar(Resource resource, User user,
+ Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload, String csarUUID) {
+ log.trace("************* created successfully from YAML, resource TOSCA ");
+
+ Either<Map<String, byte[]>, StorageOperationStatus> csar = null;
+ if (csarUIPayload != null && csarUIPayload.left() != null && csarUIPayload.left().value() != null) {
+ csar = csarUIPayload;
+ } else {
+ csar = csarOperation.getCsar(csarUUID, user);
+ }
+
+ Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = validateAndParseCsar(resource, user,
+ csarUUID, csar);
+ if (toscaYamlCsarStatus.isRight()) {
+ return Either.right(toscaYamlCsarStatus.right().value());
+ }
+ Either<String, ResponseFormat> toscaYamlChecksum = CsarValidationUtils.getToscaYamlChecksum(csar.left().value(),
+ csarUUID, componentsUtils);
+ if (toscaYamlChecksum.isRight()) {
+ log.debug("Failed to calculate checksum for CSAR {}, error {}", csarUUID,
+ toscaYamlChecksum.right().value());
+ return Either.right(toscaYamlChecksum.right().value());
+ }
+ resource.getComponentMetadataDefinition().getMetadataDataDefinition()
+ .setImportedToscaChecksum(toscaYamlChecksum.left().value());
+
+ String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+ String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
+ log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
+
+ CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), yamlFileContents,
+ false);
+ Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csarInfo);
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
+ nodeTypesInfo, csarInfo, resource);
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ",
+ csarInfo.getCsarUUID());
+ return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
+ }
+ Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents,
+ yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
+ null);
+ if (createResourceFromYaml.isRight()) {
+ log.debug("Couldn't create resource from YAML");
+ return Either.right(createResourceFromYaml.right().value());
+ }
+
+ Resource vfResource = createResourceFromYaml.left().value();
+ log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
+ vfResource.getToscaResourceName());
+ return Either.left(vfResource);
+ }
+
+ private Map<String, NodeTypeInfo> extractNodeTypesInfo(CsarInfo csarInfo) {
+ Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
+ List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
+ for (Map.Entry<String, byte[]> entry : csarInfo.getCsar().entrySet()) {
+ extractNodeTypeInfo(nodeTypesInfo, globalSubstitutes, entry);
+ }
+ if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
+ setDerivedFrom(nodeTypesInfo, globalSubstitutes);
+ }
+ markNestedVfc(csarInfo.getMappedToscaMainTemplate(), nodeTypesInfo);
+ return nodeTypesInfo;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo,
+ List<Entry<String, byte[]>> globalSubstitutes) {
+ for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
+ String yamlFileContents = new String(entry.getValue());
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
+ Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate,
+ ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+ if (nodeTypesEither.isLeft()) {
+ Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
+ for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
+ Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
+ if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
+ List<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ nodeTypeInfo.setDerivedFrom(derivedFrom);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
+ List<Entry<String, byte[]>> globalSubstitutes, Map.Entry<String, byte[]> entry) {
+ if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
+ if (!isGlobalSubstitute(entry.getKey())) {
+ String yamlFileContents = new String(entry.getValue());
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
+ Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(
+ mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
+ if (substitutionMappingsEither.isLeft()) {
+ Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left()
+ .value();
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
+ NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
+ nodeTypeInfo.setType(
+ (String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
+ nodeTypeInfo.setTemplateFileName(entry.getKey());
+ nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
+ nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
+ }
+ }
+ } else {
+ globalSubstitutes.add(entry);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
+ Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate,
+ ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
+ if (nodeTemplatesEither.isLeft()) {
+ Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
+ for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
+ Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
+ if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (nodeTypesInfo.containsKey(type)) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
+ nodeTypeInfo.setNested(true);
+ }
+ }
+ }
+ }
+ }
+
+ private boolean isGlobalSubstitute(String fileName) {
+ return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE)
+ || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
+ }
+
+ private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user,
+ String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
+ if (csar.isRight()) {
+ StorageOperationStatus value = csar.right().value();
+ log.debug("Error when fetching csar with ID {}, error: {}", csarUUID, value);
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar.left().value(),
+ csarUUID, componentsUtils);
+ if (validateCsarStatus.isRight()) {
+ ResponseFormat responseFormat = validateCsarStatus.right().value();
+ log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ return Either.right(responseFormat);
+ }
+
+ Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils
+ .getToscaYaml(csar.left().value(), csarUUID, componentsUtils);
+
+ if (toscaYamlCsarStatus.isRight()) {
+ ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
+ log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ return Either.right(responseFormat);
+ }
+ return toscaYamlCsarStatus;
+ }
+
+ private Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user,
+ boolean inTransaction) {
+ log.trace("validating resource before create");
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Resource", resource,
+ AuditingActionEnum.CREATE_RESOURCE, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user.copyData(eitherCreator.left().value());
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, resource, new ArrayList<Role>(),
+ AuditingActionEnum.CREATE_RESOURCE, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+ // VF / PNF "derivedFrom" should be null (or ignored)
+ if (ModelConverter.isAtomicComponent(resource)) {
+ Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource,
+ AuditingActionEnum.CREATE_RESOURCE);
+ if (validateDerivedFromNotEmpty.isRight()) {
+ return Either.right(validateDerivedFromNotEmpty.right().value());
+ }
+ }
+ return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
+
+ }
+
+ // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
+ // nodeTypesArtifactsToCreate, true, false, null
+ private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml,
+ String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeName) {
+
+ List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
+ log.trace("************* createResourceFromYaml before parse yaml ");
+ Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(
+ yamlName, resource, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo,
+ nodeName);
+ if (parseResourceInfoFromYamlEither.isRight()) {
+ ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ return Either.right(responseFormat);
+ }
+ log.trace("************* createResourceFromYaml after parse yaml ");
+ ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
+ log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
+ log.trace("************* createResourceFromYaml before create ");
+ Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource,
+ parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
+ nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+ log.trace("************* createResourceFromYaml after create ");
+ if (createdResourceResponse.isRight()) {
+ ResponseFormat responseFormat = createdResourceResponse.right().value();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ return Either.right(responseFormat);
+ }
+
+ return createdResourceResponse;
+
+ }
+
+ public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName,
+ Resource resource, Map<String, Object> mappedToscaTemplate, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
+ CsarInfo csarInfo) {
+
+ Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate,
+ ToscaTagNamesEnum.TOSCA_VERSION);
+ if (tosca_version.isRight()) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
+ return Either.right(responseFormat);
+ }
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
+ .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
+ Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
+ Map<String, Object> mapToConvert = new HashMap<String, Object>();
+ mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
+ Resource vfcCreated = null;
+ if (eitherNodeTypes.isLeft()) {
+ Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
+ while (nodesNameValue.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameValue.next();
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
+ || nodeTypesArtifactsToHandle.isEmpty() ? null
+ : nodeTypesArtifactsToHandle.get(nodeType.getKey());
+
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
+ Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource,
+ nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeType.getKey());
+ log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
+ if (handleNeatedVfcYaml.isRight()) {
+ return Either.right(handleNeatedVfcYaml.right().value());
+ }
+ vfcCreated = handleNeatedVfcYaml.left().value();
+ } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
+ && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
+ log.trace("************* Going to create node {}", nodeType.getKey());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this
+ .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
+ resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
+ csarInfo, true);
+ log.debug("************* Finished to create node {}", nodeType.getKey());
+
+ if (resourceCreated.isRight()) {
+ return Either.right(resourceCreated.right().value());
+ }
+ vfcCreated = resourceCreated.left().value().getLeft();
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
+ vfcCreated.getToscaResourceName());
+ }
+ if (vfcCreated != null) {
+ csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
+ }
+ mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
+ }
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName) {
+
+ Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
+ String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
+ Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
+
+ log.debug("************* Going to create node types from yaml {}", yamlName);
+ Either<Map<String, Resource>, ResponseFormat> createNodeTypesRes = createResourcesFromYamlNodeTypesList(
+ yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+ csarInfo);
+ if (createNodeTypesRes.isRight()) {
+ log.debug("Failed to create node types from yaml {}. Status is {}", yamlName,
+ createNodeTypesRes.right().value());
+ return Either.right(createNodeTypesRes.right().value());
+ }
+ log.debug("************* Finished to create node types from yaml {}", yamlName);
+
+ if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
+ log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
+ handleNestedVfcRes = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+ csarInfo, nodeName, yamlName);
+ }
+ return handleNestedVfcRes;
+ }
+
+ private Either<Resource, ResponseFormat> handleComplexVfc(Resource resource,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName, String yamlName) {
+
+ Either<Resource, ResponseFormat> result = null;
+ Resource oldComplexVfc = null;
+ Resource newComplexVfc = null;
+
+ Either<Resource, ResponseFormat> buildCvfcRes = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
+ if (buildCvfcRes.isRight()) {
+ log.debug("Failed to validate complex VFC for node {}. ", nodeName);
+ result = buildCvfcRes;
+ }
+ if (result == null) {
+ newComplexVfc = buildCvfcRes.left().value();
+ Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
+ .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
+ if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
+ oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
+ buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(),
+ nodeName).getRight());
+ }
+ if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
+ log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
+ newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } else if (oldComplexVfcRes.isLeft()) {
+ log.debug("validate derived before update");
+ Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
+ oldComplexVfcRes.left().value(), newComplexVfc,
+ ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+ if (eitherValidation.isLeft()) {
+ oldComplexVfc = oldComplexVfcRes.left().value();
+ }
+ }
+ }
+ if (result == null) {
+ result = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
+ oldComplexVfc, newComplexVfc);
+ }
+ if (result.isLeft()) {
+ newComplexVfc = result.left().value();
+ csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
+ "certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
+ result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
+ true);
+ if (result.isRight()) {
+ log.debug("Failed to certify complex VFC resource {}. ", newComplexVfc.getName());
+ }
+ }
+ if (result.isLeft()) {
+ csarInfo.getCreatedNodes().put(nodeName, result.left().value());
+ csarInfo.getCvfcToCreateQueue().remove();
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> handleComplexVfc(
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+ List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+ String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
+
+ Either<Resource, ResponseFormat> handleComplexVfcRes;
+ Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
+ String yamlContent = new String(csarInfo.getCsar().get(yamlName));
+ Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream()
+ .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
+ markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
+ if (oldComplexVfc == null) {
+ handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
+ csarInfo, nodesArtifactsToHandle, false, true, nodeName);
+ if (handleComplexVfcRes.isRight()) {
+ log.debug("Failed to create resource {} from YAML {}. ", newComplexVfc.getName(), yamlName);
+ }
+ } else {
+ handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
+ AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
+ newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
+ if (handleComplexVfcRes.isRight()) {
+ log.debug("Failed to update resource {} from YAML {}. ", oldComplexVfc.getName(), yamlName);
+ }
+ }
+ return handleComplexVfcRes;
+ }
+
+ private Either<Resource, ResponseFormat> buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
+ Map<String, NodeTypeInfo> nodesInfo) {
+
+ Either<Resource, ResponseFormat> result = null;
+ Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
+ log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
+
+ if (!csarInfo.getCvfcToCreateQueue().contains(nodeName)) {
+ csarInfo.getCvfcToCreateQueue().add(nodeName);
+ } else {
+ log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", complexVfc.getName(),
+ csarInfo.getVfResourceName());
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED,
+ csarInfo.getVfResourceName(), complexVfc.getName()));
+ }
+ if (result == null) {
+ result = validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
+ AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+ if (result.isRight()) {
+ log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
+ }
+ }
+ return result;
+ }
+
+ private String getNodeTypeActualName(String fullName) {
+ String nameWithouNamespacePrefix = fullName
+ .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ return nameWithouNamespacePrefix.substring(resourceType.length());
+ }
+
+ private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(
+ String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
+ Resource resourceVf, boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
+ boolean isNested) {
+
+ Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf,
+ nodeNameValue.getKey(), user);
+ if (resourceMetaData.isRight()) {
+ return Either.right(resourceMetaData.right().value());
+ }
+ String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
+ resourceMetaData.left().value().getResourceType(), csarInfo);
+
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf,
+ AuditingActionEnum.CHECKIN_RESOURCE, true);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock,
+ nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
+ nodeNameValue.getKey(), isNested);
+ }
+
+ private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
+ String nodeResourceType, CsarInfo csarInfo) {
+ // We need to create a Yaml from each node_types in order to create
+ // resource from each node type using import normative flow.
+ DumperOptions options = new DumperOptions();
+ options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
+ Yaml yaml = new Yaml(options);
+
+ Map<String, Object> node = new HashMap<>();
+ node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
+ .getLeft(), nodeNameValue.getValue());
+ mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
+
+ return yaml.dumpAsMap(mapToConvert);
+ }
+
+ public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
+
+ Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = this.validateDerivedFromNotEmpty(creator,
+ resource, AuditingActionEnum.CREATE_RESOURCE);
+ if (validateDerivedFromNotEmpty.isRight()) {
+ return Either.right(validateDerivedFromNotEmpty.right().value());
+ }
+ return Either.left(true);
+ }
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml,
+ UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
+ String nodeName, boolean isNested) {
+
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import",
+ LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this
+ .validateResourceCreationFromNodeType(resource, creator);
+ return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
+ lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+ }
+
+ private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf,
+ String nodeName, User user) {
+ UploadResourceInfo resourceMetaData = new UploadResourceInfo();
+
+ // validate nodetype name prefix
+ if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
+ log.debug("invalid nodeName:{} does not start with {}.", nodeName,
+ Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ yamlName, resourceMetaData.getName(), nodeName);
+ return Either.right(responseFormat);
+ }
+
+ String actualName = this.getNodeTypeActualName(nodeName);
+ String namePrefix = nodeName.replace(actualName, "");
+ String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+
+ // if we import from csar, the node_type name can be
+ // org.openecomp.resource.abstract.node_name - in this case we always
+ // create a vfc
+ if (resourceType.equals(Constants.ABSTRACT)) {
+ resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
+ }
+ // validating type
+ if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
+ log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
+ ResourceTypeEnum.values());
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ yamlName, resourceMetaData.getName(), nodeName);
+ return Either.right(responseFormat);
+ }
+
+ // Setting name
+ resourceMetaData.setName(resourceVf.getSystemName() + actualName);
+
+ // Setting type from name
+ String type = resourceType.toUpperCase();
+ resourceMetaData.setResourceType(type);
+
+ resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
+ resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+ resourceMetaData.setContactId(user.getUserId());
+ resourceMetaData.setVendorName(resourceVf.getVendorName());
+ resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
+
+ // Setting tag
+ List<String> tags = new ArrayList<>();
+ tags.add(resourceMetaData.getName());
+ resourceMetaData.setTags(tags);
+
+ // Setting category
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+ SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+ category.addSubCategory(subCategory);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ resourceMetaData.setCategories(categories);
+
+ return Either.left(resourceMetaData);
+ }
+
+ private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
+ Map<String, NodeTypeInfo> nodesInfo) {
+ Resource cvfc = new Resource();
+ NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
+ cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
+ cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
+ cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
+ cvfc.setResourceType(ResourceTypeEnum.CVFC);
+ cvfc.setAbstract(true);
+ cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
+ cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
+ cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+ cvfc.setContactId(csarInfo.getModifier().getUserId());
+ cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
+ cvfc.setVendorName(resourceVf.getVendorName());
+ cvfc.setVendorRelease(resourceVf.getVendorRelease());
+ cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
+ cvfc.setToscaResourceName(
+ buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName)
+ .getLeft());
+ cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+
+ List<String> tags = new ArrayList<>();
+ tags.add(cvfc.getName());
+ cvfc.setTags(tags);
+
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+ SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+ category.addSubCategory(subCategory);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ cvfc.setCategories(categories);
+
+ cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
+ cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
+ cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+
+ return cvfc;
+ }
+
+ private String buildCvfcName(String resourceVfName, String nodeName) {
+ String nameWithouNamespacePrefix = nodeName
+ .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
+ return addCvfcSuffixToResourceName(resourceName);
+ }
+
+ private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource,
+ ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
+ List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeName) {
+
+ boolean result = true;
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
+
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
+ "Create Resource");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ return Either.right(responseFormat);
+ }
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ }
+ try {
+ log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
+ Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
+ if (genericResourceEither.isRight()) {
+ result = false;
+ return genericResourceEither;
+ }
+ Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource,
+ csarInfo.getModifier(), isNormative, inTransaction);
+ log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
+ if (createResourcesEither.isRight()) {
+ result = false;
+ return createResourcesEither;
+ }
+ resource = createResourcesEither.left().value();
+ // add groups to resource
+ log.trace("************* Going to add inputs from yaml {}", yamlName);
+ if (resource.shouldGenerateInputs())
+ generateAndAddInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
+
+ Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
+ Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource,
+ csarInfo.getModifier(), inputs, inTransaction);
+ if (createInputsOnResource.isRight()) {
+ result = false;
+ return createInputsOnResource;
+ }
+ resource = createInputsOnResource.left().value();
+ log.trace("************* Finish to add inputs from yaml {}", yamlName);
+
+ Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
+ .getInstances();
+ log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
+
+ createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
+ actionEnum, topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeTypesArtifactsToCreate, nodeName);
+ log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
+ if (createResourcesEither.isRight()) {
+ result = false;
+ return createResourcesEither;
+ }
+
+ resource = createResourcesEither.left().value();
+ // validate update vf module group names
+ Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
+ .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
+ if (validateUpdateVfGroupNamesRes.isRight()) {
+ result = false;
+ return Either.right(validateUpdateVfGroupNamesRes.right().value());
+ }
+ // add groups to resource
+ Map<String, GroupDefinition> groups;
+ log.trace("************* Going to add groups from yaml {}", yamlName);
+
+ if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
+ groups = validateUpdateVfGroupNamesRes.left().value();
+ } else {
+ groups = parsedToscaYamlInfo.getGroups();
+ }
+ Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
+ csarInfo.getModifier(), groups);
+ if (createGroupsOnResource.isRight()) {
+ result = false;
+ return createGroupsOnResource;
+ }
+ resource = createGroupsOnResource.left().value();
+ log.trace("************* Finished to add groups from yaml {}", yamlName);
+
+ log.trace("************* Going to add artifacts from yaml {}", yamlName);
+
+ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
+ nodeTypesArtifactsToCreate);
+
+ Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
+ csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+ if (createArtifactsEither.isRight()) {
+ log.debug("failed to update artifacts {}", createArtifactsEither.right().value());
+ return createArtifactsEither;
+
+ }
+ resource = createArtifactsEither.left().value();
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
+ ASDCKpiApi.countCreatedResourcesKPI();
+ return Either.left(resource);
+
+ } finally {
+ if (!inTransaction) {
+ if (!result) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
+ log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
+ }
+
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ if (shouldLock) {
+ graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
+ NodeTypeEnum.Resource);
+ }
+ }
+ }
+
+ private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user,
+ Map<String, GroupDefinition> groups) {
+ if (groups != null && !groups.isEmpty()) {
+ Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(
+ groups, resource);
+
+ if (mergeGroupsUsingResource.isRight()) {
+ log.debug("Failed to prepare groups for creation");
+ return Either.right(mergeGroupsUsingResource.right().value());
+ }
+ List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
+ groupsAsList);
+ if (createGroups.isRight()) {
+ return Either.right(createGroups.right().value());
+ }
+ } else {
+ return Either.left(resource);
+ }
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId());
+ if (updatedResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
+ return Either.right(responseFormat);
+ }
+ return Either.left(updatedResource.left().value());
+ }
+
+ private Either<Resource, ResponseFormat> updateGroupsOnResource(Resource resource, User user,
+ Map<String, GroupDefinition> groups) {
+ if (groups != null && false == groups.isEmpty()) {
+ List<GroupDefinition> groupsFromResource = resource.getGroups();
+ Either<List<GroupDefinition>, ResponseFormat> mergeGroupsUsingResource = updateGroupMembersUsingResource(
+ groups, resource);
+
+ if (mergeGroupsUsingResource.isRight()) {
+ log.debug("Failed to prepare groups for creation");
+ return Either.right(mergeGroupsUsingResource.right().value());
+ }
+ List<GroupDefinition> groupsAsList = mergeGroupsUsingResource.left().value();
+ List<GroupDefinition> groupsToUpdate = new ArrayList<GroupDefinition>();
+ List<GroupDefinition> groupsToDelete = new ArrayList<GroupDefinition>();
+ List<GroupDefinition> groupsToCreate = new ArrayList<GroupDefinition>();
+ if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
+ for (GroupDefinition group : groupsAsList) {
+ Optional<GroupDefinition> op = groupsFromResource.stream()
+ .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
+ if (op.isPresent()) {
+ GroupDefinition groupToUpdate = op.get();
+ groupToUpdate.setMembers(group.getMembers());
+ groupsToUpdate.add(groupToUpdate);
+ } else {
+ groupsToCreate.add(group);
+ }
+ }
+ for (GroupDefinition group : groupsFromResource) {
+ Optional<GroupDefinition> op = groupsAsList.stream()
+ .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
+ if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
+
+ groupsToDelete.add(group);
+ }
+
+ }
+ } else
+ groupsToCreate.addAll(groupsAsList);
+ Either<List<GroupDefinition>, ResponseFormat> prepareGroups = null;
+ if (!groupsToCreate.isEmpty()) {
+
+ if (groupsFromResource != null && !groupsFromResource.isEmpty()) {
+ prepareGroups = groupBusinessLogic.addGroups(resource,
+ groupsToCreate);
+ } else {
+ prepareGroups = groupBusinessLogic.createGroups(resource,
+ groupsToCreate);
+ }
+
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
+ }
+ }
+
+ if (!groupsToDelete.isEmpty()) {
+ prepareGroups = groupBusinessLogic.deleteGroups(resource,
+ groupsToDelete);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
+ }
+ }
+
+ if (groupsToUpdate != null && !groupsToUpdate.isEmpty()) {
+ prepareGroups = groupBusinessLogic.updateGroups(resource, groupsToUpdate);
+ if (prepareGroups.isRight()) {
+ return Either.right(prepareGroups.right().value());
+ }
+ }
+
+ } else {
+ return Either.left(resource);
+ }
+
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId());
+ if (updatedResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
+ return Either.right(responseFormat);
+ }
+ return Either.left(updatedResource.left().value());
+ }
+
+ private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user,
+ Map<String, InputDefinition> inputs, boolean inTransaction) {
+ List<InputDefinition> resourceProperties = resource.getInputs();
+ if ((inputs != null && false == inputs.isEmpty())
+ || (resourceProperties != null && false == resourceProperties.isEmpty())) {
+
+ Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
+ resource);
+ if (createInputs.isRight()) {
+ return Either.right(createInputs.right().value());
+ }
+ } else {
+ return Either.left(resource);
+ }
+
+ Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId());
+ if (updatedResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
+ return Either.right(responseFormat);
+ }
+ return Either.left(updatedResource.left().value());
+ }
+
+ private Either<List<GroupDefinition>, ResponseFormat> updateGroupMembersUsingResource(
+ Map<String, GroupDefinition> groups, Resource component) {
+
+ List<GroupDefinition> result = new ArrayList<>();
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+
+ if (groups != null) {
+ Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
+ if (validateCyclicGroupsDependencies.isRight()) {
+ return FunctionalInterfaces.convertEitherRight(validateCyclicGroupsDependencies);
+ }
+ for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
+ String groupName = entry.getKey();
+
+ GroupDefinition groupDefinition = entry.getValue();
+
+ GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
+ updatedGroupDefinition.setMembers(null);
+
+ // get the members of the group
+ Map<String, String> members = groupDefinition.getMembers();
+ if (members != null) {
+ Set<String> compInstancesNames = members.keySet();
+
+ if (componentInstances == null || true == componentInstances.isEmpty()) {
+ String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
+ log.debug(
+ "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
+ membersAstString, groupName, component.getNormalizedName());
+ return Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+ component.getNormalizedName(), getComponentTypeForResponse(component)));
+ }
+ // Find all component instances with the member names
+ Map<String, String> memberNames = componentInstances.stream()
+ .collect(Collectors.toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+ memberNames.putAll(groups.keySet().stream().collect(Collectors.toMap(g -> g, g -> "")));
+ Map<String, String> relevantInstances = memberNames.entrySet().stream()
+ .filter(n -> compInstancesNames.contains(n.getKey()))
+ .collect(Collectors.toMap(n -> n.getKey(), n -> n.getValue()));
+
+ if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
+
+ List<String> foundMembers = new ArrayList<>();
+ if (relevantInstances != null) {
+ foundMembers = relevantInstances.keySet().stream().collect(Collectors.toList());
+ }
+ compInstancesNames.removeAll(foundMembers);
+ String membersAstString = compInstancesNames.stream().collect(Collectors.joining(","));
+ log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
+ groupName, component.getNormalizedName());
+ return Either.right(componentsUtils.getResponseFormat(
+ ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+ component.getNormalizedName(), getComponentTypeForResponse(component)));
+ }
+
+ updatedGroupDefinition.setMembers(relevantInstances);
+ }
+
+ result.add(updatedGroupDefinition);
+ }
+ }
+ return Either.left(result);
+ }
+
+ /**
+ * This Method validates that there is no cyclic group dependencies. meaning
+ * group A as member in group B which is member in group A
+ *
+ * @param allGroups
+ * @return
+ */
+ private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
+
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ try {
+ Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
+ while (allGroupsItr.hasNext() && result.isLeft()) {
+ Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
+ // Fetches a group member A
+ String groupAName = groupAEntry.getKey();
+ // Finds all group members in group A
+ Set<String> allGroupAMembersNames = new HashSet<>();
+ fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
+ // If A is a group member of itself found cyclic dependency
+ if (allGroupAMembersNames.contains(groupAName)) {
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
+ result = Either.right(responseFormat);
+ }
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ result = Either.right(responseFormat);
+ log.debug("Exception occured when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
+ }
+ return result;
+ }
+
+ /**
+ * This Method fills recursively the set groupMembers with all the members
+ * of the given group which are also of type group.
+ *
+ * @param groupName
+ * @param allGroups
+ * @param allGroupMembers
+ * @return
+ */
+ private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
+ Set<String> allGroupMembers) {
+
+ // Found Cyclic dependency
+ if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
+ return;
+ }
+ GroupDefinition groupDefinition = allGroups.get(groupName);
+ // All Members Of Current Group Resource Instances & Other Groups
+ Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
+ // Filtered Members Of Current Group containing only members which
+ // are groups
+ List<String> currGroupFilteredMembers = currGroupMembers.stream().
+ // Keep Only Elements of type group and not Resource Instances
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ // Add Filtered Elements to main Set
+ peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
+ // Collect results
+ collect(Collectors.toList());
+
+ // Recursively call the method for all the filtered group members
+ for (String innerGroupName : currGroupFilteredMembers) {
+ fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
+ }
+
+ }
+
+ private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
+ Set<String> allGroupMembers) {
+
+ boolean stop = false;
+ // In Case Not Group Stop
+ if (!allGroups.containsKey(groupName)) {
+ stop = true;
+ }
+ // In Case Group Has no members stop
+ if (!stop) {
+ GroupDefinition groupDefinition = allGroups.get(groupName);
+ stop = MapUtils.isEmpty(groupDefinition.getMembers());
+
+ }
+ // In Case all group members already contained stop
+ if (!stop) {
+ final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
+ Set<String> membersOfTypeGroup = allMembers.stream().
+ // Filter In Only Group members
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ // Collect
+ collect(Collectors.toSet());
+ stop = allGroupMembers.containsAll(membersOfTypeGroup);
+ }
+ return stop;
+ }
+
+ private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
+ String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ String nodeName) {
+
+ Either<Resource, ResponseFormat> result;
+ Either<Resource, ResponseFormat> createResourcesInstancesEither;
+
+ log.debug("************* Going to create all nodes {}", yamlName);
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName,
+ resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
+ nodeTypesInfo, csarInfo, nodeName);
+ log.debug("************* Finished to create all nodes {}", yamlName);
+ if (createdResourcesFromdNodeTypeMap.isRight()) {
+ log.debug("failed to resources from node types status is {}",
+ createdResourcesFromdNodeTypeMap.right().value());
+ return Either.right(createdResourcesFromdNodeTypeMap.right().value());
+ }
+
+ log.debug("************* Going to create all resource instances {}", yamlName);
+ createResourcesInstancesEither = createResourceInstances(csarInfo.getModifier(), yamlName, resource,
+ uploadComponentInstanceInfoMap, true, false, csarInfo.getCreatedNodes());
+
+ log.debug("************* Finished to create all resource instances {}", yamlName);
+ if (createResourcesInstancesEither.isRight()) {
+ log.debug("failed to create resource instances status is {}",
+ createResourcesInstancesEither.right().value());
+ result = createResourcesInstancesEither;
+ return createResourcesInstancesEither;
+ }
+ resource = createResourcesInstancesEither.left().value();
+ log.debug("************* Going to create all relations {}", yamlName);
+ createResourcesInstancesEither = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource,
+ uploadComponentInstanceInfoMap);
+
+ log.debug("************* Finished to create all relations {}", yamlName);
+
+ if (createResourcesInstancesEither.isRight()) {
+ log.debug("failed to create relation between resource instances status is {}",
+ createResourcesInstancesEither.right().value());
+ result = createResourcesInstancesEither;
+ return result;
+ } else {
+ resource = createResourcesInstancesEither.left().value();
+ }
+
+ log.debug("************* Going to create positions {}", yamlName);
+ Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic
+ .setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
+ log.debug("************* Finished to set positions {}", yamlName);
+ result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
+
+ return result;
+ }
+
+ private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
+ List<ArtifactDefinition> artifactsToAdd) {
+ List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName())
+ .collect(Collectors.toList());
+ artifactsToAdd.stream().forEach(a -> {
+ if (!vfcArtifactNames.contains(a.getArtifactName())) {
+ vfcArtifacts.add(a);
+ } else {
+ log.error("Can't upload two artifact with the same name {}. ", a.getArtifactName());
+ }
+ });
+
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource,
+ String topologyTemplateYaml, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
+ CsarInfo csarInfo, String nodeName) {
+
+ Either<Map<String, Resource>, ResponseFormat> result = Either.left(csarInfo.getCreatedNodes());
+ for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
+ if (nodeTypeEntry.getValue().isNested()) {
+
+ Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource,
+ nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+ nodeTypeEntry.getKey());
+ log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
+ if (createResourceFromYaml.isRight()) {
+ return Either.right(createResourceFromYaml.right().value());
+ }
+ }
+ }
+
+ Map<String, Object> mappedToscaTemplate = null;
+ if (StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
+ && nodeTypesInfo.containsKey(nodeName)) {
+ mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
+ }
+ if (MapUtils.isEmpty(mappedToscaTemplate)) {
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
+ }
+
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(
+ yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
+ if (createdNodeTypeFromMainTemplateEither.isRight()) {
+ ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
+ componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+ return Either.right(responseFormat);
+ }
+
+ // add the created node types to the cache although they are not in the
+ // graph.
+ csarInfo.getCreatedNodes().values().stream()
+ .forEach(p -> cacheManagerOperation.storeComponentInCache(p, NodeTypeEnum.Resource));
+
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
+ List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
+ boolean inTransaction) {
+
+ if (csarInfo.getCsar() != null) {
+ String vendorLicenseModelId = null;
+ String vfLicenseModelId = null;
+
+ if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
+ Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
+ if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
+ for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
+ if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL))
+ vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
+ if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
+ vfLicenseModelId = artifactEntry.getValue().getUniqueId();
+ }
+ }
+
+ }
+ // Specific Behavior for license artifacts
+ createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
+ CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
+ ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
+ Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, false, shouldLock,
+ inTransaction);
+ createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
+ CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+ ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
+ Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
+ artifactOperation, null, false, shouldLock, inTransaction);
+
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
+ createdArtifacts, shouldLock, inTransaction, artifactOperation);
+ if (eitherCreateResult.isRight()) {
+ return Either.right(eitherCreateResult.right().value());
+ }
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId());
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+
+ return Either.right(responseFormat);
+
+ }
+ resource = eitherGerResource.left().value();
+
+ Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
+
+ if (artifacsMetaCsarStatus.isLeft()) {
+ String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
+ String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
+ Either<Resource, ResponseFormat> createArtifactsFromCsar;
+ if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum()))
+ createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+ else
+ createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+
+ if (createArtifactsFromCsar.isRight()) {
+ log.debug("Couldn't create artifacts from artifacts.meta");
+ return Either.right(createArtifactsFromCsar.right().value());
+ }
+
+ return Either.left(createArtifactsFromCsar.left().value());
+ } else {
+
+ return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
+
+ }
+ }
+ return Either.left(resource);
+ }
+
+
+ private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
+ String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
+ String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
+ ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar, boolean shouldLock,
+ boolean inTransaction) {
+ byte[] artifactFileBytes = null;
+
+ if (csarInfo.getCsar().containsKey(artifactPath)) {
+ artifactFileBytes = csarInfo.getCsar().get(artifactPath);
+ }
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE) {
+ if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
+ shouldLock, inTransaction);
+ if (handleDelete.isRight()) {
+ result = Either.right(handleDelete.right().value());
+ }
+ return result;
+ }
+
+
+ if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
+ operation = artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
+ ArtifactOperationEnum.CREATE);
+ }
+
+ }
+ if (artifactFileBytes != null) {
+ Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId, artifactFileName,
+ artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
+ artifactFileBytes, null, isFromCsar);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson(
+ resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
+ addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+ if (eitherNonMetaArtifacts.isRight()) {
+ BeEcompErrorManager.getInstance()
+ .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
+ + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
+ ErrorSeverity.WARNING);
+ return Either.right(eitherNonMetaArtifacts.right().value());
+ }
+ }
+ return result;
+ }
+
+ private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
+ return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
+ }
+
+
+ private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
+ List<ArtifactDefinition> createdArtifacts,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
+ if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
+ && eitherNonMetaArtifacts.isLeft()) {
+ Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
+ if (eitherResult.isLeft()) {
+ createdArtifacts.add(eitherResult.left().value());
+ }
+ }
+ }
+
+
+ private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
+ List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
+ ArtifactOperationInfo artifactOperation) {
+
+ Either<Resource, ResponseFormat> resStatus = null;
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+
+ try {
+ List<NonMetaArtifactInfo> artifactPathAndNameList =
+ // Stream of file paths contained in csar
+ csarInfo.getCsar().entrySet().stream()
+ // Filter in only VF artifact path location
+ .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
+ .matches())
+ // Validate and add warnings
+ .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
+ collectedWarningMessages))
+ // Filter in Non Warnings
+ .filter(e -> e.isLeft())
+ // Convert from Either to NonMetaArtifactInfo
+ .map(e -> e.left().value())
+ // collect to List
+ .collect(Collectors.toList());
+
+ Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
+ if (responseFormatEither.isRight()) {
+ return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
+ ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
+ }
+
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
+
+ if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
+ vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+ vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
+ } else {
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
+ resource, artifactPathAndNameList, csarInfo.getModifier());
+
+ if (findVfCsarArtifactsToHandleRes.isRight()) {
+ resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
+ }
+ if (resStatus == null) {
+ vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
+ }
+ }
+
+
+ if (resStatus == null && vfCsarArtifactsToHandle != null) {
+
+ for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
+ .entrySet()) {
+
+ Optional<ResponseFormat> optionalCreateInDBError =
+ // Stream of artifacts to be created
+ currArtifactOperationPair.getValue().stream()
+ // create each artifact
+ .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
+ e.getArtifactName(), e.getArtifactType().getType(),
+ e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
+ CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
+ currArtifactOperationPair.getKey()),
+ createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
+ // filter in only error
+ .filter(e -> e.isRight()).
+ // Convert the error from either to
+ // ResponseFormat
+ map(e -> e.right().value()).
+ // Check if an error occurred
+ findAny();
+ // Error found on artifact Creation
+ if (optionalCreateInDBError.isPresent()) {
+ resStatus = Either.right(optionalCreateInDBError.get());
+ break;
+ }
+ }
+ }
+ if (resStatus == null) {
+ resStatus = Either.left(resource);
+ }
+ } catch (Exception e) {
+ resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ log.debug("Exception occured in createNonMetaArtifacts, message:{}", e.getMessage(), e);
+ } finally {
+ CsarUtils.handleWarningMessages(collectedWarningMessages);
+ }
+ return resStatus;
+ }
+
+ private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
+ Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
+ for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
+ if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
+ return Either.right(nonMetaArtifactInfo.getArtifactName());
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
+ Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
+
+ List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
+ // collect all Deployment and Informational artifacts of VF
+ if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
+ existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
+ }
+ if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
+ existingArtifacts.addAll(resource.getArtifacts().values());
+ }
+ existingArtifacts = existingArtifacts.stream()
+ // filter MANDATORY artifacts, LICENSE artifacts and artifacts
+ // was created from HEAT.meta
+ .filter(this::isNonMetaArtifact).collect(Collectors.toList());
+
+ List<String> artifactsToIgnore = new ArrayList<>();
+ // collect IDs of Artifacts of VF which belongs to any group
+ if (resource.getGroups() != null) {
+ resource.getGroups().stream().forEach(g -> {
+ if (g.getArtifacts() != null && !g.getArtifacts().isEmpty())
+ artifactsToIgnore.addAll(g.getArtifacts());
+ });
+ }
+ existingArtifacts = existingArtifacts.stream()
+ // filter artifacts which belongs to any group
+ .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(Collectors.toList());
+ return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
+ }
+
+ private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
+ boolean result = true;
+ if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
+ result = false;
+ }
+ return result;
+ }
+
+ private boolean isValidArtifactType(ArtifactDefinition artifact) {
+ boolean result = true;
+ if (artifact.getArtifactType() == null
+ || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
+ || ArtifactTypeEnum.findType(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
+ result = false;
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> createResourceInstancesRelations(User user, String yamlName,
+ Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ log.debug("createResourceInstancesRelations try to create relations ");
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+ if (uploadResInstancesMap == null) {
+ log.debug("UploadComponentInstanceInfo is empty, fileName {}", yamlName);
+ BeEcompErrorManager.getInstance().logInternalDataError("UploadComponentInstanceInfo is emty, fileName {}",
+ yamlName, ErrorSeverity.ERROR);
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
+ yamlName);
+ return Either.right(responseFormat);
+ }
+
+ if (componentInstancesList == null || componentInstancesList.isEmpty()) {
+ log.debug("componentInstancesList is empty in resource {} ", resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("componentInstancesList is empty in resource {} ",
+ resource.getUniqueId(), ErrorSeverity.ERROR);
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
+ yamlName);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("Before validateAndUpdatePropertyValue");
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
+ if (allDataTypes.isRight()) {
+ TitanOperationStatus status = allDataTypes.right().value();
+ BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
+ "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+ DaoStatusConverter.convertTitanStatusToStorageStatus(status)), yamlName));
+
+ }
+
+ Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+ Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
+ Map<String, Resource> originCompMap = new HashMap<>();
+ List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+
+ for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+ log.trace("Processing entry: {}", entry);
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
+ ComponentInstance currentCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ log.trace("Processing component instance: {}", compInstance);
+ if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+
+ }
+ if (currentCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
+ resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
+ resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return Either.right(responseFormat);
+ }
+ String resourceInstanceId = currentCompInstance.getUniqueId();
+ Resource originResource;
+ if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
+ Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
+ .getToscaFullElement(currentCompInstance.getComponentUid());
+ if (getOriginResourceRes.isRight()) {
+ log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
+ currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
+ getOriginResourceRes);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
+ originResource = getOriginResourceRes.left().value();
+ originCompMap.put(originResource.getUniqueId(), originResource);
+ } else {
+ originResource = originCompMap.get(currentCompInstance.getComponentUid());
+ }
+ if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
+ instRequirements.put(currentCompInstance, originResource.getRequirements());
+ if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
+ Map<String, List<CapabilityDefinition>> originCapabilities;
+ if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
+ originCapabilities = new HashMap<>();
+ originResource.getCapabilities().entrySet().stream().forEach(e -> {
+ List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l))
+ .collect(Collectors.toList());
+ originCapabilities.put(e.getKey(), list);
+ });
+ Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
+ for (List<UploadCapInfo> capabilities : uploadComponentInstanceInfo.getCapabilities().values()) {
+ for (UploadCapInfo capability : capabilities) {
+ if (CollectionUtils.isNotEmpty(capability.getProperties())) {
+ newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
+ .collect(Collectors.toMap(p -> p.getName(), p -> p)));
+ }
+ }
+ }
+ for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
+ List<CapabilityDefinition> filteredCapabilities = capabilities.stream()
+ .filter(c -> newPropertiesMap.containsKey(c.getName())).collect(Collectors.toList());
+ for (CapabilityDefinition cap : filteredCapabilities) {
+ Either<Boolean, ResponseFormat> updateRes = updatePropertyValues(cap.getProperties(),
+ newPropertiesMap.get(cap.getName()), allDataTypes.left().value());
+ if (updateRes.isRight()) {
+ log.debug("Failed to update capability properties of capability {} . Status is {}. ",
+ cap.getName(), updateRes.right().value());
+ return Either.right(updateRes.right().value());
+ }
+ }
+ }
+ } else {
+ originCapabilities = originResource.getCapabilities();
+ }
+ instCapabilties.put(currentCompInstance, originCapabilities);
+ }
+ if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
+ instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
+ instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
+ if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
+ instAttributes.put(resourceInstanceId, originResource.getAttributes());
+ if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
+ originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
+ if (addPropertiesValueToRiRes.getStatus() != 200) {
+ return Either.right(addPropertiesValueToRiRes);
+ }
+ } else {
+ ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource,
+ originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
+ if (addInputValueToRiRes.getStatus() != 200) {
+ return Either.right(addInputValueToRiRes);
+ }
+ }
+ }
+
+ Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
+ .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+ if (addPropToInst.isRight()) {
+ log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
+ addPropToInst.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
+ if (instInputs != null && !instInputs.isEmpty()) {
+ Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
+ .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ if (addInputToInst.isRight()) {
+ log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
+ addInputToInst.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
+ }
+ StorageOperationStatus addArtToInst = toscaOperationFacade
+ .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ addArtToInst = toscaOperationFacade.associateCalculatedCapReq(instCapabilties, instRequirements,
+ resource.getUniqueId());
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
+ addArtToInst);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
+ resource.getUniqueId());
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
+ addArtToInst);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ ComponentParametersView parametersView = new ComponentParametersView();
+ parametersView.disableAll();
+ parametersView.setIgnoreComponentInstances(false);
+ parametersView.setIgnoreComponentInstancesProperties(false);
+ parametersView.setIgnoreCapabilities(false);
+ parametersView.setIgnoreRequirements(false);
+
+ Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId(), parametersView);
+
+ if (eitherGetResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+
+ return Either.right(responseFormat);
+
+ }
+
+ resource = eitherGetResource.left().value();
+
+ for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
+ ComponentInstance currentCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+
+ if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+
+ }
+ if (currentCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
+ resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
+ resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return Either.right(responseFormat);
+ }
+
+ ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
+ if (addRelationToRiRes.getStatus() != 200) {
+ return Either.right(addRelationToRiRes);
+ }
+ }
+
+ addArtToInst = toscaOperationFacade.associateResourceInstances(resource.getUniqueId(), relations);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
+ addArtToInst);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
+ if (eitherGetResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+ return Either.right(responseFormat);
+ }
+ eitherGetResource = updateCalculatedCapReqWithSubstitutionMappings(eitherGetResource.left().value(),
+ uploadResInstancesMap);
+ if (eitherGetResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+ return Either.right(responseFormat);
+ }
+ }
+
+ log.debug("************* in create relations, getResource start");
+ eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
+ log.debug("************* in create relations, getResource end");
+ if (eitherGetResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+ return Either.right(responseFormat);
+ }
+ return Either.left(eitherGetResource.left().value());
+ }
+
+ private Either<Boolean, ResponseFormat> updatePropertyValues(List<ComponentInstanceProperty> properties,
+ Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
+ for (ComponentInstanceProperty property : properties) {
+ Either<String, StorageOperationStatus> updateRes = updatePropertyValue(property,
+ newProperties.get(property.getName()), allDataTypes);
+ if (updateRes.isRight()) {
+ log.debug("Failed to update capability property {} . Status is {}. ", property.getName(),
+ updateRes.right().value());
+ return Either.right(componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(updateRes.right().value())));
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<String, StorageOperationStatus> updatePropertyValue(ComponentInstanceProperty property,
+ UploadPropInfo propertyInfo, Map<String, DataTypeDefinition> allDataTypes) {
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
+ } else
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
+ ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ property.setValue(value);
+ return validatePropValueBeforeCreate(property, value, isValidate, null, allDataTypes);
+ }
+
+ private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+ Either<Resource, StorageOperationStatus> updateRes = null;
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
+ StorageOperationStatus status = toscaOperationFacade
+ .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ log.debug(
+ "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
+ resource.getUniqueId(), status);
+ updateRes = Either.right(status);
+ }
+ if (updateRes == null) {
+ fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
+ updatedInstCapabilities, updatedInstRequirements);
+ status = toscaOperationFacade.associateCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
+ resource.getUniqueId());
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ log.debug(
+ "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
+ resource.getUniqueId(), status);
+ updateRes = Either.right(status);
+ }
+ }
+ if (updateRes == null) {
+ updateRes = Either.left(resource);
+ }
+ return updateRes;
+ }
+
+ private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
+
+ componentInstances.stream().forEach(i -> {
+ fillUpdatedInstCapabilities(updatedInstCapabilities, i,
+ uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
+ fillUpdatedInstRequirements(updatedInstRequirements, i,
+ uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
+ });
+ }
+
+ private void fillUpdatedInstRequirements(
+ Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
+ ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
+ Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
+ Set<String> updatedReqNames = new HashSet<>();
+ if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
+ for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
+ updatedRequirements.put(requirements.getKey(),
+ requirements.getValue().stream()
+ .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
+ && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+ .map(r -> {
+ r.setParentName(r.getName());
+ r.setName(requirementsNamesToUpdate.get(r.getName()));
+ updatedReqNames.add(r.getName());
+ return r;
+ }).collect(Collectors.toList()));
+ }
+ }
+ if (MapUtils.isNotEmpty(updatedRequirements)) {
+ updatedInstRequirements.put(instance, updatedRequirements);
+ }
+ }
+
+ private void fillUpdatedInstCapabilities(
+ Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
+ ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
+ Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
+ Set<String> updatedCapNames = new HashSet<>();
+ if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
+ for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
+ updatedCapabilities.put(requirements.getKey(),
+ requirements.getValue().stream()
+ .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
+ && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+ .map(c -> {
+ c.setParentName(c.getName());
+ c.setName(capabilitiesNamesToUpdate.get(c.getName()));
+ updatedCapNames.add(c.getName());
+ return c;
+ }).collect(Collectors.toList()));
+ }
+ }
+ if (MapUtils.isNotEmpty(updatedCapabilities)) {
+ updatedInstCapabilties.put(instance, updatedCapabilities);
+ }
+ }
+
+ private ResponseFormat addRelationToRI(String yamlName, Resource resource,
+ UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+ List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = nodesInfoValue;
+
+ ComponentInstance currentCompInstance = null;
+
+ for (ComponentInstance compInstance : componentInstancesList) {
+
+ if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+ currentCompInstance = compInstance;
+ break;
+ }
+
+ }
+
+ if (currentCompInstance == null) {
+ log.debug("component instance with name {} in resource {} ", uploadComponentInstanceInfo.getName(),
+ resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "component instance with name " + uploadComponentInstanceInfo.getName() + " in resource {} ",
+ resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
+ yamlName);
+ return responseFormat;
+ }
+ String resourceInstanceId = currentCompInstance.getUniqueId();
+
+ Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
+
+ if (regMap != null) {
+ Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
+
+ while (nodesRegValue.hasNext()) {
+ Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
+
+ List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
+ for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
+ log.debug("Going to create relation {}", uploadRegInfo.getName());
+ String regName = uploadRegInfo.getName();
+ RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
+ regCapRelDef.setFromNode(resourceInstanceId);
+ log.debug("try to find available requirement {} ", regName);
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
+ yamlName, uploadComponentInstanceInfo, currentCompInstance,
+ uploadRegInfo.getCapabilityName());
+ if (eitherReqStatus.isRight()) {
+ log.debug("failed to find available requirement {} status is {}", regName,
+ eitherReqStatus.right().value());
+ return eitherReqStatus.right().value();
+ }
+
+ RequirementDefinition validReq = eitherReqStatus.left().value();
+ List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
+ .getRelationships();
+ if (reqAndRelationshipPairList == null)
+ reqAndRelationshipPairList = new ArrayList<>();
+ RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
+ reqAndRelationshipPair.setRequirement(regName);
+ reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
+ reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(validReq.getCapability());
+ reqAndRelationshipPair.setRelationships(relationship);
+
+ ComponentInstance currentCapCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(uploadRegInfo.getNode())) {
+ currentCapCompInstance = compInstance;
+ break;
+ }
+ }
+
+ if (currentCapCompInstance == null) {
+ log.debug("The component instance with name {} not found on resource {} ",
+ uploadRegInfo.getNode(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "component instance with name " + uploadRegInfo.getNode() + " in resource {} ",
+ resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
+ log.debug("try to find aviable Capability req name is {} ", validReq.getName());
+ CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
+ currentCapCompInstance, uploadRegInfo);
+ if (aviableCapForRel == null) {
+ log.debug("aviable capability was not found. req name is {} component instance is {}",
+ validReq.getName(), currentCapCompInstance.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError(
+ "aviable capability was not found. req name is " + validReq.getName()
+ + " component instance is " + currentCapCompInstance.getUniqueId(),
+ resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+ reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+ reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
+ CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
+ capReqRel.setRelation(reqAndRelationshipPair);
+ reqAndRelationshipPairList.add(capReqRel);
+ regCapRelDef.setRelationships(reqAndRelationshipPairList);
+ relations.add(regCapRelDef);
+ }
+ }
+ } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
+ return responseFormat;
+ }
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
+ Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
+ Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+ if (propMap != null && propMap.size() > 0) {
+ Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
+
+ List<InputDefinition> listFromMap = originResource.getInputs();
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ log.debug("failed to find properties ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ return responseFormat;
+ }
+ for (InputDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
+ }
+ }
+ List<ComponentInstanceInput> instPropList = new ArrayList<>();
+ for (List<UploadPropInfo> propertyList : propMap.values()) {
+
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ log.debug("failed to find property {} ", propName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
+ propName);
+ return responseFormat;
+ }
+ InputDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceInput property = null;
+
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
+ curPropertyDef.getType());
+ } else
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
+ ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ String innerType = null;
+ property = new ComponentInstanceInput(curPropertyDef, value, null);
+
+ Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property,
+ value, isValidate, innerType, allDataTypes);
+ if (validatevalueEiter.isRight()) {
+ return componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
+ }
+
+ property.setValue(validatevalueEiter.left().value());
+
+ if (getInputs != null && !getInputs.isEmpty()) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
+ property, currentCompInstance.getUniqueId());
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+
+ Optional<InputDefinition> optional = inputs.stream()
+ .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInput.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition input = optional.get();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
+
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ if (getInputIndex != null) {
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
+ .findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
+ }
+ }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+ // add rest of properties
+ if (!currPropertiesMap.isEmpty()) {
+ for (InputDefinition value : currPropertiesMap.values()) {
+ instPropList.add(new ComponentInstanceInput(value));
+ }
+ }
+ instInputs.put(currentCompInstance.getUniqueId(), instPropList);
+ }
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
+ Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
+ Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
+
+ Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+ Map<String, PropertyDefinition> currPropertiesMap = new HashMap<String, PropertyDefinition>();
+
+ List<PropertyDefinition> listFromMap = originResource.getProperties();
+ if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
+ log.debug("failed to find properties ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ return responseFormat;
+ }
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+ for (PropertyDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
+ }
+ }
+ List<ComponentInstanceProperty> instPropList = new ArrayList<>();
+ if (propMap != null && propMap.size() > 0) {
+ for (List<UploadPropInfo> propertyList : propMap.values()) {
+
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ log.debug("failed to find property {} ", propName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
+ propName);
+ return responseFormat;
+ }
+ PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceProperty property = null;
+
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
+ curPropertyDef.getType());
+ } else
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(),
+ ToscaTagNamesEnum.GET_INPUT.getElementName());
+ }
+ String innerType = null;
+ property = new ComponentInstanceProperty(curPropertyDef, value, null);
+
+ Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property,
+ value, isValidate, innerType, allDataTypes);
+ if (validatevalueEiter.isRight()) {
+ return componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
+ }
+
+ property.setValue(validatevalueEiter.left().value());
+
+ if (getInputs != null && !getInputs.isEmpty()) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ",
+ property, currentCompInstance.getUniqueId());
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+
+ Optional<InputDefinition> optional = inputs.stream()
+ .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInput.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition input = optional.get();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
+
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ if (getInputIndex != null) {
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
+ .findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
+
+ }
+
+ }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+ }
+ // add rest of properties
+ if (!currPropertiesMap.isEmpty()) {
+ for (PropertyDefinition value : currPropertiesMap.values()) {
+ instPropList.add(new ComponentInstanceProperty(value));
+ }
+ }
+ instProperties.put(currentCompInstance.getUniqueId(), instPropList);
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ // US740820 Relate RIs according to capability name
+ private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
+ ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+ if (null == uploadReqInfo.getCapabilityName()
+ || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {// get
+ // by
+ // capability
+ // type
+ return findAviableCapability(validReq, currentCapCompInstance);
+ }
+ return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
+ }
+
+ private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
+ ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+ CapabilityDefinition cap = null;
+ Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
+ if (!capMap.containsKey(validReq.getCapability())) {
+ return null;
+ }
+ Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
+ .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
+ if (!capByName.isPresent()) {
+ return null;
+ }
+ cap = capByName.get();
+
+ if (cap.getMaxOccurrences() != null
+ && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = cap.getLeftOccurrences();
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ cap.setLeftOccurrences(String.valueOf(left));
+
+ }
+
+ }
+ return cap;
+ }
+
+ private CapabilityDefinition findAviableCapability(RequirementDefinition validReq,
+ ComponentInstance currentCapCompInstance) {
+ CapabilityDefinition aviableCapForRel = null;
+ Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
+ if (capMap.containsKey(validReq.getCapability())) {
+ List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
+
+ for (CapabilityDefinition cap : capList) {
+ if (cap.getMaxOccurrences() != null
+ && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = cap.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = cap.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ cap.setLeftOccurrences(String.valueOf(left));
+ aviableCapForRel = cap;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ aviableCapForRel = cap;
+ break;
+ }
+ }
+ }
+ return aviableCapForRel;
+ }
+
+ private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
+ UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
+ String capName) {
+ Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
+ List<RequirementDefinition> list = comInstRegDefMap.get(capName);
+ RequirementDefinition validRegDef = null;
+ if (list == null) {
+ for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
+ for (RequirementDefinition reqDef : entry.getValue()) {
+ if (reqDef.getName().equals(regName)) {
+ if (reqDef.getMaxOccurrences() != null
+ && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = reqDef.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = reqDef.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ reqDef.setLeftOccurrences(String.valueOf(left));
+ validRegDef = reqDef;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ validRegDef = reqDef;
+ break;
+ }
+
+ }
+ }
+ if (validRegDef != null) {
+ break;
+ }
+ }
+ } else {
+ for (RequirementDefinition reqDef : list) {
+ if (reqDef.getName().equals(regName)) {
+ if (reqDef.getMaxOccurrences() != null
+ && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ String leftOccurrences = reqDef.getLeftOccurrences();
+ if (leftOccurrences == null) {
+ leftOccurrences = reqDef.getMaxOccurrences();
+ }
+ int left = Integer.parseInt(leftOccurrences);
+ if (left > 0) {
+ --left;
+ reqDef.setLeftOccurrences(String.valueOf(left));
+ validRegDef = reqDef;
+ break;
+ } else {
+ continue;
+ }
+ } else {
+ validRegDef = reqDef;
+ break;
+ }
+ }
+ }
+ }
+ if (validRegDef == null) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ return Either.right(responseFormat);
+ }
+ return Either.left(validRegDef);
+ }
+
+ @SuppressWarnings("unchecked")
+ public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource,
+ String resourceYml, Map<String, String> createdNodesToscaResourceNames,
+ Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
+
+ Map<String, Object> mappedToscaTemplate;
+ if (nodeTypesInfo != null && nodeName != null && nodeTypesInfo.containsKey(nodeName)) {
+ mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
+ } else {
+ try {
+ // DE154502 Fail if duplicate key found in file
+ mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
+
+ } catch (ParserException e) {
+ log.error("Failed to load yaml file {}", yamlFileName, e);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR,
+ yamlFileName, e.getMessage());
+ return Either.right(responseFormat);
+ }
+ }
+ Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate,
+ ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
+ if (toscaElementEither.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
+ return Either.right(responseFormat);
+ }
+
+ Either<Map<String, InputDefinition>, ResponseFormat> createInputsEither = createInputsFromYaml(yamlFileName,
+ mappedToscaTemplate, resource);
+ if (createInputsEither.isRight()) {
+ ResponseFormat responseFormat = createInputsEither.right().value();
+ return Either.right(responseFormat);
+ }
+
+ Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(
+ yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
+ if (uploadResInstancesEither.isRight()) {
+ ResponseFormat responseFormat = uploadResInstancesEither.right().value();
+ return Either.right(responseFormat);
+ }
+
+ Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml = createGroupsFromYaml(yamlFileName,
+ mappedToscaTemplate, resource);
+ if (createGroupsFromYaml.isRight()) {
+ ResponseFormat responseFormat = createGroupsFromYaml.right().value();
+ return Either.right(responseFormat);
+ }
+
+ ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
+ parsedToscaYamlInfo.setInputs(createInputsEither.left().value());
+ parsedToscaYamlInfo.setInstances(uploadResInstancesEither.left().value());
+ parsedToscaYamlInfo.setGroups(createGroupsFromYaml.left().value());
+
+ return Either.left(parsedToscaYamlInfo);
+ }
+
+ private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource,
+ Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
+ Map<String, Resource> nodeNamespaceMap) {
+
+ Either<Resource, ResponseFormat> eitherResource = null;
+ log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
+ if (uploadResInstancesMap == null || uploadResInstancesMap.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
+
+ return Either.right(responseFormat);
+
+ }
+ Map<String, Resource> existingnodeTypeMap = new HashMap<>();
+ if (nodeNamespaceMap != null && !nodeNamespaceMap.isEmpty()) {
+ nodeNamespaceMap.entrySet().stream()
+ .forEach(x -> existingnodeTypeMap.put(x.getValue().getToscaResourceName(), x.getValue()));
+ }
+
+ Iterator<Entry<String, UploadComponentInstanceInfo>> nodesInfoValue = uploadResInstancesMap.entrySet()
+ .iterator();
+ Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
+ while (nodesInfoValue.hasNext()) {
+ log.debug("*************Going to create resource instances {}", yamlName);
+ Entry<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoEntry = nodesInfoValue.next();
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = uploadComponentInstanceInfoEntry.getValue();
+
+ // updating type if the type is node type name - we need to take the
+ // updated name
+ log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName());
+ if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ uploadComponentInstanceInfo
+ .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
+ }
+
+ eitherResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
+ existingnodeTypeMap);
+ if (eitherResource.isRight()) {
+ return eitherResource;
+ }
+ Resource refResource = eitherResource.left().value();
+
+ ComponentInstance componentInstance = new ComponentInstance();
+
+ componentInstance.setComponentUid(refResource.getUniqueId());
+
+ ComponentTypeEnum containerComponentType = resource.getComponentType();
+ NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
+
+ if (containerNodeType.equals(NodeTypeEnum.Resource)
+ && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
+ && MapUtils.isNotEmpty(refResource.getCapabilities())) {
+ setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+ Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilitiesRes = getValidComponentInstanceCapabilities(
+ refResource.getUniqueId(), refResource.getCapabilities(),
+ uploadComponentInstanceInfo.getCapabilities());
+ if (getValidComponentInstanceCapabilitiesRes.isRight()) {
+ return Either.right(getValidComponentInstanceCapabilitiesRes.right().value());
+ } else {
+ componentInstance.setCapabilities(getValidComponentInstanceCapabilitiesRes.left().value());
+ }
+ }
+ if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ log.debug(
+ "createResourceInstances - not found lates version for resource instance with name {} and type ",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ return Either.right(responseFormat);
+ }
+ Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
+ componentInstance.setName(uploadComponentInstanceInfo.getName());
+ componentInstance.setIcon(origResource.getIcon());
+
+ resourcesInstancesMap.put(componentInstance, origResource);
+
+ }
+ if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
+
+ StorageOperationStatus status = toscaOperationFacade.associateComponentInstancesToComponent(resource,
+ resourcesInstancesMap, false);
+ if (status != null && status != StorageOperationStatus.OK) {
+ log.debug("Failed to add component instances to container component {}", resource.getName());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(status));
+ eitherResource = Either.right(responseFormat);
+ return eitherResource;
+ }
+
+ }
+
+ log.debug("*************Going to get resource {}", resource.getUniqueId());
+ ComponentParametersView parametersView = new ComponentParametersView();
+ parametersView.disableAll();
+ parametersView.setIgnoreComponentInstances(false);
+ parametersView.setIgnoreUsers(false);
+ parametersView.setIgnoreInputs(false); // inputs are read when creating
+ // property values on instances
+ Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
+ .getToscaElement(resource.getUniqueId(), parametersView);
+ log.debug("*************finished to get resource {}", resource.getUniqueId());
+ if (eitherGerResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+
+ return Either.right(responseFormat);
+
+ }
+
+ if (eitherGerResource.left().value().getComponentInstances() == null
+ || eitherGerResource.left().value().getComponentInstances().isEmpty()) {
+
+ log.debug("Error when create resource inctanse from csar. ComponentInstances list empty");
+ BeEcompErrorManager.getInstance().logBeDaoSystemError(
+ "Error when create resource inctanse from csar. ComponentInstances list empty");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
+ return Either.right(responseFormat);
+
+ }
+
+ return Either.left(eitherGerResource.left().value());
+ }
+
+ private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
+ Map<String, List<UploadCapInfo>> uploadedCapabilities) {
+ for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
+ if (originCapabilities.containsKey(currEntry.getKey())) {
+ currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
+ }
+ }
+ for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
+ capabilities.getValue().stream().forEach(cap -> {
+ if (uploadedCapabilities.containsKey(cap.getName())) {
+ uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
+ c.setName(cap.getName());
+ c.setType(cap.getType());
+ });
+ }
+ ;
+ });
+ }
+
+ }
+
+ private Either<Resource, ResponseFormat> validateResourceInstanceBeforeCreate(String yamlName,
+ UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap) {
+ log.debug(
+ "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type before create",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ Resource refResource = null;
+ if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+ refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
+ } else {
+ Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
+ .getLatestCertifiedNodeTypeByToscaResourceName(uploadComponentInstanceInfo.getType());
+ if (findResourceEither.isRight()) {
+ log.debug(
+ "validateResourceInstanceBeforeCreate - not found lates version for resource instance with name {} and type ",
+ uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
+ return Either.right(responseFormat);
+ }
+ refResource = findResourceEither.left().value();
+ nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
+ }
+ String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
+ if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+ log.debug(
+ "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
+ refResource.getName(), componentState);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
+ refResource.getComponentType().getValue(), refResource.getName(), componentState);
+ return Either.right(responseFormat);
+ }
+
+ if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
+ yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+ return Either.right(responseFormat);
+ }
+ return Either.left(refResource);
+ }
+
+ private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(
+ String yamlFileName, Map<String, Object> toscaJson, Resource resource,
+ Map<String, String> createdNodesToscaResourceNames) {
+ Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
+ Map<String, Object> substitutionMappings = null;
+ Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils
+ .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
+ Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils
+ .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
+ if (eitherSubstitutionMappings.isLeft()) {
+ substitutionMappings = eitherSubstitutionMappings.left().value();
+ }
+ if (eitherNodesTemlates.isLeft()) {
+ Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
+
+ Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
+ while (nodesNameValue.hasNext()) {
+ Entry<String, Object> nodeNameValue = nodesNameValue.next();
+ Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(
+ nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
+ if (eitherNode.isRight()) {
+ log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(),
+ resource.getName());
+ return Either.right(eitherNode.right().value());
+ } else {
+ UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
+ moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
+ }
+
+ }
+
+ }
+ if (moduleComponentInstances.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
+ yamlFileName);
+ return Either.right(responseFormat);
+ }
+
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(
+ Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings,
+ Map<String, String> createdNodesToscaResourceNames) {
+
+ UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
+ Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
+ nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
+ try {
+ if (nodeTemplateJsonEntry.getValue() instanceof String) {
+ String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
+ nodeTemplateInfo.setType(nodeTemplateJsonString);
+ } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
+ Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
+ // Type
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ String toscaResourceType = (String) nodeTemplateJsonMap
+ .get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
+ toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
+ }
+ nodeTemplateInfo.setType(toscaResourceType);
+ }
+
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
+ Either<Map<String, List<UploadReqInfo>>, ResponseFormat> regResponse = createReqModuleFromYaml(
+ nodeTemplateInfo, nodeTemplateJsonMap);
+ if (regResponse.isRight())
+ return Either.right(regResponse.right().value());
+ if (regResponse.left().value().size() > 0) {
+ nodeTemplateInfo.setRequirements(regResponse.left().value());
+ }
+ }
+
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
+ Either<Map<String, List<UploadCapInfo>>, ResponseFormat> eitherCapRes = createCapModuleFromYaml(
+ nodeTemplateInfo, nodeTemplateJsonMap);
+ if (eitherCapRes.isRight())
+ return Either.right(eitherCapRes.right().value());
+ if (eitherCapRes.left().value().size() > 0) {
+ nodeTemplateInfo.setCapabilities(eitherCapRes.left().value());
+ }
+ }
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+ Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(
+ nodeTemplateJsonMap);
+ if (regResponse.isRight())
+ return Either.right(regResponse.right().value());
+ if (regResponse.left().value().size() > 0) {
+ nodeTemplateInfo.setProperties(regResponse.left().value());
+ }
+ }
+ if (substitutionMappings != null) {
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
+ Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(
+ nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings
+ .get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
+ if (getCapNamesToUpdateRes.isRight())
+ return Either.right(getCapNamesToUpdateRes.right().value());
+ if (getCapNamesToUpdateRes.left().value().size() > 0) {
+ nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
+ }
+ }
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
+ Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(
+ nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings
+ .get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
+ if (getReqNamesToUpdateRes.isRight())
+ return Either.right(getReqNamesToUpdateRes.right().value());
+ if (getReqNamesToUpdateRes.left().value().size() > 0) {
+ nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
+ }
+ }
+ }
+ } else {
+
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
+ log.debug("error when creating capability, message:{}", e.getMessage(), e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
+ }
+
+ return result;
+ }
+
+ private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo,
+ Map<String, List<String>> elements) {
+ Either<Map<String, String>, ResponseFormat> response;
+ try {
+ Map<String, String> namesToUpdate = elements.entrySet().stream()
+ .filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName()))
+ .collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
+ response = Either.left(namesToUpdate);
+ } catch (Exception e) {
+ log.debug("The exception occurred upon adding names to update for instance {}: ", nodeTemplateInfo.getName(), e);
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return response;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(
+ Map<String, Object> nodeTemplateJsonMap) {
+ Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
+ Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
+ Either<Map<String, Object>, ResultStatusEnum> toscaProperties = ImportUtils
+ .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.PROPERTIES);
+ if (toscaProperties.isLeft()) {
+ Map<String, Object> jsonProperties = toscaProperties.left().value();
+ for (Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
+ // Property
+ String propName = jsonPropObj.getKey();
+ Object propValue = jsonPropObj.getValue();
+
+ if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
+ log.trace("Ignore property value {}.", propName);
+ continue;
+ }
+
+ if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
+ log.trace("Ignore property value {}.", propName);
+ continue;
+ }
+ if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
+ log.trace("Ignore property value {}.", propName);
+ continue;
+ }
+
+ if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
+ log.trace("Ignore property value {}.", propName);
+ continue;
+ }
+
+ if (valueContainsPattern(GET_ATTRIBUTE_PATTERN, propValue)) {
+ log.trace("Ignore property value {}.", propName);
+ continue;
+ }
+
+ UploadPropInfo propertyDef = new UploadPropInfo();
+ propertyDef.setValue(propValue);
+ propertyDef.setName(propName);
+ if (propValue instanceof Map) {
+ if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ propertyDef.setType(((Map<String, Object>) propValue)
+ .get(ToscaTagNamesEnum.TYPE.getElementName()).toString());
+ }
+
+ if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())
+ || ImportUtils.getPropertyJsonStringValue(propValue, ToscaPropertyType.MAP.getType())
+ .contains(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
+ createGetInputModuleFromMap(propName, (Map<String, Object>) propValue, propertyDef);
+ }
+
+ if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
+ propertyDef.setDescription(((Map<String, Object>) propValue)
+ .get(ToscaTagNamesEnum.DESCRIPTION.getElementName()).toString());
+ }
+ if (((Map<String, Object>) propValue)
+ .containsKey(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName())) {
+ propertyDef.setValue(((Map<String, Object>) propValue)
+ .get(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName()));
+ }
+ if (((Map<String, Object>) propValue).containsKey(ToscaTagNamesEnum.IS_PASSWORD.getElementName())) {
+ propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue)
+ .get(ToscaTagNamesEnum.IS_PASSWORD.getElementName()).toString()));
+ } else {
+ propertyDef.setValue(propValue);
+ }
+ } else if (propValue instanceof List) {
+ List<Object> propValueList = (List<Object>) propValue;
+
+ createInputPropList(propertyDef, propValueList);
+ propertyDef.setValue(propValue);
+ }
+
+ if (moduleProp.containsKey(propName)) {
+ moduleProp.get(propName).add(propertyDef);
+ } else {
+ List<UploadPropInfo> list = new ArrayList<UploadPropInfo>();
+ list.add(propertyDef);
+ moduleProp.put(propName, list);
+ }
+ }
+ }
+ return response;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void createInputPropList(UploadPropInfo propertyDef, List<Object> propValueList) {
+ for (Object objValue : propValueList) {
+
+ if (objValue instanceof Map) {
+ Map<String, Object> objMap = (Map<String, Object>) objValue;
+ if (objMap.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName()))
+ createGetInputModuleFromMap(propertyDef.getName(), objMap, propertyDef);
+ else {
+ Set<String> keys = objMap.keySet();
+ for (String key : keys) {
+ Object value = objMap.get(key);
+ if (value instanceof Map) {
+ createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
+
+ } else if (value instanceof List) {
+ List<Object> propSubValueList = (List<Object>) value;
+
+ createInputPropList(propertyDef, propSubValueList);
+ }
+
+ }
+ }
+
+ } else if (objValue instanceof List) {
+ List<Object> propSubValueList = (List<Object>) objValue;
+
+ createInputPropList(propertyDef, propSubValueList);
+
+ }
+
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void createGetInputModuleFromMap(String propName, Map<String, Object> propValue,
+ UploadPropInfo propertyDef) {
+
+ if (propValue.containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
+ Object getInput = propValue.get(ToscaTagNamesEnum.GET_INPUT.getElementName());
+ GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
+ List<GetInputValueDataDefinition> getInputs = propertyDef.getGet_input();
+ if (getInputs == null) {
+ getInputs = new ArrayList<GetInputValueDataDefinition>();
+ }
+ if (getInput instanceof String) {
+
+ getInputInfo.setInputName((String) getInput);
+ getInputInfo.setPropName(propName);
+
+ } else if (getInput instanceof List) {
+ List<Object> getInputList = (List<Object>) getInput;
+ getInputInfo.setPropName(propName);
+ getInputInfo.setInputName((String) getInputList.get(0));
+ if (getInputList.size() > 1) {
+ Object indexObj = getInputList.get(1);
+ if (indexObj instanceof Integer) {
+ getInputInfo.setIndexValue((Integer) indexObj);
+ } else if (indexObj instanceof Float) {
+ int index = ((Float) indexObj).intValue();
+ getInputInfo.setIndexValue(index);
+ } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj)
+ .containsKey(ToscaTagNamesEnum.GET_INPUT.getElementName())) {
+ Object index = ((Map<String, Object>) indexObj)
+ .get(ToscaTagNamesEnum.GET_INPUT.getElementName());
+ GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
+ getInputInfoIndex.setInputName((String) index);
+ getInputInfoIndex.setPropName(propName);
+ getInputInfo.setGetInputIndex(getInputInfoIndex);
+ }
+ getInputInfo.setList(true);
+ }
+
+ }
+ getInputs.add(getInputInfo);
+ propertyDef.setGet_input(getInputs);
+ propertyDef.setValue(propValue);
+ } else {
+ Set<String> keys = propValue.keySet();
+ for (String key : keys) {
+ Object value = propValue.get(key);
+ if (value instanceof Map) {
+ createGetInputModuleFromMap(key, (Map<String, Object>) value, propertyDef);
+
+ } else if (value instanceof List) {
+ List<Object> valueList = (List<Object>) value;
+ for (Object o : valueList) {
+ if (o instanceof Map) {
+ createGetInputModuleFromMap(key, (Map<String, Object>) o, propertyDef);
+
+ }
+ }
+
+ }
+
+ }
+
+ }
+ }
+
+
+ private boolean valueContainsPattern(Pattern pattern, Object propValue) {
+
+ log.debug("valueContainsToken value is {}", propValue);
+ boolean result = false;
+ if (propValue != null) {
+ log.trace("valueContainspattern value is {}", propValue.getClass());
+ Matcher matcher = pattern.matcher(propValue.toString());
+ result = matcher.find();
+ }
+
+ return result;
+
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<Map<String, List<UploadReqInfo>>, ResponseFormat> createReqModuleFromYaml(
+ UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
+ Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<String, List<UploadReqInfo>>();
+ Either<Map<String, List<UploadReqInfo>>, ResponseFormat> response = Either.left(moduleRequirements);
+ Either<List<Object>, ResultStatusEnum> requirementsListRes = ImportUtils
+ .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
+
+ if (requirementsListRes.isLeft()) {
+ for (Object jsonReqObj : requirementsListRes.left().value()) {
+ String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
+ Object reqJson = ((Map<String, Object>) jsonReqObj).get(reqName);
+ Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo,
+ moduleRequirements, reqJson, reqName);
+ if (eitherCap.isRight()) {
+ return Either.right(eitherCap.right().value());
+ }
+ }
+ } else {
+ Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = ImportUtils
+ .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.REQUIREMENTS);
+ if (requirementsMapRes.isLeft()) {
+ for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) {
+ String reqName = entry.getKey();
+ Object reqJson = entry.getValue();
+ Either<UploadReqInfo, ResponseFormat> eitherCap = addModuleNodeTemplateReq(nodeTemplateInfo,
+ moduleRequirements, reqJson, reqName);
+ if (eitherCap.isRight()) {
+ return Either.right(eitherCap.right().value());
+ }
+ }
+ }
+ }
+ return response;
+ }
+
+ private Either<UploadReqInfo, ResponseFormat> addModuleNodeTemplateReq(UploadComponentInstanceInfo nodeTemplateInfo,
+ Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
+
+ Either<UploadReqInfo, ResponseFormat> eitherRequirement = createModuleNodeTemplateReg(requirementJson);
+ if (eitherRequirement.isRight()) {
+ log.info("error when creating Requirement:{}, for node:{}", requirementName, nodeTemplateInfo);
+ return Either.right(eitherRequirement.right().value());
+ } else {
+ UploadReqInfo requirementDef = eitherRequirement.left().value();
+ requirementDef.setName(requirementName);
+ if (moduleRequirements.containsKey(requirementName)) {
+ moduleRequirements.get(requirementName).add(requirementDef);
+ } else {
+ List<UploadReqInfo> list = new ArrayList<UploadReqInfo>();
+ list.add(requirementDef);
+ moduleRequirements.put(requirementName, list);
+ }
+ }
+ return Either.left(eitherRequirement.left().value());
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<Map<String, List<UploadCapInfo>>, ResponseFormat> createCapModuleFromYaml(
+ UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
+ Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
+ Either<Map<String, List<UploadCapInfo>>, ResponseFormat> response = Either.left(moduleCap);
+ Either<List<Object>, ResultStatusEnum> capabilitiesListRes = ImportUtils
+ .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
+ if (capabilitiesListRes.isLeft()) {
+ for (Object jsonCapObj : capabilitiesListRes.left().value()) {
+ String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
+ Object capJson = ((Map<String, Object>) jsonCapObj).get(key);
+ Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo, moduleCap,
+ capJson, key);
+ if (eitherCap.isRight()) {
+ return Either.right(eitherCap.right().value());
+ }
+ }
+ } else {
+ Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = ImportUtils
+ .findFirstToscaMapElement(nodeTemplateJsonMap, ToscaTagNamesEnum.CAPABILITIES);
+ if (capabilitiesMapRes.isLeft()) {
+ for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) {
+ String capName = entry.getKey();
+ Object capJson = entry.getValue();
+ Either<UploadCapInfo, ResponseFormat> eitherCap = addModuleNodeTemplateCap(nodeTemplateInfo,
+ moduleCap, capJson, capName);
+ if (eitherCap.isRight()) {
+ return Either.right(eitherCap.right().value());
+ }
+ }
+ }
+ }
+ return response;
+ }
+
+ private Either<UploadCapInfo, ResponseFormat> addModuleNodeTemplateCap(UploadComponentInstanceInfo nodeTemplateInfo,
+ Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
+
+ Either<UploadCapInfo, ResponseFormat> eitherCap = createModuleNodeTemplateCap(capJson);
+ if (eitherCap.isRight()) {
+ log.info("error when creating Capability:{}, for node:{}", key, nodeTemplateInfo);
+ return Either.right(eitherCap.right().value());
+ } else {
+ UploadCapInfo capabilityDef = eitherCap.left().value();
+ capabilityDef.setKey(key);
+ if (moduleCap.containsKey(key)) {
+ moduleCap.get(key).add(capabilityDef);
+ } else {
+ List<UploadCapInfo> list = new ArrayList<UploadCapInfo>();
+ list.add(capabilityDef);
+ moduleCap.put(key, list);
+ }
+ }
+ return Either.left(eitherCap.left().value());
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<UploadCapInfo, ResponseFormat> createModuleNodeTemplateCap(Object capObject) {
+ UploadCapInfo capTemplateInfo = new UploadCapInfo();
+ Either<UploadCapInfo, ResponseFormat> result = Either.left(capTemplateInfo);
+
+ if (capObject instanceof String) {
+ String nodeTemplateJsonString = (String) capObject;
+ capTemplateInfo.setNode(nodeTemplateJsonString);
+ } else if (capObject instanceof Map) {
+ Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) capObject;
+ // Type
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
+ capTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
+ }
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ capTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
+ }
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
+ Either<List<Object>, ResultStatusEnum> validSourceTypesRes = ImportUtils
+ .findFirstToscaListElement(nodeTemplateJsonMap, ToscaTagNamesEnum.VALID_SOURCE_TYPES);
+ if (validSourceTypesRes.isLeft()) {
+ capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream()
+ .map(o -> o.toString()).collect(Collectors.toList()));
+ }
+ }
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+ Either<Map<String, List<UploadPropInfo>>, ResponseFormat> regResponse = createPropModuleFromYaml(
+ nodeTemplateJsonMap);
+ if (regResponse.isRight())
+ return Either.right(regResponse.right().value());
+ if (!regResponse.left().value().isEmpty()) {
+ List<UploadPropInfo> properties = new ArrayList<UploadPropInfo>();
+ regResponse.left().value().values().forEach(list -> properties.addAll(list));
+ if (!properties.isEmpty())
+ capTemplateInfo.setProperties(properties);
+ }
+ }
+ }
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<UploadReqInfo, ResponseFormat> createModuleNodeTemplateReg(Object regObject) {
+
+ UploadReqInfo regTemplateInfo = new UploadReqInfo();
+ Either<UploadReqInfo, ResponseFormat> result = Either.left(regTemplateInfo);
+
+ if (regObject instanceof String) {
+ String nodeTemplateJsonString = (String) regObject;
+ regTemplateInfo.setNode(nodeTemplateJsonString);
+ } else if (regObject instanceof Map) {
+ Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) regObject;
+ // Type
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
+ regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
+ }
+ // US740820 Relate RIs according to capability name
+ if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
+ regTemplateInfo.setCapabilityName(
+ (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
+ }
+ }
+ return result;
+ }
+
+ public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource,
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
+ boolean forceCertificationAllowed) {
+
+ Either<Resource, ResponseFormat> result = null;
+ try {
+ if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
+ && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
+ result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ if (result.isRight()) {
+ return result;
+ }
+ resource = result.left().value();
+ }
+ if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(
+ resource, user, false, inTransaction, needLock);
+ result = eitherPopulated.isLeft() ? Either.left(resource)
+ : Either.right(eitherPopulated.right().value());
+ return result;
+ }
+ return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
+ } catch (Exception e) {
+ log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ }
+
+ private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user,
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user,
+ LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
+ if (result.isLeft()) {
+ result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION,
+ lifecycleChangeInfo, inTransaction, needLock);
+ }
+ if (result.isLeft()) {
+ result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY,
+ lifecycleChangeInfo, inTransaction, needLock);
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user,
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
+ needLock);
+ }
+
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(
+ Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock,
+ CsarInfo csarInfo, String nodeName, boolean isNested) {
+
+ // check if resource already exist
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade
+ .getLatestByName(resource.getName());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
+
+ // create
+ if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+
+ Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
+ .getLatestByToscaResourceName(resource.getToscaResourceName());
+ if (csarInfo != null && csarInfo.isUpdate() && nodeName != null && latestByToscaName.isRight()
+ && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ latestByToscaName = toscaOperationFacade
+ .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType().name(),
+ csarInfo.getVfResourceName(), nodeName).getRight());
+ // update
+ if (latestByToscaName.isLeft()) {
+ log.debug("validate derived before update");
+ Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
+ latestByToscaName.left().value(), resource,
+ ValidationUtils.hasBeenCertified(latestByToscaName.left().value().getVersion()));
+ if (eitherValidation.isRight()) {
+ result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ } else {
+ result = updateExistingResourceByImport(resource, latestByToscaName.left().value(), user,
+ isNormative, needLock, isNested);
+ }
+ }
+ }
+ if (result == null && latestByToscaName.isRight()
+ && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+ } else if (result == null) {
+ StorageOperationStatus status = latestByName.right().value();
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
+ ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ log.debug("resource already exist {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+ result = Either.right(responseFormat);
+ }
+
+ }
+
+ // update
+ else if (latestByName.isLeft()) {
+ result = updateExistingResourceByImport(resource, latestByName.left().value(), user, isNormative, needLock,
+ isNested);
+ }
+
+ // error
+ else {
+ StorageOperationStatus status = latestByName.right().value();
+ log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
+ componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+ result = Either.right(responseFormat);
+ }
+ return result;
+
+ }
+
+ private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceByImport(Resource resource,
+ User user, boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
+ log.debug("resource with name {} does not exist. create new resource", resource.getName());
+ Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user,
+ AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
+ if (response.isRight()) {
+ return Either.right(response.right().value());
+ }
+ Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user,
+ AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
+ if (createResponse.isRight()) {
+ return Either.right(createResponse.right().value());
+ } else {
+ ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(),
+ ActionStatus.CREATED);
+ ASDCKpiApi.countImportResourcesKPI();
+ return Either.left(resourcePair);
+
+ }
+ }
+
+ public boolean isResourceExist(String resourceName) {
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
+ return latestByName.isLeft();
+ }
+
+ private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> updateExistingResourceByImport(
+ Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
+ boolean isNested) {
+ String lockedResourceId = oldResource.getUniqueId();
+ log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
+ oldResource.getVersion(), oldResource.getLifecycleState());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
+ try {
+ if (needLock) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(lockedResourceId, oldResource,
+ "Update Resource by Import");
+ if (lockResult.isRight()) {
+ return Either.right(lockResult.right().value());
+ }
+ }
+
+ Either<Resource, ResponseFormat> prepareResourceForUpdate = prepareResourceForUpdate(oldResource, user,
+ inTransaction, false);
+ if (prepareResourceForUpdate.isRight()) {
+ ResponseFormat responseFormat = prepareResourceForUpdate.right().value();
+ log.info("resource {} cannot be updated. reason={}", lockedResourceId,
+ responseFormat.getFormattedMessage());
+ componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
+ ResourceAuditData.newBuilder()
+ .state(oldResource.getLifecycleState().name())
+ .version(oldResource.getVersion())
+ .build());
+ result = Either.right(prepareResourceForUpdate.right().value());
+ return result;
+ }
+ oldResource = prepareResourceForUpdate.left().value();
+
+ mergeOldResourceMetadataWithNew(oldResource, newResource);
+
+ Either<Boolean, ResponseFormat> validateFieldsResponse = validateResourceFieldsBeforeUpdate(oldResource,
+ newResource, inTransaction, isNested);
+ if (validateFieldsResponse.isRight()) {
+ result = Either.right(validateFieldsResponse.right().value());
+ return result;
+ }
+
+ validateFieldsResponse = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource,
+ AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
+ if (validateFieldsResponse.isRight()) {
+ return Either.right(validateFieldsResponse.right().value());
+ }
+
+ // contact info normalization
+ newResource.setContactId(newResource.getContactId().toLowerCase());
+ // non-updatable fields
+ newResource.setCreatorUserId(user.getUserId());
+ newResource.setCreatorFullName(user.getFullName());
+ newResource.setLastUpdaterUserId(user.getUserId());
+ newResource.setLastUpdaterFullName(user.getFullName());
+ newResource.setUniqueId(oldResource.getUniqueId());
+ newResource.setVersion(oldResource.getVersion());
+ newResource.setInvariantUUID(oldResource.getInvariantUUID());
+ newResource.setLifecycleState(oldResource.getLifecycleState());
+ newResource.setUUID(oldResource.getUUID());
+ newResource.setNormalizedName(oldResource.getNormalizedName());
+ newResource.setSystemName(oldResource.getSystemName());
+ if (oldResource.getCsarUUID() != null) {
+ newResource.setCsarUUID(oldResource.getCsarUUID());
+ }
+ if (oldResource.getImportedToscaChecksum() != null) {
+ newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
+ }
+ newResource.setAbstract(oldResource.isAbstract());
+
+ if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom().isEmpty()) {
+ newResource.setDerivedFrom(oldResource.getDerivedFrom());
+ }
+ if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType().isEmpty()) {
+ newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
+ }
+ if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion().isEmpty()) {
+ newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
+ }
+ // TODO rhalili: handle artifacts here (delete from old resource and
+ // add for new)
+ // TODO rbetzer: remove after migration - in case of resources
+ // created without tosca artifacts - add the placeholders
+ if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts().isEmpty()) {
+ setToscaArtifactsPlaceHolders(newResource, user);
+ }
+ Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
+ .overrideComponent(newResource, oldResource);
+
+ if (overrideResource.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
+ componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
+
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ log.debug("Resource updated successfully!!!");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
+ ResourceAuditData.newBuilder()
+ .state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+
+
+ ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(overrideResource.left().value(),
+ ActionStatus.OK);
+ result = Either.left(resourcePair);
+ return result;
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ } else if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ if (needLock == true) {
+ log.debug("unlock resource {}", lockedResourceId);
+ graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
+ }
+ }
+
+ }
+
+ /**
+ * Merge old resource with new. Keep old category and vendor name without
+ * change
+ *
+ * @param oldResource
+ * @param newResource
+ */
+ private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
+
+ // keep old category and vendor name without change
+ // merge the rest of the resource metadata
+ if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
+ newResource.setTags(oldResource.getTags());
+ }
+
+ if (newResource.getDescription() == null) {
+ newResource.setDescription(oldResource.getDescription());
+ }
+
+ if (newResource.getVendorRelease() == null) {
+ newResource.setVendorRelease(oldResource.getVendorRelease());
+ }
+
+ if (newResource.getResourceVendorModelNumber() == null) {
+ newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
+ }
+
+ if (newResource.getContactId() == null) {
+ newResource.setContactId(oldResource.getContactId());
+ }
+
+ newResource.setCategories(oldResource.getCategories());
+ if (newResource.getVendorName() == null) {
+ newResource.setVendorName(oldResource.getVendorName());
+ }
+ }
+
+ private Either<Resource, ResponseFormat> prepareResourceForUpdate(Resource latestResource, User user,
+ boolean inTransaction, boolean needLock) {
+
+ Either<Resource, ResponseFormat> result = Either.left(latestResource);
+ // check if user can edit resource
+ if (!ComponentValidationUtils.canWorkOnResource(latestResource, user.getUserId())) {
+ // checkout
+ Either<Resource, ResponseFormat> changeState = lifecycleBusinessLogic.changeState(
+ latestResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+ new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock);
+ result = changeState;
+ }
+
+ return result;
+ }
+
+ public Either<Resource, ResponseFormat> validateResourceBeforeCreate(Resource resource, User user,
+ AuditingActionEnum actionEnum, boolean inTransaction, CsarInfo csarInfo) {
+
+ Either<Boolean, ResponseFormat> eitherValidation = validateResourceFieldsBeforeCreate(user, resource,
+ actionEnum, inTransaction);
+ if (eitherValidation.isRight()) {
+ return Either.right(eitherValidation.right().value());
+ }
+
+ eitherValidation = validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum,
+ inTransaction);
+ if (eitherValidation.isRight()) {
+ return Either.right(eitherValidation.right().value());
+ }
+ eitherValidation = validateLifecycleTypesCreate(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return Either.right(eitherValidation.right().value());
+ }
+ eitherValidation = validateResourceType(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return Either.right(eitherValidation.right().value());
+ }
+
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setContactId(resource.getContactId().toLowerCase());
+ if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
+ String resourceSystemName;
+ if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
+ resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
+ } else {
+ resourceSystemName = resource.getSystemName();
+ }
+ resource.setToscaResourceName(CommonBeUtils
+ .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+ }
+
+ // Generate invariant UUID - must be here and not in operation since it
+ // should stay constant during clone
+ // TODO
+ String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
+ resource.setInvariantUUID(invariantUUID);
+
+ return Either.left(resource);
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ if (resource.getResourceType() == null) {
+ log.debug("Invalid resource type for resource");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+ return eitherResult;
+ }
+
+ private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
+ log.debug("validate interface lifecycle Types Exist");
+ Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
+ while (intItr.hasNext() && eitherResult.isLeft()) {
+ InterfaceDefinition interfaceDefinition = intItr.next();
+ String intType = interfaceDefinition.getUniqueId();
+ Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
+ .getInterface(intType);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
+ "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+ log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
+ intType, resource.getName());
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
+ log.debug("request to data model failed with error: {}",
+ eitherCapTypeFound.right().value().name());
+ }
+
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+
+ }
+ }
+ return eitherResult;
+ }
+
+ private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
+ ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
+ boolean inTransaction) {
+
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
+ log.debug("validate capability Types Exist - capabilities section");
+
+ for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
+
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
+ eitherResult, typeEntry, inTransaction);
+ if (eitherResult.isRight()) {
+ return Either.right(eitherResult.right().value());
+ }
+ }
+ }
+
+ if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
+ log.debug("validate capability Types Exist - requirements section");
+ for (String type : resource.getRequirements().keySet()) {
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
+ resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
+ if (eitherResult.isRight()) {
+ return Either.right(eitherResult.right().value());
+ }
+ }
+ }
+
+ return eitherResult;
+ }
+
+ // @param typeObject- the object to which the validation is done
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
+ ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
+ AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
+ boolean inTransaction) {
+ Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
+ .getCapabilityType(type, inTransaction);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
+ "Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
+ resource.getName());
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
+ }
+ log.debug("Trying to get capability type {} failed with error: {}", type,
+ eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = null;
+ if (type != null)
+ errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
+ else
+ errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
+ validationObjects);
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+ return eitherResult;
+ }
+
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
+ ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
+ Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
+ boolean inTransaction) {
+ Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
+ .getCapabilityType(typeEntry.getKey(), inTransaction);
+ if (eitherCapTypeFound.isRight()) {
+ if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+ BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
+ "Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
+ log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
+ typeEntry.getKey(), resource.getName());
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
+ }
+ log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
+ eitherCapTypeFound.right().value().name());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
+ typeEntry.getKey());
+ eitherResult = Either.right(errorResponse);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ }
+ CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
+ if (capabilityTypeDefinition.getProperties() != null) {
+ for (CapabilityDefinition capDef : typeEntry.getValue()) {
+ List<ComponentInstanceProperty> properties = capDef.getProperties();
+ if (properties == null || properties.isEmpty()) {
+ properties = new ArrayList<ComponentInstanceProperty>();
+ for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+ ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
+ properties.add(newProp);
+ }
+ } else {
+ for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+ PropertyDefinition porpFromDef = prop.getValue();
+ List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
+ for (ComponentInstanceProperty cip : properties) {
+ if (!cip.getName().equals(porpFromDef.getName())) {
+ ComponentInstanceProperty newProp = new ComponentInstanceProperty(porpFromDef);
+ propsToAdd.add(newProp);
+ }
+ }
+ if (!propsToAdd.isEmpty()) {
+ properties.addAll(propsToAdd);
+ }
+ }
+ }
+ capDef.setProperties(properties);
+ }
+ }
+ return eitherResult;
+ }
+
+ public Either<Resource, ResponseFormat> createResourceByDao(Resource resource, User user,
+ AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+ // create resource
+
+ // lock new resource name in order to avoid creation resource with same
+ // name
+ if (inTransaction == false) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
+ "Create Resource");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ }
+ try {
+ if (resource.deriveFromGeneric()) {
+ Either<Resource, ResponseFormat> genericResourceEither = handleResourceGenericType(resource);
+ if (genericResourceEither.isRight())
+ return genericResourceEither;
+ }
+
+ Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative,
+ inTransaction);
+ if (respStatus.isLeft()) {
+ componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
+ respStatus.left().value(), actionEnum);
+ ASDCKpiApi.countCreatedResourcesKPI();
+ } else
+ componentsUtils.auditResource(respStatus.right().value(), user, resource, actionEnum);
+ return respStatus;
+
+ } finally {
+ if (inTransaction == false) {
+ graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
+ NodeTypeEnum.Resource);
+ }
+ }
+ }
+
+ private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditResource(responseFormat, user, persistedResource, actionEnum);
+ }
+
+ private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user,
+ boolean isNormative, boolean inTransaction) {
+ // validate resource name uniqueness
+ log.debug("validate resource name");
+ Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
+ resource.getName(), resource.getResourceType(), resource.getComponentType());
+ if (eitherValidation.isRight()) {
+ log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
+ eitherValidation.right().value());
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
+ return Either.right(errorResponse);
+ }
+ if (eitherValidation.left().value()) {
+ log.debug("resource with name: {}, already exists", resource.getName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
+ ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ return Either.right(errorResponse);
+ }
+
+ log.debug("send resource {} to dao for create", resource.getName());
+
+ createArtifactsPlaceHolderData(resource, user);
+
+ //
+
+ // enrich object
+ if (!isNormative) {
+ log.debug("enrich resource with creator, version and state");
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ resource.setVersion(INITIAL_VERSION);
+ resource.setHighestVersion(true);
+ if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
+ resource.setAbstract(false);
+ }
+
+ Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade
+ .createToscaComponent(resource);
+ if (createToscaElement.isLeft()) {
+ return Either.left(createToscaElement.left().value());
+ }
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(createToscaElement.right().value()), resource);
+
+ return Either.right(responseFormat);
+ }
+
+ private void createArtifactsPlaceHolderData(Resource resource, User user) {
+ // create mandatory artifacts
+
+ // TODO it must be removed after that artifact uniqueId creation will be
+ // moved to ArtifactOperation
+
+ setInformationalArtifactsPlaceHolder(resource, user);
+ setDeploymentArtifactsPlaceHolder(resource, user);
+ setToscaArtifactsPlaceHolders(resource, user);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
+ Resource resource = (Resource) component;
+ Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
+ if (artifactMap == null) {
+ artifactMap = new HashMap<String, ArtifactDefinition>();
+ }
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration().getDeploymentResourceArtifacts();
+ if (deploymentResourceArtifacts != null) {
+ Iterator<Entry<String, Object>> iterator = deploymentResourceArtifacts.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<String, Object> currEntry = iterator.next();
+ boolean shouldCreateArtifact = true;
+ Map<String, Object> artifactDetails = (Map<String, Object>) currEntry.getValue();
+ Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
+ if (object != null) {
+ List<String> artifactTypes = (List<String>) object;
+ if (!artifactTypes.contains(resource.getResourceType().name())) {
+ shouldCreateArtifact = false;
+ continue;
+ }
+ } else {
+ log.info("resource types for artifact placeholder {} were not defined. default is all resources",
+ currEntry.getKey());
+ }
+ if (shouldCreateArtifact) {
+ if (artifactsBusinessLogic != null) {
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
+ resource.getUniqueId(), currEntry.getKey(), (Map<String, Object>) currEntry.getValue(),
+ user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ if (artifactDefinition != null
+ && !artifactMap.containsKey(artifactDefinition.getArtifactLabel()))
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+ }
+ }
+ }
+ }
+ resource.setDeploymentArtifacts(artifactMap);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
+ Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
+ if (artifactMap == null) {
+ artifactMap = new HashMap<String, ArtifactDefinition>();
+ }
+ String resourceUniqueId = resource.getUniqueId();
+ List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getExcludeResourceCategory();
+ List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getExcludeResourceType();
+ Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
+ .getConfiguration().getInformationalResourceArtifacts();
+ List<CategoryDefinition> categories = resource.getCategories();
+ boolean isCreateArtifact = true;
+ if (exludeResourceCategory != null) {
+ String category = categories.get(0).getName();
+ for (String exlude : exludeResourceCategory) {
+ if (exlude.equalsIgnoreCase(category)) {
+ isCreateArtifact = false;
+ break;
+ }
+ }
+
+ }
+ if (isCreateArtifact && exludeResourceType != null) {
+ String resourceType = resource.getResourceType().name();
+ for (String type : exludeResourceType) {
+ if (type.equalsIgnoreCase(resourceType)) {
+ isCreateArtifact = false;
+ break;
+ }
+ }
+
+ }
+
+ if (informationalResourceArtifacts != null && isCreateArtifact) {
+ Set<String> keys = informationalResourceArtifacts.keySet();
+ for (String informationalResourceArtifactName : keys) {
+ Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
+ .get(informationalResourceArtifactName);
+ ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
+ resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+
+ }
+ }
+ resource.setArtifacts(artifactMap);
+ }
+
+ /**
+ * deleteResource
+ *
+ * @param resourceId
+ * @param user
+ * @return
+ */
+ public ResponseFormat deleteResource(String resourceId, User user) {
+ ResponseFormat responseFormat;
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
+ if (eitherCreator.isRight()) {
+ return eitherCreator.right().value();
+ }
+
+ Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
+ if (resourceStatus.isRight()) {
+ log.debug("failed to get resource {}", resourceId);
+ return componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
+ }
+
+ Resource resource = resourceStatus.left().value();
+
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(resourceId, resource, "Mark resource to delete");
+ if (lockResult.isRight()) {
+ result = StorageOperationStatus.GENERAL_ERROR;
+ return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ }
+
+ try {
+
+ result = markComponentToDelete(resource);
+ if (result.equals(StorageOperationStatus.OK)) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+ } else {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
+ }
+ return responseFormat;
+
+ } finally {
+ if (result == null || !result.equals(StorageOperationStatus.OK)) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+ }
+
+ }
+
+ public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Delete Resource", false);
+ if (eitherCreator.isRight()) {
+ return eitherCreator.right().value();
+ }
+
+ Resource resource = null;
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ try {
+
+ Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
+ .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
+ if (resourceStatus.isRight()) {
+ log.debug("failed to get resource {} version {}", resourceName, version);
+ return componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
+ }
+
+ resource = resourceStatus.left().value();
+
+ } finally {
+ if (result == null || !result.equals(StorageOperationStatus.OK)) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resourceName);
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ if (resource != null) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(resource.getUniqueId(), resource,
+ "Delete Resource");
+ if (lockResult.isRight()) {
+ result = StorageOperationStatus.GENERAL_ERROR;
+ return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ }
+ try {
+ result = markComponentToDelete(resource);
+ if (!result.equals(StorageOperationStatus.OK)) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
+ return responseFormat;
+ }
+
+ } finally {
+ if (result == null || !result.equals(StorageOperationStatus.OK)) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
+ }
+ }
+ return responseFormat;
+ }
+
+ public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
+
+ if (user != null) {
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, "Create Resource", false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ }
+
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
+ if (storageStatus.isRight()) {
+ log.debug("failed to get resource by id {}", resourceId);
+ return Either.right(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
+ }
+ if (!(storageStatus.left().value() instanceof Resource)) {
+ return Either.right(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
+ }
+ return Either.left(storageStatus.left().value());
+
+ }
+
+ public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
+ String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Resource By Name And Version", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
+ .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
+ if (getResource.isRight()) {
+ log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
+ return Either.right(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
+ }
+ return Either.left(getResource.left().value());
+ }
+
+ /**
+ * updateResourceMetadata
+ *
+ * @param user - modifier data (userId)
+ * @param inTransaction TODO
+ * @param resourceIdToUpdate - the resource identifier
+ * @param newResource
+ * @return Either<Resource, responseFormat>
+ */
+ public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
+ Resource currentResource, User user, boolean inTransaction) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Resource Metadata", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ log.debug("Get resource with id {}", resourceIdToUpdate);
+ boolean needToUnlock = false;
+ boolean rollbackNeeded = true;
+
+ try {
+ if (currentResource == null) {
+ Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
+ .getToscaElement(resourceIdToUpdate);
+ if (storageStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ }
+
+ currentResource = storageStatus.left().value();
+ }
+ // verify that resource is checked-out and the user is the last
+ // updater
+ if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ // lock resource
+ StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
+ NodeTypeEnum.Resource);
+ if (!lockResult.equals(StorageOperationStatus.OK)) {
+ BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ",
+ NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
+ log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
+ return Either.right(responseFormat);
+ }
+
+ needToUnlock = true;
+
+ // critical section starts here
+ // convert json to object
+
+ // Update and updated resource must have a non-empty "derivedFrom"
+ // list
+ // This code is not called from import resources, because of root
+ // VF "derivedFrom" should be null (or ignored)
+ if (ModelConverter.isAtomicComponent(currentResource)) {
+ Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null,
+ newResource, null);
+ if (derivedFromNotEmptyEither.isRight()) {
+ log.debug("for updated resource {}, derived from field is empty", newResource.getName());
+ return Either.right(derivedFromNotEmptyEither.right().value());
+ }
+
+ derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, currentResource, null);
+ if (derivedFromNotEmptyEither.isRight()) {
+ log.debug("for current resource {}, derived from field is empty", currentResource.getName());
+ return Either.right(derivedFromNotEmptyEither.right().value());
+ }
+ } else {
+ newResource.setDerivedFrom(null);
+ }
+
+ Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
+ user, currentResource, false, true);
+ if (dataModelResponse.isRight()) {
+ log.debug("failed to update resource metadata!!!");
+ rollbackNeeded = true;
+ return Either.right(dataModelResponse.right().value());
+ }
+
+ log.debug("Resource metadata updated successfully!!!");
+ rollbackNeeded = false;
+ return Either.left(dataModelResponse.left().value());
+
+ } finally {
+ if (!inTransaction) {
+ if (rollbackNeeded) {
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ }
+
+ if (needToUnlock) {
+ graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
+ }
+ }
+ }
+
+ private Either<List<GroupDefinition>, Boolean> updateComponentGroupName(String replacePattern, String with,
+ List<GroupDefinition> oldGroup) {
+ if (oldGroup == null || with == null || replacePattern == null || with.isEmpty() || replacePattern.isEmpty()) {
+ if (log.isInfoEnabled())
+ log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}",
+ replacePattern, with, oldGroup == null ? null : " < size : " + oldGroup.size() + " >");
+ return Either.right(false);
+ }
+ List<GroupDefinition> list = oldGroup.stream().map(group -> new GroupDefinition(group))
+ .collect(Collectors.toList());
+ for (GroupDefinition group : list) {
+ if (group != null && group.isSamePrefix(replacePattern)) {
+ String prefix = group.getName().substring(0, replacePattern.length());
+ String newGroupName = group.getName().replaceFirst(prefix, with);
+ group.setName(newGroupName);
+ }
+ }
+ return Either.left(list);
+ }
+
+ private boolean isComponentNameChanged(Resource newResource, Resource oldResource) {
+ if (newResource != null && oldResource != null) { // TODO - must protect
+ // all chain against
+ // null , use
+ // optional
+ String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ return !oldName.equals(futureName);
+ }
+ return false;
+ }
+
+ private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
+ User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
+ // region -> Update groups name for newResource
+ if (isComponentNameChanged(currentResource, newResource)) {
+ String replacePattern = Optional.ofNullable( // get currentResource
+ // name from
+ // metadata
+ Optional.ofNullable(
+ Optional.ofNullable(currentResource).orElse(null).getComponentMetadataDefinition())
+ .orElse(null).getMetadataDataDefinition())
+ .orElse(null).getName();
+ String with = Optional.ofNullable( // get newResource name from
+ // metadata
+ Optional.ofNullable(Optional.ofNullable(newResource).orElse(null).getComponentMetadataDefinition())
+ .orElse(null).getMetadataDataDefinition())
+ .orElse(null).getName();
+ if (with != null && replacePattern != null) {
+ Either<List<GroupDefinition>, Boolean> result = updateComponentGroupName(replacePattern, with,
+ currentResource.getGroups());
+ if (result.isLeft())
+ newResource.setGroups((List<GroupDefinition>) result.left().value());
+ }
+ }
+ // endregion
+
+ Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource,
+ newResource, inTransaction, false);
+ if (validateResourceFields.isRight()) {
+ return Either.right(validateResourceFields.right().value());
+ }
+ // Setting last updater and uniqueId
+ newResource.setContactId(newResource.getContactId().toLowerCase());
+ newResource.setLastUpdaterUserId(user.getUserId());
+ newResource.setUniqueId(resourceIdToUpdate);
+ // Cannot set highest version through UI
+ newResource.setHighestVersion(currentResource.isHighestVersion());
+ newResource.setCreationDate(currentResource.getCreationDate());
+
+ Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
+ newResource, user.getUserId(), shouldLock, inTransaction);
+
+ if (processUpdateOfDerivedFrom.isRight()) {
+ log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
+ return Either.right(processUpdateOfDerivedFrom.right().value());
+ }
+
+ log.debug("send resource {} to dao for update", newResource.getUniqueId());
+ if (newResource != null && newResource.getGroups() != null) {
+ for (GroupDefinition group : newResource.getGroups()) {
+ if (newResource.getComponentMetadataDefinition() != null
+ && newResource.getComponentMetadataDefinition().getMetadataDataDefinition() != null)
+ groupBusinessLogic.validateAndUpdateGroupMetadata(
+ newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(),
+ user, ComponentTypeEnum.RESOURCE_INSTANCE, group, true, false);
+ }
+ }
+ Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .updateToscaElement(newResource);
+
+ if (dataModelResponse.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
+ return Either.right(responseFormat);
+ } else if (dataModelResponse.left().value() == null) {
+ log.debug("No response from updateResource");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return Either.left(dataModelResponse.left().value());
+ }
+
+ /**
+ * validateResourceFieldsBeforeCreate
+ *
+ * @param user - modifier data (userId)
+ * @return Either<Boolean, ErrorResponse>
+ */
+ private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
+ AuditingActionEnum actionEnum, boolean inTransaction) {
+ Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, resource,
+ actionEnum);
+ if (componentsFieldsValidation.isRight()) {
+ return componentsFieldsValidation;
+ }
+
+
+ // validate category
+ log.debug("validate category");
+ Either<Boolean, ResponseFormat> eitherValidation = validateCategory(user, resource, actionEnum, inTransaction);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ // validate vendor name & release & model number
+ log.debug("validate vendor name");
+ eitherValidation = validateVendorName(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate vendor release");
+ eitherValidation = validateVendorReleaseName(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate resource vendor model number");
+ eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+
+ // validate cost
+ log.debug("validate cost");
+ eitherValidation = validateCost(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ // validate licenseType
+ log.debug("validate licenseType");
+ eitherValidation = validateLicenseType(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ // validate template (derived from)
+ log.debug("validate derived from");
+ if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ resource.setDerivedFrom(null);
+ }
+ eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return Either.right(eitherValidation.right().value());
+ }
+
+ // warn about non-updatable fields
+ checkComponentFieldsForOverrideAttempt(resource);
+ String currentCreatorFullName = resource.getCreatorFullName();
+ if (currentCreatorFullName != null) {
+ log.warn("Resource Creator fullname is automatically set and cannot be updated");
+ }
+
+ String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
+ if (currentLastUpdaterFullName != null) {
+ log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
+ }
+
+ Long currentLastUpdateDate = resource.getLastUpdateDate();
+ if (currentLastUpdateDate != null) {
+ log.warn("Resource last update date is automatically set and cannot be updated");
+ }
+
+ Boolean currentAbstract = resource.isAbstract();
+ if (currentAbstract != null) {
+ log.warn("Resource abstract is automatically set and cannot be updated");
+ }
+
+ return Either.left(true);
+ }
+
+ /**
+ * validateResourceFieldsBeforeUpdate
+ *
+ * @param currentResource - Resource object to validate
+ * @param isNested
+ * @return Either<Boolean, ErrorResponse>
+ */
+ private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource,
+ Resource updateInfoResource, boolean inTransaction, boolean isNested) {
+
+ boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
+
+ // validate resource name
+ log.debug("validate resource name before update");
+ Either<Boolean, ResponseFormat> eitherValidation = validateResourceName(currentResource, updateInfoResource,
+ hasBeenCertified, isNested);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ // validate description
+ log.debug("validate description before update");
+ eitherValidation = validateDescriptionAndCleanup(null, updateInfoResource, null);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate icon before update");
+ eitherValidation = validateIcon(currentResource, updateInfoResource, hasBeenCertified);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate tags before update");
+ eitherValidation = validateTagsListAndRemoveDuplicates(null, updateInfoResource, null);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate vendor name before update");
+ eitherValidation = validateVendorName(currentResource, updateInfoResource, hasBeenCertified);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate resource vendor model number before update");
+ eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate vendor release before update");
+ eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate contact info before update");
+ eitherValidation = validateContactId(null, updateInfoResource, null);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate derived before update");
+ eitherValidation = validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ log.debug("validate category before update");
+ eitherValidation = validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+ // warn about non-updatable fields
+ String currentResourceVersion = currentResource.getVersion();
+ String updatedResourceVersion = updateInfoResource.getVersion();
+
+ if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
+ log.warn("Resource version is automatically set and cannot be updated");
+ }
+
+ String currentCreatorUserId = currentResource.getCreatorUserId();
+ String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
+
+ if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
+ log.warn("Resource Creator UserId is automatically set and cannot be updated");
+ }
+
+ String currentCreatorFullName = currentResource.getCreatorFullName();
+ String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
+
+ if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
+ log.warn("Resource Creator fullname is automatically set and cannot be updated");
+ }
+
+ String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
+ String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
+
+ if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
+ log.warn("Resource LastUpdater userId is automatically set and cannot be updated");
+ }
+
+ String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
+ String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
+
+ if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
+ log.warn("Resource LastUpdater fullname is automatically set and cannot be updated");
+ }
+
+ Long currentCreationDate = currentResource.getCreationDate();
+ Long updatedCreationDate = updateInfoResource.getCreationDate();
+
+ if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
+ log.warn("Resource Creation date is automatically set and cannot be updated");
+ }
+
+ Long currentLastUpdateDate = currentResource.getLastUpdateDate();
+ Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
+
+ if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
+ log.warn("Resource last update date is automatically set and cannot be updated");
+ }
+
+ LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
+ LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
+
+ if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
+ log.warn("Resource lifecycle state date is automatically set and cannot be updated");
+ }
+
+ Boolean currentAbstract = currentResource.isAbstract();
+ Boolean updatedAbstract = updateInfoResource.isAbstract();
+
+ if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
+ log.warn("Resource abstract is automatically set and cannot be updated");
+ }
+
+ Boolean currentHighestVersion = currentResource.isHighestVersion();
+ Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
+
+ if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
+ log.warn("Resource highest version is automatically set and cannot be updated");
+ }
+
+ String currentUuid = currentResource.getUUID();
+ String updatedUuid = updateInfoResource.getUUID();
+
+ if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
+ log.warn("Resource UUID is automatically set and cannot be updated");
+ }
+
+ ResourceTypeEnum currentResourceType = currentResource.getResourceType();
+ ResourceTypeEnum updatedResourceType = updateInfoResource.getResourceType();
+
+ if ((updatedResourceType != null) && (!updatedResourceType.equals(currentResourceType))) {
+ log.warn("Resource Type cannot be updated");
+
+ }
+ updateInfoResource.setResourceType(currentResource.getResourceType());
+
+ String currentInvariantUuid = currentResource.getInvariantUUID();
+ String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
+
+ if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
+ log.warn("Resource invariant UUID is automatically set and cannot be updated");
+ updateInfoResource.setInvariantUUID(currentInvariantUuid);
+ }
+ return Either.left(true);
+ }
+
+
+ private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
+ String resourceNameUpdated = updateInfoResource.getName();
+ String resourceNameCurrent = currentResource.getName();
+ if (resourceNameCurrent.equals(resourceNameUpdated))
+ return true;
+ // In case of CVFC type we should support the case of old VF with CVFC
+ // instances that were created without the "Cvfc" suffix
+ return currentResource.getResourceType().equals(ResourceTypeEnum.CVFC) &&
+ resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+ }
+
+ private String addCvfcSuffixToResourceName(String resourceName) {
+ return resourceName + "Cvfc";
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceName(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified, boolean isNested) {
+ String resourceNameUpdated = updateInfoResource.getName();
+ if (!isResourceNameEquals(currentResource, updateInfoResource)) {
+ if (isNested || !hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validateResourceNameResponse = validateComponentName(null,
+ updateInfoResource, null);
+ if (validateResourceNameResponse.isRight()) {
+ ResponseFormat errorResponse = validateResourceNameResponse.right().value();
+ return Either.right(errorResponse);
+ }
+ validateResourceNameResponse = validateResourceNameExists(updateInfoResource);
+ if (validateResourceNameResponse.isRight()) {
+ ResponseFormat errorResponse = validateResourceNameResponse.right().value();
+ return Either.right(errorResponse);
+ }
+ currentResource.setName(resourceNameUpdated);
+ currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
+ currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
+
+ } else {
+ log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
+ resourceNameUpdated);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateIcon(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified) {
+ String iconUpdated = updateInfoResource.getIcon();
+ String iconCurrent = currentResource.getIcon();
+ if (!iconCurrent.equals(iconUpdated)) {
+ if (!hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validateIcon = validateIcon(null, updateInfoResource, null);
+ if (validateIcon.isRight()) {
+ ResponseFormat errorResponse = validateIcon.right().value();
+ return Either.right(errorResponse);
+ }
+ } else {
+ log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateVendorName(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified) {
+ String vendorNameUpdated = updateInfoResource.getVendorName();
+ String vendorNameCurrent = currentResource.getVendorName();
+ if (!vendorNameCurrent.equals(vendorNameUpdated)) {
+ if(updateInfoResource.getResourceType().equals(ResourceTypeEnum.VF) && hasBeenCertified ){
+ log.info("Vendor name {} cannot be updated once the resource has been certified once.",
+ vendorNameUpdated);
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+
+ }
+ else {
+ Either<Boolean, ResponseFormat> validateVendorName = validateVendorName(null, updateInfoResource, null);
+ if (validateVendorName.isRight()) {
+ ResponseFormat errorResponse = validateVendorName.right().value();
+ return Either.right(errorResponse);
+ }
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource,
+ Resource updateInfoResource) {
+ String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
+ String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
+ if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
+ Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null,
+ updateInfoResource, null);
+ if (validateResourceVendorModelNumber.isRight()) {
+ ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
+ boolean hasBeenCertified, boolean inTransaction) {
+ Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null,
+ inTransaction);
+ if (validateCategoryName.isRight()) {
+ ResponseFormat errorResponse = validateCategoryName.right().value();
+ return Either.right(errorResponse);
+ }
+ if (hasBeenCertified) {
+ CategoryDefinition currentCategory = currentResource.getCategories().get(0);
+ SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
+ CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
+ SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
+ if (!currentCategory.getName().equals(updateCategory.getName())
+ || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
+ log.info("Category {} cannot be updated once the resource has been certified once.",
+ currentResource.getCategories());
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
+ Resource updateInfoResource, boolean hasBeenCertified) {
+
+ List<String> currentDerivedFrom = currentResource.getDerivedFrom();
+ List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
+ if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
+ || updatedDerivedFrom.isEmpty()) {
+ log.trace("Update normative types");
+ return Either.left(true);
+ }
+
+ String derivedFromCurrent = currentDerivedFrom.get(0);
+ String derivedFromUpdated = updatedDerivedFrom.get(0);
+
+ if (!derivedFromCurrent.equals(derivedFromUpdated)) {
+ if (!hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null,
+ updateInfoResource, null);
+ if (validateDerivedFromExistsEither.isRight()) {
+ return validateDerivedFromExistsEither;
+ }
+ } else {
+ Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
+ currentResource, updateInfoResource, null);
+
+ if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+ log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+ return validateDerivedFromExtending;
+ }
+ }
+ } else {
+ // For derived from, we must know whether it was actually changed,
+ // otherwise we must do no action.
+ // Due to changes it inflicts on data model (remove artifacts,
+ // properties...), it's not like a flat field which can be
+ // overwritten if not changed.
+ // So we must indicate that derived from is not changed
+ updateInfoResource.setDerivedFrom(null);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
+ Resource updateInfoResource, boolean hasBeenCertified) {
+
+ List<String> currentDerivedFrom = currentResource.getDerivedFrom();
+ List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
+ if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
+ || updatedDerivedFrom.isEmpty()) {
+ log.trace("Update normative types");
+ return Either.left(true);
+ }
+
+ String derivedFromCurrent = currentDerivedFrom.get(0);
+ String derivedFromUpdated = updatedDerivedFrom.get(0);
+
+ if (!derivedFromCurrent.equals(derivedFromUpdated)) {
+ if (!hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validateDerivedFromExistsEither = validateDerivedFromExist(null,
+ updateInfoResource, null);
+ if (validateDerivedFromExistsEither.isRight()) {
+ return validateDerivedFromExistsEither;
+ }
+ } else {
+ Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
+ currentResource, updateInfoResource, null);
+
+ if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+ log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+ return validateDerivedFromExtending;
+ }
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateDerivedFromExist(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+
+ if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
+ return Either.left(true);
+ }
+
+
+ String templateName = resource.getDerivedFrom().get(0);
+
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateToscaResourceNameExists(templateName);
+ if (dataModelResponse.isRight()) {
+ StorageOperationStatus storageStatus = dataModelResponse.right().value();
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
+ log.debug("request to data model failed with error: {}", storageStatus);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
+ log.trace("audit before sending response");
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ return Either.right(responseFormat);
+ } else if (!dataModelResponse.left().value()) {
+ log.info("resource template with name: {}, does not exists", templateName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+
+ return Either.right(responseFormat);
+
+ }
+ return Either.left(true);
+ }
+
+ // Tal G for extending inheritance US815447
+ private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
+ Resource updateInfoResource, AuditingActionEnum actionEnum) {
+ String currentTemplateName = currentResource.getDerivedFrom().get(0);
+ String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
+
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+ .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
+ if (dataModelResponse.isRight()) {
+ StorageOperationStatus storageStatus = dataModelResponse.right().value();
+ BeEcompErrorManager.getInstance()
+ .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+ log.trace("audit before sending response");
+ componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
+ return Either.right(responseFormat);
+ }
+
+ if (!dataModelResponse.left().value()) {
+ log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
+ currentTemplateName);
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
+
+ return Either.right(responseFormat);
+
+ }
+ return Either.left(true);
+ }
+
+ public Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ log.debug("validate resource derivedFrom field");
+ if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
+ || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
+ log.info("derived from (template) field is missing for the resource");
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceNameExists(Resource resource) {
+
+ Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
+ .validateComponentNameExists(resource.getName(), resource.getResourceType(),
+ resource.getComponentType());
+ if (resourceOperationResponse.isLeft()) {
+ if (!resourceOperationResponse.left().value()) {
+ return Either.left(false);
+ } else {
+ log.debug("resource with name: {}, already exists", resource.getName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(
+ ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+ resource.getName());
+ return Either.right(errorResponse);
+ }
+ }
+ log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(resourceOperationResponse.right().value()));
+ return Either.right(errorResponse);
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateCategory(User user, Resource resource,
+ AuditingActionEnum actionEnum, boolean inTransaction) {
+
+ List<CategoryDefinition> categories = resource.getCategories();
+ if (categories == null || categories.size() == 0) {
+ log.debug("Resource category is empty");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ return Either.right(responseFormat);
+ }
+ if (categories.size() > 1) {
+ log.debug("Must be only one category for resource");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
+ return Either.right(responseFormat);
+ }
+ CategoryDefinition category = categories.get(0);
+ List<SubCategoryDefinition> subcategories = category.getSubcategories();
+ if (subcategories == null || subcategories.size() == 0) {
+ log.debug("Missinig subcategory for resource");
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
+ return Either.right(responseFormat);
+ }
+ if (subcategories.size() > 1) {
+ log.debug("Must be only one sub category for resource");
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
+ return Either.right(responseFormat);
+ }
+
+ SubCategoryDefinition subcategory = subcategories.get(0);
+
+ if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
+ log.debug("Resource category is empty");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ return Either.right(responseFormat);
+ }
+ if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
+ log.debug("Resource category is empty");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ return Either.right(responseFormat);
+ }
+
+ Either<Boolean, ResponseFormat> validateCategory = validateCategoryListed(category, subcategory, inTransaction);
+ if (validateCategory.isRight()) {
+ ResponseFormat responseFormat = validateCategory.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ return Either.right(responseFormat);
+ }
+
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateCategoryListed(CategoryDefinition category,
+ SubCategoryDefinition subcategory, boolean inTransaction) {
+ if (category != null && subcategory != null) {
+ log.debug("validating resource category {} against valid categories list", category);
+ Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
+ .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
+ if (categories.isRight()) {
+ log.debug("failed to retrive resource categories from Titan");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(categories.right().value());
+ return Either.right(responseFormat);
+ }
+ List<CategoryDefinition> categoryList = categories.left().value();
+ for (CategoryDefinition cat : categoryList) {
+ if (cat.getName().equals(category.getName())) {
+ for (SubCategoryDefinition subcat : cat.getSubcategories()) {
+ if (subcat.getName().equals(subcategory.getName())) {
+ return Either.left(true);
+ }
+ }
+ log.debug(
+ "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
+ subcategory, cat.getSubcategories());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ }
+ log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
+ category, categoryList);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
+ ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ return Either.left(false);
+ }
+
+ public Either<Boolean, ResponseFormat> validateVendorReleaseName(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ String vendorRelease = resource.getVendorRelease();
+
+ log.debug("validate vendor relese name");
+ if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
+ log.info("vendor relese name is missing.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ return Either.right(errorResponse);
+ }
+
+ Either<Boolean, ResponseFormat> validateVendorReleaseResponse = validateVendorReleaseName(vendorRelease);
+ if (validateVendorReleaseResponse.isRight()) {
+ ResponseFormat responseFormat = validateVendorReleaseResponse.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ }
+ return validateVendorReleaseResponse;
+ }
+
+ public Either<Boolean, ResponseFormat> validateVendorReleaseName(String vendorRelease) {
+ if (vendorRelease != null) {
+ if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
+ log.info("vendor release exceds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(
+ ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
+ log.info("vendor release is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ return Either.left(false);
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateVendorName(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ String vendorName = resource.getVendorName();
+ if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
+ log.info("vendor name is missing.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_NAME);
+ componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+ return Either.right(errorResponse);
+ }
+
+ Either<Boolean, ResponseFormat> validateVendorNameResponse = validateVendorName(vendorName);
+ if (validateVendorNameResponse.isRight()) {
+ ResponseFormat responseFormat = validateVendorNameResponse.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ }
+ return validateVendorNameResponse;
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
+ Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(
+ resourceVendorModelNumber);
+ if (validateResourceVendorModelNumber.isRight()) {
+ ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ }
+ return validateResourceVendorModelNumber;
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
+ if (vendorName != null) {
+ if (!ValidationUtils.validateVendorNameLength(vendorName)) {
+ log.info("vendor name exceds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
+ "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateVendorName(vendorName)) {
+ log.info("vendor name is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+
+ }
+ return Either.left(false);
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
+ if (StringUtils.isEmpty(resourceVendorModelNumber)) {
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
+ log.info("resource vendor model number exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(
+ ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+ // resource vendor model number is currently validated as vendor
+ // name
+ if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
+ log.info("resource vendor model number is not valid.");
+ ResponseFormat errorResponse = componentsUtils
+ .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateCost(User user, Resource resource, AuditingActionEnum actionEnum) {
+ String cost = resource.getCost();
+ if (cost != null) {
+
+ if (!ValidationUtils.validateCost(cost)) {
+ log.debug("resource cost is invalid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateLicenseType(User user, Resource resource,
+ AuditingActionEnum actionEnum) {
+ log.debug("validate licenseType");
+ String licenseType = resource.getLicenseType();
+ if (licenseType != null) {
+ List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getLicenseTypes();
+ if (!licenseTypes.contains(licenseType)) {
+ log.debug("License type {} isn't configured");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ if (actionEnum != null) {
+ // In update case, no audit is required
+ componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+ }
+ return Either.right(responseFormat);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
+ Resource updatedResource, String userId, boolean shouldLock, boolean inTransaction) {
+ Either<Operation, ResponseFormat> deleteArtifactByInterface = null;
+ if (updatedResource.getDerivedFrom() != null) {
+ log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
+ log.debug("1. Removing interface artifacts from graph");
+ // Remove all interface artifacts of resource
+ String resourceId = updatedResource.getUniqueId();
+ Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
+
+ if (interfaces != null) {
+ Collection<InterfaceDefinition> values = interfaces.values();
+ for (InterfaceDefinition interfaceDefinition : values) {
+ String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
+
+ log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
+ Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
+ if (operations != null) {
+ for (Entry<String, Operation> operationEntry : operations.entrySet()) {
+ Operation operation = operationEntry.getValue();
+ ArtifactDefinition implementation = operation.getImplementationArtifact();
+ if (implementation != null) {
+ String uniqueId = implementation.getUniqueId();
+ log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
+ uniqueId, operationEntry.getKey(), interfaceType);
+ // only thing that transacts and locks here
+ deleteArtifactByInterface = artifactsBusinessLogic.deleteArtifactByInterface(resourceId,
+ userId, uniqueId,
+ true);
+ if (deleteArtifactByInterface.isRight()) {
+ log.debug("Couldn't remove artifact definition with id {}", uniqueId);
+ if (!inTransaction) {
+ titanDao.rollback();
+ }
+ return Either.right(deleteArtifactByInterface.right().value());
+ }
+ } else {
+ log.trace("No implementation found for operation {} - nothing to delete",
+ operationEntry.getKey());
+ }
+ }
+ } else {
+ log.trace("No operations found for interface type {}", interfaceType);
+ }
+ }
+ }
+ log.debug("2. Removing properties");
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
+ .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
+
+ if (findPropertiesOfNode.isRight()
+ && !findPropertiesOfNode.right().value().equals(StorageOperationStatus.OK)) {
+ log.debug("Failed to remove all properties of resource");
+ if (!inTransaction)
+ titanDao.rollback();
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
+ }
+
+ } else {
+ log.debug("Derived from wasn't changed during update");
+ }
+
+ if (!inTransaction)
+ titanDao.commit();
+ return Either.left(true);
+
+ }
+
+ /**** Auditing *******************/
+
+ protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+ .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+
+ return webApplicationContext.getBean(class1);
+ }
+
+ public ICapabilityTypeOperation getCapabilityTypeOperation() {
+ return capabilityTypeOperation;
+ }
+
+ public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
+ this.capabilityTypeOperation = capabilityTypeOperation;
+ }
+
+ public Either<Boolean, ResponseFormat> validatePropertiesDefaultValues(Resource resource) {
+ log.debug("validate resource properties default values");
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ List<PropertyDefinition> properties = resource.getProperties();
+ String type = null;
+ String innerType = null;
+ if (properties != null) {
+ for (PropertyDefinition property : properties) {
+ if (!propertyOperation.isPropertyTypeValid(property)) {
+ log.info("Invalid type for property");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+ eitherResult = Either.right(responseFormat);
+ break;
+ }
+
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(
+ applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
+
+ type = property.getType();
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
+ .isPropertyInnerTypeValid(property, allDataTypes.left().value());
+ innerType = propertyInnerTypeValid.getLeft();
+ if (!propertyInnerTypeValid.getRight().booleanValue()) {
+ log.info("Invalid inner type for property");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(
+ ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+ eitherResult = Either.right(responseFormat);
+ break;
+ }
+ }
+
+ if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
+ log.info("Invalid default value for property");
+ ResponseFormat responseFormat;
+ if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
+ property.getName(), type, innerType, property.getDefaultValue());
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
+ property.getName(), type, property.getDefaultValue());
+ }
+ eitherResult = Either.right(responseFormat);
+ break;
+
+ }
+ }
+ }
+ return eitherResult;
+ }
+
+ @Override
+ public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
+ return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
+ }
+
+ @Override
+ public ComponentInstanceBusinessLogic getComponentInstanceBL() {
+ return componentInstanceBusinessLogic;
+ }
+
+ private String getComponentTypeForResponse(Component component) {
+ String componentTypeForResponse = "SERVICE";
+ if (component instanceof Resource) {
+ componentTypeForResponse = ((Resource) component).getResourceType().name();
+ }
+ return componentTypeForResponse;
+ }
+
+ private Either<Map<String, GroupDefinition>, ResponseFormat> createGroupsFromYaml(String yamlFileName,
+ Map<String, Object> toscaJson, Resource resource) {
+
+ Map<String, GroupDefinition> groups = new HashMap<String, GroupDefinition>();
+ Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(groups);
+
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils
+ .findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.GROUPS);
+ if (eitherNodesTemlates.isLeft()) {
+ Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
+
+ if (jsonNodeTemplates != null && false == jsonNodeTemplates.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
+ while (nodesNameValue.hasNext()) {
+ Entry<String, Object> groupNameValue = nodesNameValue.next();
+
+ String groupName = groupNameValue.getKey();
+ Either<GroupDefinition, ResponseFormat> eitherNode = createGroupInfo(groupName,
+ groupNameValue.getValue());
+ if (eitherNode.isRight()) {
+ String message = "Failed when creating group: " + groupNameValue.getKey() + " for resource:"
+ + resource.getName();
+ BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message,
+ ErrorSeverity.INFO);
+ return Either.right(eitherNode.right().value());
+ } else {
+ GroupDefinition groupDefinition = eitherNode.left().value();
+ groups.put(groupName, groupDefinition);
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ private Either<Map<String, InputDefinition>, ResponseFormat> createInputsFromYaml(String yamlFileName,
+ Map<String, Object> toscaJson, Resource resource) {
+
+ Either<Map<String, InputDefinition>, ResultStatusEnum> inputs = ImportUtils.getInputs(toscaJson);
+ if (inputs.isRight()) {
+ String message = "Failed when creating inputs: for resource:" + resource.getName();
+ BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
+ Map<String, InputDefinition> resultMap = new HashMap<>();
+ return Either.left(resultMap);
+
+ }
+
+ Either<Map<String, InputDefinition>, ResponseFormat> result = Either.left(inputs.left().value());
+
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<GroupDefinition, ResponseFormat> createGroupInfo(String groupName, Object groupTemplateJson) {
+
+ GroupDefinition groupInfo = new GroupDefinition();
+ groupInfo.setName(groupName);
+ Either<GroupDefinition, ResponseFormat> result = Either.left(groupInfo);
+
+ try {
+ if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
+ Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
+ String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (!StringUtils.isEmpty(groupType)) {
+ groupInfo.setType(groupType);
+ } else {
+ log.debug("The 'type' member is not found under group {}", groupName);
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
+ }
+
+ if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
+ groupInfo.setDescription(
+ (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+ }
+
+ if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.MEMBERS.getElementName())) {
+ Object members = groupTemplateJsonMap.get(ToscaTagNamesEnum.MEMBERS.getElementName());
+ if (members != null) {
+ if (members instanceof List) {
+ Map<String, String> membersLoaded = new HashMap<>();
+ List<?> membersAsList = (List<?>) members;
+ for (Object member : membersAsList) {
+ membersLoaded.put(member.toString(), "");
+ }
+ groupInfo.setMembers(membersLoaded);
+ } else {
+ log.debug("The 'members' member is not of type list under group {}", groupName);
+ return Either
+ .right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+ }
+ }
+ }
+
+ if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+ Object properties = groupTemplateJsonMap.get(ToscaTagNamesEnum.PROPERTIES.getElementName());
+
+ Either<List<GroupProperty>, ResponseFormat> regResponse = createPropertiesValueModuleFromYaml(
+ properties, groupName, groupType);
+ if (regResponse.isRight())
+ return Either.right(regResponse.right().value());
+ if (regResponse.left().value().size() > 0) {
+ groupInfo.convertFromGroupProperties(regResponse.left().value());
+ }
+ }
+
+ } else {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create group");
+ log.debug("error when creating group, message:{}", e.getMessage(), e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
+ }
+
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Either<List<GroupProperty>, ResponseFormat> createPropertiesValueModuleFromYaml(Object properties,
+ String groupName, String groupType) {
+
+ List<GroupProperty> result = new ArrayList<>();
+
+ if (properties == null) {
+ return Either.left(result);
+ }
+
+ Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation
+ .getLatestGroupTypeByType(groupType, true);
+
+ if (groupTypeRes.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
+ }
+
+ Map<String, PropertyDefinition> gtProperties = new HashMap<>();
+ GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
+
+ List<PropertyDefinition> propertiesDef = groupTypeDefinition.getProperties();
+
+ if (propertiesDef != null) {
+ gtProperties = propertiesDef.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
+ }
+
+ if (properties != null) {
+
+ if (properties instanceof Map) {
+
+ Map<String, Object> props = (Map<String, Object>) properties;
+ for (Entry<String, Object> entry : props.entrySet()) {
+
+ String propName = entry.getKey();
+ Object value = entry.getValue();
+
+ PropertyDefinition gtDefinition = gtProperties.get(propName);
+ if (gtDefinition == null) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_PROPERTY_NOT_FOUND,
+ propName, groupName, groupType));
+ }
+
+ ToscaPropertyType type = ToscaPropertyType.isValidType(gtDefinition.getType());
+
+ String convertedValue = null;
+ if (value != null) {
+ if (type == null || value instanceof Map || value instanceof List) {
+ convertedValue = gson.toJson(value);
+ } else {
+ convertedValue = value.toString();
+ }
+ }
+
+ GroupProperty groupProperty = new GroupProperty();
+ groupProperty.setValue(convertedValue);
+ groupProperty.setName(propName);
+
+ log.trace("After building group property {}", groupProperty);
+
+ result.add(groupProperty);
+ }
+
+ }
+
+ }
+
+ return Either.left(result);
+ }
+
+ public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
+
+ // validate user
+ if (user != null) {
+ Either<User, ResponseFormat> userValidation = validateUserExists(user, "Get resource from csar UUID",
+ false);
+ if (userValidation.isRight()) {
+ return Either.right(userValidation.right().value());
+ }
+ }
+
+ // get resource from csar uuid
+ Either<Resource, StorageOperationStatus> either = toscaOperationFacade
+ .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
+ if (either.isRight()) {
+ ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
+ csarUuid);
+ return Either.right(resp);
+ }
+
+ return Either.left(either.left().value());
+ }
+
+ @Override
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
+ String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+ return null;
+ }
+
+ private Either<Map<String, List<CapabilityDefinition>>, ResponseFormat> getValidComponentInstanceCapabilities(
+ String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
+ Map<String, List<UploadCapInfo>> uploadedCapabilities) {
+ ResponseFormat responseFormat;
+ Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
+
+ for (Entry<String, List<UploadCapInfo>> uploadedCapabilitiesEntry : uploadedCapabilities.entrySet()) {
+ String capabilityType = uploadedCapabilitiesEntry.getValue().get(0).getType();
+ if (!defaultCapabilities.containsKey(capabilityType)) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
+ capabilityType);
+ return Either.right(responseFormat);
+ } else {
+ CapabilityDefinition defaultCapability;
+ if (CollectionUtils.isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
+ defaultCapability = defaultCapabilities.get(capabilityType).get(0);
+ } else {
+ Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
+ .getToscaFullElement(resourceId);
+ if (getFullComponentRes.isRight()) {
+ log.debug("Failed to get full component {}. Status is {}. ", resourceId,
+ getFullComponentRes.right().value());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
+ resourceId);
+ return Either.right(responseFormat);
+ }
+ defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
+ }
+ if (CollectionUtils.isEmpty(defaultCapability.getProperties())
+ && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) {
+ log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
+ defaultCapability.getName(), resourceId);
+ log.debug(
+ "Failed to update capability property values. Property list of fetched capability {} is empty. ",
+ defaultCapability.getName());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
+ return Either.right(responseFormat);
+ }
+ if (CollectionUtils.isNotEmpty(defaultCapability.getProperties())
+ && CollectionUtils.isNotEmpty(uploadedCapabilitiesEntry.getValue().get(0).getProperties())) {
+ Either<Boolean, String> validationRes = validateUniquenessUpdateUploadedComponentInstanceCapability(
+ defaultCapability, uploadedCapabilitiesEntry.getValue().get(0));
+ if (validationRes.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
+ validationRes.right().value());
+ return Either.right(responseFormat);
+ }
+ }
+ List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
+ validCapabilityList.add(defaultCapability);
+ validCapabilitiesMap.put(uploadedCapabilitiesEntry.getKey(), validCapabilityList);
+ }
+ }
+ return Either.left(validCapabilitiesMap);
+ }
+
+ private Either<Boolean, String> validateUniquenessUpdateUploadedComponentInstanceCapability(
+ CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
+ List<ComponentInstanceProperty> validProperties = new ArrayList<>();
+ Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
+ .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
+ List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
+ for (UploadPropInfo property : uploadedProperties) {
+ String propertyName = property.getName().toLowerCase();
+ String propertyType = property.getType();
+ ComponentInstanceProperty validProperty;
+ if (defaultProperties.containsKey(propertyName)) {
+ if (propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType)) {
+ return Either.right(propertyName);
+ }
+ }
+ validProperty = new ComponentInstanceProperty();
+ validProperty.setName(propertyName);
+ if (property.getValue() != null)
+ validProperty.setValue(property.getValue().toString());
+ validProperty.setDescription(property.getDescription());
+ validProperty.setPassword(property.isPassword());
+ validProperties.add(validProperty);
+ }
+ defaultCapability.setProperties(validProperties);
+ return Either.left(true);
+ }
+
+ private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
+ List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
+ Resource resource, User user) {
+
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
+ ArtifactOperationEnum.class);
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
+ .left(nodeTypeArtifactsToHandle);
+ ;
+ try {
+ // add all found Csar artifacts to list to upload
+ List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
+ List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
+ List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
+ for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
+ ArtifactDefinition foundArtifact;
+
+ if (!existingArtifactsToHandle.isEmpty()) {
+ foundArtifact = existingArtifactsToHandle.stream()
+ .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
+ .orElse(null);
+ if (foundArtifact != null) {
+ if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()) == currNewArtifact
+ .getArtifactType()) {
+ if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+ currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
+ // if current artifact already exists, but has
+ // different content, add him to the list to
+ // update
+ artifactsToUpdate.add(currNewArtifact);
+ }
+ // remove found artifact from the list of existing
+ // artifacts to handle, because it was already
+ // handled
+ existingArtifactsToHandle.remove(foundArtifact);
+ // and remove found artifact from the list to
+ // upload, because it should either be updated or be
+ // ignored
+ artifactsToUpload.remove(currNewArtifact);
+ } else {
+ log.debug("Can't upload two artifact with the same name {}.",
+ currNewArtifact.getArtifactName());
+ ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
+ ActionStatus.ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
+ currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType().name(),
+ foundArtifact.getArtifactType());
+ AuditingActionEnum auditingAction = artifactsBusinessLogic
+ .detectAuditingType(artifactsBusinessLogic.new ArtifactOperationInfo(false, false,
+ ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
+ artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
+ user, null, null, foundArtifact.getUniqueId(), responseFormat,
+ resource.getComponentType(), null);
+ responseWrapper.setInnerElement(responseFormat);
+ break;
+ }
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
+ if (currArtifact.getIsFromCsar()) {
+ artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+ } else {
+ artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+
+ }
+ }
+ }
+ if (responseWrapper.isEmpty()) {
+ if (!artifactsToUpload.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
+ if (!artifactsToUpdate.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
+ if (!artifactsToDelete.isEmpty())
+ nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+ }
+ if (!responseWrapper.isEmpty()) {
+ nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+ }
+ } catch (Exception e) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+ }
+ return nodeTypeArtifactsToHandleRes;
+ }
+
+ private ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
+ String nodeTypeFullName) {
+ String actualType;
+ String actualVfName;
+ if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
+ actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
+ actualType = ResourceTypeEnum.VFC.name();
+ } else {
+ actualVfName = vfResourceName;
+ actualType = nodeResourceType;
+ }
+
+ StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+ String nameWithouNamespacePrefix = nodeTypeFullName
+ .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
+
+ if (actualName.startsWith(Constants.ABSTRACT)) {
+ toscaResourceName.append(resourceType.toLowerCase()).append('.')
+ .append(ValidationUtils.convertToSystemName(actualVfName));
+ } else {
+ toscaResourceName.append(actualType.toLowerCase()).append('.')
+ .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
+ }
+ StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
+ return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
+ previousToscaResourceName
+ .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
+ .toString());
+ }
+
+ public ICacheMangerOperation getCacheManagerOperation() {
+ return cacheManagerOperation;
+ }
+
+ public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
+ this.cacheManagerOperation = cacheManagerOperation;
+ }
+
+ ///////////////////////////////////////// DataModel
+ ///////////////////////////////////////// refactoring/////////////////////////////////////////////
+ @Override
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
+ List<String> dataParamsToReturn) {
+
+ ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
+ Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId,
+ paramsToRetuen);
+
+ if (resourceResultEither.isRight()) {
+ if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ 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);
+ return Either.right(componentsUtils.getResponseFormatByResource(
+ componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
+ }
+
+ Resource resource = resourceResultEither.left().value();
+ UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
+ dataParamsToReturn);
+ return Either.left(dataTransfer);
+ }
+
+ @Override
+ public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
+ Resource resource = (Resource) clonedComponent;
+ if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
+ Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
+ .shouldUpgradeToLatestDerived(resource);
+ if (shouldUpgradeToLatestDerived.isRight()) {
+ return Either.right(
+ componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
+ }
+ return Either.left(shouldUpgradeToLatestDerived.left().value());
+ } else {
+ return super.shouldUpgradeToLatestDerived(clonedComponent);
+ }
+ }
+
+
+} \ No newline at end of file
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 7ed90ce3b6..97dcf35c96 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
@@ -20,25 +20,12 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.auditing.impl.resourceadmin.AuditImportResourceAdminEventFactory;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
@@ -71,8 +58,9 @@ import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.common.config.EcompErrorName;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
@@ -82,882 +70,919 @@ import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
@Component("resourceImportManager")
public class ResourceImportManager {
- private ServletContext servletContext;
-
- @Autowired
- private IAuditingManager auditingManager;
-
- @Autowired
- private ResourceBusinessLogic resourceBusinessLogic;
-
- @Autowired
- private IGraphLockOperation graphLockOperation;
-
- @Autowired
- protected ComponentsUtils componentsUtils;
-
- public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern
- .compile("[\\w\\-\\_\\d\\:]+");
- @Autowired
- protected CapabilityTypeOperation capabilityTypeOperation;
- @Autowired
- protected ToscaOperationFacade toscaOperationFacade;
-
- private ResponseFormatManager responseFormatManager;
-
- private static Logger log = LoggerFactory.getLogger(ResourceImportManager.class.getName());
-
- public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
- this.toscaOperationFacade = toscaOperationFacade;
- }
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
-
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
- lifecycleChangeInfo.setUserRemarks("certification on import");
- Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
-
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false);
- }
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
-
- LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
- lifecycleChangeInfo.setUserRemarks("certification on import");
- Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
-
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false);
- }
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) {
- Resource resource = new Resource();
- ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
-
- String latestCertifiedResourceId = null;
- try {
- boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
- setConstantMetaData(resource, shouldBeCertified);
- setMetaDataFromJson(resourceMetaData, resource);
-
- Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction);
- if (validateResourceFromYaml.isRight()) {
- ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value();
- auditErrorImport(resourceMetaData, creator, validationErrorResponse, true);
- return Either.right(validationErrorResponse);
-
- }
-
- Either<Boolean, ResponseFormat> isValidResource = validationFunction.apply(resource);
- if (isValidResource.isLeft()) {
- // The flag createNewVersion if false doesn't create new version
- if (!createNewVersion) {
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
- if (latestByName.isLeft()) {
- return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource));
- }
- }
-
- response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested);
- Either<Resource, ResponseFormat> changeStateResponse;
- if (response.isLeft()) {
- resource = response.left().value().left;
-
- if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){
- Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
- resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
- if(handleNodeTypeArtifactsRes.isRight()){
- return Either.right(handleNodeTypeArtifactsRes.right().value());
- }
- }
- latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
- changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
- if (changeStateResponse.isRight()) {
- response = Either.right(changeStateResponse.right().value());
- } else {
- responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right);
- response = Either.left(responsePair);
- }
- }
- } else {
- ResponseFormat validationErrorResponse = isValidResource.right().value();
- auditErrorImport(resourceMetaData, creator, validationErrorResponse, true);
- response = Either.right(validationErrorResponse);
- }
-
- } catch (RuntimeException e) {
- ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e);
- response = Either.right(exceptionResponse);
- } finally {
- if (latestCertifiedResourceId != null && needLock) {
- log.debug("unlock resource {}", latestCertifiedResourceId);
- graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
- }
- }
-
- return response;
- }
-
- private String getLatestCertifiedResourceId(Resource resource) {
- Map<String, String> allVersions = resource.getAllVersions();
- Double latestCertifiedVersion = 0.0;
- if (allVersions != null) {
- for (String version : allVersions.keySet()) {
- Double dVersion = Double.valueOf(version);
- if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) {
- latestCertifiedVersion = dVersion;
- }
- }
- return allVersions.get(String.valueOf(latestCertifiedVersion));
- } else {
- return null;
- }
- }
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isReusable, boolean isInTransaction) {
-
- Resource resource = new Resource();
- ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED);
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
-
- try {
- setMetaDataFromJson(resourceMetaData, resource);
-
- Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource, isInTransaction);
- if (validateResourceFromYaml.isRight()) {
- ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value();
- auditErrorImport(resourceMetaData, creator, validationErrorResponse, false);
- return Either.right(validationErrorResponse);
-
- }
-
- // currently import VF isn't supported. In future will be supported
- // import VF only with CSER file!!
- if (ResourceTypeEnum.VF.equals(resource.getResourceType())) {
- log.debug("Now import VF isn't supported. It will be supported in future with CSER file only");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
- if (validateDerivedFromNotEmpty.isRight()) {
- return Either.right(validateDerivedFromNotEmpty.right().value());
- }
-
- Either<Boolean, ResponseFormat> validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
-
- if (validatePropertiesTypes.isLeft()) {
- response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
- } else {
- ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value();
- auditErrorImport(resourceMetaData, creator, validationErrorResponse, false);
- response = Either.right(validationErrorResponse);
- }
-
- } catch (RuntimeException e) {
- ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e);
- response = Either.right(exceptionResponse);
- }
-
- return response;
-
- }
-
- Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) {
- @SuppressWarnings("unchecked")
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml);
- Map<String, Object> toscaJson = toscaJsonAll;
-
- // Checks if exist and builds the node_types map
- if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) {
- toscaJson = new HashMap<String, Object>();
- toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
- }
- // Derived From
- Either<Resource, ResponseFormat> setDerivedFrom = setDerivedFrom(toscaJson, resource, inTransaction);
- if (setDerivedFrom.isRight()) {
- return Either.right(setDerivedFrom.right().value());
- }
- Resource parentResource = setDerivedFrom.left().value();
- if(StringUtils.isEmpty(resource.getToscaResourceName()))
- setToscaResourceName(toscaJson, resource);
- setAttributes(toscaJson, resource);
- eitherResult = setCapabilities(toscaJson, resource, parentResource);
- if (eitherResult.isRight())
- return eitherResult;
- eitherResult = setProperties(toscaJson, resource);
- if (eitherResult.isRight())
- return eitherResult;
- eitherResult = setRequirements(toscaJson, resource, parentResource);
- if (eitherResult.isRight())
- return eitherResult;
- setInterfaceLifecycle(toscaJson, resource);
-
- return eitherResult;
- }
-
- private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
- Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES);
- if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) {
- String toscaResourceName = toscaElement.left().value().keySet().iterator().next();
- resource.setToscaResourceName(toscaResourceName);
- }
- }
-
- private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource) {
- Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES);
- if (toscaInterfaces.isLeft()) {
- Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
- Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<String, InterfaceDefinition>();
- Iterator<Entry<String, Object>> interfacesNameValue = jsonInterfaces.entrySet().iterator();
- while (interfacesNameValue.hasNext()) {
- Entry<String, Object> interfaceNameValue = interfacesNameValue.next();
- Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue());
- if (eitherInterface.isRight()) {
- log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
- } else {
- moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value());
- }
-
- }
- if (moduleInterfaces.size() > 0) {
- resource.setInterfaces(moduleInterfaces);
- }
- }
- }
-
- private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(Object interfaceJson) {
- InterfaceDefinition interf = new InterfaceDefinition();
- Either<InterfaceDefinition, ResultStatusEnum> result = Either.left(interf);
-
- try {
- if (interfaceJson instanceof String) {
- String requirementJsonString = (String) interfaceJson;
- interf.setType(requirementJsonString);
- } else if (interfaceJson instanceof Map) {
- Map<String, Object> requirementJsonMap = (Map<String, Object>) interfaceJson;
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
- interf.setType(type);
- interf.setUniqueId(type.toLowerCase());
- }
- } else {
- result = Either.right(ResultStatusEnum.GENERAL_ERROR);
- }
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource- create interface");
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
- log.debug("error when creating interface, message:{}", e.getMessage(), e);
- result = Either.right(ResultStatusEnum.GENERAL_ERROR);
- }
-
- return result;
- }
-
- private Either<Boolean, ResponseFormat> setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS);
- if (toscaRequirements.isLeft()) {
- List<Object> jsonRequirements = toscaRequirements.left().value();
- Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<String, List<RequirementDefinition>>();
- // Checking for name duplication
- Set<String> reqNames = new HashSet<>();
- // Getting flattened list of capabilities of parent node - cap name
- // to cap type
- Either<Map<String, String>, ResponseFormat> reqName2Type = getReqName2Type(parentResource);
- if (reqName2Type.isRight()) {
- ResponseFormat responseFormat = reqName2Type.right().value();
- log.debug("Error during setting requirements of imported resource: {}", responseFormat);
- return Either.right(responseFormat);
- }
- Map<String, String> reqName2TypeMap = reqName2Type.left().value();
- for (Object jsonRequirementObj : jsonRequirements) {
- // Requirement
- Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
- String requirementName = requirementJsonWrapper.keySet().iterator().next();
- String reqNameLowerCase = requirementName.toLowerCase();
- if (reqNames.contains(reqNameLowerCase)) {
- log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase));
- }
- reqNames.add(reqNameLowerCase);
- Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
- if (eitherRequirement.isRight()) {
- log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName());
- return Either.right(eitherRequirement.right().value());
- }
- RequirementDefinition requirementDef = eitherRequirement.left().value();
- requirementDef.setName(requirementName);
- if (moduleRequirements.containsKey(requirementDef.getCapability())) {
- moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
- } else {
- List<RequirementDefinition> list = new ArrayList<RequirementDefinition>();
- list.add(requirementDef);
- moduleRequirements.put(requirementDef.getCapability(), list);
- }
-
- // Validating against req/cap of "derived from" node
- Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
- if (validateVsParentCap.isRight()) {
- return Either.right(validateVsParentCap.right().value());
- }
- if (!validateVsParentCap.left().value()) {
- log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName());
- return Either.right(responseFormat);
- }
- }
- if (moduleRequirements.size() > 0) {
- resource.setRequirements(moduleRequirements);
- }
-
- }
- return eitherResult;
-
- }
-
- private Either<RequirementDefinition, ResponseFormat> createRequirementFromImportFile(Object requirementJson) {
- RequirementDefinition requirement = new RequirementDefinition();
- Either<RequirementDefinition, ResponseFormat> result = Either.left(requirement);
-
- try {
- if (requirementJson instanceof String) {
- String requirementJsonString = (String) requirementJson;
- requirement.setCapability(requirementJsonString);
- } else if (requirementJson instanceof Map) {
- Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
- requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
- }
-
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
- requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
- }
-
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
- requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
- }
- if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
- List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
- Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList);
- if (validateAndSetOccurrencesStatus.isRight()) {
- result = Either.right(validateAndSetOccurrencesStatus.right().value());
- return result;
- }
- if (validateAndSetOccurrencesStatus.left().value() == true) {
- requirement.setMinOccurrences(occurrencesList.get(0).toString());
- requirement.setMaxOccurrences(occurrencesList.get(1).toString());
- }
-
- }
- } else {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create Requirement");
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement");
- log.debug("error when creating requirement, message:{}", e.getMessage(), e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- return result;
- }
-
- private Either<Boolean, ResponseFormat> setProperties(Map<String, Object> toscaJson, Resource resource) {
- Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
- ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
- Either<Boolean, ResponseFormat> result = Either.left(true);
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
- if (properties.isLeft()) {
- List<PropertyDefinition> propertiesList = new ArrayList<>();
- Map<String, PropertyDefinition> value = properties.left().value();
- if (value != null) {
- for (Entry<String, PropertyDefinition> 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 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<String, Object> toscaJson, Resource resource) {
- ResultStatusEnum result = ResultStatusEnum.OK;
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson);
- if (attributes.isLeft()) {
- List<PropertyDefinition> attributeList = new ArrayList<>();
- Map<String, PropertyDefinition> value = attributes.left().value();
- if (value != null) {
- for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
- String name = entry.getKey();
- PropertyDefinition attributeDef = entry.getValue();
- attributeDef.setName(name);
- attributeList.add(attributeDef);
- }
- }
- resource.setAttributes(attributeList);
- } else {
- result = attributes.right().value();
- }
- return result;
- }
-
- private Either<Resource, ResponseFormat> setDerivedFrom(Map<String, Object> toscaJson, Resource resource, boolean inTransaction) {
- Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM);
- Resource derivedFromResource = null;
- if (toscaDerivedFromElement.isLeft()) {
- String derivedFrom = toscaDerivedFromElement.left().value();
- log.debug("Derived from TOSCA name is {}", derivedFrom);
- resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom }));
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
-
- if (latestByToscaResourceName.isRight()) {
- StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
- if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) {
- operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
- }
- log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
- ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
- return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom));
- }
- derivedFromResource = latestByToscaResourceName.left().value();
- }
- return Either.left(derivedFromResource);
- }
-
- private Either<Boolean, ResponseFormat> setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
- Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES);
- if (toscaCapabilities.isLeft()) {
- Map<String, Object> jsonCapabilities = toscaCapabilities.left().value();
- Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<String, List<CapabilityDefinition>>();
- Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
- Set<String> capNames = new HashSet<>();
- // Getting flattened list of capabilities of parent node - cap name
- // to cap type
- Either<Map<String, String>, ResponseFormat> capName2Type = getCapName2Type(parentResource);
- if (capName2Type.isRight()) {
- ResponseFormat responseFormat = capName2Type.right().value();
- log.debug("Error during setting capabilities of imported resource: {}", responseFormat);
- return Either.right(responseFormat);
- }
- Map<String, String> capName2TypeMap = capName2Type.left().value();
- while (capabilitiesNameValue.hasNext()) {
- Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
-
- // Validating that no req/cap duplicates exist in imported YAML
- String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
- if (capNames.contains(capNameLowerCase)) {
- log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase));
- }
- capNames.add(capNameLowerCase);
-
- Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue());
- if (eitherCapability.isRight()) {
- log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName());
- return Either.right(eitherCapability.right().value());
- }
-
- CapabilityDefinition capabilityDef = eitherCapability.left().value();
- capabilityDef.setName(capabilityNameValue.getKey());
- if (moduleCapabilities.containsKey(capabilityDef.getType())) {
- moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
- } else {
- List<CapabilityDefinition> list = new ArrayList<CapabilityDefinition>();
- list.add(capabilityDef);
- moduleCapabilities.put(capabilityDef.getType(), list);
- }
-
- // Validating against req/cap of "derived from" node
- Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
- if (validateVsParentCap.isRight()) {
- return Either.right(validateVsParentCap.right().value());
- }
- if (!validateVsParentCap.left().value()) {
- // Here parentResource is for sure not null, so it's
- // null-safe
- log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName());
- return Either.right(responseFormat);
- }
- }
- if (moduleCapabilities.size() > 0) {
- resource.setCapabilities(moduleCapabilities);
- }
- }
-
- return eitherResult;
-
- }
-
- private Either<Map<String, String>, ResponseFormat> getCapName2Type(Resource parentResource) {
- Map<String, String> capName2type = new HashMap<>();
- if (parentResource != null) {
- Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities();
- if (capabilities != null) {
- for (List<CapabilityDefinition> capDefinitions : capabilities.values()) {
- for (CapabilityDefinition capDefinition : capDefinitions) {
- String nameLowerCase = capDefinition.getName().toLowerCase();
- if (capName2type.get(nameLowerCase) != null) {
- String parentResourceName = parentResource.getName();
- log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase);
- BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- capName2type.put(nameLowerCase, capDefinition.getType());
- }
- }
- }
- }
- return Either.left(capName2type);
- }
-
- private Either<Map<String, String>, ResponseFormat> getReqName2Type(Resource parentResource) {
- Map<String, String> reqName2type = new HashMap<>();
- if (parentResource != null) {
- Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements();
- if (requirements != null) {
- for (List<RequirementDefinition> reqDefinitions : requirements.values()) {
- for (RequirementDefinition reqDefinition : reqDefinitions) {
- String nameLowerCase = reqDefinition.getName().toLowerCase();
- if (reqName2type.get(nameLowerCase) != null) {
- String parentResourceName = parentResource.getName();
- log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase);
- BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- reqName2type.put(nameLowerCase, reqDefinition.getCapability());
- }
- }
- }
- }
- return Either.left(reqName2type);
- }
-
- private Either<Boolean, ResponseFormat> validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
- String capNameLowerCase = reqCapName.toLowerCase();
- log.trace("Validating capability {} vs parent resource", capNameLowerCase);
- String parentCapType = parentCapName2Type.get(capNameLowerCase);
- if (parentCapType != null) {
- if (childCapabilityType.equals(parentCapType)) {
- log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType);
- return Either.left(true);
- }
- Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
- if (capabilityTypeDerivedFrom.isRight()) {
- log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
- return Either.right(responseFormat);
- }
- return Either.left(capabilityTypeDerivedFrom.left().value());
- }
- return Either.left(true);
- }
-
- private Either<CapabilityDefinition, ResponseFormat> createCapabilityFromImportFile(Object capabilityJson) {
-
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- Either<CapabilityDefinition, ResponseFormat> result = Either.left(capabilityDefinition);
-
- try {
- if (capabilityJson instanceof String) {
- String capabilityJsonString = (String) capabilityJson;
- capabilityDefinition.setType(capabilityJsonString);
- } else if (capabilityJson instanceof Map) {
- Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
- // Type
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
- }
- // ValidSourceTypes
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
- capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
- }
- // ValidSourceTypes
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
- }
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
- List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
- Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList);
- if (validateAndSetOccurrencesStatus.isRight()) {
- result = Either.right(validateAndSetOccurrencesStatus.right().value());
- return result;
- }
- if (validateAndSetOccurrencesStatus.left().value() == true) {
- capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
- capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
- }
- }
- if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
-
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
- if (propertiesRes.isRight()) {
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
- return result;
- } else {
- propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
- List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
- capabilityDefinition.setProperties(capabilityProperties);
- }
- }
- } else if (!(capabilityJson instanceof List)) {
-
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
-
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability");
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
- log.debug("error when creating capability, message:{}", e.getMessage(), e);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
- }
-
- return result;
- }
-
- private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
- String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : "";
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource " + payloadName);
- BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName);
-
- log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e);
- ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
- auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative);
- return errorResponseWrapper;
- }
-
- private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus());
- String message = "";
- if (errorResponseWrapper.getMessageId() != null) {
- message = errorResponseWrapper.getMessageId() + ": ";
- }
- message += errorResponseWrapper.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName());
-
- String version, lifeCycleState;
- if (isNormative) {
- version = Constants.FIRST_CERTIFIED_VERSION_VERSION;
- lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
- } else {
- version = "";
- lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
-
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, "");
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- private void setMetaDataFromJson(UploadResourceInfo resourceMetaData, Resource resource) {
- resource.setTags(resourceMetaData.getTags());
- List<CategoryDefinition> categories = resourceMetaData.getCategories();
- resource.setCategories(categories);
- resource.setDescription(resourceMetaData.getDescription());
- resource.setIcon(resourceMetaData.getResourceIconPath());
- resource.setName(resourceMetaData.getName());
- if (categories != null && !categories.isEmpty()) {
- CategoryDefinition categoryDef = categories.get(0);
- resource.setAbstract(false);
- if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
- SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
- if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
- resource.setAbstract(true);
- }
- }
- }
- resource.setContactId(resourceMetaData.getContactId());
- resource.setCreatorUserId(resourceMetaData.getContactId());
-
- if (resourceMetaData.getVendorName() != null) {
- resource.setVendorName(resourceMetaData.getVendorName());
- }
-
- if (resourceMetaData.getVendorRelease() != null) {
- resource.setVendorRelease(resourceMetaData.getVendorRelease());
- }
-
- resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType()));
-
- }
-
- private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
- String version;
- LifecycleStateEnum state;
- if(shouldBeCertified){
- version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION;
- state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
- }else{
- version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
- state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
- }
- resource.setVersion(version);
- resource.setLifecycleState(state);
- resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
- resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
- resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
-
- }
-
- private Either<Boolean, ResponseFormat> validateOccurrences(List<Object> occurrensesList) {
-
- if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
- log.debug("Occurrenses list empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
-
- if (occurrensesList.size() < 2) {
- log.debug("Occurrenses list size not 2");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
- Object minObj = occurrensesList.get(0);
- Object maxObj = occurrensesList.get(1);
- Integer minOccurrences = null;
- Integer maxOccurrences = null;
- if (minObj instanceof Integer)
- minOccurrences = (Integer) minObj;
- else {
- log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
- if (minOccurrences < 0) {
- log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
-
- if (maxObj instanceof String) {
- if (maxObj.equals("UNBOUNDED")) {
- return Either.left(true);
- } else {
- log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
- } else {
- if (maxObj instanceof Integer)
- maxOccurrences = (Integer) maxObj;
- else {
- log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
-
- if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
- log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
- return Either.right(responseFormat);
- }
- }
-
- return Either.left(true);
-
- }
-
- public void init(ServletContext servletContext) {
- if (this.servletContext == null) {
- synchronized (this) {
- if (this.servletContext == null) {
- this.servletContext = servletContext;
- responseFormatManager = ResponseFormatManager.getInstance();
- resourceBusinessLogic = getResourceBL(servletContext);
- }
- }
- }
- }
-
- public boolean isResourceExist(String resourceName) {
- return resourceBusinessLogic.isResourceExist(resourceName);
- }
-
- private ResourceBusinessLogic getResourceBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class);
- return resourceBl;
- }
-
- public ServletContext getServletContext() {
- return servletContext;
- }
-
- public IAuditingManager getAuditingManager() {
- return auditingManager;
- }
-
- public ResponseFormatManager getResponseFormatManager() {
- return responseFormatManager;
- }
-
- public void setResponseFormatManager(ResponseFormatManager responseFormatManager) {
- this.responseFormatManager = responseFormatManager;
- }
-
- public ResourceBusinessLogic getResourceBusinessLogic() {
- return resourceBusinessLogic;
- }
-
- public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) {
- this.resourceBusinessLogic = resourceBusinessLogic;
- }
-
- public Logger getLog() {
- return log;
- }
-
- public static void setLog(Logger log) {
- ResourceImportManager.log = log;
- }
-
- public IGraphLockOperation getGraphLockOperation() {
- return graphLockOperation;
- }
-
- public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
- this.graphLockOperation = graphLockOperation;
- }
-
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
- public void setAuditingManager(IAuditingManager auditingManager) {
- this.auditingManager = auditingManager;
- }
+ private ServletContext servletContext;
+
+ @Autowired
+ private AuditingManager auditingManager;
+
+ @Autowired
+ private ResourceBusinessLogic resourceBusinessLogic;
+
+ @Autowired
+ private IGraphLockOperation graphLockOperation;
+
+ @Autowired
+ protected ComponentsUtils componentsUtils;
+
+ public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern
+ .compile("[\\w\\-\\_\\d\\:]+");
+ @Autowired
+ protected CapabilityTypeOperation capabilityTypeOperation;
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+ private ResponseFormatManager responseFormatManager;
+
+ private static final Logger log = LoggerFactory.getLogger(ResourceImportManager.class);
+
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
+
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
+ lifecycleChangeInfo.setUserRemarks("certification on import");
+ Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false);
+ }
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
+
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
+ lifecycleChangeInfo.setUserRemarks("certification on import");
+ Function<Resource, Either<Boolean, ResponseFormat>> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false);
+ }
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction,
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) {
+ Resource resource = new Resource();
+ ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
+
+ String latestCertifiedResourceId = null;
+ try {
+ boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
+ setConstantMetaData(resource, shouldBeCertified);
+ setMetaDataFromJson(resourceMetaData, resource);
+
+ Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource);
+ if (validateResourceFromYaml.isRight()) {
+ ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value();
+ auditErrorImport(resourceMetaData, creator, validationErrorResponse, true);
+ return Either.right(validationErrorResponse);
+
+ }
+
+ Either<Boolean, ResponseFormat> isValidResource = validationFunction.apply(resource);
+ if (isValidResource.isLeft()) {
+ // The flag createNewVersion if false doesn't create new version
+ if (!createNewVersion) {
+ Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
+ if (latestByName.isLeft()) {
+ return Either.right(componentsUtils.getResponseFormatByResource(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource));
+ }
+ }
+
+ response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested);
+ Either<Resource, ResponseFormat> changeStateResponse;
+ if (response.isLeft()) {
+ resource = response.left().value().left;
+
+ if(nodeTypeArtifactsToHandle !=null && !nodeTypeArtifactsToHandle.isEmpty()){
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
+ resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
+ if(handleNodeTypeArtifactsRes.isRight()){
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
+ latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
+ changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
+ if (changeStateResponse.isRight()) {
+ response = Either.right(changeStateResponse.right().value());
+ } else {
+ responsePair = new ImmutablePair<>(changeStateResponse.left().value(), response.left().value().right);
+ response = Either.left(responsePair);
+ }
+ }
+ } else {
+ ResponseFormat validationErrorResponse = isValidResource.right().value();
+ auditErrorImport(resourceMetaData, creator, validationErrorResponse, true);
+ response = Either.right(validationErrorResponse);
+ }
+
+ } catch (RuntimeException e) {
+ ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, true, e);
+ response = Either.right(exceptionResponse);
+ } finally {
+ if (latestCertifiedResourceId != null && needLock) {
+ log.debug("unlock resource {}", latestCertifiedResourceId);
+ graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
+ }
+ }
+
+ return response;
+ }
+
+ private String getLatestCertifiedResourceId(Resource resource) {
+ Map<String, String> allVersions = resource.getAllVersions();
+ Double latestCertifiedVersion = 0.0;
+ if (allVersions != null) {
+ for (String version : allVersions.keySet()) {
+ Double dVersion = Double.valueOf(version);
+ if ((dVersion > latestCertifiedVersion) && (version.endsWith(".0"))) {
+ latestCertifiedVersion = dVersion;
+ }
+ }
+ return allVersions.get(String.valueOf(latestCertifiedVersion));
+ } else {
+ return null;
+ }
+ }
+
+ public void populateResourceMetadata(UploadResourceInfo resourceMetaData, Resource resource) {
+ if (resource != null && resourceMetaData != null) {
+ resource.setDescription(resourceMetaData.getDescription());
+ resource.setTags(resourceMetaData.getTags());
+ resource.setCategories(resourceMetaData.getCategories());
+ resource.setContactId(resourceMetaData.getContactId());
+ resource.setName(resourceMetaData.getName());
+ resource.setIcon(resourceMetaData.getResourceIconPath());
+ resource.setResourceVendorModelNumber(resourceMetaData.getResourceVendorModelNumber());
+ resource.setResourceType(ResourceTypeEnum.valueOf(resourceMetaData.getResourceType()));
+ if (resourceMetaData.getVendorName() != null) {
+ resource.setVendorName(resourceMetaData.getVendorName());
+ }
+ if (resourceMetaData.getVendorRelease() != null) {
+ resource.setVendorRelease(resourceMetaData.getVendorRelease());
+ }
+ }
+ }
+
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) {
+
+ Resource resource = new Resource();
+ ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<Resource, ActionStatus>(resource, ActionStatus.CREATED);
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
+
+ try {
+ setMetaDataFromJson(resourceMetaData, resource);
+
+ Either<Boolean, ResponseFormat> validateResourceFromYaml = populateResourceFromYaml(resourceYml, resource);
+ if (validateResourceFromYaml.isRight()) {
+ ResponseFormat validationErrorResponse = validateResourceFromYaml.right().value();
+ auditErrorImport(resourceMetaData, creator, validationErrorResponse, false);
+ return Either.right(validationErrorResponse);
+
+ }
+
+ // currently import VF isn't supported. In future will be supported
+ // import VF only with CSER file!!
+ if (ResourceTypeEnum.VF.equals(resource.getResourceType())) {
+ log.debug("Now import VF isn't supported. It will be supported in future with CSER file only");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
+ if (validateDerivedFromNotEmpty.isRight()) {
+ return Either.right(validateDerivedFromNotEmpty.right().value());
+ }
+
+ Either<Boolean, ResponseFormat> validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+
+ if (validatePropertiesTypes.isLeft()) {
+ response = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
+ } else {
+ ResponseFormat validationErrorResponse = validatePropertiesTypes.right().value();
+ auditErrorImport(resourceMetaData, creator, validationErrorResponse, false);
+ response = Either.right(validationErrorResponse);
+ }
+
+ } catch (RuntimeException e) {
+ ResponseFormat exceptionResponse = handleImportResourceExecption(resourceMetaData, creator, false, e);
+ response = Either.right(exceptionResponse);
+ }
+
+ return response;
+
+ }
+
+ Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource) {
+ @SuppressWarnings("unchecked")
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml);
+ Map<String, Object> toscaJson = toscaJsonAll;
+
+ // Checks if exist and builds the node_types map
+ if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) {
+ toscaJson = new HashMap<String, Object>();
+ toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
+ }
+ // Derived From
+ Either<Resource, ResponseFormat> setDerivedFrom = setDerivedFrom(toscaJson, resource);
+ if (setDerivedFrom.isRight()) {
+ return Either.right(setDerivedFrom.right().value());
+ }
+ Resource parentResource = setDerivedFrom.left().value();
+ if(StringUtils.isEmpty(resource.getToscaResourceName())) {
+ setToscaResourceName(toscaJson, resource);
+ }
+ setAttributes(toscaJson, resource);
+ eitherResult = setCapabilities(toscaJson, resource, parentResource);
+ if (eitherResult.isRight()) {
+ return eitherResult;
+ }
+ eitherResult = setProperties(toscaJson, resource);
+ if (eitherResult.isRight()) {
+ return eitherResult;
+ }
+ eitherResult = setRequirements(toscaJson, resource, parentResource);
+ if (eitherResult.isRight()) {
+ return eitherResult;
+ }
+ setInterfaceLifecycle(toscaJson, resource);
+
+ return eitherResult;
+ }
+
+ private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
+ Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TYPES);
+ if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) {
+ String toscaResourceName = toscaElement.left().value().keySet().iterator().next();
+ resource.setToscaResourceName(toscaResourceName);
+ }
+ }
+
+ private void setInterfaceLifecycle(Map<String, Object> toscaJson, Resource resource) {
+ Either<Map<String, Object>, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.INTERFACES);
+ if (toscaInterfaces.isLeft()) {
+ Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
+ Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<String, InterfaceDefinition>();
+ Iterator<Entry<String, Object>> interfacesNameValue = jsonInterfaces.entrySet().iterator();
+ while (interfacesNameValue.hasNext()) {
+ Entry<String, Object> interfaceNameValue = interfacesNameValue.next();
+ Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue());
+ if (eitherInterface.isRight()) {
+ log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
+ } else {
+ moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value());
+ }
+
+ }
+ if (moduleInterfaces.size() > 0) {
+ resource.setInterfaces(moduleInterfaces);
+ }
+ }
+ }
+
+ private Either<InterfaceDefinition, ResultStatusEnum> createModuleInterface(Object interfaceJson) {
+ InterfaceDefinition interf = new InterfaceDefinition();
+ Either<InterfaceDefinition, ResultStatusEnum> result = Either.left(interf);
+
+ try {
+ if (interfaceJson instanceof String) {
+ String requirementJsonString = (String) interfaceJson;
+ interf.setType(requirementJsonString);
+ } else if (interfaceJson instanceof Map) {
+ Map<String, Object> requirementJsonMap = (Map<String, Object>) interfaceJson;
+ if (requirementJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ String type = (String) requirementJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ interf.setType(type);
+ interf.setUniqueId(type.toLowerCase());
+ }
+ } else {
+ result = Either.right(ResultStatusEnum.GENERAL_ERROR);
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
+ log.debug("error when creating interface, message:{}", e.getMessage(), e);
+ result = Either.right(ResultStatusEnum.GENERAL_ERROR);
+ }
+
+ return result;
+ }
+
+ private Either<Boolean, ResponseFormat> setRequirements(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ Either<List<Object>, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, ToscaTagNamesEnum.REQUIREMENTS);
+ if (toscaRequirements.isLeft()) {
+ List<Object> jsonRequirements = toscaRequirements.left().value();
+ Map<String, List<RequirementDefinition>> moduleRequirements = new HashMap<String, List<RequirementDefinition>>();
+ // Checking for name duplication
+ Set<String> reqNames = new HashSet<>();
+ // Getting flattened list of capabilities of parent node - cap name
+ // to cap type
+ Either<Map<String, String>, ResponseFormat> reqName2Type = getReqName2Type(parentResource);
+ if (reqName2Type.isRight()) {
+ ResponseFormat responseFormat = reqName2Type.right().value();
+ log.debug("Error during setting requirements of imported resource: {}", responseFormat);
+ return Either.right(responseFormat);
+ }
+ Map<String, String> reqName2TypeMap = reqName2Type.left().value();
+ for (Object jsonRequirementObj : jsonRequirements) {
+ // Requirement
+ Map<String, Object> requirementJsonWrapper = (Map<String, Object>) jsonRequirementObj;
+ String requirementName = requirementJsonWrapper.keySet().iterator().next();
+ String reqNameLowerCase = requirementName.toLowerCase();
+ if (reqNames.contains(reqNameLowerCase)) {
+ log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase));
+ }
+ reqNames.add(reqNameLowerCase);
+ Either<RequirementDefinition, ResponseFormat> eitherRequirement = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
+ if (eitherRequirement.isRight()) {
+ log.info("error when creating Requirement:{}, for resource:{}", requirementName, resource.getName());
+ return Either.right(eitherRequirement.right().value());
+ }
+ RequirementDefinition requirementDef = eitherRequirement.left().value();
+ requirementDef.setName(requirementName);
+ if (moduleRequirements.containsKey(requirementDef.getCapability())) {
+ moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
+ } else {
+ List<RequirementDefinition> list = new ArrayList<RequirementDefinition>();
+ list.add(requirementDef);
+ moduleRequirements.put(requirementDef.getCapability(), list);
+ }
+
+ // Validating against req/cap of "derived from" node
+ Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
+ if (validateVsParentCap.isRight()) {
+ return Either.right(validateVsParentCap.right().value());
+ }
+ if (!validateVsParentCap.left().value()) {
+ log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResource.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef.getName().toLowerCase(), parentResource.getName());
+ return Either.right(responseFormat);
+ }
+ }
+ if (moduleRequirements.size() > 0) {
+ resource.setRequirements(moduleRequirements);
+ }
+
+ }
+ return eitherResult;
+
+ }
+
+ private Either<RequirementDefinition, ResponseFormat> createRequirementFromImportFile(Object requirementJson) {
+ RequirementDefinition requirement = new RequirementDefinition();
+ Either<RequirementDefinition, ResponseFormat> result = Either.left(requirement);
+
+ try {
+ if (requirementJson instanceof String) {
+ String requirementJsonString = (String) requirementJson;
+ requirement.setCapability(requirementJsonString);
+ } else if (requirementJson instanceof Map) {
+ Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
+ if (requirementJsonMap.containsKey(ToscaTagNamesEnum.CAPABILITY.getElementName())) {
+ requirement.setCapability((String) requirementJsonMap.get(ToscaTagNamesEnum.CAPABILITY.getElementName()));
+ }
+
+ if (requirementJsonMap.containsKey(ToscaTagNamesEnum.NODE.getElementName())) {
+ requirement.setNode((String) requirementJsonMap.get(ToscaTagNamesEnum.NODE.getElementName()));
+ }
+
+ if (requirementJsonMap.containsKey(ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
+ requirement.setRelationship((String) requirementJsonMap.get(ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
+ }
+ if (requirementJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
+ List<Object> occurrencesList = (List) requirementJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
+ Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList);
+ if (validateAndSetOccurrencesStatus.isRight()) {
+ result = Either.right(validateAndSetOccurrencesStatus.right().value());
+ return result;
+ }
+ if (validateAndSetOccurrencesStatus.left().value()) {
+ requirement.setMinOccurrences(occurrencesList.get(0).toString());
+ requirement.setMaxOccurrences(occurrencesList.get(1).toString());
+ }
+
+ }
+ } else {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create Requirement");
+ log.debug("error when creating requirement, message:{}", e.getMessage(), e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
+ }
+
+ return result;
+ }
+
+ private Either<Boolean, ResponseFormat> setProperties(Map<String, Object> toscaJson, Resource resource) {
+ Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
+ ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
+ Either<Boolean, ResponseFormat> result = Either.left(true);
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
+ if (properties.isLeft()) {
+ List<PropertyDefinition> propertiesList = new ArrayList<>();
+ Map<String, PropertyDefinition> value = properties.left().value();
+ if (value != null) {
+ for (Entry<String, PropertyDefinition> 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 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<String, Object> toscaJson, Resource resource) {
+ ResultStatusEnum result = ResultStatusEnum.OK;
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson);
+ if (attributes.isLeft()) {
+ List<PropertyDefinition> attributeList = new ArrayList<>();
+ Map<String, PropertyDefinition> value = attributes.left().value();
+ if (value != null) {
+ for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
+ String name = entry.getKey();
+ PropertyDefinition attributeDef = entry.getValue();
+ attributeDef.setName(name);
+ attributeList.add(attributeDef);
+ }
+ }
+ resource.setAttributes(attributeList);
+ } else {
+ result = attributes.right().value();
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> setDerivedFrom(Map<String, Object> toscaJson, Resource resource) {
+ Either<String, ResultStatusEnum> toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, ToscaTagNamesEnum.DERIVED_FROM);
+ Resource derivedFromResource = null;
+ if (toscaDerivedFromElement.isLeft()) {
+ String derivedFrom = toscaDerivedFromElement.left().value();
+ log.debug("Derived from TOSCA name is {}", derivedFrom);
+ resource.setDerivedFrom(Arrays.asList(new String[] { derivedFrom }));
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
+
+ if (latestByToscaResourceName.isRight()) {
+ StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
+ if (operationStatus.equals(StorageOperationStatus.NOT_FOUND)) {
+ operationStatus = StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
+ }
+ log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
+ ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
+ return Either.right(componentsUtils.getResponseFormat(convertFromStorageResponse, derivedFrom));
+ }
+ derivedFromResource = latestByToscaResourceName.left().value();
+ }
+ return Either.left(derivedFromResource);
+ }
+
+ private Either<Boolean, ResponseFormat> setCapabilities(Map<String, Object> toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+ Either<Map<String, Object>, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.CAPABILITIES);
+ if (toscaCapabilities.isLeft()) {
+ Map<String, Object> jsonCapabilities = toscaCapabilities.left().value();
+ Map<String, List<CapabilityDefinition>> moduleCapabilities = new HashMap<String, List<CapabilityDefinition>>();
+ Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
+ Set<String> capNames = new HashSet<>();
+ // Getting flattened list of capabilities of parent node - cap name
+ // to cap type
+ Either<Map<String, String>, ResponseFormat> capName2Type = getCapName2Type(parentResource);
+ if (capName2Type.isRight()) {
+ ResponseFormat responseFormat = capName2Type.right().value();
+ log.debug("Error during setting capabilities of imported resource: {}", responseFormat);
+ return Either.right(responseFormat);
+ }
+ Map<String, String> capName2TypeMap = capName2Type.left().value();
+ while (capabilitiesNameValue.hasNext()) {
+ Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
+
+ // Validating that no req/cap duplicates exist in imported YAML
+ String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
+ if (capNames.contains(capNameLowerCase)) {
+ log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase));
+ }
+ capNames.add(capNameLowerCase);
+
+ Either<CapabilityDefinition, ResponseFormat> eitherCapability = createCapabilityFromImportFile(capabilityNameValue.getValue());
+ if (eitherCapability.isRight()) {
+ log.debug("error when creating capability:{}, for resource:{}", capabilityNameValue.getKey(), resource.getName());
+ return Either.right(eitherCapability.right().value());
+ }
+
+ CapabilityDefinition capabilityDef = eitherCapability.left().value();
+ capabilityDef.setName(capabilityNameValue.getKey());
+ if (moduleCapabilities.containsKey(capabilityDef.getType())) {
+ moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
+ } else {
+ List<CapabilityDefinition> list = new ArrayList<CapabilityDefinition>();
+ list.add(capabilityDef);
+ moduleCapabilities.put(capabilityDef.getType(), list);
+ }
+
+ // Validating against req/cap of "derived from" node
+ Either<Boolean, ResponseFormat> validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
+ if (validateVsParentCap.isRight()) {
+ return Either.right(validateVsParentCap.right().value());
+ }
+ if (!validateVsParentCap.left().value()) {
+ // Here parentResource is for sure not null, so it's
+ // null-safe
+ log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResource.getName());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef.getName().toLowerCase(), parentResource.getName());
+ return Either.right(responseFormat);
+ }
+ }
+ if (moduleCapabilities.size() > 0) {
+ resource.setCapabilities(moduleCapabilities);
+ }
+ }
+
+ return eitherResult;
+
+ }
+
+ private Either<Map<String, String>, ResponseFormat> getCapName2Type(Resource parentResource) {
+ Map<String, String> capName2type = new HashMap<>();
+ if (parentResource != null) {
+ Map<String, List<CapabilityDefinition>> capabilities = parentResource.getCapabilities();
+ if (capabilities != null) {
+ for (List<CapabilityDefinition> capDefinitions : capabilities.values()) {
+ for (CapabilityDefinition capDefinition : capDefinitions) {
+ String nameLowerCase = capDefinition.getName().toLowerCase();
+ if (capName2type.get(nameLowerCase) != null) {
+ String parentResourceName = parentResource.getName();
+ log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase);
+ BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ capName2type.put(nameLowerCase, capDefinition.getType());
+ }
+ }
+ }
+ }
+ return Either.left(capName2type);
+ }
+
+ private Either<Map<String, String>, ResponseFormat> getReqName2Type(Resource parentResource) {
+ Map<String, String> reqName2type = new HashMap<>();
+ if (parentResource != null) {
+ Map<String, List<RequirementDefinition>> requirements = parentResource.getRequirements();
+ if (requirements != null) {
+ for (List<RequirementDefinition> reqDefinitions : requirements.values()) {
+ for (RequirementDefinition reqDefinition : reqDefinitions) {
+ String nameLowerCase = reqDefinition.getName().toLowerCase();
+ if (reqName2type.get(nameLowerCase) != null) {
+ String parentResourceName = parentResource.getName();
+ log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase);
+ BeEcompErrorManager.getInstance().logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ reqName2type.put(nameLowerCase, reqDefinition.getCapability());
+ }
+ }
+ }
+ }
+ return Either.left(reqName2type);
+ }
+
+ private Either<Boolean, ResponseFormat> validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
+ String capNameLowerCase = reqCapName.toLowerCase();
+ log.trace("Validating capability {} vs parent resource", capNameLowerCase);
+ String parentCapType = parentCapName2Type.get(capNameLowerCase);
+ if (parentCapType != null) {
+ if (childCapabilityType.equals(parentCapType)) {
+ log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType);
+ return Either.left(true);
+ }
+ Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
+ if (capabilityTypeDerivedFrom.isRight()) {
+ log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
+ return Either.right(responseFormat);
+ }
+ return Either.left(capabilityTypeDerivedFrom.left().value());
+ }
+ return Either.left(true);
+ }
+
+ private Either<CapabilityDefinition, ResponseFormat> createCapabilityFromImportFile(Object capabilityJson) {
+
+ CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
+ Either<CapabilityDefinition, ResponseFormat> result = Either.left(capabilityDefinition);
+
+ try {
+ if (capabilityJson instanceof String) {
+ String capabilityJsonString = (String) capabilityJson;
+ capabilityDefinition.setType(capabilityJsonString);
+ } else if (capabilityJson instanceof Map) {
+ Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
+ // Type
+ if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ capabilityDefinition.setType((String) capabilityJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
+ }
+ // ValidSourceTypes
+ if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
+ capabilityDefinition.setValidSourceTypes((List<String>) capabilityJsonMap.get(ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
+ }
+ // ValidSourceTypes
+ if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
+ capabilityDefinition.setDescription((String) capabilityJsonMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+ }
+ if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
+ List<Object> occurrencesList = (List) capabilityJsonMap.get(ToscaTagNamesEnum.OCCURRENCES.getElementName());
+ Either<Boolean, ResponseFormat> validateAndSetOccurrencesStatus = validateOccurrences(occurrencesList);
+ if (validateAndSetOccurrencesStatus.isRight()) {
+ result = Either.right(validateAndSetOccurrencesStatus.right().value());
+ return result;
+ }
+ if (validateAndSetOccurrencesStatus.left().value()) {
+ capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
+ capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
+ }
+ }
+ if (capabilityJsonMap.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
+
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
+ if (propertiesRes.isRight()) {
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
+ return result;
+ } else {
+ propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
+ List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream().map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
+ capabilityDefinition.setProperties(capabilityProperties);
+ }
+ }
+ } else if (!(capabilityJson instanceof List)) {
+
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
+
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
+ log.debug("error when creating capability, message:{}", e.getMessage(), e);
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
+ }
+
+ return result;
+ }
+
+ private ResponseFormat handleImportResourceExecption(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
+ String payloadName = (resourceMetaData != null) ? resourceMetaData.getPayloadName() : "";
+ BeEcompErrorManager.getInstance().logBeSystemError("Import Resource " + payloadName);
+
+ log.debug("Error when importing resource from payload:{} Exception text: {}", payloadName, e.getMessage(), e);
+ ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ auditErrorImport(resourceMetaData, user, errorResponseWrapper, isNormative);
+ return errorResponseWrapper;
+ }
+
+ private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
+// EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.IMPORT_RESOURCE.getName());
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceMetaData.getName());
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue());
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId());
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, errorResponseWrapper.getStatus());
+// String message = "";
+// if (errorResponseWrapper.getMessageId() != null) {
+// message = errorResponseWrapper.getMessageId() + ": ";
+// }
+// message += errorResponseWrapper.getFormattedMessage();
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName());
+
+ String version, lifeCycleState;
+ if (isNormative) {
+ version = Constants.FIRST_CERTIFIED_VERSION_VERSION;
+ lifeCycleState = LifecycleStateEnum.CERTIFIED.name();
+ } else {
+ version = "";
+ lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
+
+ }
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, version);
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, lifeCycleState);
+// auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, "");
+// getAuditingManager().auditEvent(auditingFields);
+
+
+ String message = "";
+ if (errorResponseWrapper.getMessageId() != null) {
+ message = errorResponseWrapper.getMessageId() + ": ";
+ }
+ message += errorResponseWrapper.getFormattedMessage();
+
+
+
+ AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
+ CommonAuditData.newBuilder()
+ .status(errorResponseWrapper.getStatus())
+ .description(message)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ ResourceAuditData.newBuilder()
+ .state(lifeCycleState)
+ .version(version)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .state("")
+ .version("")
+ .build(),
+ ComponentTypeEnum.RESOURCE.getValue(), resourceMetaData.getName(), "", user, "");
+ getAuditingManager().auditEvent(factory);
+
+ }
+
+ private void setMetaDataFromJson(UploadResourceInfo resourceMetaData, Resource resource) {
+ this.populateResourceMetadata(resourceMetaData, resource);
+ resource.setCreatorUserId(resourceMetaData.getContactId());
+ List<CategoryDefinition> categories = resourceMetaData.getCategories();
+ calculateResourceIsAbstract(resource, categories);
+ }
+
+ private void calculateResourceIsAbstract(Resource resource, List<CategoryDefinition> categories) {
+ if (categories != null && !categories.isEmpty()) {
+ CategoryDefinition categoryDef = categories.get(0);
+ resource.setAbstract(false);
+ if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
+ SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
+ if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
+ resource.setAbstract(true);
+ }
+ }
+ }
+ }
+
+ private void setConstantMetaData(Resource resource, boolean shouldBeCertified) {
+ String version;
+ LifecycleStateEnum state;
+ if(shouldBeCertified){
+ version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION;
+ state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
+ }else{
+ version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
+ state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
+ }
+ resource.setVersion(version);
+ resource.setLifecycleState(state);
+ resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+ resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
+ resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateOccurrences(List<Object> occurrensesList) {
+
+ if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
+ log.debug("Occurrenses list empty");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+
+ if (occurrensesList.size() < 2) {
+ log.debug("Occurrenses list size not 2");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+ Object minObj = occurrensesList.get(0);
+ Object maxObj = occurrensesList.get(1);
+ Integer minOccurrences = null;
+ Integer maxOccurrences = null;
+ if (minObj instanceof Integer)
+ minOccurrences = (Integer) minObj;
+ else {
+ log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+ if (minOccurrences < 0) {
+ log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+
+ if (maxObj instanceof String) {
+ if ("UNBOUNDED".equals(maxObj)) {
+ return Either.left(true);
+ } else {
+ log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+ } else {
+ if (maxObj instanceof Integer)
+ maxOccurrences = (Integer) maxObj;
+ else {
+ log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+
+ if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
+ log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_OCCURRENCES);
+ return Either.right(responseFormat);
+ }
+ }
+
+ return Either.left(true);
+
+ }
+
+ public synchronized void init(ServletContext servletContext) {
+ if (this.servletContext == null) {
+ this.servletContext = servletContext;
+ responseFormatManager = ResponseFormatManager.getInstance();
+ resourceBusinessLogic = getResourceBL(servletContext);
+ }
+ }
+
+ public boolean isResourceExist(String resourceName) {
+ return resourceBusinessLogic.isResourceExist(resourceName);
+ }
+
+ private ResourceBusinessLogic getResourceBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ ResourceBusinessLogic resourceBl = webApplicationContext.getBean(ResourceBusinessLogic.class);
+ return resourceBl;
+ }
+
+ public ServletContext getServletContext() {
+ return servletContext;
+ }
+
+ public AuditingManager getAuditingManager() {
+ return auditingManager;
+ }
+
+ public ResponseFormatManager getResponseFormatManager() {
+ return responseFormatManager;
+ }
+
+ public void setResponseFormatManager(ResponseFormatManager responseFormatManager) {
+ this.responseFormatManager = responseFormatManager;
+ }
+
+ public ResourceBusinessLogic getResourceBusinessLogic() {
+ return resourceBusinessLogic;
+ }
+
+ public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) {
+ this.resourceBusinessLogic = resourceBusinessLogic;
+ }
+
+ public Logger getLog() {
+ return log;
+ }
+
+ public IGraphLockOperation getGraphLockOperation() {
+ return graphLockOperation;
+ }
+
+ public void setGraphLockOperation(IGraphLockOperation graphLockOperation) {
+ this.graphLockOperation = graphLockOperation;
+ }
+
+ public void setServletContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
+ public void setAuditingManager(AuditingManager auditingManager) {
+ this.auditingManager = auditingManager;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
index 136121484d..a6344929a5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
@@ -34,44 +34,44 @@ import org.slf4j.LoggerFactory;
public class ResponseFormatManager {
- private volatile static ResponseFormatManager instance;
- private static ConfigurationManager configurationManager;
- private static Logger log = LoggerFactory.getLogger(ResponseFormatManager.class.getName());
+ private volatile static ResponseFormatManager instance;
+ private static ConfigurationManager configurationManager;
+ private static final Logger log = LoggerFactory.getLogger(ResponseFormatManager.class);
- public static ResponseFormatManager getInstance() {
- if (instance == null) {
+ public static ResponseFormatManager getInstance() {
+ if (instance == null) {
- instance = init();
- }
- return instance;
- }
+ instance = init();
+ }
+ return instance;
+ }
- private static synchronized ResponseFormatManager init() {
- if (instance == null) {
- instance = new ResponseFormatManager();
- configurationManager = ConfigurationManager.getConfigurationManager();
- }
- return instance;
- }
+ private static synchronized ResponseFormatManager init() {
+ if (instance == null) {
+ instance = new ResponseFormatManager();
+ configurationManager = ConfigurationManager.getConfigurationManager();
+ }
+ return instance;
+ }
- public ResponseFormat getResponseFormat(ActionStatus responseEnum, String... variables) {
- ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration();
- ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name());
- if (errorInfo == null) {
- log.debug("failed to locate {} in error configuration", responseEnum.name());
- errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name());
- }
- ResponseFormat errorResponseWrapper = new ResponseFormat(errorInfo.getCode());
- String errorMessage = errorInfo.getMessage();
- String errorMessageId = errorInfo.getMessageId();
- ErrorInfoType errorInfoType = errorInfo.getErrorInfoType();
- if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) {
- errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables));
- } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) {
- errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables));
- } else if (errorInfoType.equals(ErrorInfoType.OK)) {
- errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables));
- }
- return errorResponseWrapper;
- }
+ public ResponseFormat getResponseFormat(ActionStatus responseEnum, String... variables) {
+ ErrorConfiguration errorConfiguration = configurationManager.getErrorConfiguration();
+ ErrorInfo errorInfo = errorConfiguration.getErrorInfo(responseEnum.name());
+ if (errorInfo == null) {
+ log.debug("failed to locate {} in error configuration", responseEnum);
+ errorInfo = errorConfiguration.getErrorInfo(ActionStatus.GENERAL_ERROR.name());
+ }
+ ResponseFormat errorResponseWrapper = new ResponseFormat(errorInfo.getCode());
+ String errorMessage = errorInfo.getMessage();
+ String errorMessageId = errorInfo.getMessageId();
+ ErrorInfoType errorInfoType = errorInfo.getErrorInfoType();
+ if (errorInfoType.equals(ErrorInfoType.SERVICE_EXCEPTION)) {
+ errorResponseWrapper.setServiceException(new ServiceException(errorMessageId, errorMessage, variables));
+ } else if (errorInfoType.equals(ErrorInfoType.POLICY_EXCEPTION)) {
+ errorResponseWrapper.setPolicyException(new PolicyException(errorMessageId, errorMessage, variables));
+ } else if (errorInfoType.equals(ErrorInfoType.OK)) {
+ errorResponseWrapper.setOkResponseInfo(new OkResponseInfo(errorMessageId, errorMessage, variables));
+ }
+ return errorResponseWrapper;
+ }
}
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 23852c30a2..14db1408b7 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,39 +20,33 @@
package org.openecomp.sdc.be.components.impl;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
+import com.google.common.base.Strings;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload;
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
+import org.openecomp.sdc.be.components.path.ForwardingPathValidator;
+import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
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.cassandra.AuditCassandraDao;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.datamodel.ServiceRelations;
import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -67,6 +61,8 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -79,12 +75,12 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
import org.openecomp.sdc.common.util.GeneralUtility;
@@ -96,1997 +92,2213 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.function.Function;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("serviceBusinessLogic")
public class ServiceBusinessLogic extends ComponentBusinessLogic {
- private static final String STATUS_SUCCESS_200 = "200";
-
- private static final String STATUS_DEPLOYED = "DEPLOYED";
-
- @Autowired
- private IElementOperation elementDao;
-
- @Autowired
- private IDistributionEngine distributionEngine;
-
- // @Autowired
- // private AuditingDao auditingDao;
-
- @Autowired
- private AuditCassandraDao auditCassandraDao;
-
- @Autowired
- private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic;
-
- @Autowired
- private GroupBusinessLogic groupBusinessLogic;
-
- @Autowired
- private ICacheMangerOperation cacheManagerOperation;
-
- private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName());
- private static final String INITIAL_VERSION = "0.1";
-
- public ServiceBusinessLogic() {
- log.debug("ServiceBusinessLogic started");
- }
-
- public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) {
-
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- log.debug("check request state");
- Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user);
- if (validateEnum.isRight()) {
- return Either.right(validateEnum.right().value());
- }
- DistributionTransitionEnum distributionTransition = validateEnum.left().value();
- AuditingActionEnum auditAction = (distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT);
- Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction);
- if (commentResponse.isRight()) {
- return Either.right(commentResponse.right().value());
- }
- String comment = commentResponse.left().value();
-
- Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment);
- if (validateService.isRight()) {
- return Either.right(validateService.right().value());
- }
- Service service = validateService.left().value();
- DistributionStatusEnum initState = service.getDistributionStatus();
-
- Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment);
- if (validateUser.isRight()) {
- return Either.right(validateUser.right().value());
- }
- user = validateUser.left().value();
-
- // lock resource
- /*
- * StorageOperationStatus lockResult = graphLockOperation.lockComponent(serviceId, NodeTypeEnum.Service); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.
- * BeFailedLockObjectError, "ChangeServiceDistributionState"); log.debug("Failed to lock service {} error - {}", serviceId, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
- * service.getVersion(), service.getServiceName());
- *
- * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); }
- */
- Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState");
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- createAudit(user, auditAction, comment, service, responseFormat);
- return Either.right(responseFormat);
- }
-
- try {
-
- DistributionStatusEnum newState;
- if (distributionTransition == DistributionTransitionEnum.APPROVE) {
- newState = DistributionStatusEnum.DISTRIBUTION_APPROVED;
- } else {
- newState = DistributionStatusEnum.DISTRIBUTION_REJECTED;
- }
- Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState);
- if (result.isRight()) {
- titanDao.rollback();
- BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState");
- log.debug("service {} is change destribuation status failed", service.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName());
- createAudit(user, auditAction, comment, service, responseFormat);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- titanDao.commit();
- Service updatedService = result.left().value();
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, updatedService.getDistributionStatus().name());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, initState.name());
- createAudit(user, auditAction, comment, updatedService, responseFormat, auditingFields);
- return Either.left(result.left().value());
-
- } finally {
- graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
- }
-
- }
-
- public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<List<Map<String, Object>>, ActionStatus> result;
- try {
-
- // Certified Version
- if (componentVersion.endsWith(".0")) {
- Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID);
- if (eitherAuditingForCertified.isLeft()) {
- result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value()));
- } else {
- result = Either.right(eitherAuditingForCertified.right().value());
- }
- }
- // Uncertified Version
- else {
- result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion);
- }
- } catch (Exception e) {
- log.debug("get Audit Records failed with exception {}", e);
- result = Either.right(ActionStatus.GENERAL_ERROR);
- }
-
- if (result.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(result.right().value()));
- } else {
- return Either.left(result.left().value());
- }
-
- }
-
- private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) {
- // First Query
- Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
-
- if (eitherprevVerAudit.isRight()) {
- return Either.right(eitherprevVerAudit.right().value());
- }
-
- // Second Query
- Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
- if (eitherCurrVerAudit.isRight()) {
- return Either.right(eitherCurrVerAudit.right().value());
- }
-
- List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
- List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
-
- List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>();
- duplicateElements.addAll(prevVerAuditList);
- duplicateElements.retainAll(currVerAuditList);
-
- List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>();
- joinedNonDuplicatedList.addAll(prevVerAuditList);
- joinedNonDuplicatedList.removeAll(duplicateElements);
- joinedNonDuplicatedList.addAll(currVerAuditList);
-
- return Either.left(joinedNonDuplicatedList);
- }
-
- private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
-
- List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>();
- for (AuditingGenericEvent auditEvent : prevVerAuditList) {
- auditEvent.fillFields();
- prevVerAudit.add(auditEvent.getFields());
- }
- return prevVerAudit;
- }
-
- /**
- * createService
- *
- * @param service
- * - Service
- * @param user
- * - modifier data (userId)
- * @return Either<Service, responseFormat>
- */
- public Either<Service, ResponseFormat> createService(Service service, User user) {
-
- // get user details
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- // validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
- service.setCreatorUserId(user.getUserId());
-
- // warn on overridden fields
- checkFieldsForOverideAttampt(service);
- // enrich object
- log.debug("enrich service with version and state");
- service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- service.setVersion(INITIAL_VERSION);
- service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
- service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
-
- Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE);
- if (createServiceResponse.isRight()) {
- return createServiceResponse;
- }
- return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user);
- }
-
- private void checkFieldsForOverideAttampt(Service service) {
- checkComponentFieldsForOverrideAttempt(service);
- if ((service.getDistributionStatus() != null)) {
- log.info("Distribution Status cannot be defined by user. This field will be overridden by the application");
- }
- }
-
- private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) {
- log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
- }
-
- log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult);
-
- try {
-
- createMandatoryArtifactsData(service, user);
- createServiceApiArtifactsData(service, user);
- setToscaArtifactsPlaceHolders(service, user);
- Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service);
- if (genericServiceEither.isRight())
- return Either.right(genericServiceEither.right().value());
-
- generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value());
-
- Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
-
- // service created successfully!!!
- if (dataModelResponse.isLeft()) {
- log.debug("Service created successfully!!!");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- ASDCKpiApi.countCreatedServicesKPI();
- return Either.left(dataModelResponse.left().value());
- }
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
- log.debug("audit before sending response");
- componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
-
- } finally {
- graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service);
- }
- }
-
- @SuppressWarnings("unchecked")
- private void createServiceApiArtifactsData(Service service, User user) {
- // create mandatory artifacts
-
- // TODO it must be removed after that artifact uniqueId creation will be
- // moved to ArtifactOperation
- // String serviceUniqueId =
- // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
- // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
- String serviceUniqueId = service.getUniqueId();
- Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
- if (artifactMap == null)
- artifactMap = new HashMap<String, ArtifactDefinition>();
-
- Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
- List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
-
- List<CategoryDefinition> categories = service.getCategories();
- boolean isCreateArtifact = true;
- if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
- for (String exlude : exludeServiceCategory) {
- if (exlude.equalsIgnoreCase(categories.get(0).getName())) {
- isCreateArtifact = false;
- break;
- }
- }
-
- }
-
- if (serviceApiArtifacts != null && isCreateArtifact) {
- Set<String> keys = serviceApiArtifacts.keySet();
- for (String serviceApiArtifactName : keys) {
- Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName);
- ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true);
- artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API);
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
- }
-
- service.setServiceApiArtifacts(artifactMap);
- }
- }
-
- private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) {
-
- Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum);
- if (validationResponse.isRight()) {
- return Either.right(validationResponse.right().value());
- }
- service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- service.setContactId(service.getContactId().toLowerCase());
-
- // Generate invariant UUID - must be here and not in operation since it
- // should stay constant during clone
- String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
- service.setInvariantUUID(invariantUUID);
-
- return Either.left(service);
- }
-
- private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) {
- Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum);
- if (componentsFieldsValidation.isRight()) {
- return componentsFieldsValidation;
- }
-
- log.debug("validate service name uniqueness");
- Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
- if (serviceNameUniquenessValidation.isRight()) {
- return serviceNameUniquenessValidation;
- }
-
- log.debug("validate category");
- Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
- if (categoryValidation.isRight()) {
- return categoryValidation;
- }
-
- // validate project name (ProjectCode) - mandatory in service
- log.debug("validate projectName");
- Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
- if (projectCodeValidation.isRight()) {
- return projectCodeValidation;
- }
-
- log.debug("validate service type");
- Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum);
- if (serviceTypeValidation.isRight()) {
- return serviceTypeValidation;
- }
-
- log.debug("validate service role");
- Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum);
- if (serviceRoleValidation.isRight()) {
- return serviceRoleValidation;
- }
-
- return Either.left(true);
-
- }
-
- private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) {
- log.debug("validate Service category");
-
- if (service.getCategories() == null || service.getCategories().size() == 0) {
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
- componentsUtils.auditComponentAdmin(errorResponse, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(errorResponse);
- }
-
- Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories());
- if (validatCategory.isRight()) {
- ResponseFormat responseFormat = validatCategory.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
- }
-
- return Either.left(true);
- }
-
- public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
-
- // DE242223
- titanDao.commit();
-
- if (dataModelResponse.isLeft()) {
- Map<String, Boolean> result = new HashMap<>();
- result.put("isValid", dataModelResponse.left().value());
- log.debug("validation was successfully performed.");
- return Either.left(result);
- }
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
- return Either.right(responseFormat);
- }
-
- public void setElementDao(IElementOperation elementDao) {
- this.elementDao = elementDao;
- }
-
- public void setCassandraAuditingDao(AuditCassandraDao auditingDao) {
- this.auditCassandraDao = auditingDao;
- }
-
- /*
- * public void setUserAdmin(UserAdminBuisinessLogic userAdmin) { this.userAdmin = userAdmin; }
- *
- * public void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; }
- *
- * public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { this.graphLockOperation = graphLockOperation; }
- */
-
- public ArtifactsBusinessLogic getArtifactBl() {
- return artifactsBusinessLogic;
- }
-
- public void setArtifactBl(ArtifactsBusinessLogic artifactBl) {
- this.artifactsBusinessLogic = artifactBl;
- }
-
- public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) {
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- // validate user role
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<Role>(), null, null);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
-
- Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
- if (storageStatus.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
- }
-
- Service currentService = storageStatus.left().value();
-
- if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) {
- log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate);
- if (validationRsponse.isRight()) {
- log.info("service update metadata: validations field.");
- return validationRsponse;
- }
- Service serviceToUpdate = validationRsponse.left().value();
- // lock resource
-
- Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
- }
- try {
- Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate);
- if (updateResponse.isRight()) {
- titanDao.rollback();
- BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
- log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- titanDao.commit();
- return Either.left(updateResponse.left().value());
- } finally {
- graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
- }
- }
-
- private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
-
- boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
- Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- String creatorUserIdUpdated = serviceUpdate.getCreatorUserId();
- String creatorUserIdCurrent = currentService.getCreatorUserId();
- if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) {
- log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated);
- }
-
- String creatorFullNameUpdated = serviceUpdate.getCreatorFullName();
- String creatorFullNameCurrent = currentService.getCreatorFullName();
- if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) {
- log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated);
- }
-
- String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId();
- String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId();
- if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) {
- log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated);
- }
-
- String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName();
- String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName();
- if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) {
- log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated);
- }
-
- response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus();
- DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus();
- if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals((distributionStatusCurrent != null ? distributionStatusCurrent.name() : null))) {
- log.info("update srvice: recived request to update distributionStatus to {} the field is not updatable ignoring.", distributionStatusUpdated);
- }
-
- if (serviceUpdate.getProjectCode() != null) {
- response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
- }
-
- response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- Long creationDateUpdated = serviceUpdate.getCreationDate();
- Long creationDateCurrent = currentService.getCreationDate();
- if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) {
- log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated);
- }
-
- String versionUpdated = serviceUpdate.getVersion();
- String versionCurrent = currentService.getVersion();
- if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
- log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
- }
-
- response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateContactId(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate();
- Long lastUpdateDateCurrent = currentService.getLastUpdateDate();
- if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) {
- log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated);
- }
-
- LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState();
- LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState();
- if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) {
- log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated);
- }
-
- Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion();
- Boolean isHighestVersionCurrent = currentService.isHighestVersion();
- if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) {
- log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated);
- }
-
- String uuidUpdated = serviceUpdate.getUUID();
- String uuidCurrent = currentService.getUUID();
- if (!uuidCurrent.equals(uuidUpdated)) {
- log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
- }
-
- response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null);
- if (response.isRight()) {
- ResponseFormat errorResponse = response.right().value();
- return Either.right(errorResponse);
- }
-
- String currentInvariantUuid = currentService.getInvariantUUID();
- String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
-
- if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
- log.warn("Product invariant UUID is automatically set and cannot be updated");
- serviceUpdate.setInvariantUUID(currentInvariantUuid);
- }
- validateAndUpdateEcompNaming(currentService, serviceUpdate);
-
- currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext());
-
- return Either.left(currentService);
-
- }
-
- private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) {
- Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming();
- Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming();
- if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr != isEcompoGeneratedUpdate) {
- currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate);
- }
- String namingPolicyUpd = serviceUpdate.getNamingPolicy();
- if (!currentService.isEcompGeneratedNaming()) {
- if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) {
- log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false");
- currentService.setNamingPolicy("");
- } else {
- currentService.setNamingPolicy(namingPolicyUpd);
- }
- }else{
- currentService.setNamingPolicy(namingPolicyUpd);
- }
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
- String contactIdUpdated = serviceUpdate.getContactId();
- String contactIdCurrent = currentService.getContactId();
- if (!contactIdCurrent.equals(contactIdUpdated)) {
- Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction);
- if (validatContactId.isRight()) {
- ResponseFormat errorRespons = validatContactId.right().value();
- return Either.right(errorRespons);
- }
- currentService.setContactId(contactIdUpdated.toLowerCase());
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
- List<String> tagsUpdated = serviceUpdate.getTags();
- List<String> tagsCurrent = currentService.getTags();
- if (tagsUpdated == null || tagsUpdated.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS);
- componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, "", "", audatingAction, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
- }
-
- if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
- Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction);
- if (validatResponse.isRight()) {
- ResponseFormat errorRespons = validatResponse.right().value();
- return Either.right(errorRespons);
- }
- currentService.setTags(tagsUpdated);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
- String descriptionUpdated = serviceUpdate.getDescription();
- String descriptionCurrent = currentService.getDescription();
- if (!descriptionCurrent.equals(descriptionUpdated)) {
- Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction);
- if (validateDescriptionResponse.isRight()) {
- ResponseFormat errorRespons = validateDescriptionResponse.right().value();
- return Either.right(errorRespons);
- }
- currentService.setDescription(serviceUpdate.getDescription());
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
- String projectCodeUpdated = serviceUpdate.getProjectCode();
- String projectCodeCurrent = currentService.getProjectCode();
- if (!projectCodeCurrent.equals(projectCodeUpdated)) {
-
- Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction);
- if (validatProjectCodeResponse.isRight()) {
- ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
- return Either.right(errorRespons);
- }
- currentService.setProjectCode(projectCodeUpdated);
-
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
- String iconUpdated = serviceUpdate.getIcon();
- String iconCurrent = currentService.getIcon();
- if (!iconCurrent.equals(iconUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction);
- if (validatIconResponse.isRight()) {
- ResponseFormat errorRespons = validatIconResponse.right().value();
- return Either.right(errorRespons);
- }
- currentService.setIcon(iconUpdated);
- } else {
- log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) {
- String serviceNameUpdated = serviceUpdate.getName();
- String serviceNameCurrent = currentService.getName();
- if (!serviceNameCurrent.equals(serviceNameUpdated)) {
- if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction);
- if (validatServiceNameResponse.isRight()) {
- ResponseFormat errorRespons = validatServiceNameResponse.right().value();
- return Either.right(errorRespons);
- }
-
- Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction);
- if (serviceNameUniquenessValidation.isRight()) {
- return serviceNameUniquenessValidation;
- }
- currentService.setName(serviceNameUpdated);
- currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
- currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
-
- } else {
- log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
- String updatedServiceType = updatedService.getServiceType();
- String currentServiceType = currentService.getServiceType();
- if (!currentServiceType.equals(updatedServiceType)) {
- Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction);
- if (validateServiceType.isRight()) {
- ResponseFormat errorResponse = validateServiceType.right().value();
- componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE);
- return Either.right(errorResponse);
- }
- currentService.setServiceType(updatedServiceType);
- }
- return Either.left(true);
- }
-
- protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
- String serviceType = ((Service)component).getServiceType();
- if (serviceType != null){
- serviceType = cleanUpText(serviceType);
- Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType);
- if (validateServiceType.isRight()) {
- ResponseFormat responseFormat = validateServiceType.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
- }
- return Either.left(true);
- } else {
- return Either.left(false);
- }
- }
-
-
- private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) {
- if (serviceType.equals("")){
- return Either.left(true);
- } else {
- if (!ValidationUtils.validateServiceTypeLength(serviceType)) {
- log.info("service type exceeds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH);
- return Either.right(errorResponse);
- }
-
- if (!ValidationUtils.validateIsEnglish(serviceType)) {
- log.info("service type is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- }
-
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
- String updatedServiceRole = updatedService.getServiceRole();
- String currentServiceRole = currentService.getServiceRole();
- if (!currentServiceRole.equals(updatedServiceRole)) {
- Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction);
- if (validateServiceRole.isRight()) {
- ResponseFormat errorResponse = validateServiceRole.right().value();
- componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE);
- return Either.right(errorResponse);
- }
- currentService.setServiceRole(updatedServiceRole);
- }
- return Either.left(true);
- }
-
- protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
- String serviceRole = ((Service)component).getServiceRole();
- if (serviceRole != null){
- serviceRole = cleanUpText(serviceRole);
-
- Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole);
- if (validateServiceRole.isRight()) {
- ResponseFormat responseFormat = validateServiceRole.right().value();
- componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE);
- return Either.right(responseFormat);
- }
- return Either.left(true);
- } else {
- return Either.left(false);
- }
- }
-
-
- private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) {
- if (serviceRole.equals("")){
- return Either.left(true);
- } else {
- if (!ValidationUtils.validateServiceRoleLength(serviceRole)) {
- log.info("service role exceeds limit.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH);
- return Either.right(errorResponse);
- }
-
- if (!ValidationUtils.validateIsEnglish(serviceRole)) {
- log.info("service role is not valid.");
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
- }
-
-
-
- private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
- List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
- List<CategoryDefinition> categoryCurrent = currentService.getCategories();
- Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction);
- if (validatCategoryResponse.isRight()) {
- ResponseFormat errorRespons = validatCategoryResponse.right().value();
- return Either.right(errorRespons);
- }
- if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) {
- if (!hasBeenCertified) {
- currentService.setCategories(categoryUpdated);
- } else {
- log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated);
- ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED);
- return Either.right(errorResponse);
- }
- }
- return Either.left(true);
-
- }
-
- public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
- if (list != null) {
- if (list.size() > 1) {
- log.debug("Must be only one category for service");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue());
- return Either.right(responseFormat);
- }
- CategoryDefinition category = list.get(0);
- if (category.getSubcategories() != null) {
- log.debug("Subcategories cannot be defined for service");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY);
- return Either.right(responseFormat);
- }
- if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
- log.debug("Resource category is empty");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
- return Either.right(responseFormat);
- }
-
- log.debug("validating service category {} against valid categories list", list);
- Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories();
- if (categorys.isRight()) {
- log.debug("failed to retrive service categories from Titan");
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value());
- return Either.right(responseFormat);
- }
- List<CategoryDefinition> categoryList = categorys.left().value();
- for (CategoryDefinition value : categoryList) {
- if (value.getName().equals(category.getName())) {
- return Either.left(true);
- }
- }
- log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()));
- }
- return Either.left(false);
- }
-
- public ResponseFormat deleteService(String serviceId, User user) {
- ResponseFormat responseFormat;
- String ecompErrorContext = "delete service";
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
- user = eitherCreator.left().value();
-
- Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
- if (serviceStatus.isRight()) {
- log.debug("failed to get service {}", serviceId);
- return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
- }
-
- Service service = serviceStatus.left().value();
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
- if (lockResult.isRight()) {
- result = StorageOperationStatus.GENERAL_ERROR;
- return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- }
-
- try {
-
- result = markComponentToDelete(service);
- if (result.equals(StorageOperationStatus.OK)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- } else {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
- }
- return responseFormat;
-
- } finally {
- if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
- BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
- }
- }
-
- public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) {
- ResponseFormat responseFormat;
- String ecompErrorContext = "delete service";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return validateEmptyResult.right().value();
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return eitherCreator.right().value();
- }
- user = eitherCreator.left().value();
-
- Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
- if (getResult.isRight()) {
- return getResult.right().value();
- }
- Service service = getResult.left().value();
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
- if (lockResult.isRight()) {
- result = StorageOperationStatus.GENERAL_ERROR;
- return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- }
-
- try {
- result = markComponentToDelete(service);
- if (result.equals(StorageOperationStatus.OK)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
- } else {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
- responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
- }
- return responseFormat;
-
- } finally {
- if (result == null || !result.equals(StorageOperationStatus.OK)) {
- log.warn("operation failed. do rollback");
- BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
- }
- }
-
- public Either<Service, ResponseFormat> getService(String serviceId, User user) {
- String ecompErrorContext = "Get service";
- Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
- if (validateEmptyResult.isRight()) {
- return Either.right(validateEmptyResult.right().value());
- }
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
-
- Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
- if (storageStatus.isRight()) {
- log.debug("failed to get service by id {}", serviceId);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
- }
-
- if(!(storageStatus.left().value() instanceof Service)){
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
- }
- Service service = storageStatus.left().value();
- return Either.left(service);
-
-
-
-
- }
-
- public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
- Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
- if (storageStatus.isRight()) {
- log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
- }
- Service service = storageStatus.left().value();
- return Either.left(service);
- }
-
- @SuppressWarnings("unchecked")
- private void createMandatoryArtifactsData(Service service, User user) {
- // create mandatory artifacts
-
- // TODO it must be removed after that artifact uniqueId creation will be
- // moved to ArtifactOperation
- // String serviceUniqueId =
- // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
- // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
- String serviceUniqueId = service.getUniqueId();
- Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
- if (artifactMap == null)
- artifactMap = new HashMap<String, ArtifactDefinition>();
-
- Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
- List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
-
- String category = service.getCategories().get(0).getName();
- boolean isCreateArtifact = true;
- if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
- for (String exlude : exludeServiceCategory) {
- if (exlude.equalsIgnoreCase(category)) {
- isCreateArtifact = false;
- break;
- }
- }
-
- }
-
- if (informationalServiceArtifacts != null && isCreateArtifact) {
- Set<String> keys = informationalServiceArtifacts.keySet();
- for (String informationalServiceArtifactName : keys) {
- Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName);
- ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false);
- artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
- }
-
- service.setArtifacts(artifactMap);
- }
- }
-
- private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) {
-
- ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
-
- if (isServiceApi) {
- artifactInfo.setMandatory(false);
- artifactInfo.setServiceApi(true);
- }
- return artifactInfo;
- }
-
- private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) {
- DistributionTransitionEnum transitionEnum = null;
-
- transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
- if (transitionEnum == null) {
- BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution");
- log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString());
- ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- return Either.right(error);
- }
-
- return Either.left(transitionEnum);
- }
-
- private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) {
- String data = comment.getUserRemarks();
-
- if (data == null || data.trim().isEmpty()) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
- log.debug("user comment cannot be empty or null.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- data = ValidationUtils.removeNoneUtf8Chars(data);
- data = ValidationUtils.removeHtmlTags(data);
- data = ValidationUtils.normaliseWhitespace(data);
- data = ValidationUtils.stripOctets(data);
-
- if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
- log.debug("user comment exceeds limit.");
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
- }
- if (!ValidationUtils.validateIsEnglish(data)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- return Either.left(data);
- }
-
- private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) {
- Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
- if (storageStatus.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
- createAudit(user, auditAction, comment, responseFormat);
- return Either.right(responseFormat);
- }
- Service service = storageStatus.left().value();
-
- if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
- log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
- createAudit(user, auditAction, comment, service, responseFormat);
- return Either.right(responseFormat);
- }
- return Either.left(service);
- }
-
- private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) {
- log.debug("get user from DB");
-
- // get user details
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- // validate user role
- List<Role> roles = new ArrayList<>();
- roles.add(Role.ADMIN);
- roles.add(Role.GOVERNOR);
- roles.add(Role.OPS);
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment);
- if (validateRes.isRight()) {
- return Either.right(validateRes.right().value());
- }
- return Either.left(user);
- }
-
- private void createAudit(User user, AuditingActionEnum auditAction, String comment, ResponseFormat responseFormat) {
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
-
- createAudit(user, auditAction, comment, null, responseFormat, auditingFields);
- }
-
- private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) {
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, component.getDistributionStatus().name());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, component.getDistributionStatus().name());
- createAudit(user, auditAction, comment, component, component.getLifecycleState().name(), component.getVersion(), responseFormat, auditingFields);
- }
-
- private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- log.debug("audit before sending response");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
- componentsUtils.auditComponent(responseFormat, user, component, null, null, auditAction, ComponentTypeEnum.SERVICE, auditingFields);
- }
-
- private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, String prevState, String prevVersion, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- log.debug("audit before sending response");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
- componentsUtils.auditComponent(responseFormat, user, component, prevState, prevVersion, auditAction, ComponentTypeEnum.SERVICE, auditingFields);
- }
-
- public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
-
- Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
-
- User user = eitherCreator.left().value();
-
- Either<Service, ResponseFormat> result = null;
- ResponseFormat response = null;
- Service updatedService = null;
- String did = ThreadLocalsHolder.getUuid();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, did);
- // DE194021
- String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
- if (configuredEnvName != null && false == envName.equals(configuredEnvName)) {
- log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
- envName = configuredEnvName;
- }
- // DE194021
-
- ServletContext servletContext = request.getSession().getServletContext();
- boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE
- if (!isDistributionEngineUp) {
- BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
- log.debug("Distribution Engine is DOWN");
- response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- return Either.right(response);
- }
-
- Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId);
- if (serviceRes.isRight()) {
- log.debug("failed retrieving service");
- response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
- componentsUtils.auditComponent(response, user, null, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields);
- return Either.right(response);
- }
- Service service = serviceRes.left().value();
- String dcurrStatus = service.getDistributionStatus().name();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, dcurrStatus);
-
- Either<INotificationData, StorageOperationStatus> readyForDistribution = distributionEngine.isReadyForDistribution(service, did, envName);
- if (readyForDistribution.isLeft()) {
- INotificationData notificationData = readyForDistribution.left().value();
- StorageOperationStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName());
- if (notifyServiceResponse == StorageOperationStatus.OK) {
- Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
- if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
- updatedService = updateStateRes.left().value();
- dcurrStatus = updatedService.getDistributionStatus().name();
- } else {
- // The response is not relevant
- updatedService = service;
- }
- ASDCKpiApi.countActivatedDistribution();
- response = componentsUtils.getResponseFormat(ActionStatus.OK);
- result = Either.left(updatedService);
- } else {
- BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
- log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
- response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- result = Either.right(response);
- }
- } else {
- StorageOperationStatus distEngineValidationResponse = readyForDistribution.right().value();
- response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(distEngineValidationResponse), service.getName(), envName);
- result = Either.right(response);
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, dcurrStatus);
- componentsUtils.auditComponent(response, user, service, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields);
- return result;
- }
-
- // convert to private after deletion of temp url
- public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
-
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- String serviceId = service.getUniqueId();
- Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation");
- if (lockResult.isRight()) {
- return Either.right(lockResult.right().value());
- }
- try {
- Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
- if (result.isRight()) {
- titanDao.rollback();
- BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation");
- log.debug("service {} change distribution status failed", serviceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- titanDao.commit();
- return Either.left(result.left().value());
- } finally {
- graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
- }
- }
-
- public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
-
- Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
-
- log.debug("mark distribution deployed");
-
- AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
- Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
- if (getServiceResponse.isRight()) {
- BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
- log.debug("service {} not found", serviceId);
- ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
-
- return Either.right(responseFormat);
- }
-
- Service service = getServiceResponse.left().value();
-
- Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service);
- if (validateRoleForDeploy.isRight()) {
- return Either.right(validateRoleForDeploy.right().value());
- }
- user = validateRoleForDeploy.left().value();
-
- return checkDistributionAndDeploy(did, user, auditAction, service);
-
- }
-
- public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) {
- Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
- // Only one VF Module Artifact per instance - add it to a list of one
- buildArtifactGenList(service, modifier, shouldLock, ri);
-
- return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
-
- }
-
- private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, ComponentInstance ri) {
- List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>();
-
- if (ri.getOriginType() == OriginTypeEnum.VF) {
- asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
- }
- return asList;
- }
-
- private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
-
- return currVF.getGroupInstances();
- }
-
- private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
- ArtifactDefinition vfModuleAertifact = null;
- if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
- Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
- if (optionalVfModuleArtifact.isPresent()) {
- vfModuleAertifact = optionalVfModuleArtifact.get();
- }
- }
- if (vfModuleAertifact == null) {
- Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement());
- if (createVfModuleArtifact.isLeft()) {
- vfModuleAertifact = createVfModuleArtifact.left().value();
- } else {
- responseWrapper.setInnerElement(createVfModuleArtifact.right().value());
- }
- }
- return vfModuleAertifact;
- }
-
- private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper) {
- // Converts GroupDefinition to VfModuleArtifactPayload which is the
- // format used in the payload
-
- // List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList());
- List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>();
- if (groupsForCurrVF != null) {
- for (GroupInstance groupInstance : groupsForCurrVF) {
- VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
- vfModulePayloadForCurrVF.add(modulePayload);
- }
- Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
- // Update Payload With Heat Env
-// vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance));
-
- final Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
- payloadWrapper.setInnerElement(vfModulePayloadString);
- }
-
- }
-
- private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) {
- ArtifactDefinition vfModuleAertifact = null;
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
- Wrapper<String> payloadWrapper = new Wrapper<>();
- List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper);
- if (responseWrapper.isEmpty()) {
- fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper);
- }
- if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) {
- vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
- }
- if (responseWrapper.isEmpty() && vfModuleAertifact != null) {
- vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper, service);
- }
-
- Either<ArtifactDefinition, ResponseFormat> result;
- if (responseWrapper.isEmpty()) {
- result = Either.left(vfModuleAertifact);
- } else {
- result = Either.right(responseWrapper.getInnerElement());
- }
-
- return result;
- }
-
- private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) {
- ArtifactDefinition result = null;
-// final Either<Resource, StorageOperationStatus> 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<ArtifactDefinition, ResponseFormat> 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;
- }
-
- return result;
- }
-
- private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) {
-
- ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
- String newCheckSum = null;
-
- vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
- vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
- vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
- vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
- vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata");
- vfModuleArtifactDefinition.setTimeout(0);
- vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
- vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString);
- if (vfModulePayloadString != null) {
- newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes());
- }
- vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
-
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
-
- Either<ArtifactDefinition, ResponseFormat> result;
- if (addArifactToComponent.isLeft()) {
- result = Either.left(addArifactToComponent.left().value());
- } else {
- result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value())));
- }
-
- return result;
- }
-
- public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock) {
-
- Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance ->
- // Get All Deployment Artifacts
- service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
- // Filter in Only Heat Env
- filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
- // Create ArtifactGenerator from those Artifacts
- map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, resourceInstance.getUniqueId())).collect(Collectors.toList());
-
- return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
-
- }
-
- private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, User modifier, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
-
- // Get Flat List of (Callable) ArtifactGenerator for all the RI in the
- // service
- if (service.getComponentInstances() != null) {
- List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
- if (artifactGenList != null && !artifactGenList.isEmpty()) {
- for (ArtifactGenerator<CallVal> entry : artifactGenList) {
- Either<CallVal, ResponseFormat> callRes;
- try {
- callRes = entry.call();
- if (callRes.isRight()) {
- log.debug("Failed to generate artifact error : {}", callRes.right().value());
- return Either.right(callRes.right().value());
- }
- } catch (Exception e) {
- log.debug("Failed to generate artifact exception : {}", e);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
- }
- }
- return Either.left(service);
- }
-
- abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
-
- }
-
- class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
- ArtifactDefinition artifactDefinition;
- Service service;
- String resourceInstanceName;
- User modifier;
- String instanceId;
- boolean shouldLock;
-
- HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, String instanceId) {
- this.artifactDefinition = artifactDefinition;
- this.service = service;
- this.resourceInstanceName = resourceInstanceName;
- this.modifier = modifier;
- this.shouldLock = shouldLock;
- this.instanceId = instanceId;
- }
-
- @Override
- public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, instanceId);
- }
-
- public ArtifactDefinition getArtifactDefinition() {
- return artifactDefinition;
- }
-
- }
-
- class VfModuleArtifacGenerator extends ArtifactGenerator<ArtifactDefinition> {
- private User user;
- private ComponentInstance componentInstance;
- private Service service;
- boolean shouldLock;
-
- @Override
- public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
- return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock);// generateVfModuleArtifact(user, componentInstance, service, shouldLock);
- }
-
- private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) {
- super();
- this.user = user;
- this.componentInstance = componentInstance;
- this.service = service;
- this.shouldLock = shouldLock;
- }
-
- }
-
- private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
- boolean isDeployed = isDistributionDeployed(did, service);
- if (isDeployed) {
- return Either.left(service);
- }
- Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service);
- if (distributionSuccess.isRight()) {
- return Either.right(distributionSuccess.right().value());
- }
-
- log.debug("mark distribution {} as deployed - success", did);
- componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user);
- return Either.left(service);
- }
-
- private boolean isDistributionDeployed(String did, Service service) {
- Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
-
- boolean isDeployed = false;
- if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
- // already deployed
- log.debug("distribution {} is already deployed", did);
- isDeployed = true;
- }
- return isDeployed;
- }
-
- protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) {
-
- log.trace("checkDistributionSuccess");
- // get all "DRequest" records for this distribution
- // Either<List<ESTimeBasedEvent>, ActionStatus> distRequestsResponse =
- // auditingDao.getListOfDistributionByAction(did,
- // AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), "",
- // ResourceAdminEvent.class);
- Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
- if (distRequestsResponse.isRight()) {
- ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value());
- return Either.right(error);
- }
-
- List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
- if (distributionRequests.isEmpty()) {
- BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
- log.info("distribution {} is not found", did);
- ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND);
- return Either.right(error);
- }
- boolean isRequestSucceeded = false;
- for (ResourceAdminEvent event : distributionRequests) {
- String eventStatus = event.getStatus();
- if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
- isRequestSucceeded = true;
- break;
- }
- }
-
- // get all "DNotify" records for this distribution
- // Either<List<ESTimeBasedEvent>, ActionStatus>
- // distNotificationsResponse =
- // auditingDao.getListOfDistributionByAction(did,
- // AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), "",
- // DistributionNotificationEvent.class);
- Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
- if (distNotificationsResponse.isRight()) {
- ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value());
- return Either.right(error);
- }
-
- List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value();
- boolean isNotificationsSucceeded = false;
- for (DistributionNotificationEvent event : distributionNotifications) {
- String eventStatus = event.getStatus();
- if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
- isNotificationsSucceeded = true;
- break;
- }
- }
-
- // if request failed OR there are notifications that failed
- if (!(isRequestSucceeded && isNotificationsSucceeded)) {
-
- log.info("distribution {} has failed", did);
- ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
- auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
- return Either.right(error);
- }
- return Either.left(true);
- }
-
- private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) {
-
- ResponseFormat error = componentsUtils.getResponseFormat(status, params);
- String message = "";
- if (error.getMessageId() != null) {
- message = error.getMessageId() + ": ";
- }
- message += error.getFormattedMessage();
-
- if (service != null) {
- componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
- } else {
- componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user);
- }
- return error;
- }
-
- private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
- log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId());
- auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND);
- return Either.right(responseFormat);
- }
- user = eitherCreator.left().value();
- log.debug("validate user role");
- List<Role> roles = new ArrayList<>();
- roles.add(Role.ADMIN);
- roles.add(Role.OPS);
- Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null);
- if (validateRes.isRight()) {
- log.info("role {} is not allowed to perform this action", user.getRole());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION);
- return Either.right(responseFormat);
- }
- return Either.left(user);
-
- }
-
- @Override
- public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
-
- }
-
- @Override
- public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
- return deleteMarkedComponents(ComponentTypeEnum.SERVICE);
- }
-
- private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
- return healthCheckBl;
- }
-
- @Override
- public ComponentInstanceBusinessLogic getComponentInstanceBL() {
- return serviceComponentInstanceBusinessLogic;
- }
-
- @Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
-
- Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false);
- if (resp.isRight()) {
- return Either.right(resp.right().value());
- }
- Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
- if (getComponentRes.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
- return Either.right(responseFormat);
- }
-
- List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
- // componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
-
- return Either.left(componentInstances);
- }
-
- public ICacheMangerOperation getCacheManagerOperation() {
- return cacheManagerOperation;
- }
-
- public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
- this.cacheManagerOperation = cacheManagerOperation;
- }
-
- /**
- * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
- *
- * @param modifier
- * @param serviceId
- * @param componentInstanceId
- * @param groupInstanceId
- * @param newProperties
- * @return
- */
- public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
-
- Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
- Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes;
- Component component = null;
- Either<Boolean, ResponseFormat> lockResult = null;
- log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId);
- try {
- validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier);
- if (validateUserAndComponentRes.isRight()) {
- log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId);
- actionResult = Either.right(validateUserAndComponentRes.right().value());
- }
- if (actionResult == null) {
- component = validateUserAndComponentRes.left().value().getKey();
- lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service");
- if (lockResult.isRight()) {
- log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage());
- actionResult = Either.right(lockResult.right().value());
- } else {
- log.debug("The service with system name {} locked. ", component.getSystemName());
- }
- }
- if (actionResult == null) {
- actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties);
- if (actionResult.isRight()) {
- log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage());
- }
- }
- } catch (Exception e) {
- log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
- actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally {
- if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) {
- graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service);
- }
- }
- return actionResult;
- }
-
- private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
-
- Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
- Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
- Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes;
- ComponentInstance relatedComponentInstance = null;
- GroupInstance oldGroupInstance = null;
- Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null;
- GroupInstance updatedGroupInstance = null;
- boolean inTransaction = true;
- boolean shouldCloseTransaction = true;
- findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId);
- if (findGroupInstanceRes.isRight()) {
- log.debug("Group instance {} not found. ", groupInstanceId);
- actionResult = Either.right(findGroupInstanceRes.right().value());
- }
- if (actionResult == null) {
- oldGroupInstance = findGroupInstanceRes.left().value().getValue();
- relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
- updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction);
- if (updateGroupInstanceResult.isRight()) {
- log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
- actionResult = Either.right(updateGroupInstanceResult.right().value());
- }
- }
- if (actionResult == null) {
- updatedGroupInstance = updateGroupInstanceResult.left().value();
- if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
- updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction);
- if (updateParentsModificationTimeRes.isRight()) {
- log.debug("Failed to update modification time. ", oldGroupInstance.getName());
- actionResult = Either.right(updateParentsModificationTimeRes.right().value());
- }
- }
- }
- if (actionResult == null) {
- actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties());
- }
- return actionResult;
- }
-
- private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
- boolean inTranscation, boolean shouldCloseTransaction) {
-
- Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
- Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
- Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = serviceComponentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
- updatedGroupInstance.getModificationTime(), inTranscation);
- if (updateComponentInstanceRes.isRight()) {
- log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
- actionResult = Either.right(updateComponentInstanceRes.right().value());
- } else {
- serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime());
- if (serviceMetadataUpdateResult.isRight()) {
- log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
- } else {
- actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
- }
- }
- return actionResult;
- }
-
- private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) {
-
- Either<ImmutablePair<Component, User>, ResponseFormat> result = null;
- Either<Component, ResponseFormat> validateComponentExistsRes = null;
- User currUser = null;
- Component component = null;
- Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues");
- if (validationUserResult.isRight()) {
- log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId);
- result = Either.right(validationUserResult.right().value());
- }
- if (result == null) {
- currUser = validationUserResult.left().value();
- validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
- if (validateComponentExistsRes.isRight()) {
- log.debug("Failed to validate service existing {}. ", serviceId);
- result = Either.right(validateComponentExistsRes.right().value());
- }
- }
- if (result == null) {
- component = validateComponentExistsRes.left().value();
- if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
- log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- }
- if (result == null) {
- result = Either.left(new ImmutablePair<>(component, currUser));
- }
- return result;
- }
-
- private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) {
-
- Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null;
- GroupInstance groupInstance = null;
- ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId);
- if (foundComponentInstance == null) {
- log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
- } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) {
- groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
- if (groupInstance == null) {
- log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
- actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName()));
- }
- }
- if (actionResult == null) {
- actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance));
- }
- return actionResult;
- }
-
- private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
- ComponentInstance componentInstance = null;
- if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
- componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
- }
- return componentInstance;
- }
-
- private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) {
- Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false);
- if (result.isLeft()) {
- List<Role> roles = new ArrayList<>();
- roles.add(Role.ADMIN);
- roles.add(Role.DESIGNER);
- Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles);
- if (validationRoleRes.isRight()) {
- result = Either.right(validationRoleRes.right().value());
- }
- }
- return result;
- }
-
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) {
-
- ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
- Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen);
-
- if (serviceResultEither.isRight()) {
- 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()), ""));
- }
-
- Service service = serviceResultEither.left().value();
- UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
- return Either.left(dataTransfer);
- }
+ private static final String STATUS_SUCCESS_200 = "200";
+
+ private static final String STATUS_DEPLOYED = "DEPLOYED";
+
+ @Autowired
+ private IElementOperation elementDao;
+
+ @Autowired
+ private IDistributionEngine distributionEngine;
+
+ @Autowired
+ private AuditCassandraDao auditCassandraDao;
+
+ @Autowired
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+ @Autowired
+ private GroupBusinessLogic groupBusinessLogic;
+
+ @Autowired
+ private ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ private ServiceDistributionValidation serviceDistributionValidation;
+
+ private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class);
+ private static final String INITIAL_VERSION = "0.1";
+ @Autowired
+ private ForwardingPathOperation forwardingPathOperation;
+
+ @Autowired
+ private ForwardingPathValidator forwardingPathValidator;
+
+ public ServiceBusinessLogic() {
+ log.debug("ServiceBusinessLogic started");
+ }
+
+ public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ log.debug("check request state");
+ Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user);
+ if (validateEnum.isRight()) {
+ return Either.right(validateEnum.right().value());
+ }
+ DistributionTransitionEnum distributionTransition = validateEnum.left().value();
+ AuditingActionEnum auditAction = distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT;
+ Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction);
+ if (commentResponse.isRight()) {
+ return Either.right(commentResponse.right().value());
+ }
+ String comment = commentResponse.left().value();
+
+ Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment);
+ if (validateService.isRight()) {
+ return Either.right(validateService.right().value());
+ }
+ Service service = validateService.left().value();
+ Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment);
+ if (validateUser.isRight()) {
+ return Either.right(validateUser.right().value());
+ }
+ user = validateUser.left().value();
+
+ // lock resource
+
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ createAudit(user, auditAction, comment, service, responseFormat);
+ return Either.right(responseFormat);
+ }
+
+ try {
+
+ DistributionStatusEnum newState;
+ if (distributionTransition == DistributionTransitionEnum.APPROVE) {
+ newState = DistributionStatusEnum.DISTRIBUTION_APPROVED;
+ } else {
+ newState = DistributionStatusEnum.DISTRIBUTION_REJECTED;
+ }
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, newState);
+ if (result.isRight()) {
+ titanDao.rollback();
+ BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState");
+ log.debug("service {} is change destribuation status failed", service.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName());
+ createAudit(user, auditAction, comment, service, responseFormat);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ titanDao.commit();
+ Service updatedService = result.left().value();
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ log.debug("audit before sending response");
+ componentsUtils.auditComponent(responseFormat, user, updatedService, auditAction, ComponentTypeEnum.SERVICE, ResourceAuditData.newBuilder().build(), comment);
+ return Either.left(result.left().value());
+ } finally {
+ graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
+ }
+
+ }
+
+ public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<List<Map<String, Object>>, ActionStatus> result;
+ try {
+
+ // Certified Version
+ if (componentVersion.endsWith(".0")) {
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID);
+ if (eitherAuditingForCertified.isLeft()) {
+ result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value()));
+ } else {
+ result = Either.right(eitherAuditingForCertified.right().value());
+ }
+ }
+ // Uncertified Version
+ else {
+ result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion);
+ }
+ } catch (Exception e) {
+ log.debug("get Audit Records failed with exception {}", e);
+ result = Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ if (result.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(result.right().value()));
+ } else {
+ return Either.left(result.left().value());
+ }
+
+ }
+
+ private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) {
+ // First Query
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
+
+ if (eitherprevVerAudit.isRight()) {
+ return Either.right(eitherprevVerAudit.right().value());
+ }
+
+ // Second Query
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
+ if (eitherCurrVerAudit.isRight()) {
+ return Either.right(eitherCurrVerAudit.right().value());
+ }
+
+ List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
+ List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
+
+ List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>();
+ duplicateElements.addAll(prevVerAuditList);
+ duplicateElements.retainAll(currVerAuditList);
+
+ List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>();
+ joinedNonDuplicatedList.addAll(prevVerAuditList);
+ joinedNonDuplicatedList.removeAll(duplicateElements);
+ joinedNonDuplicatedList.addAll(currVerAuditList);
+
+ return Either.left(joinedNonDuplicatedList);
+ }
+
+ private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
+
+ List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>();
+ for (AuditingGenericEvent auditEvent : prevVerAuditList) {
+ auditEvent.fillFields();
+ prevVerAudit.add(auditEvent.getFields());
+ }
+ return prevVerAudit;
+ }
+
+ /**
+ * createService
+ *
+ * @param service
+ * - Service
+ * @param user
+ * - modifier data (userId)
+ * @return Either<Service, responseFormat>
+ */
+ public Either<Service, ResponseFormat> createService(Service service, User user) {
+
+ // get user details
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+ service.setCreatorUserId(user.getUserId());
+
+ // warn on overridden fields
+ checkFieldsForOverideAttampt(service);
+ // enrich object
+ log.debug("enrich service with version and state");
+ service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ service.setVersion(INITIAL_VERSION);
+ service.setConformanceLevel(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel());
+ service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE);
+ if (createServiceResponse.isRight()) {
+ return createServiceResponse;
+ }
+ return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, user);
+ }
+
+ private void checkFieldsForOverideAttampt(Service service) {
+ checkComponentFieldsForOverrideAttempt(service);
+ if (service.getDistributionStatus() != null) {
+ log.info("Distribution Status cannot be defined by user. This field will be overridden by the application");
+ }
+ }
+
+ private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, User user) {
+ log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult);
+
+ try {
+
+ createMandatoryArtifactsData(service, user);
+ createServiceApiArtifactsData(service, user);
+ setToscaArtifactsPlaceHolders(service, user);
+ Either<Resource, ResponseFormat> genericServiceEither = fetchAndSetDerivedFromGenericType(service);
+ if (genericServiceEither.isRight())
+ return Either.right(genericServiceEither.right().value());
+
+ generateAndAddInputsFromGenericTypeProperties(service, genericServiceEither.left().value());
+
+ Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
+
+ // service created successfully!!!
+ if (dataModelResponse.isLeft()) {
+ log.debug("Service created successfully!!!");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
+ ASDCKpiApi.countCreatedServicesKPI();
+ return Either.left(dataModelResponse.left().value());
+ }
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
+ log.debug("audit before sending response");
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+
+ } finally {
+ graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void createServiceApiArtifactsData(Service service, User user) {
+ // create mandatory artifacts
+
+ // TODO it must be removed after that artifact uniqueId creation will be
+ // moved to ArtifactOperation
+ String serviceUniqueId = service.getUniqueId();
+ Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
+ if (artifactMap == null)
+ artifactMap = new HashMap<String, ArtifactDefinition>();
+
+ Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
+ List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
+
+ List<CategoryDefinition> categories = service.getCategories();
+ boolean isCreateArtifact = true;
+ if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
+ for (String exlude : exludeServiceCategory) {
+ if (exlude.equalsIgnoreCase(categories.get(0).getName())) {
+ isCreateArtifact = false;
+ break;
+ }
+ }
+
+ }
+
+ if (serviceApiArtifacts != null && isCreateArtifact) {
+ Set<String> keys = serviceApiArtifacts.keySet();
+ for (String serviceApiArtifactName : keys) {
+ Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName);
+ ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true);
+ artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API);
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+ }
+
+ service.setServiceApiArtifacts(artifactMap);
+ }
+ }
+
+ private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) {
+
+ Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum);
+ if (validationResponse.isRight()) {
+ return Either.right(validationResponse.right().value());
+ }
+ service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ service.setContactId(service.getContactId().toLowerCase());
+
+ // Generate invariant UUID - must be here and not in operation since it
+ // should stay constant during clone
+ String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
+ service.setInvariantUUID(invariantUUID);
+
+ return Either.left(service);
+ }
+
+ private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) {
+ Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum);
+ if (componentsFieldsValidation.isRight()) {
+ return componentsFieldsValidation;
+ }
+
+ log.debug("validate service name uniqueness");
+ Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
+ if (serviceNameUniquenessValidation.isRight()) {
+ return serviceNameUniquenessValidation;
+ }
+
+ log.debug("validate category");
+ Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
+ if (categoryValidation.isRight()) {
+ return categoryValidation;
+ }
+
+ // validate project name (ProjectCode) - mandatory in service
+ log.debug("validate projectName");
+ Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
+ if (projectCodeValidation.isRight()) {
+ return projectCodeValidation;
+ }
+
+ log.debug("validate service type");
+ Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum);
+ if (serviceTypeValidation.isRight()) {
+ return serviceTypeValidation;
+ }
+
+ log.debug("validate service role");
+ Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum);
+ if (serviceRoleValidation.isRight()) {
+ return serviceRoleValidation;
+ }
+
+ return Either.left(true);
+
+ }
+
+ private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) {
+ log.debug("validate Service category");
+
+ if (service.getCategories() == null || service.getCategories().size() == 0) {
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+
+ Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories());
+ if (validatCategory.isRight()) {
+ ResponseFormat responseFormat = validatCategory.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+
+ return Either.left(true);
+ }
+
+ public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
+
+ // DE242223
+ titanDao.commit();
+
+ if (dataModelResponse.isLeft()) {
+ Map<String, Boolean> result = new HashMap<>();
+ result.put("isValid", dataModelResponse.left().value());
+ log.debug("validation was successfully performed.");
+ return Either.left(result);
+ }
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+
+ return Either.right(responseFormat);
+ }
+
+ public void setElementDao(IElementOperation elementDao) {
+ this.elementDao = elementDao;
+ }
+
+ public void setCassandraAuditingDao(AuditCassandraDao auditingDao) {
+ this.auditCassandraDao = auditingDao;
+ }
+
+ public ArtifactsBusinessLogic getArtifactBl() {
+ return artifactsBusinessLogic;
+ }
+
+ public void setArtifactBl(ArtifactsBusinessLogic artifactBl) {
+ this.artifactsBusinessLogic = artifactBl;
+ }
+
+ public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) {
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
+ if (storageStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ }
+
+ Service currentService = storageStatus.left().value();
+
+ if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) {
+ log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+
+ Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate);
+ if (validationRsponse.isRight()) {
+ log.info("service update metadata: validations field.");
+ return validationRsponse;
+ }
+ Service serviceToUpdate = validationRsponse.left().value();
+ // lock resource
+
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata");
+ if (lockResult.isRight()) {
+ return Either.right(lockResult.right().value());
+ }
+ try {
+ Either<Service, StorageOperationStatus> updateResponse = toscaOperationFacade.updateToscaElement(serviceToUpdate);
+ if (updateResponse.isRight()) {
+ titanDao.rollback();
+ BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
+ log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ titanDao.commit();
+ return Either.left(updateResponse.left().value());
+ } finally {
+ graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
+ }
+ }
+
+ public Either<Set<String>, ResponseFormat> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) {
+ Service serviceToDelete = initServiceToDeletePaths(serviceId, pathIdsToDelete);
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "deleteForwardingPaths", serviceToDelete, null, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
+ if (storageStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ }
+ Service service = storageStatus.left().value();
+ Either<Set<String>, StorageOperationStatus> result = null;
+ if (lock) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service");
+ if (lockResult.isRight()) {
+ titanDao.rollback();
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils
+ .convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ }
+ }
+ try{
+ result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete);
+ if (result.isRight()) {
+ log.debug("Failed to lock service {}. Response is {}. ", service.getName(), result.right().value());
+ titanDao.rollback();
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE)));
+ }
+ titanDao.commit();
+ log.debug("The service with system name {} locked. ", service.getSystemName());
+
+ } catch (Exception e){
+ log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e);
+ titanDao.rollback();
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
+ }
+ return Either.left(result.left().value());
+ }
+
+ private Service initServiceToDeletePaths(String serviceId, Collection<String> pathIdsToDelete) {
+ Service serviceToDelete = new Service();
+ serviceToDelete.setUniqueId(serviceId);
+ serviceToDelete.setForwardingPaths(new HashMap<>());
+ pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition()));
+ return serviceToDelete;
+ }
+
+ public Either<Service, ResponseFormat> updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) {
+ return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock);
+ }
+
+ public Either<Service, ResponseFormat> createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) {
+ return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock);
+ }
+
+ private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path){
+ ForwardingPathDataDefinition dataDefinition = new ForwardingPathDataDefinition(path.getName());
+ dataDefinition.setName(Strings.nullToEmpty(path.getName()).trim());
+ dataDefinition.setProtocol(Strings.nullToEmpty(path.getProtocol()).trim());
+ dataDefinition.setDestinationPortNumber(Strings.nullToEmpty(path.getDestinationPortNumber()).trim());
+ dataDefinition.setUniqueId(path.getUniqueId());
+ dataDefinition.setPathElements(path.getPathElements());
+ dataDefinition.setDescription(path.getDescription());
+ dataDefinition.setToscaResourceName(path.getToscaResourceName());
+ return dataDefinition;
+ }
+
+ private Either<Service, ResponseFormat> createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) {
+ Either<Service, ResponseFormat> eitherCreator1 = validateUserAndRole(serviceUpdate, user, errorContext);
+ if (eitherCreator1 != null) return eitherCreator1;
+
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = serviceUpdate.getForwardingPaths();
+
+ Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths =
+ forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
+ entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue()))));
+
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(),
+ serviceId, isUpdate);
+ if(booleanResponseFormatEither.isRight()){
+ return Either.right(booleanResponseFormatEither.right().value());
+ }
+
+ Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId);
+
+ if(serviceStorageOperationStatusEither.isRight()){
+ StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value();
+ log.debug("Failed to fetch service information by service id, error {}", errorStatus);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
+ }
+ Service storedService = serviceStorageOperationStatusEither.left().value();
+
+ Set<ForwardingPathDataDefinition> forwardingPathDataDefinitions = trimmedForwardingPaths.entrySet().stream().map(entry -> entry.getValue())
+ .collect(Collectors.toSet());
+
+ Either<ForwardingPathDataDefinition, StorageOperationStatus> result;
+ Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME);
+ if (forwardingPathOrigin.isRight()) {
+ StorageOperationStatus errorStatus = forwardingPathOrigin.right().value();
+ log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
+ }
+ Component component = forwardingPathOrigin.left().value();
+ final String toscaResourceName;
+ if ( component.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ toscaResourceName = ((Resource) component).getToscaResourceName();
+ } else {
+ toscaResourceName = "";
+ }
+ Either<Boolean, ResponseFormat> lockResult = null;
+ if (lock) {
+ lockResult =
+ lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service");
+ if (lockResult.isRight()) {
+ log.debug("Failed to lock service {}. Response is {}. ", storedService.getName(),
+ lockResult.right().value().getFormattedMessage());
+ return Either.right(lockResult.right().value());
+ } else {
+ log.debug("The service with system name {} locked. ", storedService.getSystemName());
+ }
+ }
+ Map<String, ForwardingPathDataDefinition> resultMap = new HashMap<>();
+ try {
+ trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName));
+
+ try {
+ for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) {
+ if (isUpdate) {
+ result = forwardingPathOperation.updateForwardingPath(serviceId, forwardingPathDataDefinition);
+ } else {
+ result = forwardingPathOperation.addForwardingPath(serviceId, forwardingPathDataDefinition);
+ }
+ if (result.isRight()) {
+ titanDao.rollback();
+ return Either.right(componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE),
+ ""));
+ } else {
+ ForwardingPathDataDefinition fpDataDefinition = result.left().value();
+ resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition);
+ }
+ }
+
+ } catch (Exception e) {
+ titanDao.rollback();
+ log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(),
+ e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ titanDao.commit();
+ } finally {
+ if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) {
+ graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service);
+ }
+ }
+ Service service = createServiceWithForwardingPathForResponse(serviceId, resultMap);
+ return Either.left(service);
+ }
+
+ private Service createServiceWithForwardingPathForResponse(String serviceId, Map<String,ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) {
+ Service service = new Service();
+ service.setUniqueId(serviceId);
+ service.setForwardingPaths(forwardingPathDataDefinitionMap);
+ return service;
+ }
+
+ private Either<Service, ResponseFormat> validateUserAndRole(Service serviceUpdate, User user, String errorContext) {
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, errorContext, serviceUpdate, null, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+ return null;
+ }private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
+
+ boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
+ Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ String creatorUserIdUpdated = serviceUpdate.getCreatorUserId();
+ String creatorUserIdCurrent = currentService.getCreatorUserId();
+ if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) {
+ log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated);
+ }
+
+ String creatorFullNameUpdated = serviceUpdate.getCreatorFullName();
+ String creatorFullNameCurrent = currentService.getCreatorFullName();
+ if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) {
+ log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated);
+ }
+
+ String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId();
+ String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId();
+ if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) {
+ log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated);
+ }
+
+ String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName();
+ String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName();
+ if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) {
+ log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated);
+ }
+
+ response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus();
+ DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus();
+ if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals(distributionStatusCurrent != null ? distributionStatusCurrent.name() : null)) {
+ log.info("update service: received request to update distributionStatus to {}. the field is read only, ignoring.", distributionStatusUpdated);
+ }
+
+ if (serviceUpdate.getProjectCode() != null) {
+ response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+ }
+
+ response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ Long creationDateUpdated = serviceUpdate.getCreationDate();
+ Long creationDateCurrent = currentService.getCreationDate();
+ if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) {
+ log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated);
+ }
+
+ String versionUpdated = serviceUpdate.getVersion();
+ String versionCurrent = currentService.getVersion();
+ if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
+ log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
+ }
+
+ response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateContactId(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate();
+ Long lastUpdateDateCurrent = currentService.getLastUpdateDate();
+ if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) {
+ log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated);
+ }
+
+ LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState();
+ LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState();
+ if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) {
+ log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated);
+ }
+
+ Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion();
+ Boolean isHighestVersionCurrent = currentService.isHighestVersion();
+ if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) {
+ log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated);
+ }
+
+ String uuidUpdated = serviceUpdate.getUUID();
+ String uuidCurrent = currentService.getUUID();
+ if (!uuidCurrent.equals(uuidUpdated)) {
+ log.info("update service: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
+ }
+
+ response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ String currentInvariantUuid = currentService.getInvariantUUID();
+ String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
+
+ if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
+ log.warn("Product invariant UUID is automatically set and cannot be updated");
+ serviceUpdate.setInvariantUUID(currentInvariantUuid);
+ }
+ validateAndUpdateEcompNaming(currentService, serviceUpdate);
+
+ currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext());
+
+ return Either.left(currentService);
+
+ }
+
+ private void validateAndUpdateEcompNaming(Service currentService, Service serviceUpdate) {
+ Boolean isEcompoGeneratedCurr = currentService.isEcompGeneratedNaming();
+ Boolean isEcompoGeneratedUpdate = serviceUpdate.isEcompGeneratedNaming();
+ if (isEcompoGeneratedUpdate != null && isEcompoGeneratedCurr.equals(isEcompoGeneratedUpdate)) {
+ currentService.setEcompGeneratedNaming(isEcompoGeneratedUpdate);
+ }
+ String namingPolicyUpd = serviceUpdate.getNamingPolicy();
+ if (!currentService.isEcompGeneratedNaming()) {
+ if (ValidationUtils.validateStringNotEmpty(namingPolicyUpd)) {
+ log.warn("NamingPolicy must be empty for EcompGeneratedNaming=false");
+ currentService.setNamingPolicy("");
+ } else {
+ currentService.setNamingPolicy(namingPolicyUpd);
+ }
+ }else{
+ currentService.setNamingPolicy(namingPolicyUpd);
+ }
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+ String contactIdUpdated = serviceUpdate.getContactId();
+ String contactIdCurrent = currentService.getContactId();
+ if (!contactIdCurrent.equals(contactIdUpdated)) {
+ Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction);
+ if (validatContactId.isRight()) {
+ ResponseFormat errorRespons = validatContactId.right().value();
+ return Either.right(errorRespons);
+ }
+ currentService.setContactId(contactIdUpdated.toLowerCase());
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ List<String> tagsUpdated = serviceUpdate.getTags();
+ List<String> tagsCurrent = currentService.getTags();
+ if (tagsUpdated == null || tagsUpdated.isEmpty()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS);
+ componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, audatingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+
+ if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
+ Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction);
+ if (validatResponse.isRight()) {
+ ResponseFormat errorRespons = validatResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentService.setTags(tagsUpdated);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ String descriptionUpdated = serviceUpdate.getDescription();
+ String descriptionCurrent = currentService.getDescription();
+ if (!descriptionCurrent.equals(descriptionUpdated)) {
+ Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction);
+ if (validateDescriptionResponse.isRight()) {
+ ResponseFormat errorRespons = validateDescriptionResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentService.setDescription(serviceUpdate.getDescription());
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+ String projectCodeUpdated = serviceUpdate.getProjectCode();
+ String projectCodeCurrent = currentService.getProjectCode();
+ if (!projectCodeCurrent.equals(projectCodeUpdated)) {
+
+ Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction);
+ if (validatProjectCodeResponse.isRight()) {
+ ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentService.setProjectCode(projectCodeUpdated);
+
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ String iconUpdated = serviceUpdate.getIcon();
+ String iconCurrent = currentService.getIcon();
+ if (!iconCurrent.equals(iconUpdated)) {
+ if (!hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction);
+ if (validatIconResponse.isRight()) {
+ ResponseFormat errorRespons = validatIconResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ currentService.setIcon(iconUpdated);
+ } else {
+ log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) {
+ String serviceNameUpdated = serviceUpdate.getName();
+ String serviceNameCurrent = currentService.getName();
+ if (!serviceNameCurrent.equals(serviceNameUpdated)) {
+ if (!hasBeenCertified) {
+ Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction);
+ if (validatServiceNameResponse.isRight()) {
+ ResponseFormat errorRespons = validatServiceNameResponse.right().value();
+ return Either.right(errorRespons);
+ }
+
+ Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction);
+ if (serviceNameUniquenessValidation.isRight()) {
+ return serviceNameUniquenessValidation;
+ }
+ currentService.setName(serviceNameUpdated);
+ currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
+ currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
+
+ } else {
+ log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedServiceType = updatedService.getServiceType();
+ String currentServiceType = currentService.getServiceType();
+ if (!currentServiceType.equals(updatedServiceType)) {
+ Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction);
+ if (validateServiceType.isRight()) {
+ ResponseFormat errorResponse = validateServiceType.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setServiceType(updatedServiceType);
+ }
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ String serviceType = ((Service)component).getServiceType();
+ if (serviceType != null){
+ serviceType = cleanUpText(serviceType);
+ Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType);
+ if (validateServiceType.isRight()) {
+ ResponseFormat responseFormat = validateServiceType.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ } else {
+ return Either.left(false);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) {
+ if (serviceType.equals("")){
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateServiceTypeLength(serviceType)) {
+ log.info("service type exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(serviceType)) {
+ log.info("service type is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedServiceRole = updatedService.getServiceRole();
+ String currentServiceRole = currentService.getServiceRole();
+ if (!currentServiceRole.equals(updatedServiceRole)) {
+ Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction);
+ if (validateServiceRole.isRight()) {
+ ResponseFormat errorResponse = validateServiceRole.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setServiceRole(updatedServiceRole);
+ }
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ String serviceRole = ((Service)component).getServiceRole();
+ if (serviceRole != null){
+ serviceRole = cleanUpText(serviceRole);
+
+ Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole);
+ if (validateServiceRole.isRight()) {
+ ResponseFormat responseFormat = validateServiceRole.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ } else {
+ return Either.left(false);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) {
+ if (serviceRole.equals("")){
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateServiceRoleLength(serviceRole)) {
+ log.info("service role exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(serviceRole)) {
+ log.info("service role is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
+ List<CategoryDefinition> categoryCurrent = currentService.getCategories();
+ Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction);
+ if (validatCategoryResponse.isRight()) {
+ ResponseFormat errorRespons = validatCategoryResponse.right().value();
+ return Either.right(errorRespons);
+ }
+ if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) {
+ if (!hasBeenCertified) {
+ currentService.setCategories(categoryUpdated);
+ } else {
+ log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated);
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED);
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+
+ }
+
+ public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
+ if (list != null) {
+ if (list.size() > 1) {
+ log.debug("Must be only one category for service");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue());
+ return Either.right(responseFormat);
+ }
+ CategoryDefinition category = list.get(0);
+ if (category.getSubcategories() != null) {
+ log.debug("Subcategories cannot be defined for service");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY);
+ return Either.right(responseFormat);
+ }
+ if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
+ log.debug("Resource category is empty");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ return Either.right(responseFormat);
+ }
+
+ log.debug("validating service category {} against valid categories list", list);
+ Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories();
+ if (categorys.isRight()) {
+ log.debug("failed to retrive service categories from Titan");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value());
+ return Either.right(responseFormat);
+ }
+ List<CategoryDefinition> categoryList = categorys.left().value();
+ for (CategoryDefinition value : categoryList) {
+ if (value.getName().equals(category.getName())) {
+ return Either.left(true);
+ }
+ }
+ log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()));
+ }
+ return Either.left(false);
+ }
+
+ public Either<ServiceRelations, ResponseFormat> getServiceComponentsRelations(String serviceId, User user) {
+ Either<Service, ResponseFormat> serviceResponseFormatEither = getService(serviceId, user);
+ if (serviceResponseFormatEither.isRight()){
+ return Either.right(serviceResponseFormatEither.right().value());
+ }
+ final ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(serviceResponseFormatEither.left().value());
+ return Either.left(serviceRelations);
+
+
+ }public ResponseFormat deleteService(String serviceId, User user) {
+ ResponseFormat responseFormat;
+ String ecompErrorContext = "delete service";
+
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
+ if (eitherCreator.isRight()) {
+ return eitherCreator.right().value();
+ }
+ user = eitherCreator.left().value();
+
+ Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
+ if (serviceStatus.isRight()) {
+ log.debug("failed to get service {}", serviceId);
+ return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
+ }
+
+ Service service = serviceStatus.left().value();
+
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
+ if (lockResult.isRight()) {
+ result = StorageOperationStatus.GENERAL_ERROR;
+ return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ }
+
+ try {
+
+ result = markComponentToDelete(service);
+ if (result.equals(StorageOperationStatus.OK)) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+ } else {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
+ }
+ return responseFormat;
+
+ } finally {
+ if (result == null || !result.equals(StorageOperationStatus.OK)) {
+ log.warn("operation failed. do rollback");
+ BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
+ }
+ }
+
+ public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) {
+ ResponseFormat responseFormat;
+ String ecompErrorContext = "delete service";
+ Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
+ if (validateEmptyResult.isRight()) {
+ return validateEmptyResult.right().value();
+ }
+
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
+ if (eitherCreator.isRight()) {
+ return eitherCreator.right().value();
+ }
+ user = eitherCreator.left().value();
+
+ Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
+ if (getResult.isRight()) {
+ return getResult.right().value();
+ }
+ Service service = getResult.left().value();
+
+ StorageOperationStatus result = StorageOperationStatus.OK;
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
+ if (lockResult.isRight()) {
+ result = StorageOperationStatus.GENERAL_ERROR;
+ return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ }
+
+ try {
+ result = markComponentToDelete(service);
+ if (result.equals(StorageOperationStatus.OK)) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+ } else {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+ responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
+ }
+ return responseFormat;
+
+ } finally {
+ if (result == null || !result.equals(StorageOperationStatus.OK)) {
+ log.warn("operation failed. do rollback");
+ BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
+ }
+ }
+
+ public Either<Service, ResponseFormat> getService(String serviceId, User user) {
+ String ecompErrorContext = "Get service";
+ Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
+ if (validateEmptyResult.isRight()) {
+ return Either.right(validateEmptyResult.right().value());
+ }
+
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
+ if (storageStatus.isRight()) {
+ log.debug("failed to get service by id {}", serviceId);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
+ }
+
+ if(!(storageStatus.left().value() instanceof Service)){
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
+ }
+ Service service = storageStatus.left().value();
+ return Either.left(service);
+
+
+
+
+ }
+
+ public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
+ if (storageStatus.isRight()) {
+ log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
+ }
+ Service service = storageStatus.left().value();
+ return Either.left(service);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void createMandatoryArtifactsData(Service service, User user) {
+ // create mandatory artifacts
+
+ // TODO it must be removed after that artifact uniqueId creation will be
+ // moved to ArtifactOperation
+ String serviceUniqueId = service.getUniqueId();
+ Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
+ if (artifactMap == null)
+ artifactMap = new HashMap<String, ArtifactDefinition>();
+
+ Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
+ List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
+
+ String category = service.getCategories().get(0).getName();
+ boolean isCreateArtifact = true;
+ if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
+ for (String exlude : exludeServiceCategory) {
+ if (exlude.equalsIgnoreCase(category)) {
+ isCreateArtifact = false;
+ break;
+ }
+ }
+
+ }
+
+ if (informationalServiceArtifacts != null && isCreateArtifact) {
+ Set<String> keys = informationalServiceArtifacts.keySet();
+ for (String informationalServiceArtifactName : keys) {
+ Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName);
+ ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false);
+ artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+
+ }
+
+ service.setArtifacts(artifactMap);
+ }
+ }
+
+ private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) {
+
+ ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
+
+ if (isServiceApi) {
+ artifactInfo.setMandatory(false);
+ artifactInfo.setServiceApi(true);
+ }
+ return artifactInfo;
+ }
+
+ private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) {
+ DistributionTransitionEnum transitionEnum = null;
+
+ transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
+ if (transitionEnum == null) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution");
+ log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString());
+ ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(error);
+ }
+
+ return Either.left(transitionEnum);
+ }
+
+ private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) {
+ String data = comment.getUserRemarks();
+
+ if (data == null || data.trim().isEmpty()) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
+ log.debug("user comment cannot be empty or null.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ data = ValidationUtils.removeNoneUtf8Chars(data);
+ data = ValidationUtils.removeHtmlTags(data);
+ data = ValidationUtils.normaliseWhitespace(data);
+ data = ValidationUtils.stripOctets(data);
+
+ if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
+ log.debug("user comment exceeds limit.");
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
+ }
+ if (!ValidationUtils.validateIsEnglish(data)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ return Either.left(data);
+ }
+
+ private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) {
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
+ if (storageStatus.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
+ log.debug("audit before sending response");
+ componentsUtils.auditComponent(responseFormat, user, auditAction, serviceId, ComponentTypeEnum.SERVICE, comment);
+ return Either.right(responseFormat);
+ }
+ Service service = storageStatus.left().value();
+
+ if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
+ log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
+ createAudit(user, auditAction, comment, service, responseFormat);
+ return Either.right(responseFormat);
+ }
+ return Either.left(service);
+ }
+
+ private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) {
+ log.debug("get user from DB");
+
+ // get user details
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ // validate user role
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.GOVERNOR);
+ roles.add(Role.OPS);
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment);
+ if (validateRes.isRight()) {
+ return Either.right(validateRes.right().value());
+ }
+ return Either.left(user);
+ }
+
+ private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) {
+ log.debug("audit before sending response");
+ componentsUtils.auditComponent(responseFormat, user, component, auditAction, ComponentTypeEnum.SERVICE,
+ ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(component.getVersion()).build(), comment);
+ }
+
+ private String getEnvNameFromConfiguration() {
+ String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
+ log.trace("Update environment name to be {}", configuredEnvName);
+ return configuredEnvName;
+ }
+
+ public Either<String, ResponseFormat> activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier, ServiceDistributionReqInfo data) {
+
+ Either<ActivationRequestInformation, ResponseFormat> activationRequestInformationEither = serviceDistributionValidation.validateActivateServiceRequest(serviceId, envId, modifier, data);
+ if (activationRequestInformationEither.isRight()) {
+ return Either.right(activationRequestInformationEither.right().value());
+ }
+
+ ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value();
+
+ Either<String, ResponseFormat> result = null;
+ ResponseFormat response = null;
+ String did = ThreadLocalsHolder.getUuid();
+ Service service = activationRequestInformation.getServiceToActivate();
+
+ StorageOperationStatus readyForDistribution = distributionEngine.verifyServiceHasDeploymentArtifacts(service);
+ if (readyForDistribution.equals(StorageOperationStatus.OK)) {
+ result = buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
+ } else {
+ response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envId);
+ result = Either.right(response);
+ }
+ return result;
+ }
+
+ public Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) {
+ String envName = getEnvNameFromConfiguration();
+ INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext);
+ ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier.getUserId(), modifier.getFullName());
+ if (notifyServiceResponse == ActionStatus.OK) {
+ return Either.left(did);
+ } else {
+ BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
+ log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
+ ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESPONSE_FROM_PROXY);
+ return Either.right(error);
+ }
+ }
+
+ public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
+
+ Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+
+ User user = eitherCreator.left().value();
+
+ Either<Service, ResponseFormat> result = null;
+ ResponseFormat response = null;
+ Service updatedService = null;
+ String did = ThreadLocalsHolder.getUuid();
+ // DE194021
+ String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
+ if (configuredEnvName != null && false == envName.equals(configuredEnvName)) {
+ log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
+ envName = configuredEnvName;
+ }
+ // DE194021
+
+ ServletContext servletContext = request.getSession().getServletContext();
+ boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE
+ if (!isDistributionEngineUp) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
+ log.debug("Distribution Engine is DOWN");
+ response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(response);
+ }
+
+ Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId);
+ if (serviceRes.isRight()) {
+ log.debug("failed retrieving service");
+ response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
+ componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE,
+ ResourceAuditData.newBuilder().build(), did);
+ return Either.right(response);
+ }
+ Service service = serviceRes.left().value();
+ String dcurrStatus = service.getDistributionStatus().name();
+ String updatedStatus = dcurrStatus;
+ StorageOperationStatus readyForDistribution = distributionEngine.isReadyForDistribution(service, envName);
+ if (readyForDistribution.equals(StorageOperationStatus.OK)) {
+ INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null);
+ ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName());
+ if (notifyServiceResponse == ActionStatus.OK) {
+ Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
+ if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
+ updatedService = updateStateRes.left().value();
+ updatedStatus = updatedService.getDistributionStatus().name();
+ } else {
+ // The response is not relevant
+ updatedService = service;
+ }
+ ASDCKpiApi.countActivatedDistribution();
+ response = componentsUtils.getResponseFormat(ActionStatus.OK);
+ result = Either.left(updatedService);
+ } else {
+ BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
+ log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
+ response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ result = Either.right(response);
+ }
+ } else {
+ response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution), service.getName(), envName);
+ result = Either.right(response);
+ }
+ componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE,
+ ResourceAuditData.newBuilder().distributionStatus(dcurrStatus).build(),
+ ResourceAuditData.newBuilder().distributionStatus(updatedStatus).build(), service.getName(),
+ null, null, did);
+ return result;
+ }
+
+ // convert to private after deletion of temp url
+ public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ String serviceId = service.getUniqueId();
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation");
+ if (lockResult.isRight()) {
+ return Either.right(lockResult.right().value());
+ }
+ try {
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
+ if (result.isRight()) {
+ titanDao.rollback();
+ BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation");
+ log.debug("service {} change distribution status failed", serviceId);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ titanDao.commit();
+ return Either.left(result.left().value());
+ } finally {
+ graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
+ }
+ }
+
+ public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+
+ log.debug("mark distribution deployed");
+
+ AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
+ Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
+ if (getServiceResponse.isRight()) {
+ BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
+ log.debug("service {} not found", serviceId);
+ ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
+
+ return Either.right(responseFormat);
+ }
+
+ Service service = getServiceResponse.left().value();
+
+ Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service);
+ if (validateRoleForDeploy.isRight()) {
+ return Either.right(validateRoleForDeploy.right().value());
+ }
+ user = validateRoleForDeploy.left().value();
+
+ return checkDistributionAndDeploy(did, user, auditAction, service);
+
+ }
+
+ public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) {
+ Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
+ // Only one VF Module Artifact per instance - add it to a list of one
+ buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri);
+
+ return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator);
+
+ }
+
+ private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, boolean inTransaction, ComponentInstance ri) {
+ List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<ArtifactGenerator<ArtifactDefinition>>();
+
+ if (ri.getOriginType() == OriginTypeEnum.VF) {
+ asList = Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock, inTransaction));
+ }
+ return asList;
+ }
+
+ private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
+ Map<String, ArtifactDefinition> deploymentArtifacts = currVF.getDeploymentArtifacts();
+ if(currVF.getGroupInstances() != null){
+ currVF.getGroupInstances().stream().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts));
+ }
+ return currVF.getGroupInstances();
+ }
+
+ private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+ ArtifactDefinition vfModuleAertifact = null;
+ if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
+ Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
+ if (optionalVfModuleArtifact.isPresent()) {
+ vfModuleAertifact = optionalVfModuleArtifact.get();
+ }
+ }
+ if (vfModuleAertifact == null) {
+ Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement());
+ if (createVfModuleArtifact.isLeft()) {
+ vfModuleAertifact = createVfModuleArtifact.left().value();
+ } else {
+ responseWrapper.setInnerElement(createVfModuleArtifact.right().value());
+ }
+ }
+ return vfModuleAertifact;
+ }
+
+ private void fillVfModuleInstHeatEnvPayload(List<GroupInstance> groupsForCurrVF, Wrapper<String> payloadWrapper) {
+ // Converts GroupDefinition to VfModuleArtifactPayload which is the
+ // format used in the payload
+
+ List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = new ArrayList<VfModuleArtifactPayload>();
+ if (groupsForCurrVF != null) {
+ for (GroupInstance groupInstance : groupsForCurrVF) {
+ VfModuleArtifactPayload modulePayload = new VfModuleArtifactPayload(groupInstance);
+ vfModulePayloadForCurrVF.add(modulePayload);
+ }
+ Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
+
+ final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
+ payloadWrapper.setInnerElement(vfModulePayloadString);
+ }
+
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) {
+ ArtifactDefinition vfModuleAertifact = null;
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ Wrapper<String> payloadWrapper = new Wrapper<>();
+ List<GroupInstance> groupsForCurrVF = collectGroupsInstanceForCompInstance(currVFInstance, responseWrapper);
+ if (responseWrapper.isEmpty()) {
+ fillVfModuleInstHeatEnvPayload(groupsForCurrVF, payloadWrapper);
+ }
+ if (responseWrapper.isEmpty() && payloadWrapper.getInnerElement() != null) {
+ vfModuleAertifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
+ }
+ if (responseWrapper.isEmpty() && vfModuleAertifact != null) {
+ vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service);
+ }
+
+ Either<ArtifactDefinition, ResponseFormat> result;
+ if (responseWrapper.isEmpty()) {
+ result = Either.left(vfModuleAertifact);
+ } else {
+ result = Either.right(responseWrapper.getInnerElement());
+ }
+
+ return result;
+ }
+
+ private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) {
+ ArtifactDefinition result = null;
+ Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, () -> 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;
+ }
+
+ return result;
+ }
+
+ private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) {
+
+ ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
+ String newCheckSum = null;
+
+ vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
+ vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
+ vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
+ vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
+ vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata");
+ vfModuleArtifactDefinition.setTimeout(0);
+ vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
+ vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString);
+ if (vfModulePayloadString != null) {
+ newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes());
+ }
+ vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
+
+ Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactToscaOperation.addArifactToComponent(vfModuleArtifactDefinition, service.getUniqueId(), NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
+
+ Either<ArtifactDefinition, ResponseFormat> result;
+ if (addArifactToComponent.isLeft()) {
+ result = Either.left(addArifactToComponent.left().value());
+ } else {
+ result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value())));
+ }
+
+ return result;
+ }
+
+ public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) {
+
+ Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance ->
+ // Get All Deployment Artifacts
+ service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
+ // Filter in Only Heat Env
+ filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
+ // Create ArtifactGenerator from those Artifacts
+ map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction, resourceInstance.getUniqueId())).collect(Collectors.toList());
+
+ return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator);
+
+ }
+
+ private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
+
+ // Get Flat List of (Callable) ArtifactGenerator for all the RI in the
+ // service
+ if (service.getComponentInstances() != null) {
+ List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
+ if (artifactGenList != null && !artifactGenList.isEmpty()) {
+ for (ArtifactGenerator<CallVal> entry : artifactGenList) {
+ Either<CallVal, ResponseFormat> callRes;
+ try {
+ callRes = entry.call();
+ if (callRes.isRight()) {
+ log.debug("Failed to generate artifact error : {}", callRes.right().value());
+ return Either.right(callRes.right().value());
+ }
+ } catch (Exception e) {
+ log.debug("Failed to generate artifact exception : {}", e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ }
+ }
+ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
+ if (storageStatus.isRight()) {
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+ }
+
+ Service currentService = storageStatus.left().value();
+
+ return Either.left(currentService);
+
+ }
+
+ abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
+
+ }
+
+ class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
+ ArtifactDefinition artifactDefinition;
+ Service service;
+ String resourceInstanceName;
+ User modifier;
+ String instanceId;
+ boolean shouldLock;
+ boolean inTransaction;
+
+ HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) {
+ this.artifactDefinition = artifactDefinition;
+ this.service = service;
+ this.resourceInstanceName = resourceInstanceName;
+ this.modifier = modifier;
+ this.shouldLock = shouldLock;
+ this.instanceId = instanceId;
+ this.inTransaction = inTransaction;
+ }
+
+ @Override
+ public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
+ return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, inTransaction, instanceId);
+ }
+
+ public ArtifactDefinition getArtifactDefinition() {
+ return artifactDefinition;
+ }
+
+ }
+
+ class VfModuleArtifacGenerator extends ArtifactGenerator<ArtifactDefinition> {
+ private User user;
+ private ComponentInstance componentInstance;
+ private Service service;
+ boolean shouldLock;
+ boolean inTransaction;
+
+ @Override
+ public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
+ return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction);
+ }
+
+ private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock, boolean inTransaction) {
+ super();
+ this.user = user;
+ this.componentInstance = componentInstance;
+ this.service = service;
+ this.shouldLock = shouldLock;
+ this.inTransaction = inTransaction;
+ }
+
+ }
+
+ private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
+ boolean isDeployed = isDistributionDeployed(did, service);
+ if (isDeployed) {
+ return Either.left(service);
+ }
+ Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service);
+ if (distributionSuccess.isRight()) {
+ return Either.right(distributionSuccess.right().value());
+ }
+
+ log.debug("mark distribution {} as deployed - success", did);
+ componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user);
+ return Either.left(service);
+ }
+
+ private boolean isDistributionDeployed(String did, Service service) {
+ Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
+
+ boolean isDeployed = false;
+ if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
+ // already deployed
+ log.debug("distribution {} is already deployed", did);
+ isDeployed = true;
+ }
+ return isDeployed;
+ }
+
+ protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) {
+
+ log.trace("checkDistributionSuccess");
+ // get all "DRequest" records for this distribution
+
+ Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
+ if (distRequestsResponse.isRight()) {
+ ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value());
+ return Either.right(error);
+ }
+
+ List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
+ if (distributionRequests.isEmpty()) {
+ BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
+ log.info("distribution {} is not found", did);
+ ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND);
+ return Either.right(error);
+ }
+ boolean isRequestSucceeded = false;
+ for (ResourceAdminEvent event : distributionRequests) {
+ String eventStatus = event.getStatus();
+ if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
+ isRequestSucceeded = true;
+ break;
+ }
+ }
+
+ // get all "DNotify" records for this distribution
+ Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
+ if (distNotificationsResponse.isRight()) {
+ ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value());
+ return Either.right(error);
+ }
+
+ List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value();
+ boolean isNotificationsSucceeded = false;
+ for (DistributionNotificationEvent event : distributionNotifications) {
+ String eventStatus = event.getStatus();
+ if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
+ isNotificationsSucceeded = true;
+ break;
+ }
+ }
+
+ // if request failed OR there are notifications that failed
+ if (!(isRequestSucceeded && isNotificationsSucceeded)) {
+
+ log.info("distribution {} has failed", did);
+ ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
+ auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
+ return Either.right(error);
+ }
+ return Either.left(true);
+ }
+
+ private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) {
+
+ ResponseFormat error = componentsUtils.getResponseFormat(status, params);
+ String message = "";
+ if (error.getMessageId() != null) {
+ message = error.getMessageId() + ": ";
+ }
+ message += error.getFormattedMessage();
+
+ if (service != null) {
+ componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
+ } else {
+ componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user);
+ }
+ return error;
+ }
+
+ private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
+ log.debug("validateRoleForDeploy method - user is not listed. userId= {}", user.getUserId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId());
+ auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND);
+ return Either.right(responseFormat);
+ }
+ user = eitherCreator.left().value();
+ log.debug("validate user role");
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.OPS);
+ Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null);
+ if (validateRes.isRight()) {
+ log.info("role {} is not allowed to perform this action", user.getRole());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION);
+ return Either.right(responseFormat);
+ }
+ return Either.left(user);
+
+ }
+
+ @Override
+ public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
+
+ }
+
+ @Override
+ public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
+ return deleteMarkedComponents(ComponentTypeEnum.SERVICE);
+ }
+
+ private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
+ return healthCheckBl;
+ }
+
+ @Override
+ public ComponentInstanceBusinessLogic getComponentInstanceBL() {
+ return componentInstanceBusinessLogic;
+ }
+
+ @Override
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+
+ Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false);
+ if (resp.isRight()) {
+ return Either.right(resp.right().value());
+ }
+ Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+ if (getComponentRes.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
+ return Either.right(responseFormat);
+ }
+
+ List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
+
+ return Either.left(componentInstances);
+ }
+
+ public ICacheMangerOperation getCacheManagerOperation() {
+ return cacheManagerOperation;
+ }
+
+ public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
+ this.cacheManagerOperation = cacheManagerOperation;
+ }
+
+ public void setForwardingPathOperation(ForwardingPathOperation forwardingPathOperation) {
+ this.forwardingPathOperation = forwardingPathOperation;
+ }
+
+ @Override
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }/**
+ * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
+ *
+ * @param modifier
+ * @param serviceId
+ * @param componentInstanceId
+ * @param groupInstanceId
+ * @param newProperties
+ * @return
+ */
+ public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
+
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
+ Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes;
+ Component component = null;
+ Either<Boolean, ResponseFormat> lockResult = null;
+ log.debug("Going to update group instance {} of service {} with new property values. ", groupInstanceId, serviceId);
+ try {
+ validateUserAndComponentRes = validateUserAndComponent(serviceId, modifier);
+ if (validateUserAndComponentRes.isRight()) {
+ log.debug("Cannot update group instance {} of service {} with new property values. Validation failed. ", groupInstanceId, serviceId);
+ actionResult = Either.right(validateUserAndComponentRes.right().value());
+ }
+ if (actionResult == null) {
+ component = validateUserAndComponentRes.left().value().getKey();
+ lockResult = lockComponentByName(component.getSystemName(), component, "Update Group Instance on Service");
+ if (lockResult.isRight()) {
+ log.debug("Failed to lock service {}. Response is {}. ", component.getName(), lockResult.right().value().getFormattedMessage());
+ actionResult = Either.right(lockResult.right().value());
+ } else {
+ log.debug("The service with system name {} locked. ", component.getSystemName());
+ }
+ }
+ if (actionResult == null) {
+ actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties);
+ if (actionResult.isRight()) {
+ log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage());
+ }
+ }
+ } catch (Exception e) {
+ log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) {
+ graphLockOperation.unlockComponentByName(component.getSystemName(), component.getUniqueId(), NodeTypeEnum.Service);
+ }
+ }
+ return actionResult;
+ }
+
+ private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
+
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
+ Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes;
+ ComponentInstance relatedComponentInstance = null;
+ GroupInstance oldGroupInstance = null;
+ Either<GroupInstance, ResponseFormat> updateGroupInstanceResult = null;
+ GroupInstance updatedGroupInstance = null;
+ boolean inTransaction = true;
+ boolean shouldCloseTransaction = true;
+ findGroupInstanceRes = findGroupInstanceOnRelatedComponentInstance(component, componentInstanceId, groupInstanceId);
+ if (findGroupInstanceRes.isRight()) {
+ log.debug("Group instance {} not found. ", groupInstanceId);
+ actionResult = Either.right(findGroupInstanceRes.right().value());
+ }
+ if (actionResult == null) {
+ oldGroupInstance = findGroupInstanceRes.left().value().getValue();
+ relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
+ updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties, inTransaction);
+ if (updateGroupInstanceResult.isRight()) {
+ log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
+ actionResult = Either.right(updateGroupInstanceResult.right().value());
+ }
+ }
+ if (actionResult == null) {
+ updatedGroupInstance = updateGroupInstanceResult.left().value();
+ if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
+ updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction, shouldCloseTransaction);
+ if (updateParentsModificationTimeRes.isRight()) {
+ log.debug("Failed to update modification time. ", oldGroupInstance.getName());
+ actionResult = Either.right(updateParentsModificationTimeRes.right().value());
+ }
+ }
+ }
+ if (actionResult == null) {
+ actionResult = Either.left(updatedGroupInstance.convertToGroupInstancesProperties());
+ }
+ return actionResult;
+ }
+
+ private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
+ boolean inTranscation, boolean shouldCloseTransaction) {
+
+ Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
+ Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
+ Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = componentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
+ updatedGroupInstance.getModificationTime(), inTranscation);
+ if (updateComponentInstanceRes.isRight()) {
+ log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
+ actionResult = Either.right(updateComponentInstanceRes.right().value());
+ } else {
+ serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component, updatedGroupInstance.getModificationTime());
+ if (serviceMetadataUpdateResult.isRight()) {
+ log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
+ } else {
+ actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
+ }
+ }
+ return actionResult;
+ }
+
+ private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) {
+
+ Either<ImmutablePair<Component, User>, ResponseFormat> result = null;
+ Either<Component, ResponseFormat> validateComponentExistsRes = null;
+ User currUser = null;
+ Component component = null;
+ Either<User, ResponseFormat> validationUserResult = validateUserIgnoreAudit(modifier, "updateGroupInstancePropertyValues");
+ if (validationUserResult.isRight()) {
+ log.debug("Failed to validate user with userId for update service {}. ", modifier.getUserId(), serviceId);
+ result = Either.right(validationUserResult.right().value());
+ }
+ if (result == null) {
+ currUser = validationUserResult.left().value();
+ validateComponentExistsRes = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
+ if (validateComponentExistsRes.isRight()) {
+ log.debug("Failed to validate service existing {}. ", serviceId);
+ result = Either.right(validateComponentExistsRes.right().value());
+ }
+ }
+ if (result == null) {
+ component = validateComponentExistsRes.left().value();
+ if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
+ log.info("Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+ if (result == null) {
+ result = Either.left(new ImmutablePair<>(component, currUser));
+ }
+ return result;
+ }
+
+ private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) {
+
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null;
+ GroupInstance groupInstance = null;
+ ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId);
+ if (foundComponentInstance == null) {
+ log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
+ } else if (!CollectionUtils.isEmpty(foundComponentInstance.getGroupInstances())) {
+ groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
+ if (groupInstance == null) {
+ log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
+ actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName()));
+ }
+ }
+ if (actionResult == null) {
+ actionResult = Either.left(new ImmutablePair<>(foundComponentInstance, groupInstance));
+ }
+ return actionResult;
+ }
+
+ private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
+ ComponentInstance componentInstance = null;
+ if (!CollectionUtils.isEmpty(component.getComponentInstances())) {
+ componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
+ }
+ return componentInstance;
+ }
+
+ private Either<User, ResponseFormat> validateUserIgnoreAudit(User modifier, String ecompErrorContext) {
+ Either<User, ResponseFormat> result = validateUser(modifier, ecompErrorContext, null, null, false);
+ if (result.isLeft()) {
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.DESIGNER);
+ Either<Boolean, ResponseFormat> validationRoleRes = validateUserRole(result.left().value(), roles);
+ if (validationRoleRes.isRight()) {
+ result = Either.right(validationRoleRes.right().value());
+ }
+ }
+ return result;
+ }
+
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) {
+
+ ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
+ Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToRetuen);
+
+ if (serviceResultEither.isRight()) {
+ 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()), ""));
+ }
+
+ Service service = serviceResultEither.left().value();
+ UiComponentDataTransfer dataTransfer = UiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
+ return Either.left(dataTransfer);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
deleted file mode 100644
index d1cc93acc8..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
+++ /dev/null
@@ -1,40 +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.components.impl;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.springframework.stereotype.Component;
-
-@Component("serviceComponentInstanceBusinessLogic")
-public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
-
-
- @Override
- protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
- return NodeTypeEnum.Resource;
- }
-
- @Override
- protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
- return ComponentTypeEnum.RESOURCE_INSTANCE;
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
deleted file mode 100644
index c5db7ee022..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
+++ /dev/null
@@ -1,44 +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.components.impl;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
-@Component("vfComponentInstanceBusinessLogic")
-public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
-
- private static Logger log = LoggerFactory.getLogger(VFComponentInstanceBusinessLogic.class.getName());
-
- @Override
- protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
- return NodeTypeEnum.Resource;
- }
-
- @Override
- protected ComponentTypeEnum getComponentTypeOfComponentInstance() {
- return ComponentTypeEnum.RESOURCE_INSTANCE;
- }
-
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
new file mode 100644
index 0000000000..6347bc2eaf
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
@@ -0,0 +1,44 @@
+package org.openecomp.sdc.be.components.impl.exceptions;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+public class ComponentException extends RuntimeException {
+
+ /**
+ * This class will be initialized either by action status and params or by ResponseFormat
+ */
+
+ private final transient ResponseFormat responseFormat;
+
+ private final ActionStatus actionStatus;
+ private final String[] params;
+
+ public ComponentException(ResponseFormat responseFormat) {
+ this(responseFormat, ActionStatus.OK, null);
+ }
+
+ public ComponentException(ActionStatus actionStatus, String... params) {
+ this(null, actionStatus, params);
+ }
+
+ private ComponentException(ResponseFormat responseFormat, ActionStatus actionStatus, String... params) {
+ this.actionStatus = actionStatus;
+ this.params = params;
+ this.responseFormat = responseFormat;
+ }
+
+ public ResponseFormat getResponseFormat() {
+ return responseFormat;
+ }
+
+ public ActionStatus getActionStatus() {
+ return actionStatus;
+ }
+
+ public String[] getParams() {
+ return params;
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
index 7f6abe7f2c..236be437af 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
@@ -1,9 +1,6 @@
package org.openecomp.sdc.be.components.impl.generic;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -20,7 +17,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component
public class GenericTypeBusinessLogic {
@@ -81,6 +80,9 @@ public class GenericTypeBusinessLogic {
}
private <T extends Component> String getGenericTypeToscaName(T component) {
+ if(component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()){
+ return component.getDerivedFromGenericType();
+ }
return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
new file mode 100644
index 0000000000..30a93fa0bc
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
@@ -0,0 +1,70 @@
+package org.openecomp.sdc.be.components.impl.utils;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class PolicyTypeImportUtils {
+
+ private PolicyTypeImportUtils() {
+ }
+
+ public static boolean isPolicyTypesEquals(PolicyTypeDefinition pt1, PolicyTypeDefinition pt2) {
+ if (pt1 == pt2) {
+ return true;
+ }
+ if (pt1 == null || pt2 == null) {
+ return false;
+ }
+ return Objects.equals(pt1.getType(), pt2.getType()) &&
+ Objects.equals(pt1.getVersion(), pt2.getVersion()) &&
+ Objects.equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) &&
+ Objects.equals(pt1.getTargets(), pt2.getTargets()) &&
+ Objects.equals(pt1.getMetadata(), pt2.getMetadata()) &&
+ Objects.equals(pt1.getDescription(), pt2.getDescription()) &&
+ PolicyTypeImportUtils.isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties());
+ }
+
+ private static boolean isPolicyPropertiesEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
+ if (pt1Props == pt2Props) {
+ return true;
+ }
+ if (pt1Props == null || pt2Props == null) {
+ return false;
+ }
+ if (isPropertiesListSizesNotEquals(pt1Props, pt2Props)) {
+ return false;
+ }
+ Map<String, PropertyDefinition> pt1PropsByName = MapUtil.toMap(pt1Props, PropertyDefinition::getName);
+ long numberOfEqualsProperties = pt2Props.stream().filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)).count();
+ return numberOfEqualsProperties == pt1Props.size();
+ }
+
+ private static boolean policyPropertyEquals(PropertyDefinition pt1Prop, PropertyDefinition pt2Prop) {
+ if (pt1Prop == pt2Prop) {
+ return true;
+ }
+ if (pt1Prop == null || pt2Prop == null) {
+ return false;
+ }
+ return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) &&
+ Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition()) &&
+ Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) &&
+ Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword()) &&
+ Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) &&
+ Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType()) &&
+ Objects.equals(pt1Prop.getType(), pt2Prop.getType());
+ }
+
+ private static boolean isPropertiesListSizesNotEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
+ return CollectionUtils.isEmpty(pt1Props) && CollectionUtils.isNotEmpty(pt2Props) ||
+ CollectionUtils.isEmpty(pt2Props) && CollectionUtils.isNotEmpty(pt1Props) ||
+ pt1Props.size() != pt2Props.size();
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java
new file mode 100644
index 0000000000..df98a7f707
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperation.java
@@ -0,0 +1,66 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+@org.springframework.stereotype.Component
+public class GroupMembersUpdateOperation implements PostChangeVersionOperation {
+
+ private static final Logger log = LoggerFactory.getLogger(GroupMembersUpdateOperation.class);
+ private final GroupsOperation groupsOperation;
+ private final ComponentsUtils componentsUtils;
+
+ public GroupMembersUpdateOperation(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) {
+ this.groupsOperation = groupsOperation;
+ this.componentsUtils = componentsUtils;
+ }
+
+ @Override
+ public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ return updateGroupMembersOnChangeVersion(container, prevVersion, newVersion);
+ }
+
+ private ActionStatus updateGroupMembersOnChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ log.debug("#updateGroupMembersOnChangeVersion - replacing all group members for component instance {} with new component instance.", prevVersion.getUniqueId(), newVersion.getUniqueId());
+ if (isEmpty(container.getGroups())) {
+ log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups.", container.getUniqueId());
+ return ActionStatus.OK;
+ }
+ List<GroupDefinition> groupsWithPrevInstAsMember = container.resolveGroupsByMember(prevVersion.getUniqueId());
+ if (isEmpty(groupsWithPrevInstAsMember)) {
+ log.debug("#updateGroupMembersOnChangeVersion - container {} has no groups with component instance {} as member.", container.getUniqueId(), prevVersion.getUniqueId());
+ return ActionStatus.OK;
+ }
+ replacePrevInstanceMemberWithNewInstance(prevVersion, newVersion, groupsWithPrevInstAsMember);
+ return updateGroups(container, groupsWithPrevInstAsMember);
+ }
+
+ private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) {
+ log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId());
+ return groupsOperation.updateGroups(container, groupsToUpdate)
+ .either(groupsUpdated -> ActionStatus.OK,
+ err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
+ }
+
+ private void replacePrevInstanceMemberWithNewInstance(ComponentInstance prevVersion, ComponentInstance newVersion, List<GroupDefinition> groupsWithPrevInstAsMember) {
+ groupsWithPrevInstAsMember.forEach(grp -> replacePrevInstanceMemberWithNewInstance(grp, prevVersion.getUniqueId(), newVersion.getUniqueId()));
+ }
+
+ private void replacePrevInstanceMemberWithNewInstance(GroupDefinition groupDefinition, String prevInstanceId, String newInstanceId) {
+ Map<String, String> membersNameToId = groupDefinition.getMembers();
+ String prevInstanceMemberName = MapUtils.invertMap(membersNameToId).get(prevInstanceId).toString();
+ membersNameToId.replace(prevInstanceMemberName, newInstanceId);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java
new file mode 100644
index 0000000000..8824b2e097
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperation.java
@@ -0,0 +1,67 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.function.UnaryOperator;
+
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+@org.springframework.stereotype.Component
+public class PolicyTargetsUpdateOperation implements PostChangeVersionOperation {
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyTargetsUpdateOperation.class);
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final ComponentsUtils componentsUtils;
+
+ public PolicyTargetsUpdateOperation(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.componentsUtils = componentsUtils;
+ }
+
+ @Override
+ public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ return replacePolicyTargetsInstanceId(container, prevVersion, newVersion);
+ }
+
+ private ActionStatus replacePolicyTargetsInstanceId(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ log.debug("#replacePolicyTargetsInstanceId - replacing all policy targets for component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId());
+ List<PolicyDefinition> policiesWithPrevInstanceAsTarget = container.resolvePoliciesByComponentInstanceTarget(prevVersion.getUniqueId());
+ if (isEmpty(policiesWithPrevInstanceAsTarget)) {
+ return ActionStatus.OK;
+ }
+ replaceTargetsPrevInstanceIdWithNewInstanceId(prevVersion, newVersion, policiesWithPrevInstanceAsTarget);
+ return updatePolicies(container, policiesWithPrevInstanceAsTarget);
+ }
+
+ private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) {
+ log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId());
+ StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
+ return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
+ }
+
+ private void replaceTargetsPrevInstanceIdWithNewInstanceId(ComponentInstance prevVersion, ComponentInstance newVersion, List<PolicyDefinition> policiesWithPrevInstanceAsTarget) {
+ policiesWithPrevInstanceAsTarget.forEach(policy -> updatePolicyTargetWithNewInstanceVersion(policy, prevVersion.getUniqueId(), newVersion.getUniqueId()));
+ }
+
+ private void updatePolicyTargetWithNewInstanceVersion(PolicyDefinition policyDefinition, String prevInstanceId, String newInstanceId) {
+ List<String> policyInstanceTargets = policyDefinition.resolveComponentInstanceTargets();
+ if (isEmpty(policyInstanceTargets)) {
+ return;
+ }
+ policyInstanceTargets.replaceAll(prevInstanceIdByNewInstanceId(prevInstanceId, newInstanceId));
+ }
+
+ private UnaryOperator<String> prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) {
+ return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java
new file mode 100644
index 0000000000..ee16c203bf
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperation.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+@FunctionalInterface
+public interface PostChangeVersionOperation {
+
+ ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion);
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java
new file mode 100644
index 0000000000..ee37536886
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestrator.java
@@ -0,0 +1,32 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+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.Iterator;
+import java.util.List;
+
+@org.springframework.stereotype.Component
+public class PostChangeVersionOperationOrchestrator {
+
+ private static final Logger log = LoggerFactory.getLogger(PostChangeVersionOperationOrchestrator.class);
+ private final List<PostChangeVersionOperation> postChangeVersionOperations;
+
+ public PostChangeVersionOperationOrchestrator(List<PostChangeVersionOperation> postChangeVersionOperations) {
+ this.postChangeVersionOperations = postChangeVersionOperations;
+ }
+
+ public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
+ log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
+ ActionStatus postOperationsResult = ActionStatus.OK;
+ Iterator<PostChangeVersionOperation> postChangeVersionIter = postChangeVersionOperations.iterator();
+ while(postChangeVersionIter.hasNext() && postOperationsResult == ActionStatus.OK) {
+ postOperationsResult = postChangeVersionIter.next().onChangeVersion(container, prevVersion, newVersion);
+ }
+ return postOperationsResult;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
index 47e494f66d..c229d87593 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
@@ -20,7 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.Arrays;
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
@@ -45,151 +45,151 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.Arrays;
public class CertificationChangeTransition extends LifeCycleTransition {
- private static Logger log = LoggerFactory.getLogger(CertificationChangeTransition.class.getName());
-
- private LifecycleStateEnum nextState;
- private LifeCycleTransitionEnum name;
- private AuditingActionEnum auditingAction;
- private ArtifactsBusinessLogic artifactsManager;
-
- public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
-
- this.name = name;
-
- // authorized roles
- Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER };
- addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles));
- addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles));
- // TODO to be later defined for product
-
- //additional authorized roles for resource type
- Role[] resourceRoles = { Role.DESIGNER};
- addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
-
- switch (this.name) {
- case CERTIFY:
- this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE;
- this.nextState = LifecycleStateEnum.CERTIFIED;
- break;
- case FAIL_CERTIFICATION:
- this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE;
- nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
- break;
- case CANCEL_CERTIFICATION:
- this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE;
- nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION;
- break;
- default:
- break;
- }
-
- }
-
- @Override
- public LifeCycleTransitionEnum getName() {
- return name;
- }
-
- @Override
- public AuditingActionEnum getAuditingAction() {
- return auditingAction;
- }
-
- public ArtifactsBusinessLogic getArtifactsManager() {
- return artifactsManager;
- }
-
- public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
- this.artifactsManager = artifactsManager;
- }
-
- private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph");
- log.debug("certification change failed on graph");
-
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- return responseFormat;
- }
-
- @Override
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
- String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
- // validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
- log.error("userRoleValidation failed");
- return userValidationResponse;
- }
-
- if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
- log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION);
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
- log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE);
- log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner);
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- return Either.left(true);
- }
-
- @Override
- public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
- log.info("start performing certification change for resource {}", component.getUniqueId());
- Either<? extends Component, ResponseFormat> result = null;
-
- try {
- Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
- if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
- certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
- } else {
- certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState);
- }
-
- if (certificationChangeResult.isRight()) {
- ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType);
- result = Either.right(responseFormat);
- return result;
- }
-
- if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
- component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID());
- if (deleteOldComponentVersions.isRight()) {
- ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType);
- result = Either.right(responseFormat);
- }
- }
-
- result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value()));
- return result;
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
- if (inTransaction == false) {
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- }
- } else {
- if (inTransaction == false) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- }
-
- }
+ private static final Logger log = LoggerFactory.getLogger(CertificationChangeTransition.class);
+
+ private LifecycleStateEnum nextState;
+ private LifeCycleTransitionEnum name;
+ private AuditingActionEnum auditingAction;
+ private ArtifactsBusinessLogic artifactsManager;
+
+ public CertificationChangeTransition(LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+
+ this.name = name;
+
+ // authorized roles
+ Role[] certificationChangeRoles = { Role.ADMIN, Role.TESTER };
+ addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(certificationChangeRoles));
+ addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles));
+ // TODO to be later defined for product
+
+ //additional authorized roles for resource type
+ Role[] resourceRoles = { Role.DESIGNER};
+ addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
+
+ switch (this.name) {
+ case CERTIFY:
+ this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE;
+ this.nextState = LifecycleStateEnum.CERTIFIED;
+ break;
+ case FAIL_CERTIFICATION:
+ this.auditingAction = AuditingActionEnum.FAIL_CERTIFICATION_RESOURCE;
+ nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
+ break;
+ case CANCEL_CERTIFICATION:
+ this.auditingAction = AuditingActionEnum.CANCEL_CERTIFICATION_RESOURCE;
+ nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION;
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ @Override
+ public LifeCycleTransitionEnum getName() {
+ return name;
+ }
+
+ @Override
+ public AuditingActionEnum getAuditingAction() {
+ return auditingAction;
+ }
+
+ public ArtifactsBusinessLogic getArtifactsManager() {
+ return artifactsManager;
+ }
+
+ public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
+ this.artifactsManager = artifactsManager;
+ }
+
+ private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph");
+ log.debug("certification change failed on graph");
+
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ return responseFormat;
+ }
+
+ @Override
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+
+ // validate user
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ log.error("userRoleValidation failed");
+ return userValidationResponse;
+ }
+
+ if (!oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
+ log.error("oldState={} should be={}",oldState,ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION);
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ log.error("oldState={} should not be={}",oldState,ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE);
+ log.error("&& modifier({})!={} && modifier.role({})!={}",modifier,owner);
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ return Either.left(true);
+ }
+
+ @Override
+ public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+
+ log.info("start performing certification change for resource {}", component.getUniqueId());
+ Either<? extends Component, ResponseFormat> result = null;
+
+ try {
+ Either<ToscaElement, StorageOperationStatus> certificationChangeResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
+ if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
+ certificationChangeResult = lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+ } else {
+ certificationChangeResult = lifeCycleOperation.cancelOrFailCertification(component.getUniqueId(), modifier.getUserId(), owner.getUserId(), nextState);
+ }
+
+ if (certificationChangeResult.isRight()) {
+ ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType);
+ result = Either.right(responseFormat);
+ return result;
+ }
+
+ if (nextState.equals(LifecycleStateEnum.CERTIFIED)) {
+ Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifeCycleOperation.deleteOldToscaElementVersions(ModelConverter.getVertexType(component), componentType, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
+ component.getComponentMetadataDefinition().getMetadataDataDefinition().getUUID());
+ if (deleteOldComponentVersions.isRight()) {
+ ResponseFormat responseFormat = formatCertificationError(component, deleteOldComponentVersions.right().value(), componentType);
+ result = Either.right(responseFormat);
+ }
+ }
+
+ result = Either.left(ModelConverter.convertFromToscaElement(certificationChangeResult.left().value()));
+ return result;
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ }
+
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
index 4a7f446739..dfd7beeaf1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
@@ -35,21 +28,11 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
-import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
@@ -63,289 +46,257 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.*;
public class CertificationRequestTransition extends LifeCycleTransition {
- private static Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class.getName());
-
- private CapabilityOperation capabilityOperation;
- private ServiceBusinessLogic serviceBusinessLogic;
- public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
- CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
-
- // authorized roles
- Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
- // Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER,
- // Role.PRODUCT_STRATEGIST};
- addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
- // TODO to be later defined for product
- // addAuthorizedRoles(ComponentTypeEnum.PRODUCT,
- // Arrays.asList(productCheckoutRoles));
-
- //additional authorized roles for resource type
- Role[] resourceRoles = { Role.TESTER};
- addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
-
- this.serviceBusinessLogic = serviceBusinessLogic;
- this.capabilityOperation = capabilityOperation;
- }
-
- @Override
- public LifeCycleTransitionEnum getName() {
- return LifeCycleTransitionEnum.CERTIFICATION_REQUEST;
- }
-
- @Override
- public AuditingActionEnum getAuditingAction() {
- return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE;
- }
-
- protected Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) {
- Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-
- List<ComponentInstance> resourceInstance = component.getComponentInstances();
- if (resourceInstance != null) {
- Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny();
- // Uncertified Resource Found
- if (nonCertifiedRIOptional.isPresent()) {
- ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get();
- ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType());
- eitherResult = Either.right(resFormat);
- }
- }
- return eitherResult;
- }
-
- private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
-
- ResponseFormat responseFormat;
- Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
- if (eitherResource.isRight()) {
-
- responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-
- } else {
- ActionStatus actionStatus;
- Resource resource = eitherResource.left().value();
- Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
-
- if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
- if (status.isRight() || status.left().value() == null) {
- actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND;
- } else {
- actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
- }
- } else {
- if (status.isRight() || status.left().value() == null)
- actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES;
- else {
- actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
- }
-
- }
- String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service";
- responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName());
- }
- return responseFormat;
- }
-
- private Either<ActionStatus, Map<String, ArtifactDefinition>> validateMandatoryArtifactsSupplied(Map<String, ArtifactDefinition> artifacts) {
-
- if (artifacts == null || artifacts.isEmpty()) {
- return Either.left(ActionStatus.OK);
- }
-
- Map<String, ArtifactDefinition> invalidArtifacts = new HashMap<>();
- for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
-
- ArtifactDefinition artifactDefinition = artifact.getValue();
- if (artifactDefinition.getMandatory()) {
- String artifactEsId = artifactDefinition.getEsId();
- if (artifactEsId == null || artifactEsId.isEmpty()) {
- invalidArtifacts.put(artifact.getKey(), artifactDefinition);
- }
- }
- }
-
- if (invalidArtifacts.isEmpty()) {
- return Either.left(ActionStatus.OK);
- } else {
- return Either.right(invalidArtifacts);
- }
- }
-
- @Override
- public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
- log.debug("start performing certification request for resource {}", component.getUniqueId());
-
- ActionStatus actionStatus;
- ResponseFormat responseFormat;
- Either<? extends Component, ResponseFormat> result = null;
- try{
- if (component.getToscaType().equals(ToscaElementTypeEnum.TopologyTemplate.getValue())) {
-
- Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
- if (statusCert.isRight()) {
- return Either.right(statusCert.right().value());
- }
-
- statusCert = validateConfiguredAtomicReqCapSatisfied(component);
- if (statusCert.isRight()) {
- return Either.right(statusCert.right().value());
- }
- }
- if (componentType == ComponentTypeEnum.SERVICE) {
-
- Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock);
-
- if (generateHeatEnvResult.isRight()) {
- return Either.right(generateHeatEnvResult.right().value());
- }
- Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts((Service) component, modifier, shouldLock);
- if (generateVfModuleResult.isRight()) {
- return Either.right(generateVfModuleResult.right().value());
- }
- }
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
- if (eitherPopulated != null && eitherPopulated.isRight()) {
- return Either.right(eitherPopulated.right().value());
- }
-
- NodeTypeEnum nodeType = componentType.equals(ComponentTypeEnum.SERVICE) ? NodeTypeEnum.Service : NodeTypeEnum.Resource;
-
-
- Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
- if (certificationRequestResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = certificationRequestResult.right().value();
- actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
- }
- responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- }
- else {
- result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value()));
- }
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
- if (!inTransaction) {
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- }
- } else {
- if (!inTransaction) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- }
- return result;
- }
-
- private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) {
- log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId());
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null) {
- // Prepare relationships data structures
- // Better make it list than set in case we need to count req/cap
- // occurrences in the future
- Map<String, List<String>> reqName2Ids = new HashMap<>();
- Map<String, List<String>> capName2Ids = new HashMap<>();
-// Either<Boolean, ResponseFormat> parseRelationsForReqCapVerificationRes = parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids);
-// if(parseRelationsForReqCapVerificationRes.isRight()){
-// return parseRelationsForReqCapVerificationRes;
-// }
- Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert();
- Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert();
- for (ComponentInstance compInst : componentInstances) {
- String compInstId = compInst.getUniqueId();
- OriginTypeEnum originType = compInst.getOriginType();
- if (originType == null) {
- log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId());
- continue;
- }
- String compInstType = originType.getValue();
- // Validating configured requirements fulfilled
- if (null != requirementsToFulfillBeforeCert) {
- Set<String> reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType);
- if (reqToFulfillForType != null) {
- for (String reqNameToFulfill : reqToFulfillForType) {
- List<String> reqNameList = reqName2Ids.get(reqNameToFulfill);
- if (reqNameList == null || !reqNameList.contains(compInstId)) {
- log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType);
- ComponentTypeEnum componentType = component.getComponentType();
- String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
- ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement",
- reqNameToFulfill, "fulfilled");
- return Either.right(responseFormat);
- }
- }
- }
- }
- // Validating configured capabilities consumed
- if (null != capabilitiesToConsumeBeforeCert) {
- Set<String> capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType);
- if (capToConsumeForType != null) {
- for (String capNameToConsume : capToConsumeForType) {
- List<String> capNameList = capName2Ids.get(capNameToConsume);
- if (capNameList == null || !capNameList.contains(compInstId)) {
- log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType);
- ComponentTypeEnum componentType = component.getComponentType();
- String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
- ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability",
- capNameToConsume, "consumed");
- return Either.right(responseFormat);
- }
- }
- }
- }
- }
- }
- log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId());
- return Either.left(true);
- }
-
- @Override
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
- String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
- // validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
- return userValidationResponse;
- }
-
- // case of "atomic" checkin and certification request - modifier must be
- // the owner
- if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- // other states
- if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
- if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
- if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- return Either.left(true);
- }
+ private static final Logger log = LoggerFactory.getLogger(CertificationRequestTransition.class);
+
+ private CapabilityOperation capabilityOperation;
+ private ServiceBusinessLogic serviceBusinessLogic;
+ public CertificationRequestTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder, ServiceBusinessLogic serviceBusinessLogic,
+ CapabilityOperation capabilityOperation, ToscaExportHandler toscaExportUtils, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+
+ // authorized roles
+ Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
+ addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
+ // TODO to be later defined for product
+ // addAuthorizedRoles(ComponentTypeEnum.PRODUCT,
+ // Arrays.asList(productCheckoutRoles));
+
+ //additional authorized roles for resource type
+ Role[] resourceRoles = { Role.TESTER};
+ addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
+
+ this.serviceBusinessLogic = serviceBusinessLogic;
+ this.capabilityOperation = capabilityOperation;
+ }
+
+ @Override
+ public LifeCycleTransitionEnum getName() {
+ return LifeCycleTransitionEnum.CERTIFICATION_REQUEST;
+ }
+
+ @Override
+ public AuditingActionEnum getAuditingAction() {
+ return AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE;
+ }
+
+ protected Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) {
+ Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+
+ List<ComponentInstance> resourceInstance = component.getComponentInstances();
+ if (resourceInstance != null) {
+ Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny();
+ // Uncertified Resource Found
+ if (nonCertifiedRIOptional.isPresent()) {
+ ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get();
+ ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType());
+ eitherResult = Either.right(resFormat);
+ }
+ }
+ return eitherResult;
+ }
+
+ private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
+
+ ResponseFormat responseFormat;
+ Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
+ if (eitherResource.isRight()) {
+
+ responseFormat = componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+
+ } else {
+ ActionStatus actionStatus;
+ Resource resource = eitherResource.left().value();
+ Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
+
+ if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
+ if (status.isRight() || status.left().value() == null) {
+ actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND;
+ } else {
+ actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
+ }
+ } else {
+ if (status.isRight() || status.left().value() == null)
+ actionStatus = ActionStatus.FOUND_LIST_VALIDATED_RESOURCES;
+ else {
+ actionStatus = ActionStatus.FOUND_ALREADY_VALIDATED_RESOURCE;
+ }
+
+ }
+ String compType = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : "service";
+ responseFormat = componentUtils.getResponseFormat(actionStatus, compType, resource.getName());
+ }
+ return responseFormat;
+ }
+
+ @Override
+ public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+
+ log.debug("start performing certification request for resource {}", component.getUniqueId());
+
+ ActionStatus actionStatus;
+ ResponseFormat responseFormat;
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ if (component.isTopologyTemplate()) {
+
+ Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
+ if (statusCert.isRight()) {
+ return Either.right(statusCert.right().value());
+ }
+
+ statusCert = validateConfiguredAtomicReqCapSatisfied(component);
+ if (statusCert.isRight()) {
+ return Either.right(statusCert.right().value());
+ }
+ }
+ if (componentType == ComponentTypeEnum.SERVICE) {
+
+ Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction);
+
+ if (generateHeatEnvResult.isRight()) {
+ return Either.right(generateHeatEnvResult.right().value());
+ }
+ Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction);
+ if (generateVfModuleResult.isRight()) {
+ return Either.right(generateVfModuleResult.right().value());
+ }
+ component = generateVfModuleResult.left().value();
+
+ }
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
+ if (eitherPopulated != null && eitherPopulated.isRight()) {
+ return Either.right(eitherPopulated.right().value());
+ }
+
+ Either<ToscaElement, StorageOperationStatus> certificationRequestResult = lifeCycleOperation.requestCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+ if (certificationRequestResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = certificationRequestResult.right().value();
+ actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(certificationRequestResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (!inTransaction) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (!inTransaction) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ }
+ return result;
+ }
+
+ private Either<Boolean, ResponseFormat> validateConfiguredAtomicReqCapSatisfied(Component component) {
+ log.debug("Submit for testing validation - Start validating configured req/cap satisfied for inner atomic instances, component id:{}", component.getUniqueId());
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (componentInstances != null) {
+ // Prepare relationships data structures
+ // Better make it list than set in case we need to count req/cap
+ // occurrences in the future
+ Map<String, List<String>> reqName2Ids = new HashMap<>();
+ Map<String, List<String>> capName2Ids = new HashMap<>();
+ Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert();
+ Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert();
+ for (ComponentInstance compInst : componentInstances) {
+ String compInstId = compInst.getUniqueId();
+ OriginTypeEnum originType = compInst.getOriginType();
+ if (originType == null) {
+ log.error("Origin type is not set for component instance {} - it shouldn't happen. Skipping this component instance...", compInst.getUniqueId());
+ continue;
+ }
+ String compInstType = originType.getValue();
+ // Validating configured requirements fulfilled
+ if (null != requirementsToFulfillBeforeCert) {
+ Set<String> reqToFulfillForType = requirementsToFulfillBeforeCert.get(compInstType);
+ if (reqToFulfillForType != null) {
+ for (String reqNameToFulfill : reqToFulfillForType) {
+ List<String> reqNameList = reqName2Ids.get(reqNameToFulfill);
+ if (reqNameList == null || !reqNameList.contains(compInstId)) {
+ log.debug("Requirement {} wasn't fulfilled for component instance {} of type {}", reqNameToFulfill, compInstId, compInstType);
+ ComponentTypeEnum componentType = component.getComponentType();
+ String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
+ ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "requirement",
+ reqNameToFulfill, "fulfilled");
+ return Either.right(responseFormat);
+ }
+ }
+ }
+ }
+ // Validating configured capabilities consumed
+ if (null != capabilitiesToConsumeBeforeCert) {
+ Set<String> capToConsumeForType = capabilitiesToConsumeBeforeCert.get(compInstType);
+ if (capToConsumeForType != null) {
+ for (String capNameToConsume : capToConsumeForType) {
+ List<String> capNameList = capName2Ids.get(capNameToConsume);
+ if (capNameList == null || !capNameList.contains(compInstId)) {
+ log.debug("Capability {} wasn't consumed for component instance {} of type {}", capNameToConsume, compInstId, compInstType);
+ ComponentTypeEnum componentType = component.getComponentType();
+ String compParam = (componentType == ComponentTypeEnum.RESOURCE) ? "VF" : componentType.getValue().toLowerCase();
+ ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, component.getName(), compParam, originType.getDisplayValue(), compInst.getName(), "capability",
+ capNameToConsume, "consumed");
+ return Either.right(responseFormat);
+ }
+ }
+ }
+ }
+ }
+ }
+ log.debug("Submit for testing validation - validating configured req/cap satisfied for inner atomic instances finished successfully, component id:{}", component.getUniqueId());
+ return Either.left(true);
+ }
+
+ @Override
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ log.debug("validate before certification request. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+
+ // validate user
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ return userValidationResponse;
+ }
+
+ // case of "atomic" checkin and certification request - modifier must be
+ // the owner
+ if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ // other states
+ if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+ if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+ if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ return Either.left(true);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
index bfe51ded48..0d9631e6ee 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
@@ -20,8 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.Arrays;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -43,106 +42,106 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.Arrays;
public class CheckinTransition extends LifeCycleTransition {
- private static Logger log = LoggerFactory.getLogger(CheckinTransition.class.getName());
-
- public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
-
- // authorized roles
- Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
- Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
- addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
-
- }
-
- @Override
- public LifeCycleTransitionEnum getName() {
- return LifeCycleTransitionEnum.CHECKIN;
- }
-
- @Override
- public AuditingActionEnum getAuditingAction() {
- return AuditingActionEnum.CHECKIN_RESOURCE;
- }
-
- @Override
- public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
- log.debug("start performing checkin for {} {}", componentType.name(), component.getUniqueId());
-
- Either<? extends Component, ResponseFormat> result = null;
- try{
- Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation.
- checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId());
-
- if (checkinResourceResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = checkinResourceResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
- }
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- }
- else {
- result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value()));
- }
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
- if (inTransaction == false) {
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- }
- } else {
- if (inTransaction == false) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- }
- return result;
- }
-
- @Override
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
- String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
- // validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
- return userValidationResponse;
- }
-
- if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN;
- if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){
- action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION;
- } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){
- action = ActionStatus.COMPONENT_ALREADY_CERTIFIED;
- }
- ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- return Either.left(true);
- }
+ private static final Logger log = LoggerFactory.getLogger(CheckinTransition.class);
+
+ public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+
+ // authorized roles
+ Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
+ Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
+ addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
+
+ }
+
+ @Override
+ public LifeCycleTransitionEnum getName() {
+ return LifeCycleTransitionEnum.CHECKIN;
+ }
+
+ @Override
+ public AuditingActionEnum getAuditingAction() {
+ return AuditingActionEnum.CHECKIN_RESOURCE;
+ }
+
+ @Override
+ public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+ log.debug("start performing checkin for {} {}", componentType, component.getUniqueId());
+
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation.
+ checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+
+ if (checkinResourceResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = checkinResourceResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(checkinResourceResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+
+ // validate user
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ return userValidationResponse;
+ }
+
+ if (!oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
+ ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN;
+ if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)){
+ action = ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION;
+ } else if (oldState.equals(LifecycleStateEnum.CERTIFIED)){
+ action = ActionStatus.COMPONENT_ALREADY_CERTIFIED;
+ }
+ ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) && !modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ return Either.left(true);
+ }
}
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 b7983b1174..e5afcaeae5 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
@@ -20,9 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.Arrays;
-import java.util.List;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -32,11 +30,7 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.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.*;
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;
@@ -49,148 +43,149 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
public class CheckoutTransition extends LifeCycleTransition {
- private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName());
-
- public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
-
- // authorized roles
- Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
- Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
- addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
-
- }
-
- @Override
- public LifeCycleTransitionEnum getName() {
- return LifeCycleTransitionEnum.CHECKOUT;
- }
-
- @Override
- public AuditingActionEnum getAuditingAction() {
- return AuditingActionEnum.CHECKOUT_RESOURCE;
- }
-
- @Override
- public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
- log.debug("start performing {} for resource {}", getName().name(), component.getUniqueId());
-
- Either<? extends Component, ResponseFormat> result = null;
- try {
-
- Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
-
- if (checkoutResourceResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = checkoutResourceResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
- }
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- } else {
-
- Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value());
- if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){
- Either<Component, ActionStatus> upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent);
- if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){
- result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value()));
- return result;
- }
- if ( upgradeToLatestDerived.isLeft() ){
- //get resource after update derived
- clonedComponent = upgradeToLatestDerived.left().value();
- }
- }
- result = Either.left(clonedComponent);
- Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent);
- if (upgradeToLatestGeneric.isRight())
- result = Either.right(upgradeToLatestGeneric.right().value());
- else if (upgradeToLatestGeneric.left().value() ) {
- StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent);
- if (StorageOperationStatus.OK != response) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- }
- }
-
- }
-
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
- if (inTransaction == false) {
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- }
- } else {
- if (inTransaction == false) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- }
- return result;
- }
-
- private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
-
- StorageOperationStatus updateStatus = StorageOperationStatus.OK;
- Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent);
- if (updateEither.isRight())
- updateStatus = updateEither.right().value();
- else if (clonedComponent.shouldGenerateInputs()) {
- List<InputDefinition> newInputs = clonedComponent.getInputs();
- updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME);
- }
- return updateStatus;
- }
-
- @Override
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
- String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
- // validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
- return userValidationResponse;
- }
-
- // Disabled as of 1604 patch after discussing with Ella/Eli/Michael
-
- /*
- * if (componentType == ComponentTypeEnum.PRODUCT){ Either<Boolean, ResponseFormat> productContactsEither = productContactsValidation((Product)component, modifier); if (productContactsEither.isRight()){ return productContactsEither; } }
- */
-
- // check resource is not locked by another user
- if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
- if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
- }
- return Either.left(true);
- }
+ private static final Logger log = LoggerFactory.getLogger(CheckoutTransition.class);
+
+ public CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+
+ // authorized roles
+ Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
+ Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
+ addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
+
+ }
+
+ @Override
+ public LifeCycleTransitionEnum getName() {
+ return LifeCycleTransitionEnum.CHECKOUT;
+ }
+
+ @Override
+ public AuditingActionEnum getAuditingAction() {
+ return AuditingActionEnum.CHECKOUT_RESOURCE;
+ }
+
+ @Override
+ public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+
+ log.debug("start performing {} for resource {}", getName(), component.getUniqueId());
+
+ Either<? extends Component, ResponseFormat> result = null;
+ try {
+
+ Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+
+ if (checkoutResourceResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = checkoutResourceResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ } else {
+
+ Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value());
+ if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NodeType ){
+ Either<Component, ActionStatus> upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent);
+ if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){
+ result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value()));
+ return result;
+ }
+ if ( upgradeToLatestDerived.isLeft() ){
+ //get resource after update derived
+ clonedComponent = upgradeToLatestDerived.left().value();
+ }
+ }
+ result = Either.left(clonedComponent);
+ Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent);
+ if (upgradeToLatestGeneric.isRight())
+ result = Either.right(upgradeToLatestGeneric.right().value());
+ else if (upgradeToLatestGeneric.left().value() ) {
+ StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent);
+ if (StorageOperationStatus.OK != response) {
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ }
+
+ }
+
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ }
+ return result;
+ }
+
+ private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
+
+ StorageOperationStatus updateStatus = StorageOperationStatus.OK;
+ Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent);
+ if (updateEither.isRight())
+ updateStatus = updateEither.right().value();
+ else if (clonedComponent.shouldGenerateInputs()) {
+ List<InputDefinition> newInputs = clonedComponent.getInputs();
+ updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME);
+ }
+ return updateStatus;
+ }
+
+ @Override
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+
+ // validate user
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ return userValidationResponse;
+ }
+
+ // Disabled as of 1604 patch after discussing with Ella/Eli/Michael
+
+ /*
+ * if (componentType == ComponentTypeEnum.PRODUCT){ Either<Boolean, ResponseFormat> productContactsEither = productContactsValidation((Product)component, modifier); if (productContactsEither.isRight()){ return productContactsEither; } }
+ */
+
+ // check resource is not locked by another user
+ if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
+ if (!modifier.getRole().equals(Role.DESIGNER.name()) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+ }
+ return Either.left(true);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
index 87e8175960..4270295e36 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
@@ -20,10 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -45,130 +42,129 @@ import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public abstract class LifeCycleTransition {
- protected ConfigurationManager configurationManager;
- @Autowired
- protected ToscaElementLifecycleOperation lifeCycleOperation;
- @Autowired
- protected TitanDao titanDao;
- protected ComponentsUtils componentUtils;
-
- protected Map<ComponentTypeEnum, List<Role>> authorizedRoles;
- protected Map<ResourceTypeEnum, List<Role>> resourceAuthorizedRoles;
-
- ToscaOperationFacade toscaOperationFacade;
-
- protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
-
- this.configurationManager = ConfigurationManager.getConfigurationManager();
- this.lifeCycleOperation = lifecycleOperation2;
- this.componentUtils = componentUtils;
- this.authorizedRoles = new HashMap<>();
- this.resourceAuthorizedRoles = new HashMap<>();
- this.toscaOperationFacade = toscaOperationFacade;
- this.titanDao = titanDao;
- }
-
- public abstract LifeCycleTransitionEnum getName();
-
- public abstract AuditingActionEnum getAuditingAction();
-
- public ConfigurationManager getConfigurationManager() {
- return configurationManager;
- }
-
- public void setConfigurationManager(ConfigurationManager configurationManager) {
- this.configurationManager = configurationManager;
- }
-
- public ToscaElementLifecycleOperation getLifeCycleOperation() {
- return lifeCycleOperation;
- }
-
- public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) {
- this.lifeCycleOperation = lifeCycleOperation;
- }
-
- public List<Role> getAuthorizedRoles(ComponentTypeEnum componentType) {
- return authorizedRoles.get(componentType);
- }
-
- public void addAuthorizedRoles(ComponentTypeEnum componentType, List<Role> authorizedRoles) {
- this.authorizedRoles.put(componentType, authorizedRoles);
- }
-
- public List<Role> getResourceAuthorizedRoles(ResourceTypeEnum resourceType) {
- return resourceAuthorizedRoles.get(resourceType);
- }
-
- public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List<Role> authorizedRoles) {
- this.resourceAuthorizedRoles.put(resourceType, authorizedRoles);
- }
-
- public abstract Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction);
-
- public abstract Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo);
-
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) {
-
- return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null);
- }
-
- /**
- * getComponentOwner
- *
- * @param resource
- * @return
- */
- protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType) {
-
- return getComponentOwner(component, componentType, false);
- }
-
- protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) {
-
- Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId());
- if (resourceOwnerResult.isRight()) {
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType);
- return Either.right(responseFormat);
- }
- return Either.left(resourceOwnerResult.left().value());
- }
-
- protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
-
- // validate user
- //first check the user for the component and then for the resource
- if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) {
- return Either.left(true);
- }
- // this is only used in 2 cases
- //1. when creating vfc/cp when import vf from csar - when we
- // create resources from node type, we create need to change the state
- // to certified
- //2. certification flow upno upgrade migration
- if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) {
- return Either.left(true);
- }
-
- ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- return Either.right(responseFormat);
- }
-
- protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) {
- if (componentType.equals(ComponentTypeEnum.RESOURCE)){
- ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
- if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) {
- return true;
- }
- } else {
- return false;
- }
-
- return false;
- }
+ protected ConfigurationManager configurationManager;
+ @Autowired
+ protected ToscaElementLifecycleOperation lifeCycleOperation;
+ @Autowired
+ protected TitanDao titanDao;
+ protected ComponentsUtils componentUtils;
+
+ protected Map<ComponentTypeEnum, List<Role>> authorizedRoles;
+ protected Map<ResourceTypeEnum, List<Role>> resourceAuthorizedRoles;
+
+ ToscaOperationFacade toscaOperationFacade;
+
+ protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+
+ this.configurationManager = ConfigurationManager.getConfigurationManager();
+ this.lifeCycleOperation = lifecycleOperation2;
+ this.componentUtils = componentUtils;
+ this.authorizedRoles = new HashMap<>();
+ this.resourceAuthorizedRoles = new HashMap<>();
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.titanDao = titanDao;
+ }
+
+ public abstract LifeCycleTransitionEnum getName();
+
+ public abstract AuditingActionEnum getAuditingAction();
+
+ public ConfigurationManager getConfigurationManager() {
+ return configurationManager;
+ }
+
+ public void setConfigurationManager(ConfigurationManager configurationManager) {
+ this.configurationManager = configurationManager;
+ }
+
+ public ToscaElementLifecycleOperation getLifeCycleOperation() {
+ return lifeCycleOperation;
+ }
+
+ public void setLifeCycleOperation(ToscaElementLifecycleOperation lifeCycleOperation) {
+ this.lifeCycleOperation = lifeCycleOperation;
+ }
+
+ public List<Role> getAuthorizedRoles(ComponentTypeEnum componentType) {
+ return authorizedRoles.get(componentType);
+ }
+
+ public void addAuthorizedRoles(ComponentTypeEnum componentType, List<Role> authorizedRoles) {
+ this.authorizedRoles.put(componentType, authorizedRoles);
+ }
+
+ public List<Role> getResourceAuthorizedRoles(ResourceTypeEnum resourceType) {
+ return resourceAuthorizedRoles.get(resourceType);
+ }
+
+ public void addResouceAuthorizedRoles(ResourceTypeEnum resourceType, List<Role> authorizedRoles) {
+ this.resourceAuthorizedRoles.put(resourceType, authorizedRoles);
+ }
+
+ public abstract Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean needLock, boolean inTransaction);
+
+ public abstract Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo);
+
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) {
+
+ return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null);
+ }
+
+ /**
+ * getComponentOwner
+ *
+ * @param resource
+ * @return
+ */
+ protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType) {
+
+ return getComponentOwner(component, componentType, false);
+ }
+
+ protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType, boolean inTransaction) {
+
+ Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId());
+ if (resourceOwnerResult.isRight()) {
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType);
+ return Either.right(responseFormat);
+ }
+ return Either.left(resourceOwnerResult.left().value());
+ }
+
+ protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+
+ // validate user
+ //first check the user for the component and then for the resource
+ if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) {
+ return Either.left(true);
+ }
+ // this is only used in 2 cases
+ //1. when creating vfc/cp when import vf from csar - when we
+ // create resources from node type, we create need to change the state
+ // to certified
+ //2. certification flow upno upgrade migration
+ if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) {
+ return Either.left(true);
+ }
+
+ ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ return Either.right(responseFormat);
+ }
+
+ protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) {
+ if (componentType.equals(ComponentTypeEnum.RESOURCE)){
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
index e478bc6924..75b0bd934a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
@@ -20,12 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.annotation.PostConstruct;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
@@ -33,7 +28,6 @@ import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
@@ -56,414 +50,399 @@ import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
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.ValidationUtils;
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;
+import javax.annotation.PostConstruct;
+import java.util.HashMap;
+import java.util.Map;
@org.springframework.stereotype.Component("lifecycleBusinessLogic")
public class LifecycleBusinessLogic {
- private static final String COMMENT = "comment";
+ private static final String COMMENT = "comment";
+
+ @Autowired
+ private IGraphLockOperation graphLockOperation = null;
+
+ @Autowired
+ private ArtifactsBusinessLogic artifactsBusinessLogic;
+
+ @Autowired
+ private TitanDao titanDao;
+
+ @Autowired
+ private CapabilityOperation capabilityOperation;
+
+ private static final Logger log = LoggerFactory.getLogger(LifecycleBusinessLogic.class);
- @Autowired
- private IGraphLockOperation graphLockOperation = null;
+ @javax.annotation.Resource
+ private ComponentsUtils componentUtils;
- @Autowired
- private ArtifactsBusinessLogic artifactsBusinessLogic;
+ @javax.annotation.Resource
+ private ToscaElementLifecycleOperation lifecycleOperation;
+ @javax.annotation.Resource
+ ArtifactsBusinessLogic artifactsManager;
- @Autowired
- private TitanDao titanDao;
+ @javax.annotation.Resource
+ private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
- @Autowired
- private CapabilityOperation capabilityOperation;
+ @javax.annotation.Resource
+ private ServiceBusinessLogic serviceBusinessLogic;
- private static Logger log = LoggerFactory.getLogger(LifecycleBusinessLogic.class.getName());
+ @javax.annotation.Resource
+ private ResourceBusinessLogic resourceBusinessLogic;
- @javax.annotation.Resource
- private ComponentsUtils componentUtils;
+ @javax.annotation.Resource
+ private ProductBusinessLogic productBusinessLogic;
- @javax.annotation.Resource
- private ToscaElementLifecycleOperation lifecycleOperation;
- @javax.annotation.Resource
- ArtifactsBusinessLogic artifactsManager;
-
- @javax.annotation.Resource
- private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
-
- @javax.annotation.Resource
- private ServiceBusinessLogic serviceBusinessLogic;
-
- @javax.annotation.Resource
- private ResourceBusinessLogic resourceBusinessLogic;
-
- @javax.annotation.Resource
- private ProductBusinessLogic productBusinessLogic;
-
- @Autowired
- private ToscaExportHandler toscaExportUtils;
-
- @Autowired
- ICacheMangerOperation cacheManagerOperation;
-
- @Autowired
- ToscaOperationFacade toscaOperationFacade;
-
- private Map<String, LifeCycleTransition> stateTransitions;
- private static volatile boolean isInitialized = false;
-
- @PostConstruct
- public void init() {
- // init parameters
- if (!isInitialized) {
- synchronized (this) {
- if (!isInitialized) {
- initStateOperations();
- isInitialized = true;
- }
- }
- }
- }
-
- private void initStateOperations() {
- stateTransitions = new HashMap<String, LifeCycleTransition>();
-
- LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- stateTransitions.put(checkoutOp.getName().name(), checkoutOp);
-
- UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic);
- stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp);
-
- LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- stateTransitions.put(checkinOp.getName().name(), checkinOp);
-
- LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
- stateTransitions.put(certificationRequest.getName().name(), certificationRequest);
-
- LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- stateTransitions.put(startCertification.getName().name(), startCertification);
-
- LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- stateTransitions.put(failCertification.getName().name(), failCertification);
-
- LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- stateTransitions.put(cancelCertification.getName().name(), cancelCertification);
-
- CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
- successCertification.setArtifactsManager(artifactsBusinessLogic);
- stateTransitions.put(successCertification.getName().name(), successCertification);
- }
-
- public LifeCycleTransition getLifecycleTransition(LifeCycleTransitionEnum transitionEnum) {
- return stateTransitions.get(transitionEnum.name());
- }
-
- public Either<Service, ResponseFormat> changeServiceState(String serviceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
- return (Either<Service, ResponseFormat>) changeComponentState(ComponentTypeEnum.SERVICE, serviceId, modifier, transitionEnum, changeInfo, inTransaction, needLock);
- }
-
- // TODO: rhalili - should use changeComponentState when possible
- public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
- return (Either<Resource, ResponseFormat>) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock);
- }
-
- private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){
- if (componentType.equals(ComponentTypeEnum.RESOURCE)){
- ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
- if (resourceType.equals(ResourceTypeEnum.VFCMT)){
- return true;
- }
- }
- return false;
- }
-
- public Either<? extends Component, ResponseFormat> changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
- boolean needLock) {
-
- LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name());
- if (lifeCycleTransition == null) {
- log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
- ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE);
- return Either.right(error);
- }
- Component component = null;
- log.info("get resource from graph");
- ResponseFormat errorResponse;
-
- Either<? extends Component, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo);
- if (eitherResourceResponse.isRight()) {
- return eitherResourceResponse;
- }
- component = eitherResourceResponse.left().value();
- String resourceCurrVersion = component.getVersion();
- LifecycleStateEnum resourceCurrState = component.getLifecycleState();
-
- // lock resource
- if (!inTransaction && needLock) {
- log.info("lock component {}", componentId);
- Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component);
- if (eitherLockResource.isRight()) {
- errorResponse = eitherLockResource.right().value();
- componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, null);
- log.error("lock component {} failed", componentId);
- return Either.right(errorResponse);
- }
- log.debug("after lock component {}", componentId);
- }
- try {
- Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum);
- if (commentValidationResult.isRight()) {
- errorResponse = commentValidationResult.right().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
- componentUtils.auditComponent(errorResponse, modifier, component, resourceCurrState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
- return Either.right(errorResponse);
- }
- changeInfo.setUserRemarks(commentValidationResult.left().value());
- log.debug("after validate component");
- Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType);
- if (validateHighestVersion.isRight()) {
- return Either.right(validateHighestVersion.right().value());
- }
- log.debug("after validate Highest Version");
- if (isComponentVFCMT(component,componentType)){
- Either<? extends Component, ResponseFormat> changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, inTransaction, component);
- if (changeVFCMTStateResponse.isRight()){
- return changeVFCMTStateResponse;
- }
- }
-
- return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction);
- } finally {
- component.setUniqueId(componentId);
- if (!inTransaction && needLock) {
- log.info("unlock component {}", componentId);
- NodeTypeEnum nodeType = componentType.getNodeType();
- log.info("During change state, another component {} has been created/updated", componentId);
- graphLockOperation.unlockComponent(componentId, nodeType);
-
- }
- }
-
- }
-
- /*
- * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin
- * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400
- */
- private Either<? extends Component, ResponseFormat> changeVFCMTState(ComponentTypeEnum componentType, User modifier,
- LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
- Component component) {
- LifecycleStateEnum oldState = component.getLifecycleState();
- if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) ||
- transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){
- return Either.right(componentUtils.getResponseFormat(
- ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName()));
- } //certify is done directly from checkin
- else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){
- //we will call for submit for testing first and then for certify
- Either<? extends Component, ResponseFormat> actionResponse = changeState(component,
- stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()),
- componentType, modifier, changeInfo, inTransaction);
- if (actionResponse.isRight()) {
- return actionResponse;
- }
- actionResponse = changeState(component,
- stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()),
- componentType, modifier, changeInfo, inTransaction);
- if (actionResponse.isRight()) {
- return actionResponse;
- }
- }
- return Either.left(null);
- }
-
- private Either<? extends Component, ResponseFormat> changeState(Component component, LifeCycleTransition lifeCycleTransition,
- ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){
- ResponseFormat errorResponse;
-
- LifecycleStateEnum oldState = component.getLifecycleState();
- String resourceCurrVersion = component.getVersion();
- ComponentBusinessLogic bl = getComponentBL(componentType);
-
- Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction);
- if (ownerResult.isRight()) {
- return Either.right(ownerResult.right().value());
- }
- User owner = ownerResult.left().value();
- log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId());
-
- Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
- if (stateValidationResult.isRight()) {
- log.error("Failed to validateBeforeTransition");
- errorResponse = stateValidationResult.right().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
- componentUtils.auditComponent(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
- return Either.right(errorResponse);
- }
-
- Either<? extends Component, ResponseFormat> operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction);
-
- if (operationResult.isRight()) {
- errorResponse = operationResult.right().value();
- log.info("audit before sending error response");
- componentUtils.auditComponentAdmin(errorResponse, modifier, component, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType);
-
- return Either.right(errorResponse);
- }
- Component resourceAfterOperation = operationResult.left().value();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
- componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, oldState.name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
- return operationResult;
-
- }
-
- private Either<? extends Component, ResponseFormat> getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) {
-
- Either<? extends Component, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId);
-
- ResponseFormat errorResponse;
- if (eitherResourceResponse.isRight()) {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
- errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
- log.debug("audit before sending response");
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, changeInfo.getUserRemarks());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentId);
- componentUtils.auditComponent(errorResponse, modifier, null, Constants.EMPTY_STRING, Constants.EMPTY_STRING, lifeCycleTransition.getAuditingAction(), componentType, auditingFields);
-
- return Either.right(errorResponse);
- }
- return Either.left(eitherResourceResponse.left().value());
- }
-
- private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) {
- ResponseFormat errorResponse;
- if (!resource.isHighestVersion()) {
- log.debug("resource version {} is not the last version of resource {}", resource.getVersion(), resource.getName());
- errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase());
- componentUtils.auditResource(errorResponse, modifier, resource, resource.getLifecycleState().name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), null);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateResourceNotDeleted(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) {
-
- ResponseFormat errorResponse;
- if ((resource.getIsDeleted() != null) && (resource.getIsDeleted() == true)) {
- ActionStatus actionStatus = ActionStatus.RESOURCE_NOT_FOUND;
- errorResponse = componentUtils.getResponseFormatByResource(actionStatus, resource.getName());
- log.debug("resource {} {} is marked for delete", resource.getName(), resource.getVersion());
- componentUtils.auditResource(errorResponse, modifier, null, "", "", lifeCycleTransition.getAuditingAction(), null);
-
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) {
- ResponseFormat errorResponse;
- if (!component.isHighestVersion()) {
- log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(),
- component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase());
- componentUtils.auditComponentAdmin(errorResponse, modifier, component, component.getLifecycleState().name(), resourceCurrVersion, lifeCycleTransition.getAuditingAction(), componentType);
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
-
- private Either<Boolean, ResponseFormat> lockComponent(ComponentTypeEnum componentType, Component component) {
- NodeTypeEnum nodeType = componentType.getNodeType();
- StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType);
-
- if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
- return Either.left(true);
- } else {
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus);
- ResponseFormat responseFormat = componentUtils.getResponseFormat(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- return Either.right(responseFormat);
- }
-
- }
-
- private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) {
- String comment = changeInfo.getUserRemarks();
- if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum
- || LifeCycleTransitionEnum.CERTIFICATION_REQUEST == transitionEnum
- // import?
- ) {
-
- if (!ValidationUtils.validateStringNotEmpty(comment)) {
- log.debug("user comment cannot be empty or null.");
- ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT);
- return Either.right(errorResponse);
- }
-
- comment = ValidationUtils.removeNoneUtf8Chars(comment);
- comment = ValidationUtils.removeHtmlTags(comment);
- comment = ValidationUtils.normaliseWhitespace(comment);
- comment = ValidationUtils.stripOctets(comment);
-
- if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) {
- log.debug("user comment exceeds limit.");
- return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
- }
- if (!ValidationUtils.validateIsEnglish(comment)) {
- return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- }
- return Either.left(comment);
- }
-
- private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) {
- ComponentBusinessLogic businessLogic;
- switch (componentTypeEnum) {
- case RESOURCE: {
- businessLogic = this.resourceBusinessLogic;
- break;
- }
- case SERVICE: {
- businessLogic = this.serviceBusinessLogic;
- break;
- }
- case PRODUCT: {
- businessLogic = this.productBusinessLogic;
- break;
- }
-
- default: {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL");
- throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
- }
- }
- return businessLogic;
- }
-
- public Either<Component, ResponseFormat> getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) {
-
- Either<Component, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid);
-
- if (latestVersionEither.isRight()) {
-
- return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid));
- }
-
- Component latestComponent = latestVersionEither.left().value();
-
- return Either.left(latestComponent);
- }
+ @Autowired
+ private ToscaExportHandler toscaExportUtils;
+
+ @Autowired
+ ICacheMangerOperation cacheManagerOperation;
+
+ @Autowired
+ ToscaOperationFacade toscaOperationFacade;
+
+ private Map<String, LifeCycleTransition> stateTransitions;
+ private static volatile boolean isInitialized = false;
+
+ @PostConstruct
+ public void init() {
+ // init parameters
+ if (!isInitialized) {
+ synchronized (this) {
+ if (!isInitialized) {
+ initStateOperations();
+ isInitialized = true;
+ }
+ }
+ }
+ }
+
+ private void initStateOperations() {
+ stateTransitions = new HashMap<String, LifeCycleTransition>();
+
+ LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ stateTransitions.put(checkoutOp.getName().name(), checkoutOp);
+
+ UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ undoCheckoutOp.setArtifactsBusinessLogic(artifactsBusinessLogic);
+ stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp);
+
+ LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ stateTransitions.put(checkinOp.getName().name(), checkinOp);
+
+ LifeCycleTransition certificationRequest = new CertificationRequestTransition(componentUtils, lifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
+ stateTransitions.put(certificationRequest.getName().name(), certificationRequest);
+
+ LifeCycleTransition startCertification = new StartCertificationTransition(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ stateTransitions.put(startCertification.getName().name(), startCertification);
+
+ LifeCycleTransition failCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.FAIL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ stateTransitions.put(failCertification.getName().name(), failCertification);
+
+ LifeCycleTransition cancelCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CANCEL_CERTIFICATION, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ stateTransitions.put(cancelCertification.getName().name(), cancelCertification);
+
+ CertificationChangeTransition successCertification = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+ successCertification.setArtifactsManager(artifactsBusinessLogic);
+ stateTransitions.put(successCertification.getName().name(), successCertification);
+ }
+
+ public LifeCycleTransition getLifecycleTransition(LifeCycleTransitionEnum transitionEnum) {
+ return stateTransitions.get(transitionEnum.name());
+ }
+
+ public Either<Service, ResponseFormat> changeServiceState(String serviceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
+ return (Either<Service, ResponseFormat>) changeComponentState(ComponentTypeEnum.SERVICE, serviceId, modifier, transitionEnum, changeInfo, inTransaction, needLock);
+ }
+
+ // TODO: rhalili - should use changeComponentState when possible
+ public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
+ return (Either<Resource, ResponseFormat>) changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock);
+ }
+
+ private boolean isComponentVFCMT(Component component, ComponentTypeEnum componentType){
+ if (componentType.equals(ComponentTypeEnum.RESOURCE)){
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ if (resourceType.equals(ResourceTypeEnum.VFCMT)){
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public Either<? extends Component, ResponseFormat> changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
+ boolean needLock) {
+
+ LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name());
+ if (lifeCycleTransition == null) {
+ log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
+ ResponseFormat error = componentUtils.getInvalidContentErrorAndAudit(modifier,componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
+ return Either.right(error);
+ }
+ Component component = null;
+ log.info("get resource from graph");
+ ResponseFormat errorResponse;
+
+ Either<? extends Component, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition, changeInfo);
+ if (eitherResourceResponse.isRight()) {
+ return eitherResourceResponse;
+ }
+ component = eitherResourceResponse.left().value();
+ String resourceCurrVersion = component.getVersion();
+ LifecycleStateEnum resourceCurrState = component.getLifecycleState();
+
+ // lock resource
+ if (!inTransaction && needLock) {
+ log.info("lock component {}", componentId);
+ Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component);
+ if (eitherLockResource.isRight()) {
+ errorResponse = eitherLockResource.right().value();
+ componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType,
+ ResourceAuditData.newBuilder().state(resourceCurrState.name()).version(resourceCurrVersion).build());
+
+ log.error("lock component {} failed", componentId);
+ return Either.right(errorResponse);
+ }
+ log.debug("after lock component {}", componentId);
+ }
+ try {
+ Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum);
+ if (commentValidationResult.isRight()) {
+ errorResponse = commentValidationResult.right().value();
+ componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType,
+ ResourceAuditData.newBuilder()
+ .state(resourceCurrState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks());
+ return Either.right(errorResponse);
+ }
+ changeInfo.setUserRemarks(commentValidationResult.left().value());
+ log.debug("after validate component");
+ Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType);
+ if (validateHighestVersion.isRight()) {
+ return Either.right(validateHighestVersion.right().value());
+ }
+ log.debug("after validate Highest Version");
+ if (isComponentVFCMT(component,componentType)){
+ Either<? extends Component, ResponseFormat> changeVFCMTStateResponse = changeVFCMTState(componentType, modifier, transitionEnum, changeInfo, true, component);
+ if (changeVFCMTStateResponse.isRight()){
+ return changeVFCMTStateResponse;
+ }
+ component = changeVFCMTStateResponse.left().value();
+ }
+ return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction);
+ } finally {
+ component.setUniqueId(componentId);
+ if (!inTransaction && needLock) {
+ log.info("unlock component {}", componentId);
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ log.info("During change state, another component {} has been created/updated", componentId);
+ graphLockOperation.unlockComponent(componentId, nodeType);
+
+ }
+ }
+
+ }
+
+ /*
+ * special case for certification of VFCMT - VFCMT can be certified by Designer or Tester right after checkin
+ * in case the operation "submit for test" / "start testing" is done to "VFCMT" - please return error 400
+ */
+ private Either<? extends Component, ResponseFormat> changeVFCMTState(ComponentTypeEnum componentType, User modifier,
+ LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
+ Component component) {
+ LifecycleStateEnum oldState = component.getLifecycleState();
+ Component updatedComponent = component;
+ if (transitionEnum.equals(LifeCycleTransitionEnum.START_CERTIFICATION) ||
+ transitionEnum.equals(LifeCycleTransitionEnum.CERTIFICATION_REQUEST)){
+ return Either.right(componentUtils.getResponseFormat(
+ ActionStatus.RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID, transitionEnum.getDisplayName()));
+ } //certify is done directly from checkin
+ else if (transitionEnum.equals(LifeCycleTransitionEnum.CERTIFY) && oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)){
+ //we will call for submit for testing first and then for certify
+ Either<? extends Component, ResponseFormat> actionResponse = changeState(component,
+ stateTransitions.get(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.name()),
+ componentType, modifier, changeInfo, inTransaction);
+ if (actionResponse.isRight()) {
+ return actionResponse;
+ }
+ updatedComponent = actionResponse.left().value();
+ actionResponse = changeState(updatedComponent,
+ stateTransitions.get(LifeCycleTransitionEnum.START_CERTIFICATION.name()),
+ componentType, modifier, changeInfo, inTransaction);
+ if (actionResponse.isRight()) {
+ return actionResponse;
+ }
+ updatedComponent = actionResponse.left().value();
+
+ }
+ return Either.left(updatedComponent);
+ }
+
+ private Either<? extends Component, ResponseFormat> changeState(Component component, LifeCycleTransition lifeCycleTransition,
+ ComponentTypeEnum componentType, User modifier, LifecycleChangeInfoWithAction changeInfo,boolean inTransaction){
+ ResponseFormat errorResponse;
+
+ LifecycleStateEnum oldState = component.getLifecycleState();
+ String resourceCurrVersion = component.getVersion();
+ ComponentBusinessLogic bl = getComponentBL(componentType);
+
+ Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType, inTransaction);
+ if (ownerResult.isRight()) {
+ return Either.right(ownerResult.right().value());
+ }
+ User owner = ownerResult.left().value();
+ log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId());
+
+ Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
+ if (stateValidationResult.isRight()) {
+ log.error("Failed to validateBeforeTransition");
+ errorResponse = stateValidationResult.right().value();
+ componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType,
+ ResourceAuditData.newBuilder().version(resourceCurrVersion).state(oldState.name()).build(), changeInfo.getUserRemarks());
+ return Either.right(errorResponse);
+ }
+
+ Either<? extends Component, ResponseFormat> operationResult = lifeCycleTransition.changeState(componentType, component, bl, modifier, owner, false, inTransaction);
+
+ if (operationResult.isRight()) {
+ errorResponse = operationResult.right().value();
+ log.info("audit before sending error response");
+ componentUtils.auditComponentAdmin(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType,
+ ResourceAuditData.newBuilder().state(oldState.name()).version(resourceCurrVersion).build());
+
+ return Either.right(errorResponse);
+ }
+ Component resourceAfterOperation = operationResult.left().value();
+ componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation, lifeCycleTransition.getAuditingAction(), componentType,
+ ResourceAuditData.newBuilder().state(oldState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks());
+ return operationResult;
+
+ }
+
+ private Either<? extends Component, ResponseFormat> getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier, LifeCycleTransition lifeCycleTransition, LifecycleChangeInfoWithAction changeInfo) {
+
+ Either<? extends Component, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId);
+
+ ResponseFormat errorResponse;
+ if (eitherResourceResponse.isRight()) {
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
+ errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
+ log.debug("audit before sending response");
+ componentUtils.auditComponent(errorResponse, modifier, lifeCycleTransition.getAuditingAction(), componentId, componentType, changeInfo.getUserRemarks());
+
+ return Either.right(errorResponse);
+ }
+ return Either.left(eitherResourceResponse.left().value());
+ }
+
+ private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Resource resource, String resourceCurrVersion) {
+ ResponseFormat errorResponse;
+ if (!resource.isHighestVersion()) {
+ log.debug("resource version {} is not the last version of resource {}", resource.getVersion(), resource.getName());
+ errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase());
+ componentUtils.auditResource(errorResponse, modifier, resource, lifeCycleTransition.getAuditingAction(), ResourceAuditData.newBuilder()
+ .state(resource.getLifecycleState().name()).version(resourceCurrVersion).build());
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) {
+ ResponseFormat errorResponse;
+ if (!component.isHighestVersion()) {
+ log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(),
+ component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+ errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase());
+ componentUtils.auditComponentAdmin(errorResponse, modifier, component,lifeCycleTransition.getAuditingAction(), componentType,
+ ResourceAuditData.newBuilder().state(component.getLifecycleState().name()).version(resourceCurrVersion).build());
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> lockComponent(ComponentTypeEnum componentType, Component component) {
+ NodeTypeEnum nodeType = componentType.getNodeType();
+ StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType);
+
+ if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
+ return Either.left(true);
+ } else {
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus);
+ ResponseFormat responseFormat = componentUtils.getResponseFormat(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+ return Either.right(responseFormat);
+ }
+
+ }
+
+ private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) {
+ String comment = changeInfo.getUserRemarks();
+ if (LifeCycleTransitionEnum.CANCEL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.FAIL_CERTIFICATION == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum
+ || LifeCycleTransitionEnum.CERTIFICATION_REQUEST == transitionEnum
+ // import?
+ ) {
+
+ if (!ValidationUtils.validateStringNotEmpty(comment)) {
+ log.debug("user comment cannot be empty or null.");
+ ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT);
+ return Either.right(errorResponse);
+ }
+
+ comment = ValidationUtils.removeNoneUtf8Chars(comment);
+ comment = ValidationUtils.removeHtmlTags(comment);
+ comment = ValidationUtils.normaliseWhitespace(comment);
+ comment = ValidationUtils.stripOctets(comment);
+
+ if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) {
+ log.debug("user comment exceeds limit.");
+ return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
+ }
+ if (!ValidationUtils.validateIsEnglish(comment)) {
+ return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ }
+ return Either.left(comment);
+ }
+
+ private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) {
+ ComponentBusinessLogic businessLogic;
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ businessLogic = this.resourceBusinessLogic;
+ break;
+ case SERVICE:
+ businessLogic = this.serviceBusinessLogic;
+ break;
+ case PRODUCT:
+ businessLogic = this.productBusinessLogic;
+ break;
+ default:
+ throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
+ }
+ return businessLogic;
+ }
+
+ public Either<Component, ResponseFormat> getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) {
+
+ Either<Component, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid);
+
+ if (latestVersionEither.isRight()) {
+
+ return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid));
+ }
+
+ Component latestComponent = latestVersionEither.left().value();
+
+ return Either.left(latestComponent);
+ }
/**
* Performs Force certification.
* Note that a Force certification is allowed for the first certification only,
@@ -476,59 +455,59 @@ public class LifecycleBusinessLogic {
* @param needLock
* @return
*/
- public Either<Resource, ResponseFormat> forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
- Either<Resource, ResponseFormat> result = null;
- Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null;
- if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){
- log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction().name());
- result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- }
- if(!isFirstCertification(resource.getVersion())){
- log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName());
- result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
- }
- // lock resource
- if(result == null && !inTransaction && needLock){
- log.info("lock component {}", resource.getUniqueId());
- Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(resource.getComponentType(), resource);
- if (eitherLockResource.isRight()) {
- log.error("lock component {} failed", resource.getUniqueId());
- result = Either.right(eitherLockResource.right().value());
- }
- log.info("after lock component {}", resource.getUniqueId());
- }
- try{
- if(result == null){
- certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion());
- if (certifyResourceRes.isRight()) {
- StorageOperationStatus status = certifyResourceRes.right().value();
- log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status);
- result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource));
- }
- }
- if(result == null){
- result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value()));
- }
- } finally {
- log.info("unlock component {}", resource.getUniqueId());
- if (!inTransaction) {
- if(result.isLeft()){
- titanDao.commit();
- } else{
- titanDao.rollback();
- }
- if(needLock){
- NodeTypeEnum nodeType = resource.getComponentType().getNodeType();
- log.info("During change state, another component {} has been created/updated", resource.getUniqueId());
- graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType);
- }
- }
- }
- return result;
- }
-
- public boolean isFirstCertification(String previousVersion) {
- return previousVersion.split("\\.")[0].equals("0");
- }
+ public Either<Resource, ResponseFormat> forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ Either<Resource, ResponseFormat> result = null;
+ Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null;
+ if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){
+ log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction());
+ result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+ if(!isFirstCertification(resource.getVersion())){
+ log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName());
+ result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+ // lock resource
+ if(result == null && !inTransaction && needLock){
+ log.info("lock component {}", resource.getUniqueId());
+ Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(resource.getComponentType(), resource);
+ if (eitherLockResource.isRight()) {
+ log.error("lock component {} failed", resource.getUniqueId());
+ result = Either.right(eitherLockResource.right().value());
+ }
+ log.info("after lock component {}", resource.getUniqueId());
+ }
+ try{
+ if(result == null){
+ certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion());
+ if (certifyResourceRes.isRight()) {
+ StorageOperationStatus status = certifyResourceRes.right().value();
+ log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status);
+ result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource));
+ }
+ }
+ if(result == null){
+ result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value()));
+ }
+ } finally {
+ log.info("unlock component {}", resource.getUniqueId());
+ if (!inTransaction) {
+ if(result.isLeft()){
+ titanDao.commit();
+ } else{
+ titanDao.rollback();
+ }
+ if(needLock){
+ NodeTypeEnum nodeType = resource.getComponentType().getNodeType();
+ log.info("During change state, another component {} has been created/updated", resource.getUniqueId());
+ graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType);
+ }
+ }
+ }
+ return result;
+ }
+
+ public boolean isFirstCertification(String previousVersion) {
+ return previousVersion.split("\\.")[0].equals("0");
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java
index 0c35caf41b..dcce9b002c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java
@@ -22,21 +22,21 @@ package org.openecomp.sdc.be.components.lifecycle;
public class LifecycleChangeInfoBase {
- public LifecycleChangeInfoBase() {
- }
+ public LifecycleChangeInfoBase() {
+ }
- public LifecycleChangeInfoBase(String userRemarks) {
- super();
- this.userRemarks = userRemarks;
- }
+ public LifecycleChangeInfoBase(String userRemarks) {
+ super();
+ this.userRemarks = userRemarks;
+ }
- private String userRemarks;
+ private String userRemarks;
- public String getUserRemarks() {
- return userRemarks;
- }
+ public String getUserRemarks() {
+ return userRemarks;
+ }
- public void setUserRemarks(String userRemarks) {
- this.userRemarks = userRemarks;
- }
+ public void setUserRemarks(String userRemarks) {
+ this.userRemarks = userRemarks;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java
index 5d8b29ecdc..51ec61ea6b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java
@@ -22,29 +22,29 @@ package org.openecomp.sdc.be.components.lifecycle;
public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase {
- public enum LifecycleChanceActionEnum {
- CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION
- };
+ public enum LifecycleChanceActionEnum {
+ CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION
+ };
- private LifecycleChanceActionEnum action;
+ private LifecycleChanceActionEnum action;
- public LifecycleChangeInfoWithAction() {
- }
+ public LifecycleChangeInfoWithAction() {
+ }
- public LifecycleChangeInfoWithAction(String userRemarks) {
- super(userRemarks);
- }
+ public LifecycleChangeInfoWithAction(String userRemarks) {
+ super(userRemarks);
+ }
- public LifecycleChangeInfoWithAction(String userRemarks, LifecycleChanceActionEnum action) {
- super(userRemarks);
- this.action = action;
- }
+ public LifecycleChangeInfoWithAction(String userRemarks, LifecycleChanceActionEnum action) {
+ super(userRemarks);
+ this.action = action;
+ }
- public LifecycleChanceActionEnum getAction() {
- return action;
- }
+ public LifecycleChanceActionEnum getAction() {
+ return action;
+ }
- public void setAction(LifecycleChanceActionEnum action) {
- this.action = action;
- }
+ public void setAction(LifecycleChanceActionEnum action) {
+ this.action = action;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
index b74ae5d8e5..4dddc044f2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
@@ -48,97 +48,97 @@ import fj.data.Either;
public class StartCertificationTransition extends LifeCycleTransition {
- private static Logger log = LoggerFactory.getLogger(StartCertificationTransition.class.getName());
-
- public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
-
- // authorized roles
- Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER };
- addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles));
- addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles));
- // TODO to be later defined for product
-
- //additional authorized roles for resource type
- Role[] resourceRoles = { Role.DESIGNER};
- addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
- }
-
- @Override
- public LifeCycleTransitionEnum getName() {
- return LifeCycleTransitionEnum.START_CERTIFICATION;
- }
-
- @Override
- public AuditingActionEnum getAuditingAction() {
- return AuditingActionEnum.START_CERTIFICATION_RESOURCE;
- }
-
- @Override
- public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
- log.debug("start performing certification test for resource {}", component.getUniqueId());
- Either<? extends Component, ResponseFormat> result = null;
- try{
- Either<ToscaElement, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
- if (stateChangeResult.isRight()) {
- log.debug("start certification failed on graph");
- StorageOperationStatus response = stateChangeResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
- if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
- actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
- }
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- }
- else {
- result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value()));
- }
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
- if (inTransaction == false) {
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- }
- } else {
- if (inTransaction == false) {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- }
- return result;
- }
-
- @Override
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
- String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
- // validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
- return userValidationResponse;
- }
-
- if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- return Either.left(true);
- }
+ private static final Logger log = LoggerFactory.getLogger(StartCertificationTransition.class);
+
+ public StartCertificationTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+
+ // authorized roles
+ Role[] rsrcServiceStartCertificationRoles = { Role.ADMIN, Role.TESTER };
+ addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(rsrcServiceStartCertificationRoles));
+ addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(rsrcServiceStartCertificationRoles));
+ // TODO to be later defined for product
+
+ //additional authorized roles for resource type
+ Role[] resourceRoles = { Role.DESIGNER};
+ addResouceAuthorizedRoles(ResourceTypeEnum.VFCMT, Arrays.asList(resourceRoles));
+ }
+
+ @Override
+ public LifeCycleTransitionEnum getName() {
+ return LifeCycleTransitionEnum.START_CERTIFICATION;
+ }
+
+ @Override
+ public AuditingActionEnum getAuditingAction() {
+ return AuditingActionEnum.START_CERTIFICATION_RESOURCE;
+ }
+
+ @Override
+ public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+
+ log.debug("start performing certification test for resource {}", component.getUniqueId());
+ Either<? extends Component, ResponseFormat> result = null;
+ try{
+ Either<ToscaElement, StorageOperationStatus> stateChangeResult = lifeCycleOperation.startCertificationToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
+ if (stateChangeResult.isRight()) {
+ log.debug("start certification failed on graph");
+ StorageOperationStatus response = stateChangeResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+
+ if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
+ actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
+ }
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(stateChangeResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
+ if (inTransaction == false) {
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ }
+ } else {
+ if (inTransaction == false) {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ log.debug("validate before start certification test. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+
+ // validate user
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ return userValidationResponse;
+ }
+
+ if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) || oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, componentName, componentType.name().toLowerCase());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CERTIFIED, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ if (oldState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ return Either.left(true);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
index 324e46016f..9444faa27a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
@@ -20,7 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.Arrays;
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
@@ -44,97 +44,97 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.Arrays;
public class UndoCheckoutTransition extends LifeCycleTransition {
- private static Logger log = LoggerFactory.getLogger(CheckoutTransition.class.getName());
- private ArtifactsBusinessLogic artifactsManager;
-
- public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
- super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
-
- // authorized roles
- Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
- Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
- addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
- addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
-
- }
-
- @Override
- public LifeCycleTransitionEnum getName() {
- return LifeCycleTransitionEnum.UNDO_CHECKOUT;
- }
-
- @Override
- public AuditingActionEnum getAuditingAction() {
- return AuditingActionEnum.UNDO_CHECKOUT_RESOURCE;
- }
-
- public ArtifactsBusinessLogic getArtifactsBusinessLogic() {
- return artifactsManager;
- }
-
- public void setArtifactsBusinessLogic(ArtifactsBusinessLogic artifactsBusinessLogic) {
- this.artifactsManager = artifactsBusinessLogic;
- }
-
- @Override
- public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
- String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
- // validate user
- Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
- if (userValidationResponse.isRight()) {
- return userValidationResponse;
- }
-
- // check resource is not locked by another user
- if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
- ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
- return Either.right(error);
- }
-
- return Either.left(true);
- }
-
- @Override
- public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
- Either<? extends Component, ResponseFormat> result = null;
- log.debug("start performing undo-checkout for resource {}", component.getUniqueId());
-
- try {
- Either<ToscaElement, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId());
-
- if (undoCheckoutResourceResult.isRight()) {
- log.debug("checkout failed on graph");
- StorageOperationStatus response = undoCheckoutResourceResult.right().value();
- ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
- ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
- result = Either.right(responseFormat);
- }
- else {
- result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value()));
- }
- } finally {
- if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph");
- log.debug("operation failed. do rollback");
- titanDao.rollback();
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
- }
- }
- return result;
- }
+ private static final Logger log = LoggerFactory.getLogger(CheckoutTransition.class);
+ private ArtifactsBusinessLogic artifactsManager;
+
+ public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, TitanDao titanDao) {
+ super(componentUtils, lifecycleOperation, toscaOperationFacade, titanDao);
+
+ // authorized roles
+ Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
+ Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
+ addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
+ addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
+
+ }
+
+ @Override
+ public LifeCycleTransitionEnum getName() {
+ return LifeCycleTransitionEnum.UNDO_CHECKOUT;
+ }
+
+ @Override
+ public AuditingActionEnum getAuditingAction() {
+ return AuditingActionEnum.UNDO_CHECKOUT_RESOURCE;
+ }
+
+ public ArtifactsBusinessLogic getArtifactsBusinessLogic() {
+ return artifactsManager;
+ }
+
+ public void setArtifactsBusinessLogic(ArtifactsBusinessLogic artifactsBusinessLogic) {
+ this.artifactsManager = artifactsBusinessLogic;
+ }
+
+ @Override
+ public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+ String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
+
+ // validate user
+ Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+ if (userValidationResponse.isRight()) {
+ return userValidationResponse;
+ }
+
+ // check resource is not locked by another user
+ if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
+ ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+ return Either.right(error);
+ }
+
+ return Either.left(true);
+ }
+
+ @Override
+ public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+
+ Either<? extends Component, ResponseFormat> result = null;
+ log.debug("start performing undo-checkout for resource {}", component.getUniqueId());
+
+ try {
+ Either<ToscaElement, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId());
+
+ if (undoCheckoutResourceResult.isRight()) {
+ log.debug("checkout failed on graph");
+ StorageOperationStatus response = undoCheckoutResourceResult.right().value();
+ ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
+ ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
+ result = Either.right(responseFormat);
+ }
+ else {
+ result = Either.left(ModelConverter.convertFromToscaElement(undoCheckoutResourceResult.left().value()));
+ }
+ } finally {
+ if (result == null || result.isRight()) {
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Undo Checkout failed on graph");
+ log.debug("operation failed. do rollback");
+ titanDao.rollback();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ return result;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java
index 9c140b36c7..e6dd6457cf 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java
@@ -1,9 +1,6 @@
package org.openecomp.sdc.be.components.merge;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -12,7 +9,9 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
@Component
public class GlobalInputsFilteringBusinessLogic extends BaseBusinessLogic {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java
index eb359e949e..4bd799805f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogic.java
@@ -1,7 +1,6 @@
package org.openecomp.sdc.be.components.merge;
-import java.util.List;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL;
import org.openecomp.sdc.be.components.merge.resource.MergeResourceBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -11,7 +10,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.List;
@Component
public class GlobalTypesMergeBusinessLogic implements MergeResourceBusinessLogic {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java
index 6c20e501f9..058d4c2555 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java
@@ -1,15 +1,15 @@
package org.openecomp.sdc.be.components.merge;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.RelationshipInfo;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
import org.springframework.stereotype.Component;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
@Component
public class RelationsComparator {
@@ -45,8 +45,8 @@ public class RelationsComparator {
private boolean findRelation(Resource oldResource, List<RequirementCapabilityRelDef> oldRelations, Resource newResource, RequirementCapabilityRelDef newRelation) {
for (RequirementCapabilityRelDef oldRelation : oldRelations) {
- RelationshipInfo oldRelationship = oldRelation.getSingleRelationship().getRelation();
- RelationshipInfo newRelationship = newRelation.getSingleRelationship().getRelation();
+ RelationshipInfo oldRelationship = oldRelation.resolveSingleRelationship().getRelation();
+ RelationshipInfo newRelationship = newRelation.resolveSingleRelationship().getRelation();
if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(oldResource, oldRelation, newResource, newRelation)) {
return true;
}
@@ -70,12 +70,12 @@ public class RelationsComparator {
private boolean isRelationshipCapabilityEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) {
if(oldRelationship.getCapabilityUid() !=null && newRelationship.getCapabilityUid() != null){
- return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid());
+ return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid());
}
else if(oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null){
- return true;
+ return true;
}
- return false;
+ return false;
}
private boolean isRelationshipTypeEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) {
@@ -84,12 +84,12 @@ public class RelationsComparator {
private boolean isRelationshipReqNameEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) {
if(oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null){
- return oldRelationship.getRequirement().equals(newRelationship.getRequirement());
+ return oldRelationship.getRequirement().equals(newRelationship.getRequirement());
}
else if(oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null){
- return true;
+ return true;
}
- return false;
+ return false;
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java
index 8b48b0897a..0f68f9f409 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java
@@ -1,8 +1,6 @@
package org.openecomp.sdc.be.components.merge;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.exception.SdcActionException;
@@ -15,7 +13,8 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
@org.springframework.stereotype.Component
public class TopologyComparator {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java
new file mode 100644
index 0000000000..0a467ef876
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.components.merge.capability;
+
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+
+import java.util.List;
+import java.util.Map;
+
+public interface CapabilityResolver {
+
+ /**
+ *
+ * @param container the instance container
+ * @param prevInstanceOrigNode the prev instance's original node type
+ * @param cmptInstanceId the current instance id
+ * @param prevCapabilities list of previous capabilities for which to find their corresponding new capabilities
+ * @return a mapping between the prev capability to its corresponding new capability (if exists)
+ */
+ Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities);
+
+ /**
+ *
+ * @param oldInstance the old instance of which its capabilities are to be mapped as the key
+ * @param currInstance the curr instance of which its capabilities are to be mapped as the value
+ * @return a mapping between the prev capability to its corresponding new capability (if exists)
+ */
+ Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance);
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java
new file mode 100644
index 0000000000..8400b32f9b
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java
@@ -0,0 +1,82 @@
+package org.openecomp.sdc.be.components.merge.capability;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+
+import java.util.*;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+@org.springframework.stereotype.Component
+public class SimpleCapabilityResolver implements CapabilityResolver {
+
+ private MergeInstanceUtils mergeInstanceUtils;
+
+ public SimpleCapabilityResolver(MergeInstanceUtils mergeInstanceUtils) {
+ this.mergeInstanceUtils = mergeInstanceUtils;
+ }
+
+ @Override
+ public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities) {
+ Map<String, List<CapabilityDefinition>> newCapabilitiesByType = resolveInstanceCapabilities(container, cmptInstanceId).getCapabilities();
+ Map<String, String> oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId, prevCapabilities);
+ return mapOldToNewCapabilities(prevCapabilities, newCapabilitiesByType, oldCapOwnerToNewOwner);
+ }
+
+ @Override
+ public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance) {
+ Map<String, List<CapabilityDefinition>> newCapabilitiesByType = currInstance.getCapabilities();
+ Map<String, String> oldCapOwnerToNewOwner = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance);
+ List<CapabilityDefinition> prevCapabilities = oldInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList());
+ return mapOldToNewCapabilities(prevCapabilities, newCapabilitiesByType, oldCapOwnerToNewOwner);
+ }
+
+ private Map<CapabilityDefinition, CapabilityDefinition> mapOldToNewCapabilities(List<CapabilityDefinition> prevCapabilities, Map<String, List<CapabilityDefinition>> newCapabilitiesByType, Map<String, String> oldCapOwnerToNewOwner) {
+ Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapability = prevCapabilities
+ .stream()
+ .collect(HashMap::new,
+ (resultMap, prevCap) -> mapOldToNewCapability(newCapabilitiesByType, oldCapOwnerToNewOwner, resultMap, prevCap),
+ HashMap::putAll);
+ removeNotFoundNewCapabilities(oldToNewCapability);
+ return oldToNewCapability;
+ }
+
+ private CapabilityDefinition mapOldToNewCapability(Map<String, List<CapabilityDefinition>> newCapabilitiesByType, Map<String, String> oldCapOwnerToNewOwner, Map<CapabilityDefinition, CapabilityDefinition> resultMap, CapabilityDefinition prevCap) {
+ return resultMap.put(prevCap, findCurrCapability(newCapabilitiesByType, prevCap, oldCapOwnerToNewOwner.get(prevCap.getOwnerId())));
+ }
+
+ private Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities) {
+ List<String> prevCapOwnerIds = prevCapabilities.stream().map(CapabilityDefinition::getOwnerId).distinct().collect(Collectors.toList());
+ return mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, origInstanceNode, cmptInstanceId, prevCapOwnerIds);
+ }
+
+ private void removeNotFoundNewCapabilities(Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapMap) {
+ oldToNewCapMap.values().removeIf(Objects::isNull);
+ }
+
+ private ComponentInstance resolveInstanceCapabilities(Component capabilityOwnerContainer, String cmptInstanceId) {
+ return MapUtil.toMap(capabilityOwnerContainer.getComponentInstances(), ComponentInstance::getUniqueId).get(cmptInstanceId);
+ }
+
+
+ private CapabilityDefinition findCurrCapability(Map<String, List<CapabilityDefinition>> capabilitiesByType, CapabilityDefinition oldCap, String newCapOwnerId) {
+ List<CapabilityDefinition> newCapOfType = capabilitiesByType.get(oldCap.getType());
+ if (newCapOwnerId == null || CollectionUtils.isEmpty(newCapOfType)) {
+ return null;
+ }
+ return newCapOfType.stream().filter(sameNameAndOwner(oldCap.getName(), newCapOwnerId))
+ .findFirst().orElse(null);
+
+ }
+
+ private Predicate<CapabilityDefinition> sameNameAndOwner(String capName, String newCapOwnerId) {
+ return newCap -> newCap.getName().equals(capName) && newCap.getOwnerId().equals(newCapOwnerId);
+ }
+
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java
index 1e1bc862cf..82deee598d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java
@@ -1,15 +1,15 @@
package org.openecomp.sdc.be.components.merge.heat;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
/**
* Created by chaya on 9/14/2017.
*/
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java
index b8ea5e35c4..be5e5367b8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java
@@ -1,9 +1,7 @@
package org.openecomp.sdc.be.components.merge.input;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
+import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -12,10 +10,13 @@ import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
@org.springframework.stereotype.Component
-public class ComponentInputsMergeBL {
+public class ComponentInputsMergeBL implements ComponentsMergeCommand {
@javax.annotation.Resource
private InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic;
@@ -26,6 +27,17 @@ public class ComponentInputsMergeBL {
@javax.annotation.Resource
private ComponentsUtils componentsUtils;
+ @Override
+ public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
+ List<InputDefinition> inputsToMerge = currentComponent.getInputs() != null ? currentComponent.getInputs() : new ArrayList<>();
+ return this.mergeAndRedeclareComponentInputs(prevComponent, currentComponent, inputsToMerge);
+ }
+
+ @Override
+ public String description() {
+ return "merge component inputs";
+ }
+
public ActionStatus mergeAndRedeclareComponentInputs(Component prevComponent, Component newComponent, List<InputDefinition> inputsToMerge) {
mergeInputs(prevComponent, inputsToMerge);
List<InputDefinition> previouslyDeclaredInputs = inputsValuesMergingBusinessLogic.getPreviouslyDeclaredInputsToMerge(prevComponent, newComponent);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java
index e49d2b2c87..e0e7947226 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java
@@ -1,12 +1,5 @@
package org.openecomp.sdc.be.components.merge.input;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
@@ -14,6 +7,9 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.InputDefinition;
+import java.util.*;
+import java.util.stream.Collectors;
+
@org.springframework.stereotype.Component
public class InputsValuesMergingBusinessLogic {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java
new file mode 100644
index 0000000000..e7117a2aeb
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java
@@ -0,0 +1,103 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.components.merge.capability.CapabilityResolver;
+import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Map;
+
+@org.springframework.stereotype.Component
+public class ComponentCapabilitiesPropertiesMergeBL implements ComponentsMergeCommand {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ComponentCapabilitiesPropertiesMergeBL.class);
+
+ private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic;
+ private ToscaOperationFacade toscaOperationFacade;
+ private ComponentsUtils componentsUtils;
+ private CapabilityResolver capabilityResolver;
+
+ public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, CapabilityResolver capabilityResolver) {
+ this.dataDefinitionsValuesMergingBusinessLogic = dataDefinitionsValuesMergingBusinessLogic;
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.componentsUtils = componentsUtils;
+ this.capabilityResolver = capabilityResolver;
+ }
+
+ @Override
+ public String description() {
+ return "merge component instances capabilities properties";
+ }
+
+ @Override
+ public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
+ StorageOperationStatus mergeStatus = getCmptWithCapabilitiesProps(currentComponent.getUniqueId())
+ .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap),
+ err -> err);
+ return componentsUtils.convertFromStorageResponse(mergeStatus);
+ }
+
+ public ActionStatus mergeComponentInstanceCapabilities(Component currentComponent, Component origInstanceCmpt, String instanceId, List<CapabilityDefinition> prevInstanceCapabilities) {
+ if (CollectionUtils.isEmpty(prevInstanceCapabilities)) {
+ return ActionStatus.OK;
+ }
+ Map<CapabilityDefinition, CapabilityDefinition> oldToNewCap = capabilityResolver.resolvePrevCapToNewCapability(currentComponent, origInstanceCmpt, instanceId, prevInstanceCapabilities);
+ oldToNewCap.forEach(this::mergeCapabilityProperties);
+ StorageOperationStatus updateStatus = updateInstanceCapabilitiesProperties(currentComponent, instanceId);
+ return componentsUtils.convertFromStorageResponse(updateStatus);
+ }
+
+ private StorageOperationStatus mergeCmptCalculatedCapabilitiesProperties(Component prevComponent, Component currentComponent) {
+ List<ComponentInstance> prevInstances = prevComponent.getComponentInstances();
+ if (prevInstances == null) {
+ return StorageOperationStatus.OK;
+ }
+ prevInstances.forEach(prevInstance -> mergeInstanceCapabilities(prevInstance, currentComponent));
+ return updateComponentCapabilitiesProperties(currentComponent);
+ }
+
+ private void mergeInstanceCapabilities(ComponentInstance prevInstance, Component currComponent) {
+ ComponentInstance currInstance = MapUtil.toMap(currComponent.getComponentInstances(), ComponentInstance::getName).get(prevInstance.getName());
+ Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapabilities = capabilityResolver.resolvePrevCapIdToNewCapability(prevInstance, currInstance);
+ oldToNewCapabilities.forEach(this::mergeCapabilityProperties);
+ }
+
+ private void mergeCapabilityProperties(CapabilityDefinition prevCapability, CapabilityDefinition currCapability) {
+ dataDefinitionsValuesMergingBusinessLogic.mergeInstanceDataDefinitions(prevCapability.getProperties(), currCapability.getProperties());
+ }
+
+ private StorageOperationStatus updateComponentCapabilitiesProperties(Component currComponent) {
+ return toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currComponent);
+ }
+
+ private StorageOperationStatus updateInstanceCapabilitiesProperties(Component currComponent, String instanceId) {
+ return toscaOperationFacade.updateComponentInstanceCapabilityProperties(currComponent, instanceId);
+ }
+
+ private Either<Component, StorageOperationStatus> getCmptWithCapabilitiesProps(String cmptId) {
+ ComponentParametersView propertiesCapabilitiesFilter = new ComponentParametersView(true);
+ propertiesCapabilitiesFilter.setIgnoreCapabiltyProperties(false);
+ propertiesCapabilitiesFilter.setIgnoreComponentInstances(false);
+ propertiesCapabilitiesFilter.setIgnoreCapabilities(false);
+ return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter)
+ .right()
+ .map(err -> {
+ LOGGER.debug("failed to fetch cmpt {} with properties capabilities. status: {}", cmptId, err);
+ return err;
+ });
+
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java
index cac8c977e3..d16fa251e2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java
@@ -1,10 +1,6 @@
package org.openecomp.sdc.be.components.merge.instance;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -16,7 +12,10 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
/**
* Created by chaya on 9/20/2017.
@@ -81,7 +80,7 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService =
artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent,
user, jsonForUpdateArtifact, artifactsBusinessLogic.new ArtifactOperationInfo(
- false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Link), currentArtifactDefinition.getValue());
+ false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue());
if (uploadArtifactToService.isRight()) {
return Either.right(uploadArtifactToService.right().value());
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java
new file mode 100644
index 0000000000..afad19baf2
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMerge.java
@@ -0,0 +1,47 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+
+@org.springframework.stereotype.Component
+public class ComponentInstanceCapabiliteisPropertiesMerge implements ComponentInstanceMergeInterface {
+
+ private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL;
+ private ComponentsUtils componentsUtils;
+
+ public ComponentInstanceCapabiliteisPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL, ComponentsUtils componentsUtils) {
+ this.capabilitiesPropertiesMergeBL = capabilitiesPropertiesMergeBL;
+ this.componentsUtils = componentsUtils;
+ }
+
+ @Override
+ public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+ dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance));
+ dataHolder.setOrigInstanceNode(originComponent);
+ }
+
+ @Override
+ public Either<Component, ResponseFormat> mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
+ Component origInstanceNode = dataHolder.getOrigInstanceNode();
+ List<CapabilityDefinition> origInstanceCapabilities = dataHolder.getOrigInstanceCapabilities();
+ ActionStatus mergeStatus = capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(updatedContainerComponent, origInstanceNode, newInstanceId, origInstanceCapabilities);
+ return Either.iif(!ActionStatus.OK.equals(mergeStatus), () -> componentsUtils.getResponseFormat(mergeStatus), () -> updatedContainerComponent);
+ }
+
+ private List<CapabilityDefinition> getAllInstanceCapabilities(ComponentInstance currentResourceInstance) {
+ return isNotEmpty( currentResourceInstance.getCapabilities() ) ? currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()) : new ArrayList<>() ;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java
new file mode 100644
index 0000000000..20a5abc591
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java
@@ -0,0 +1,113 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import fj.data.Either;
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+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 java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@org.springframework.stereotype.Component
+public class ComponentInstanceForwardingPathMerge implements ComponentInstanceMergeInterface {
+
+ private static Logger log = LoggerFactory.getLogger(ComponentInstanceForwardingPathMerge.class);
+
+ @Autowired
+ private ServiceBusinessLogic serviceBusinessLogic;
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Autowired
+ private ComponentsUtils componentsUtils;
+
+ @Override
+ public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent,
+ ComponentInstance currentResourceInstance, Component originComponent) {
+ dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance));
+ dataHolder.setOrigInstanceNode(originComponent);
+ dataHolder.setOrigComponentInstId(currentResourceInstance.getUniqueId());
+ }
+
+ @Override
+ public Either<Component, ResponseFormat> mergeDataAfterCreate(User user, DataForMergeHolder dataHolder,
+ Component updatedContainerComponent, String newInstanceId) {
+ if (!(updatedContainerComponent instanceof Service)) {
+ // no need to handle forwarding paths
+ return Either.left(updatedContainerComponent);
+ }
+ Service service = (Service) updatedContainerComponent;
+ ComponentInstance ci = service.getComponentInstanceById(newInstanceId).orElse(null);
+ if (ci == null){
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, newInstanceId);
+ return Either.right(responseFormat);
+ }
+ Either<Component, StorageOperationStatus> resourceEither = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
+ if (resourceEither.isRight() ) {
+ log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
+ ResponseFormat responseFormat = componentsUtils
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(resourceEither.right().value()));
+ return Either.right(responseFormat);
+ }
+
+ Component fetchedComponent = resourceEither.left().value();
+
+ Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils()
+ .updateForwardingPathOnVersionChange(service, dataHolder, fetchedComponent, newInstanceId);
+ Map<String, ForwardingPathDataDefinition> updated = pair.getValue0();
+ Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1();
+ if (deleted != null && !deleted.isEmpty()) {
+ Either<Set<String>, ResponseFormat> deleteEither = serviceBusinessLogic
+ .deleteForwardingPaths(service.getUniqueId(), new HashSet<>(deleted.keySet()), user, false);
+ if (deleteEither.isRight()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Failed to delete forwarding paths : {}", deleted.values().stream()
+ .map(ForwardingPathDataDefinition::getName).collect(Collectors.joining(", ", "( ", " )")));
+ }
+ return Either.right(deleteEither.right().value());
+ }
+ deleted.keySet().forEach(key -> service.getForwardingPaths().remove(key));
+ }
+ if (updated != null && !updated.isEmpty()) {
+ Service updateFPService = new Service();
+ updateFPService.setForwardingPaths(updated);
+ Either<Service, ResponseFormat> updateFPEither = serviceBusinessLogic
+ .updateForwardingPath(service.getUniqueId(), updateFPService, user, false);
+ if (updateFPEither.isRight()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Failed to update forwarding paths : {}", updated.values().stream()
+ .map(ForwardingPathDataDefinition::getName).collect(Collectors.joining(", ", "( ", " )")));
+ }
+ return Either.right(updateFPEither.right().value());
+ }
+ updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key,forwardingPathDataDefinition));
+ }
+ return Either.left(updatedContainerComponent);
+ }
+
+
+ private List<CapabilityDefinition> getAllInstanceCapabilities(ComponentInstance currentResourceInstance) {
+ return currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java
index 1561cdc797..3938281ad2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java
@@ -1,8 +1,6 @@
package org.openecomp.sdc.be.components.merge.instance;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -17,7 +15,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
/**
* Created by chaya on 9/20/2017.
@@ -25,7 +24,7 @@ import fj.data.Either;
@org.springframework.stereotype.Component("ComponentInstanceHeatEnvMerge")
public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInterface {
- private static Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(ComponentInstanceHeatEnvMerge.class);
@Autowired
private ArtifactsBusinessLogic artifactsBusinessLogic;
@@ -52,7 +51,7 @@ public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInte
Map<String, Object> json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null);
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json,
- artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update), null);
+ artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE), null);
if (uploadArtifactToService.isRight()) {
log.error("Failed to update artifact {} on resourceInstance {}", artifactInfo.getArtifactLabel(), newInstanceId);
return Either.right(uploadArtifactToService.right().value());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java
index 4e49eef94c..2e289456e6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBL.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java
@@ -1,9 +1,7 @@
-package org.openecomp.sdc.be.components.merge.property;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
+package org.openecomp.sdc.be.components.merge.instance;
+import fj.data.Either;
+import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
@@ -13,10 +11,12 @@ import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
@org.springframework.stereotype.Component
-public class ComponentInstanceInputsMergeBL {
+public class ComponentInstanceInputsMergeBL implements ComponentsMergeCommand {
@javax.annotation.Resource
private ToscaOperationFacade toscaOperationFacade;
@@ -27,13 +27,19 @@ public class ComponentInstanceInputsMergeBL {
@javax.annotation.Resource
private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic;
- public ActionStatus mergeComponentInstancesInputs(Component oldComponent, Component newComponent) {
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = newComponent.getComponentInstancesInputs();
+ @Override
+ public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs = currentComponent.getComponentInstancesInputs();
if (componentInstancesInputs == null) {
return ActionStatus.OK;
}
- componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(oldComponent, newComponent, instanceId, instInputs));
- return updateComponentInstancesInputs(newComponent, componentInstancesInputs);
+ componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs));
+ return updateComponentInstancesInputs(currentComponent, componentInstancesInputs);
+ }
+
+ @Override
+ public String description() {
+ return "merge component instance inputs";
}
public ActionStatus mergeComponentInstanceInputs(List<ComponentInstanceInput> oldInstProps, List<InputDefinition> oldInputs, Component newComponent, String instanceId) {
@@ -68,5 +74,4 @@ public class ComponentInstanceInputsMergeBL {
propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstInputs, oldInputs, instInputs, newComponent.getInputs());
}
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java
index 04af6b7fc0..d17469a287 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java
@@ -1,7 +1,6 @@
package org.openecomp.sdc.be.components.merge.instance;
-import java.util.List;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
@@ -15,14 +14,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.List;
/**
* Created by chaya on 9/12/2017.
*/
@org.springframework.stereotype.Component("componentInstanceMergeDataBusinessLogic")
public class ComponentInstanceMergeDataBusinessLogic {
- private static Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(ComponentInstanceMergeDataBusinessLogic.class);
@Autowired
private List<ComponentInstanceMergeInterface> componentInstancesMergeBLs;
@@ -60,7 +59,7 @@ public class ComponentInstanceMergeDataBusinessLogic {
*/
public Either<Component, ResponseFormat> mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, String newContainerComponentId, String newInstanceId) {
- Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId);
+ Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities(newContainerComponentId);
if (componentWithInstancesInputsAndProperties.isRight()) {
log.error("Component with id {} was not found", newContainerComponentId);
StorageOperationStatus storageOperationStatus = componentWithInstancesInputsAndProperties.right().value();
@@ -79,12 +78,15 @@ public class ComponentInstanceMergeDataBusinessLogic {
return Either.left(updatedContainerComponent);
}
- private Either<Component, StorageOperationStatus> getComponentWithInstancesInputsAndProperties(String containerComponentId) {
+ private Either<Component, StorageOperationStatus> getComponentWithInstancesMergeEntities(String containerComponentId) {
ComponentParametersView filter = new ComponentParametersView(true);
filter.setIgnoreComponentInstances(false);
filter.setIgnoreComponentInstancesInputs(false);
filter.setIgnoreComponentInstancesProperties(false);
+ filter.setIgnoreCapabilities(false);
+ filter.setIgnoreCapabiltyProperties(false);
filter.setIgnoreArtifacts(false);
+ filter.setIgnoreForwardingPath(false);
return toscaOperationFacade.getToscaElement(containerComponentId, filter);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java
index 1d2849b94c..f4bcfdab5c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java
@@ -1,12 +1,11 @@
package org.openecomp.sdc.be.components.merge.instance;
+import fj.data.Either;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
-
/**
* Created by chaya on 9/20/2017.
*/
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java
index 43e3ec624a..99b1d389ed 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBL.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java
@@ -1,22 +1,21 @@
-package org.openecomp.sdc.be.components.merge.property;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
+package org.openecomp.sdc.be.components.merge.instance;
+import fj.data.Either;
+import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
@org.springframework.stereotype.Component
-public class ComponentInstancePropertiesMergeBL {
+public class ComponentInstancePropertiesMergeBL implements ComponentsMergeCommand {
@javax.annotation.Resource
private ToscaOperationFacade toscaOperationFacade;
@@ -27,13 +26,19 @@ public class ComponentInstancePropertiesMergeBL {
@javax.annotation.Resource
private DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic;
- public ActionStatus mergeComponentInstancesProperties(Component oldComponent, Resource newResource) {
- Map<String, List<ComponentInstanceProperty>> newInstProps = newResource.getComponentInstancesProperties();
+ @Override
+ public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
+ Map<String, List<ComponentInstanceProperty>> newInstProps = currentComponent.getComponentInstancesProperties();
if (newInstProps == null) {
return ActionStatus.OK;
}
- newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(oldComponent, newResource, instanceId, newProps) );
- return updateComponentInstancesProperties(newResource, newInstProps);
+ newInstProps.forEach((instanceId, newProps) -> mergeOldInstancePropertiesValues(prevComponent, currentComponent, instanceId, newProps) );
+ return updateComponentInstancesProperties(currentComponent, newInstProps);
+ }
+
+ @Override
+ public String description() {
+ return "merge component instance properties";
}
@@ -68,6 +73,4 @@ public class ComponentInstancePropertiesMergeBL {
return ActionStatus.OK;
}
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java
index 765ddb57f6..b63cc38690 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java
@@ -1,20 +1,10 @@
package org.openecomp.sdc.be.components.merge.instance;
-import java.util.ArrayList;
-import java.util.List;
-
+import fj.data.Either;
import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.exception.ResponseFormat;
@@ -22,7 +12,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
/**
* Created by chaya on 9/20/2017.
@@ -30,7 +21,7 @@ import fj.data.Either;
@org.springframework.stereotype.Component("ComponentInstancePropsAndInputsMerge")
public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMergeInterface {
- private static Logger log = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class.getName());
+ private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInstancePropsAndInputsMerge.class);
@Autowired
private ToscaOperationFacade toscaOperationFacade;
@@ -81,19 +72,19 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
ActionStatus actionStatus = componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId);
if (actionStatus != ActionStatus.OK) {
- log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps);
+ LOGGER.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps);
return Either.right(actionStatus);
}
return Either.left(newComponentInstancesProps);
}
private Either<List<ComponentInstanceInput>, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) {
- List<ComponentInstanceInput> originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs();
+ List<ComponentInstanceInput> originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs();
List<InputDefinition> originComponentsInputs = dataHolder.getOrigComponentInputs();
List<ComponentInstanceInput> newComponentInstancesInputs = updatedComponent.safeGetComponentInstanceInput(instanceId);
ActionStatus actionStatus = resourceInstanceInputsMergeBL.mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, instanceId);
if (actionStatus != ActionStatus.OK) {
- log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs);
+ LOGGER.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs);
return Either.right(actionStatus);
}
return Either.left(newComponentInstancesInputs);
@@ -106,14 +97,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
// get instance inputs and properties after merge
Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId);
if (componentWithInstancesInputsAndProperties.isRight()) {
- log.error("Component %s was not found", newContainerComponentId);
+ LOGGER.error("Component %s was not found", newContainerComponentId);
return Either.right(componentsUtils.convertFromStorageResponse(componentWithInstancesInputsAndProperties.right().value()));
}
Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value();
ActionStatus redeclareStatus = resourceInputsMergeBL.redeclareComponentInputsForInstance(origComponentInputs, updatedContainerComponent, newInstanceId);
if (redeclareStatus != ActionStatus.OK) {
- log.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer);
+ LOGGER.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer);
Either.right(redeclareStatus);
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java
new file mode 100644
index 0000000000..96f878abe0
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java
@@ -0,0 +1,416 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+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.RelationshipInfo;
+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.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.att.aft.dme2.internal.google.common.annotations.VisibleForTesting;
+
+import fj.data.Either;
+
+
+@org.springframework.stereotype.Component("ComponentInstanceRelashionMerge")
+public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInterface {
+ private static Logger log = LoggerFactory.getLogger(ComponentInstanceRelationMerge.class);
+
+ @Autowired
+ private ComponentsUtils componentsUtils;
+
+ @Autowired
+ private MergeInstanceUtils mergeInstanceUtils;
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+
+ @Override
+ public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+ //All Relationships - container (service) holds info about all relations
+ //Filter by UniqueId in from/to
+ List<RequirementCapabilityRelDef> relationsFrom = getRelations(RequirementCapabilityRelDef::getFromNode,
+ containerComponent,
+ currentResourceInstance);
+
+ List<RequirementCapabilityRelDef> relationsTo = getRelations(RequirementCapabilityRelDef::getToNode,
+ containerComponent,
+ currentResourceInstance);
+
+ if (!relationsFrom.isEmpty() || !relationsTo.isEmpty()) {
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(currentResourceInstance, originComponent);
+
+ if (vfcInstances != null) {
+ List<RelationMergeInfo> fromRelInfoList = convert(relationsFrom, rel -> mapRelationRequirement(rel, vfcInstances));
+ List<RelationMergeInfo> toRelInfoList = convert(relationsTo, rel -> mapRelationCapability(rel, vfcInstances));
+
+ // Encapsulate all needed info in one container
+ VfRelationsMergeInfo vfRelationsMergeInfo = new VfRelationsMergeInfo(fromRelInfoList, toRelInfoList);
+ // Save it
+ dataHolder.setVfRelationsInfo(vfRelationsMergeInfo);
+ }
+ }
+ else {
+ log.debug("No relations relevant to currentResourceInstance {} found in container component", currentResourceInstance);
+ }
+
+ }
+
+
+ @Override
+ public Either<Component, ResponseFormat> mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
+ Wrapper<Either<Component, ResponseFormat>> resultWrapper = new Wrapper<>();
+
+ VfRelationsMergeInfo vfRelationsMergeInfo = getRelationsMergeInfo(dataHolder, updatedContainerComponent, resultWrapper);
+
+ ComponentInstance newComponentInstance = null;
+ if(resultWrapper.isEmpty()) {
+ //Component Instance
+ newComponentInstance = loadComponentInstance(updatedContainerComponent, newInstanceId, resultWrapper);
+ }
+
+ if(resultWrapper.isEmpty() && vfRelationsMergeInfo != null) {
+ // Load VFCI and filter them by name
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(newComponentInstance);
+ if(vfcInstances != null) {
+ Map<String, ComponentInstance> vfciMap = mergeInstanceUtils.convertToVfciNameMap(vfcInstances);
+
+ // Process Relationships
+ List<RelationMergeInfo> toRelationsInfo = vfRelationsMergeInfo.getToRelationsInfo();
+ Stream<RequirementCapabilityRelDef> toRelationsInfoStream = null;
+ if (toRelationsInfo != null) {
+ toRelationsInfoStream = toRelationsInfo.stream()
+ .map(oldCapInfo -> restoreCapabilityRelation(oldCapInfo, newInstanceId, vfciMap, updatedContainerComponent))
+ .filter(Objects::nonNull);
+ }
+
+ List<RelationMergeInfo> fromRelationsInfo = vfRelationsMergeInfo.getFromRelationsInfo();
+ Stream<RequirementCapabilityRelDef> fromRelationsInfoStream = null;
+ if( fromRelationsInfo != null) {
+ //For Each old requirement relation info
+ fromRelationsInfoStream = fromRelationsInfo.stream()
+ .map(oldReqInfo -> restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent))
+ .filter(Objects::nonNull);
+ }
+
+ // Save relations in updated container (service)
+ List<RequirementCapabilityRelDef> updatedRelations = getUpdatedRelations(toRelationsInfoStream, fromRelationsInfoStream);
+ StorageOperationStatus saveResult = toscaOperationFacade.associateResourceInstances(updatedContainerComponent.getUniqueId(), updatedRelations);
+ if (saveResult == StorageOperationStatus.OK) {
+ resultWrapper.setInnerElement(Either.left(updatedContainerComponent));
+ }
+ else {
+ log.debug("Failed to associate instances of resource {} status is {}", updatedContainerComponent.getUniqueId(), saveResult);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(saveResult), updatedContainerComponent.getUniqueId());
+ resultWrapper.setInnerElement(Either.right(responseFormat));
+ }
+ }
+ }
+
+ return resultWrapper.getInnerElement();
+ }
+
+ @VisibleForTesting
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }
+
+
+ @VisibleForTesting
+ public void setComponentsUtils(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
+
+ @VisibleForTesting
+ public void setMergeInstanceUtils(MergeInstanceUtils mergeInstanceUtils) {
+ this.mergeInstanceUtils = mergeInstanceUtils;
+ }
+
+ /**
+ * @param containerComponent
+ * @param instanceId
+ * @param resultWrapper
+ * @return
+ */
+ private ComponentInstance loadComponentInstance(Component containerComponent, String instanceId,
+ Wrapper<Either<Component, ResponseFormat>> resultWrapper) {
+ ComponentInstance componentInstance = containerComponent.getComponentInstanceById(instanceId).orElse(null);
+ if (componentInstance == null) {
+ log.debug("Failed to get VF instance by new VF instance ID: {}", instanceId);
+ resultWrapper.setInnerElement(Either.left(containerComponent));
+ }
+
+ return componentInstance;
+ }
+
+
+ private List<RequirementCapabilityRelDef> getUpdatedRelations(Stream<RequirementCapabilityRelDef> toRelationsInfoStream,
+ Stream<RequirementCapabilityRelDef> fromRelationsInfoStream) {
+ Stream<RequirementCapabilityRelDef> updatedRelationsStream = Stream.empty();
+
+ if (toRelationsInfoStream != null) {
+ updatedRelationsStream = Stream.concat(updatedRelationsStream, toRelationsInfoStream);
+ }
+
+ if (fromRelationsInfoStream != null) {
+ updatedRelationsStream = Stream.concat(updatedRelationsStream, fromRelationsInfoStream);
+ }
+
+ return updatedRelationsStream.collect(Collectors.toList());
+ }
+
+ private List<RequirementCapabilityRelDef> getRelations(Function<RequirementCapabilityRelDef, String> getNodeFunc,
+ Component containerComponent,
+ ComponentInstance currentResourceInstance) {
+
+ final List<RequirementCapabilityRelDef> componentInstancesRelations = containerComponent.getComponentInstancesRelations();
+ final String vfInstanceId = currentResourceInstance.getUniqueId();
+
+ return componentInstancesRelations.stream()
+ .filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId))
+ .collect(Collectors.toList());
+ }
+
+ private List<RelationMergeInfo> convert(List<RequirementCapabilityRelDef> relationsDef,
+ Function<RequirementCapabilityRelDef, RelationMergeInfo> mapFunc) {
+ return relationsDef.stream()
+ .map(mapFunc::apply)
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
+ }
+
+ private RelationMergeInfo mapRelationCapability(RequirementCapabilityRelDef relDef, List<ComponentInstance> vfcInstances) {
+ // Id of the VfcInstance that is the owner of the capability
+ String ownerId = relDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId();
+ return createRelationMergeInfo(vfcInstances, ownerId, currVfcInst -> mapVfcInstanceCapability(currVfcInst, relDef));
+ }
+
+ private RelationMergeInfo mapRelationRequirement(RequirementCapabilityRelDef relDef, List<ComponentInstance> vfcInstances) {
+ // Id of the VfcInstance that is the owner of the requirement
+ String ownerId = relDef.resolveSingleRelationship().getRelation().getRequirementOwnerId();
+ return createRelationMergeInfo(vfcInstances, ownerId, currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relDef));
+ }
+
+ private RelationMergeInfo createRelationMergeInfo(List<ComponentInstance> vfcInstances, String ownerId, Function<ComponentInstance, RelationMergeInfo> mapFunc) {
+ return vfcInstances.stream()
+ .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId))
+ .map(mapFunc::apply)
+ .filter(Objects::nonNull)
+ .findAny()
+ .orElse(null);
+ }
+
+
+ private RelationMergeInfo mapVfcInstanceCapability(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) {
+ String capabilityUniqueId = relDef.resolveSingleRelationship().getRelation().getCapabilityUid();
+
+
+ String vfcInstanceName = vfcInstance.getName();
+ String vfcUid = vfcInstance.getComponentUid();
+
+ Either<Resource, StorageOperationStatus> vfcResource = toscaOperationFacade.getToscaElement(vfcUid);
+ if(vfcResource.isLeft()) {
+ Resource vfc = vfcResource.left().value();
+
+ CapabilityDefinition capabilityDef = retrieveCapabilityDefinition(capabilityUniqueId, vfc);
+ String capabilityType;
+ String capabilityName;
+ if (capabilityDef != null) {
+ capabilityType = capabilityDef.getType();
+ capabilityName = capabilityDef.getName();
+ }
+ else {
+ log.debug("Failed to retrieve capability type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getCapability(), capabilityUniqueId);
+ capabilityType = null;
+ capabilityName = null;
+ }
+
+ return new RelationMergeInfo(capabilityType, capabilityName, vfcInstanceName, relDef);
+ }
+ else {
+ log.debug("Failed to load VFC by uid {}", vfcUid);
+ return null;
+ }
+ }
+
+ private RelationMergeInfo mapVfcInstanceRequirement(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) {
+ String requirementUniqueId = relDef.resolveSingleRelationship().getRelation().getRequirementUid();
+
+ String vfcInstanceName = vfcInstance.getName();
+ String vfcUid = vfcInstance.getComponentUid();
+
+ Either<Resource, StorageOperationStatus> vfcResource = toscaOperationFacade.getToscaElement(vfcUid);
+ if(vfcResource.isLeft()) {
+ Resource vfc = vfcResource.left().value();
+
+ RequirementDefinition requirementDef = retrieveRequirementDefinition(requirementUniqueId, vfc);
+ String requirementType;
+ String requirementName;
+ if (requirementDef != null) {
+ requirementType = requirementDef.getCapability();
+ requirementName = requirementDef.getName();
+ }
+ else {
+ log.debug("Failed to retrieve requirement type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId);
+ requirementType = null;
+ requirementName = null;
+ }
+
+ return new RelationMergeInfo(requirementType, requirementName, vfcInstanceName, relDef);
+ }
+ else {
+ log.debug("Failed to load VFC by uid {}", vfcUid);
+ return null;
+ }
+ }
+
+ private CapabilityDefinition retrieveCapabilityDefinition(String uniqueId, Resource vfc) {
+ return vfc.getCapabilities().values().stream()
+ .flatMap(List::stream)
+ .filter(Objects::nonNull)
+ .filter(def -> uniqueId.equals(def.getUniqueId()))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private String retrieveCapabilityUid(String name, Component vfc) {
+ return vfc.getCapabilities().values().stream()
+ .flatMap(List::stream)
+ .filter(Objects::nonNull)
+ .filter(def -> name.equals(def.getName()))
+ .findFirst()
+ .map(CapabilityDefinition::getUniqueId)
+ .orElse(null);
+ }
+
+ private RequirementDefinition retrieveRequirementDefinition(String uniqueId, Resource vfc) {
+ return vfc.getRequirements().values().stream()
+ .flatMap(List::stream)
+ .filter(Objects::nonNull)
+ .filter(def -> uniqueId.equals(def.getUniqueId()))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private String retrieveRequirementUid(String name, Component vfc) {
+ return vfc.getRequirements().values().stream()
+ .flatMap(List::stream)
+ .filter(Objects::nonNull)
+ .filter(def -> name.equals(def.getName()))
+ .findFirst()
+ .map(RequirementDefinition::getUniqueId)
+ .orElse(null);
+ }
+
+
+
+ private VfRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder,
+ Component updatedContainerComponent,
+ Wrapper<Either<Component, ResponseFormat>> resultWrapper) {
+ VfRelationsMergeInfo vfRelationsMergeInfo = dataHolder.getVfRelationsMergeInfo();
+ if (vfRelationsMergeInfo == null) {
+ log.debug("There is no info about relations should be restored.");
+ resultWrapper.setInnerElement(Either.left(updatedContainerComponent));
+ }
+
+ return vfRelationsMergeInfo;
+ }
+
+
+ private RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo,
+ String newInstanceId,
+ Map<String, ComponentInstance> vfciMap,
+ Component updatedContainerComponent) {
+ String oldVfcInstanceName = oldCapInfo.getVfcInstanceName();
+
+ ComponentInstance newVfcInstance = vfciMap.get(oldVfcInstanceName);
+ if (newVfcInstance != null) {
+ // Append relation to updated container
+ RequirementCapabilityRelDef oldRelDef = oldCapInfo.getRelDef();
+ oldRelDef.setToNode(newInstanceId);
+
+ RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation();
+ oldRelationshipInfo.setCapabilityOwnerId(newVfcInstance.getUniqueId());
+ oldRelationshipInfo.getRelationship().setType(oldCapInfo.getCapReqType());
+
+
+ String vfcUid = newVfcInstance.getComponentUid();
+ Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(vfcUid);
+
+ if(eitherComponent.isLeft()) {
+ String capabilityUid = retrieveCapabilityUid(oldCapInfo.getCapReqName() , eitherComponent.left().value());
+ oldRelationshipInfo.setCapabilityUid(capabilityUid);
+ }
+ else {
+ log.debug("Unexpected error: resource was not loaded for VF ID: {}", vfcUid);
+ }
+
+ updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef);
+ return oldRelDef;
+ }
+ else {
+ log.debug("Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName);
+ return null;
+ }
+ }
+
+
+
+ private RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo,
+ String newInstanceId,
+ Map<String, ComponentInstance> vfciMap,
+ Component updatedContainerComponent) {
+ String oldVfcInstanceName = oldReqInfo.getVfcInstanceName();
+
+ ComponentInstance newVfcInstance = vfciMap.get(oldReqInfo.getVfcInstanceName());
+ if (newVfcInstance != null) {
+ // Append relation to updated container
+ RequirementCapabilityRelDef oldRelDef = oldReqInfo.getRelDef();
+ oldRelDef.setFromNode(newInstanceId);
+
+ RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation();
+ oldRelationshipInfo.setRequirementOwnerId(newVfcInstance.getUniqueId());
+ oldRelationshipInfo.getRelationship().setType(oldReqInfo.getCapReqType());
+
+ String vfcUid = newVfcInstance.getComponentUid();
+ Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(vfcUid);
+
+ if(eitherComponent.isLeft()) {
+ String requirementUid = retrieveRequirementUid(oldReqInfo.getCapReqName() , eitherComponent.left().value());
+ oldRelationshipInfo.setRequirementUid(requirementUid);
+ }
+ else {
+ log.debug("Unexpected error: resource was not loaded for VF ID: {}", vfcUid);
+ }
+
+ updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef);
+ return oldRelDef;
+ }
+ else {
+ log.debug("Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName);
+ return null;
+ }
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java
new file mode 100644
index 0000000000..5dcb1dda79
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentsMergeCommand.java
@@ -0,0 +1,22 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+
+public interface ComponentsMergeCommand {
+
+ /**
+ * encapsulates the logic of merging component inner entities from the previous component into the currently updated component
+ * @param prevComponent the old component, whose entities need to be merged
+ * @param currentComponent the new component, whose entities need to be merged
+ * @return the status of the merge process
+ */
+ ActionStatus mergeComponents(Component prevComponent, Component currentComponent);
+
+ /**
+ *
+ * @return short description of the command for logging purposes
+ */
+ String description();
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java
index c5fb1d4a86..ac0959897d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java
@@ -6,8 +6,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
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.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.InputDefinition;
@@ -23,6 +24,10 @@ public class DataForMergeHolder {
private Map<String, ArtifactDefinition> origCompInstDeploymentArtifactsCreatedOnTheInstance;
private Map<String, ArtifactDefinition> origCompInstInformationalArtifactsCreatedOnTheInstance;
private List<ArtifactDefinition> origComponentInstanceHeatEnvArtifacts;
+ private VfRelationsMergeInfo vfRelationsMergeInfo;
+ private List<CapabilityDefinition> origInstanceCapabilities;
+ private Component origInstanceNode;
+ private String origComponentInstId;
public DataForMergeHolder() {
origComponentInstanceInputs = new ArrayList<>();
@@ -30,7 +35,7 @@ public class DataForMergeHolder {
origComponentInputs = new ArrayList<>();
origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>();
origCompInstDeploymentArtifactsCreatedOnTheInstance = new HashMap<>();
-
+ origInstanceCapabilities = new ArrayList<>();
}
public List<ArtifactDefinition> getOrigComponentInstanceHeatEnvArtifacts() {
@@ -109,6 +114,35 @@ public class DataForMergeHolder {
origCompInstInformationalArtifactsCreatedOnTheInstance = origInformationalArtifacts;
}
+ public void setVfRelationsInfo(VfRelationsMergeInfo vfRelationsMergeInfo) {
+ this.vfRelationsMergeInfo = vfRelationsMergeInfo;
+ }
+
+ public VfRelationsMergeInfo getVfRelationsMergeInfo() {
+ return vfRelationsMergeInfo;
+ }
+
+ public List<CapabilityDefinition> getOrigInstanceCapabilities() {
+ return origInstanceCapabilities;
+ }
+ public void setOrigInstanceCapabilities(List<CapabilityDefinition> origInstanceCapabilities) {
+ this.origInstanceCapabilities = origInstanceCapabilities;
+ }
+ public Component getOrigInstanceNode() {
+ return origInstanceNode;
+ }
+
+ public void setOrigInstanceNode(Component origInstanceNode) {
+ this.origInstanceNode = origInstanceNode;
+ }
+
+ public String getOrigComponentInstId() {
+ return origComponentInstId;
+ }
+
+ public void setOrigComponentInstId(String origComponentInstId) {
+ this.origComponentInstId = origComponentInstId;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java
new file mode 100644
index 0000000000..4ab802ad35
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java
@@ -0,0 +1,49 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+
+public class RelationMergeInfo {
+ private String capReqType;
+ private String vfcInstanceName;
+ private RequirementCapabilityRelDef relDef;
+ private String capReqName;
+
+ public RelationMergeInfo(String capReqType, String capReqName, String vfcInstanceName, RequirementCapabilityRelDef relDef) {
+ this.capReqType = capReqType;
+ this.capReqName = capReqName;
+ this.vfcInstanceName = vfcInstanceName;
+ this.relDef = relDef;
+ }
+
+ public String getCapReqType() {
+ return capReqType;
+ }
+
+ public void setCapReqType(String type) {
+ this.capReqType = type;
+ }
+
+ public String getVfcInstanceName() {
+ return vfcInstanceName;
+ }
+
+ public void setVfcInstanceName(String vfcInstanceName) {
+ this.vfcInstanceName = vfcInstanceName;
+ }
+
+ public RequirementCapabilityRelDef getRelDef() {
+ return relDef;
+ }
+
+ public void setRelDef(RequirementCapabilityRelDef relDef) {
+ this.relDef = relDef;
+ }
+
+ public String getCapReqName() {
+ return capReqName;
+ }
+
+ public void setCapReqName(String capReqName) {
+ this.capReqName = capReqName;
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java
new file mode 100644
index 0000000000..e116b66408
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/VfRelationsMergeInfo.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import java.util.List;
+
+public class VfRelationsMergeInfo {
+ private List<RelationMergeInfo> fromRelationsInfo;
+ private List<RelationMergeInfo> toRelationsInfo;
+
+ public VfRelationsMergeInfo(List<RelationMergeInfo> fromRelationsInfo, List<RelationMergeInfo> toRelationsInfo) {
+ this.fromRelationsInfo = fromRelationsInfo;
+ this.toRelationsInfo = toRelationsInfo;
+ }
+
+ public List<RelationMergeInfo> getFromRelationsInfo() {
+ return fromRelationsInfo;
+ }
+
+ public void setFromRelationsInfo(List<RelationMergeInfo> fromRelationsInfo) {
+ this.fromRelationsInfo = fromRelationsInfo;
+ }
+
+ public List<RelationMergeInfo> getToRelationsInfo() {
+ return toRelationsInfo;
+ }
+
+ public void setToRelationsInfo(List<RelationMergeInfo> toRelationsInfo) {
+ this.toRelationsInfo = toRelationsInfo;
+ }
+
+} \ No newline at end of file
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java
index 96d3bce97e..139ac386a1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java
@@ -1,11 +1,12 @@
package org.openecomp.sdc.be.components.merge.property;
-import java.util.List;
-
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
import org.springframework.stereotype.Component;
+import java.util.Collections;
+import java.util.List;
+
@Component
public class DataDefinitionsValuesMergingBusinessLogic {
@@ -30,6 +31,11 @@ public class DataDefinitionsValuesMergingBusinessLogic {
}
+ public <T extends PropertyDataDefinition> void mergeInstanceDataDefinitions(List<T> oldInstanceDataDefinition, List<T> updatedInstanceDataDefinition) {
+ List<InputDefinition> emptyInputsList = Collections.emptyList();
+ mergeInstanceDataDefinitions(oldInstanceDataDefinition, emptyInputsList, updatedInstanceDataDefinition, emptyInputsList);
+ }
+
private void mergeInstanceDefinition(MergePropertyData mergeData) {
if (isSameType(mergeData.getOldProp(), mergeData.getNewProp())) {
propertyValueMergeBL.mergePropertyValue(mergeData.getOldProp(), mergeData.getNewProp(), mergeData.getGetInputNamesToMerge());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java
index 63a7a1b3a0..df65c1161f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java
@@ -1,10 +1,10 @@
package org.openecomp.sdc.be.components.merge.property;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+
import java.util.ArrayList;
import java.util.List;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-
/**
* A POJO which represents an instance property data definition (a {@link org.openecomp.sdc.be.model.ComponentInstanceProperty} or {@link org.openecomp.sdc.be.model.ComponentInstanceInput})
* that its value needs to be merged during an upgrade of a VSP.
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java
index 6b083596c7..318840d60a 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java
@@ -1,15 +1,7 @@
package org.openecomp.sdc.be.components.merge.property;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
-import org.openecomp.sdc.be.components.impl.ImportUtils;
+import com.google.gson.Gson;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
@@ -22,9 +14,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import com.google.gson.Gson;
-
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.*;
+import java.util.stream.Collectors;
@Component
public class PropertyDataValueMergeBusinessLogic {
@@ -88,39 +80,6 @@ public class PropertyDataValueMergeBusinessLogic {
return propertyConvertor.convertToToscaObject(propertyType, propValue, innerType, dataTypes);
}
-
- @SuppressWarnings("unchecked")
- private Object removeUnwantedGetInputValues(Object val, List<String> getInputNamesToMerge) {
- if (val instanceof Map) {
- return removeUnwantedGetInputValues((Map<String, Object>) val, getInputNamesToMerge);
- }
- if (val instanceof List) {
- return removeUnwantedGetInputValues((List<Object>)val, getInputNamesToMerge);
- }
- return val;
- }
-
- private List<Object> removeUnwantedGetInputValues(List<Object> listVal, List<String> getInputNamesToMerge) {
- return listVal.stream().map(val -> removeUnwantedGetInputValues(val, getInputNamesToMerge)).collect(Collectors.toList());
- }
-
- private Map<String, Object> removeUnwantedGetInputValues(Map<String, Object> val, List<String> getInputNamesToMerge) {
- return val.entrySet().stream().filter(entry -> !isGetInputEntry(entry) || isGetInputToMerge(getInputNamesToMerge, entry))
- .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), getInputNamesToMerge)));
- }
-
- private boolean isGetInputToMerge(List<String> getInputNamesToMerge, Map.Entry<String, Object> entry) {
- return getInputNamesToMerge.contains(retrieveGetInputInputName(entry.getValue()));
- }
-
- private String retrieveGetInputInputName(Object getInputValue) {
- return getInputValue instanceof List ? (String)((List) getInputValue).get(0) : (String)getInputValue;
- }
-
- private boolean isGetInputEntry(Map.Entry<String, Object> oldValEntry) {
- return oldValEntry.getKey().equals(ImportUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
- }
-
private boolean isEmptyValue(Object val) {
return val == null ||
val instanceof Map && ((Map) val).isEmpty() ||
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java
index 09f26a39ee..df3030567d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java
@@ -1,15 +1,15 @@
package org.openecomp.sdc.be.components.merge.property;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
public class PropertyInstanceMergeDataBuilder {
private final static PropertyInstanceMergeDataBuilder INSTANCE = new PropertyInstanceMergeDataBuilder();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java
index 88601bb521..9fcb864fe9 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java
@@ -1,13 +1,13 @@
package org.openecomp.sdc.be.components.merge.property;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.components.impl.ImportUtils;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.sdc.be.components.impl.ImportUtils;
-
public abstract class PropertyValueMerger {
abstract Object merge(Object oldVal, Object newVal, List<String> someStrings);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java
index 39381e7322..ce0ed0eed2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/ScalarPropertyValueMerger.java
@@ -1,9 +1,9 @@
package org.openecomp.sdc.be.components.merge.property;
-import java.util.List;
-
import org.springframework.stereotype.Component;
+import java.util.List;
+
@Component("scalar-prop-value-merger")
public class ScalarPropertyValueMerger extends PropertyValueMerger {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java
index 9d11eb9aaf..cdfeded356 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBLFactory.java
@@ -1,14 +1,13 @@
package org.openecomp.sdc.be.components.merge.resource;
+import fj.data.Either;
import org.openecomp.sdc.be.components.merge.GlobalTypesMergeBusinessLogic;
import org.openecomp.sdc.be.components.merge.TopologyComparator;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Resource;
import org.springframework.stereotype.Component;
-import fj.data.Either;
-
@Component
public class MergeResourceBLFactory {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java
index 251fb1a64e..0ffe693187 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java
@@ -1,62 +1,38 @@
package org.openecomp.sdc.be.components.merge.resource;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL;
+import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
+import java.util.List;
+
@Component
public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogic {
- private final static Logger log = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class.getName());
+ private static final Logger LOGGER = LoggerFactory.getLogger(ResourceDataMergeBusinessLogic.class);
- @javax.annotation.Resource
- private ComponentInputsMergeBL inputsValuesMergeBL;
+ private List<ComponentsMergeCommand> componentMergingCommands;
- @javax.annotation.Resource
- private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBL;
-
- @javax.annotation.Resource
- private ComponentInstanceInputsMergeBL instanceInputsValueMergeBL;
+ public ResourceDataMergeBusinessLogic(List<ComponentsMergeCommand> componentMergingCommands) {
+ this.componentMergingCommands = componentMergingCommands;
+ }
@Override
public ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource) {
if (oldResource == null) {
return ActionStatus.OK;
}
-
- ActionStatus mergeInstInputsStatus = instancePropertiesValueMergeBL.mergeComponentInstancesProperties(oldResource, newResource);
- if (mergeInstInputsStatus != ActionStatus.OK) {
- log.error("failed to merge instance properties of resource {} status is {}", newResource.getUniqueId(), mergeInstInputsStatus);
- return mergeInstInputsStatus;
- }
-
- ActionStatus mergeInstPropsStatus = instanceInputsValueMergeBL.mergeComponentInstancesInputs(oldResource, newResource);
- if (mergeInstPropsStatus != ActionStatus.OK) {
- log.error("failed to merge instance inputs of resource {} status is {}", newResource.getUniqueId(), mergeInstPropsStatus);
- return mergeInstPropsStatus;
- }
-
- ActionStatus mergeInputsStatus = mergeInputs(oldResource, newResource);
- if (mergeInputsStatus != ActionStatus.OK) {
- log.error("failed to merge inputs of resource {} status is {}", newResource.getUniqueId(), mergeInputsStatus);
- return mergeInputsStatus;
+ for (ComponentsMergeCommand componentMergeCommand : componentMergingCommands) {
+ ActionStatus mergeStatus = componentMergeCommand.mergeComponents(oldResource, newResource);
+ if (mergeStatus != ActionStatus.OK) {
+ LOGGER.error("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(), mergeStatus);
+ return mergeStatus;
+ }
}
return ActionStatus.OK;
}
- private ActionStatus mergeInputs(Resource oldResource, Resource newResource) {
- List<InputDefinition> inputsToMerge = newResource.getInputs() != null ? newResource.getInputs() : new ArrayList<>();
- return inputsValuesMergeBL.mergeAndRedeclareComponentInputs(oldResource, newResource, inputsToMerge);
- }
-
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java
new file mode 100644
index 0000000000..4ff7e06db5
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java
@@ -0,0 +1,257 @@
+package org.openecomp.sdc.be.components.merge.utils;
+
+import fj.data.Either;
+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.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import static java.util.function.Function.identity;
+
+/**
+ * This class is Utils class but it should be bean
+ * @author dr2032
+ *
+ */
+@org.springframework.stereotype.Component("MergeInstanceUtils")
+public class MergeInstanceUtils {
+ private Logger log = LoggerFactory.getLogger(MergeInstanceUtils.class);
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+ /**
+ * Maps capability owner IDs of old component instance to capability owner IDs of the new component instance
+ * @param container containing new component instance
+ * @param origInstanceNode old component (in case of PROXY it should be actual service)
+ * @param newInstanceId - ID of new instance of the component
+ * @param oldCapabilitiesOwnerIds
+ * @return
+ */
+ public Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container,
+ Component origInstanceNode,
+ String newInstanceId,
+ List<String> oldCapabilitiesOwnerIds) {
+
+ Map<String, String> resultMap;
+
+ if (ModelConverter.isAtomicComponent(origInstanceNode) || isCVFC(origInstanceNode)) {
+ resultMap = prepareMapForAtomicComponent(newInstanceId, oldCapabilitiesOwnerIds);
+ }
+ else {
+ resultMap = prepareMapForNonAtomicComponent(container, origInstanceNode, newInstanceId, oldCapabilitiesOwnerIds);
+ }
+
+ return resultMap;
+ }
+
+
+ private static boolean isCVFC(Component component) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ if (!componentType.equals(ComponentTypeEnum.RESOURCE)) {
+ return false;
+ }
+
+ Resource resource = (Resource) component;
+ ResourceTypeEnum resourceType = resource.getResourceType();
+ return resourceType == ResourceTypeEnum.CVFC;
+ }
+
+
+ /**
+ * Maps capability owner IDs of old component instance to capability owner IDs of the new component instance
+ * @param oldInstance
+ * @param newInstance
+ * @return
+ */
+ public Map<String, String> mapOldToNewCapabilitiesOwnerIds(ComponentInstance oldInstance, ComponentInstance newInstance) {
+ List<ComponentInstance> oldVfcInstances = getVfcInstances(oldInstance);
+ List<ComponentInstance> newVfcInstances = getVfcInstances(newInstance);
+
+ Map<String, ComponentInstance> newVfciNameMap = convertToVfciNameMap(newVfcInstances);
+
+ return oldVfcInstances.stream()
+ .filter(oldVfci -> newVfciNameMap.containsKey(oldVfci.getName()))
+ .collect(Collectors.toMap(ComponentInstance::getUniqueId, oldVfci -> newVfciNameMap.get(oldVfci.getName()).getUniqueId()));
+ }
+
+
+ /**
+ * Method converts list of Component Instances to map of the instances where the key is their name
+ * @param componentInstances
+ * @return
+ */
+ public Map<String, ComponentInstance> convertToVfciNameMap(List<ComponentInstance> componentInstances) {
+ return componentInstances != null ?
+ componentInstances.stream()
+ .collect(Collectors.toMap(ComponentInstance::getName, identity())): Collections.emptyMap();
+ }
+
+
+
+ /**
+ * Returns List of componentInstances by specified componentInstance
+ * If componentInstance is for atomic component the returned list will contain the specified componentInstance only.
+ * @param componentInstance
+ * @return
+ */
+ public List<ComponentInstance> getVfcInstances(ComponentInstance componentInstance) {
+ if (componentInstance == null) {
+ return Collections.emptyList();
+ }
+
+
+ List<ComponentInstance> vfcInstances;
+
+ String componentId = componentInstance.getActualComponentUid();
+ Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(componentId);
+
+ if(eitherComponent.isLeft()) {
+ Component component = eitherComponent.left().value();
+ vfcInstances = getVfcInstances(componentInstance, component);
+ }
+ else {
+ log.debug("Unexpected error: resource was not loaded for VF ID: {}", componentId);
+ vfcInstances = Collections.emptyList();
+ }
+
+ return vfcInstances;
+ }
+
+
+ /**
+ * Returns List of componentInstances by specified componentInstance and component
+ * If componentInstance is for atomic component the returned list will contain the specified componentInstance only.
+ * @param componentInstance
+ * @param eitherComponent
+ * @return
+ */
+ public List<ComponentInstance> getVfcInstances(ComponentInstance componentInstance, Component component) {
+ if (componentInstance == null || component == null) {
+ return Collections.emptyList();
+ }
+
+
+ List<ComponentInstance> vfcInstances;
+
+ if (ModelConverter.isAtomicComponent(component) || isCVFC(component)) {
+ if (componentInstance.getIsProxy()) {
+ // Component is proxy and it doesn't contain required data
+ vfcInstances = getVfcInstances(componentInstance);
+ }
+ else {
+ vfcInstances = Arrays.asList(componentInstance);
+ }
+ }
+ else {
+ vfcInstances = recursiveScanForAtomicComponentInstances(component);
+ }
+
+ return vfcInstances;
+ }
+
+
+ @VisibleForTesting
+ public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ }
+
+
+
+ /**
+ * @param component
+ * @return
+ */
+ private List<ComponentInstance> recursiveScanForAtomicComponentInstances(Component component) {
+ List<ComponentInstance> vfcInstances;
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (componentInstances != null) {
+ // Go recursively to collect atomic components only
+ vfcInstances = componentInstances.stream()
+ .map(this::getVfcInstances)
+ .flatMap(List::stream)
+ .collect(Collectors.toList());
+ }
+ else {
+ vfcInstances = Collections.emptyList();
+ }
+
+ return vfcInstances;
+ }
+
+
+
+ /**
+ * @param newInstanceId
+ * @param oldCapabilitiesOwnerIds
+ * @return
+ */
+ private Map<String, String> prepareMapForAtomicComponent(String newInstanceId, List<String> oldCapabilitiesOwnerIds) {
+ Map<String, String> resultMap;
+
+ int oldCapabilityOwnerIdsSize = oldCapabilitiesOwnerIds.size();
+ if (oldCapabilityOwnerIdsSize == 1) {
+ resultMap = new HashMap<>();
+ resultMap.put(oldCapabilitiesOwnerIds.get(0), newInstanceId);
+ }
+ else {
+ log.debug("For automic component the list of old capabilities owner Ids should contains one element while actual size is {},", oldCapabilityOwnerIdsSize);
+ resultMap = Collections.emptyMap();
+ }
+
+ return resultMap;
+ }
+
+ /**
+ * @param container
+ * @param origInstanceNode
+ * @param newInstanceId
+ * @param oldCapabilitiesOwnerIds
+ * @return
+ */
+ private Map<String, String> prepareMapForNonAtomicComponent(Component container, Component origInstanceNode,
+ String newInstanceId, List<String> oldCapabilitiesOwnerIds) {
+ Map<String, String> resultMap;
+ List<ComponentInstance> oldVfcInstances = recursiveScanForAtomicComponentInstances(origInstanceNode);
+
+ ComponentInstance newInstance = container.getComponentInstanceById(newInstanceId).orElse(null);
+ if (newInstance == null) {
+ log.debug("Failed to get component instance by newInstanceId: {}.", newInstanceId);
+ resultMap = Collections.emptyMap();
+ }
+ else {
+ resultMap = mapOldVfcIdsToNewOnes(oldCapabilitiesOwnerIds, oldVfcInstances, newInstance);
+ }
+ return resultMap;
+ }
+
+ /**
+ * @param oldCapabilitiesOwnerIds
+ * @param oldVfcInstances
+ * @param newInstance
+ * @return
+ */
+ private Map<String, String> mapOldVfcIdsToNewOnes(List<String> oldCapabilitiesOwnerIds,
+ List<ComponentInstance> oldVfcInstances, ComponentInstance newInstance) {
+ List<ComponentInstance> newVfcInstances = getVfcInstances(newInstance);
+ Map<String, ComponentInstance> newVfciNameMap = convertToVfciNameMap(newVfcInstances);
+
+ return oldVfcInstances.stream()
+ .filter(oldVfc -> oldCapabilitiesOwnerIds.contains(oldVfc.getUniqueId()))
+ .filter(oldVfci -> newVfciNameMap.containsKey(oldVfci.getName()))
+ .collect(Collectors.toMap(ComponentInstance::getUniqueId, oldVfci -> newVfciNameMap.get(oldVfci.getName()).getUniqueId()));
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java
new file mode 100644
index 0000000000..469ae31f2d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java
@@ -0,0 +1,173 @@
+package org.openecomp.sdc.be.components.path;
+
+import fj.data.Either;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.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 org.springframework.stereotype.Component;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+@Component("forwardingPathValidator")
+public class ForwardingPathValidator {
+
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ForwardingPathValidator.class);
+ private static final int PATH_NAME_LENGTH = 200;
+ private static final int PROTOCOL_LENGTH = 200;
+ private static final int DESTINATION_PORT_LENGTH = 200;
+
+ public Either<Boolean, ResponseFormat> validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths,
+ String serviceId, boolean isUpdate) {
+ for (ForwardingPathDataDefinition path : paths) {
+ Either<Boolean, ResponseFormat> forwardingPathResponseEither = validateForwardingPath(path,
+ serviceId, isUpdate);
+ if (forwardingPathResponseEither.isRight()) {
+ return forwardingPathResponseEither;
+ }
+ }
+ return Either.left(Boolean.TRUE);
+ }
+
+ private Either<Boolean, ResponseFormat> validateForwardingPath(ForwardingPathDataDefinition path,
+ String serviceId, boolean isUpdate) {
+ ResponseFormatManager responseFormatManager = getResponseFormatManager();
+
+ Either<Boolean, ResponseFormat> errorResponseName = validateName(path,
+ responseFormatManager, serviceId, isUpdate);
+ if (errorResponseName != null)
+ return errorResponseName;
+
+ Either<Boolean, ResponseFormat> protocolErrorResponse = validateProtocol(path, responseFormatManager);
+ if (protocolErrorResponse != null)
+ return protocolErrorResponse;
+
+ Either<Boolean, ResponseFormat> portNumberResponse = validateDestinationPortNumber(path, responseFormatManager);
+ if (portNumberResponse != null)
+ return portNumberResponse;
+
+ return Either.left(true);
+ }
+
+ private Either<Boolean, ResponseFormat> validateDestinationPortNumber(ForwardingPathDataDefinition dataDefinition,
+ ResponseFormatManager responseFormatManager) {
+ if (dataDefinition.getDestinationPortNumber() != null &&
+ dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH ) {
+ LOGGER.debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ",
+ dataDefinition.getDestinationPortNumber());
+ ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
+ .FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH, dataDefinition.getDestinationPortNumber());
+ return Either.right(errorResponse);
+ }
+ return null;
+ }
+
+ private Either<Boolean, ResponseFormat> validateProtocol(ForwardingPathDataDefinition dataDefinition,
+ ResponseFormatManager responseFormatManager) {
+ if (dataDefinition.getProtocol() != null && dataDefinition.getProtocol().length() > PROTOCOL_LENGTH) {
+ LOGGER.debug("Forwarding path protocol {} too long, , maximum allowed 200 characters ", dataDefinition.getProtocol());
+ ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
+ .FORWARDING_PATH_PROTOCOL_MAXIMUM_LENGTH, dataDefinition.getProtocol());
+ return Either.right(errorResponse);
+ }
+ return null;
+ }
+
+ private Either<Boolean, ResponseFormat> validateName(ForwardingPathDataDefinition dataDefinition,
+ ResponseFormatManager responseFormatManager,
+ String serviceId, boolean isUpdate) {
+ String pathName = dataDefinition.getName();
+ Either<Boolean, ResponseFormat> pathEmptyResponse = validatePathNameIfEmpty(responseFormatManager, pathName);
+ if (pathEmptyResponse != null)
+ return pathEmptyResponse;
+
+ Either<Boolean, ResponseFormat> pathLengthResponse = validatePathNameLength(responseFormatManager, pathName);
+ if (pathLengthResponse != null)
+ return pathLengthResponse;
+
+ Either<Boolean, ResponseFormat> isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager );
+ if(isPathNameUniqueResponse.isRight()) {
+ return Either.right(isPathNameUniqueResponse.right().value());
+ }
+ if (!isPathNameUniqueResponse.left().value()) {
+ LOGGER.debug("Forwarding path name {} already in use ", dataDefinition.getName());
+ ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
+ .FORWARDING_PATH_NAME_ALREADY_IN_USE, dataDefinition.getName());
+ return Either.right(errorResponse);
+ }
+ return null;
+ }
+
+ private Either<Boolean, ResponseFormat> validatePathNameLength(ResponseFormatManager responseFormatManager, String pathName) {
+ if (pathName.length() > PATH_NAME_LENGTH) {
+ LOGGER.debug("Forwarding path name {} too long, , maximum allowed 200 characters ", pathName);
+ ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
+ .FORWARDING_PATH_NAME_MAXIMUM_LENGTH, pathName);
+ return Either.right(errorResponse);
+ }
+ return null;
+ }
+
+ private Either<Boolean, ResponseFormat> validatePathNameIfEmpty(ResponseFormatManager responseFormatManager, String pathName) {
+ if (StringUtils.isEmpty(pathName)) {
+ LOGGER.debug("Forwarding Path Name can't be empty");
+ ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.FORWARDING_PATH_NAME_EMPTY);
+ return Either.right(errorResponse);
+ }
+ return null;
+ }
+
+
+ private Either<Boolean, ResponseFormat> validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId,
+ boolean isUpdate, ResponseFormatManager responseFormatManager) {
+ boolean isPathNameUnique = false;
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreForwardingPath(false);
+ Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
+ .getToscaElement(serviceId, filter);
+ if (forwardingPathOrigin.isRight()){
+ return Either.right(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
+ Map<String, String> pathNames = new HashMap<>();
+ allPaths.forEach( path -> pathNames.put(path.getUniqueId(), path.getName()) );
+
+ if (isUpdate){
+ for(Map.Entry<String, String> entry : pathNames.entrySet()){
+ if (entry.getKey().equals(dataDefinition.getUniqueId()) && entry.getValue().
+ equals(dataDefinition.getName())) {
+ isPathNameUnique = true;
+ }
+
+ if(entry.getKey().equals(dataDefinition.getUniqueId()) && !pathNames.values().contains(dataDefinition.getName())){
+ isPathNameUnique = true;
+ }
+ }
+ }
+ else
+ if (!pathNames.values().contains(dataDefinition.getName())){
+ isPathNameUnique = true;
+ }
+
+ return Either.left(isPathNameUnique);
+ }
+
+ protected ResponseFormatManager getResponseFormatManager() {
+ return ResponseFormatManager.getInstance();
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java
new file mode 100644
index 0000000000..f59831621c
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDecelerator.java
@@ -0,0 +1,75 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceInput;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+@org.springframework.stereotype.Component
+public class ComponentInstanceInputPropertyDecelerator extends DefaultPropertyDecelerator<ComponentInstance, ComponentInstanceInput> {
+
+ private static final Logger log = LoggerFactory.getLogger(ComponentInstanceInputPropertyDecelerator.class);
+ private ToscaOperationFacade toscaOperationFacade;
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+ public ComponentInstanceInputPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
+ super(componentsUtils, propertyOperation);
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
+ }
+
+ @Override
+ ComponentInstanceInput createDeclaredProperty(PropertyDataDefinition prop) {
+ return new ComponentInstanceInput(prop);
+ }
+
+ @Override
+ Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceInput> properties) {
+ log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId, component.getUniqueId());
+ Map<String, List<ComponentInstanceInput>> instProperties = Collections.singletonMap(cmptInstanceId, properties);
+ return toscaOperationFacade.addComponentInstanceInputsToComponent(component, instProperties);
+ }
+
+ @Override
+ Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) {
+ log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId());
+ return component.getComponentInstanceById(propertiesOwnerId);
+ }
+
+ @Override
+ void addPropertiesListToInput(ComponentInstanceInput declaredProp, PropertyDataDefinition originalProp, InputDefinition input) {
+ List<ComponentInstanceInput> inputsValueList = input.getInputs();
+ if(inputsValueList == null) {
+ inputsValueList = new ArrayList<>(); // adding the property with the new value for UI
+ }
+ inputsValueList.add(declaredProp);
+ input.setInputs(inputsValueList);
+ }
+
+ @Override
+ public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) {
+ List<ComponentInstanceInput> componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId());
+ if (CollectionUtils.isEmpty(componentInstanceInputsByInputId)) {
+ return StorageOperationStatus.OK;
+ }
+ componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath()));
+ return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java
new file mode 100644
index 0000000000..ab4c4e29c2
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDecelerator.java
@@ -0,0 +1,75 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+@org.springframework.stereotype.Component
+public class ComponentInstancePropertyDecelerator extends DefaultPropertyDecelerator<ComponentInstance, ComponentInstanceProperty> {
+
+ private static final Logger log = LoggerFactory.getLogger(ComponentInstancePropertyDecelerator.class);
+ private ToscaOperationFacade toscaOperationFacade;
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+ public ComponentInstancePropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
+ super(componentsUtils, propertyOperation);
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
+ }
+
+ @Override
+ ComponentInstanceProperty createDeclaredProperty(PropertyDataDefinition prop) {
+ return new ComponentInstanceProperty(prop);
+ }
+
+ @Override
+ Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceProperty> properties) {
+ log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId, component.getUniqueId());
+ Map<String, List<ComponentInstanceProperty>> instProperties = Collections.singletonMap(cmptInstanceId, properties);
+ return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties, cmptInstanceId);
+ }
+
+ @Override
+ Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) {
+ log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId());
+ return component.getComponentInstanceById(propertiesOwnerId);
+ }
+
+ @Override
+ void addPropertiesListToInput(ComponentInstanceProperty declaredProp, PropertyDataDefinition originalProp, InputDefinition input) {
+ List<ComponentInstanceProperty> propertiesList = input.getProperties();
+ if(propertiesList == null) {
+ propertiesList = new ArrayList<>(); // adding the property with the new value for UI
+ }
+ propertiesList.add(declaredProp);
+ input.setProperties(propertiesList);
+ }
+
+ @Override
+ public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) {
+ List<ComponentInstanceProperty> componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, input.getUniqueId());
+ if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) {
+ return StorageOperationStatus.OK;
+ }
+ componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath()));
+ return toscaOperationFacade.updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), componentInstancePropertiesDeclaredAsInput);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java
new file mode 100644
index 0000000000..e053096480
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDecelerator.java
@@ -0,0 +1,413 @@
+package org.openecomp.sdc.be.components.property;
+
+import com.google.gson.Gson;
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.json.simple.JSONObject;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
+import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.Yaml;
+
+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.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.common.api.Constants.GET_INPUT;
+
+public abstract class DefaultPropertyDecelerator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements PropertyDecelerator {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultPropertyDecelerator.class);
+ private static final short LOOP_PROTECTION_LEVEL = 10;
+ private final Gson gson = new Gson();
+ private ComponentsUtils componentsUtils;
+ private PropertyOperation propertyOperation;
+
+ public DefaultPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) {
+ this.componentsUtils = componentsUtils;
+ this.propertyOperation = propertyOperation;
+ }
+
+ @Override
+ public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare) {
+ log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId);
+ return resolvePropertiesOwner(component, propertiesOwnerId)
+ .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare))
+ .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
+ }
+
+ abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop);
+
+ abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId, List<PROPERTYTYPE> properties);
+
+ abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId);
+
+ abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, PropertyDataDefinition originalProp, InputDefinition input);
+
+ private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) {
+ log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId);
+ return StorageOperationStatus.NOT_FOUND;
+ }
+
+ private Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, PropertiesOwner propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) {
+ PropertiesDeclarationData inputsProperties = createInputsAndOverridePropertiesValues(component.getUniqueId(), propertiesOwner, propsToDeclare);
+ return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate())
+ .left()
+ .map(updatePropsRes -> inputsProperties.getInputsToCreate());
+ }
+
+ private PropertiesDeclarationData createInputsAndOverridePropertiesValues(String componentId, PropertiesOwner propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) {
+ List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
+ List<InputDefinition> createdInputs = propsToDeclare.stream()
+ .map(propInput -> declarePropertyInput(componentId, propertiesOwner, declaredProperties, propInput))
+ .collect(Collectors.toList());
+ return new PropertiesDeclarationData(createdInputs, declaredProperties);
+ }
+
+ private InputDefinition declarePropertyInput(String componentId, PropertiesOwner propertiesOwner, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) {
+ PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
+ propInput.setOwnerId(null);
+ propInput.setParentUniqueId(null);
+ InputDefinition inputDefinition = createInput(componentId, propertiesOwner, propInput, prop);
+ PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
+ if(!declaredProperties.contains(declaredProperty)){
+ declaredProperties.add(declaredProperty);
+ }
+ addPropertiesListToInput(declaredProperty, prop, inputDefinition);
+ return inputDefinition;
+ }
+
+ private InputDefinition createInput(String componentId, PropertiesOwner propertiesOwner, ComponentInstancePropInput propInput, PropertyDataDefinition prop) {
+ String generatedInputName = generateInputName(propertiesOwner.getNormalizedName(), propInput);
+ return createInputFromProperty(componentId, propertiesOwner, generatedInputName, propInput, prop);
+ }
+
+ private String generateInputName(String inputName, ComponentInstancePropInput propInput) {
+ String[] parsedPropNames = propInput.getParsedPropNames();
+ if(parsedPropNames != null){
+ for(String str: parsedPropNames){
+ inputName += "_" + str;
+ }
+ } else {
+ inputName += "_" + propInput.getName();
+ }
+ return inputName;
+ }
+
+ private PropertyDataDefinition resolveProperty(List<PROPERTYTYPE> propertiesToCreate, ComponentInstancePropInput propInput) {
+ Optional<PROPERTYTYPE> resolvedProperty = propertiesToCreate.stream()
+ .filter(p -> p.getName().equals(propInput.getName()))
+ .findFirst();
+ return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput;
+ }
+
+ private InputDefinition createInputFromProperty(String componentId, PropertiesOwner propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) {
+ String propertiesName = propInput.getPropertiesName() ;
+ PropertyDefinition selectedProp = propInput.getInput();
+ String[] parsedPropNames = propInput.getParsedPropNames();
+ InputDefinition input;
+ boolean complexProperty = false;
+ if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+ complexProperty = true;
+ input = new InputDefinition(selectedProp);
+ }else{
+ input = new InputDefinition(prop);
+ }
+ input.setDefaultValue(prop.getValue());
+ input.setName(inputName);
+ input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, input.getName()));
+ input.setInputPath(propertiesName);
+ input.setInstanceUniqueId(propertiesOwner.getUniqueId());
+ input.setPropertyId(propInput.getUniqueId());
+ changePropertyValueToGetInputValue(inputName, parsedPropNames, input, prop, complexProperty);
+ ((IComponentInstanceConnectedElement)prop).setComponentInstanceId(propertiesOwner.getUniqueId());
+ ((IComponentInstanceConnectedElement)prop).setComponentInstanceName(propertiesOwner.getName());
+ return input;
+ }
+
+ private void changePropertyValueToGetInputValue(String inputName, String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop, boolean complexProperty) {
+ JSONObject jobject = new JSONObject();
+ if(prop.getValue() == null || prop.getValue().isEmpty()){
+ if(complexProperty){
+
+ jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
+ prop.setValue(jobject.toJSONString());
+
+ }else{
+
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+
+ }
+
+ }else{
+
+ String value = prop.getValue();
+ Object objValue = new Yaml().load(value);
+ if( objValue instanceof Map || objValue instanceof List){
+ if(!complexProperty){
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+
+
+ }else{
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
+ createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
+
+ String json = gson.toJson(mappedToscaTemplate);
+ prop.setValue(json);
+
+ }
+
+ }else{
+ jobject.put(GET_INPUT, input.getName());
+ prop.setValue(jobject.toJSONString());
+
+ }
+
+ }
+
+
+ if(CollectionUtils.isEmpty(prop.getGetInputValues())){
+ prop.setGetInputValues(new ArrayList<>());
+ }
+ List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues();
+
+ GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
+ getInputValueDataDefinition.setInputId(input.getUniqueId());
+ getInputValueDataDefinition.setInputName(input.getName());
+ getInputValues.add(getInputValueDataDefinition);
+ }
+
+ private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
+
+ while(i >= 1){
+ if( i == parsedPropNames.length -1){
+ JSONObject jobProp = new JSONObject();
+ jobProp.put(GET_INPUT, inputName);
+ ooj.put(parsedPropNames[i], jobProp);
+ i--;
+ return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
+ }else{
+ JSONObject res = new JSONObject();
+ res.put(parsedPropNames[i], ooj);
+ i --;
+ res = createJSONValueForProperty (i, parsedPropNames, res, inputName);
+ return res;
+ }
+ }
+
+ return ooj;
+ }
+
+ private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
+ while(index < inputNames.length){
+ if(lhm1.containsKey(inputNames[index])){
+ Object value = lhm1.get(inputNames[index]);
+ if (value instanceof Map){
+ if(index == inputNames.length -1){
+ ((Map) value).put(GET_INPUT, inputName);
+ return (Map) value;
+
+ }else{
+ index++;
+ return createInputValue((Map)value, index, inputNames, inputName);
+ }
+ }else{
+ Map<String, Object> jobProp = new HashMap<>();
+ if(index == inputNames.length -1){
+ jobProp.put(GET_INPUT, inputName);
+ lhm1.put(inputNames[index], jobProp);
+ return lhm1;
+ }else{
+ lhm1.put(inputNames[index], jobProp);
+ index++;
+ return createInputValue(jobProp, index, inputNames, inputName);
+ }
+ }
+ }else{
+ Map<String, Object> jobProp = new HashMap<>();
+ lhm1.put(inputNames[index], jobProp);
+ if(index == inputNames.length -1){
+ jobProp.put(GET_INPUT, inputName);
+ return jobProp;
+ }else{
+ index++;
+ return createInputValue(jobProp, index, inputNames, inputName);
+ }
+ }
+ }
+ return lhm1;
+ }
+
+ private class PropertiesDeclarationData {
+ private List<InputDefinition> inputsToCreate;
+ private List<PROPERTYTYPE> propertiesToUpdate;
+
+ PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PROPERTYTYPE> propertiesToUpdate) {
+ this.inputsToCreate = inputsToCreate;
+ this.propertiesToUpdate = propertiesToUpdate;
+ }
+
+ List<InputDefinition> getInputsToCreate() {
+ return inputsToCreate;
+ }
+
+ List<PROPERTYTYPE> getPropertiesToUpdate() {
+ return propertiesToUpdate;
+ }
+ }
+
+ Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, List<String> pathOfComponentInstances) {
+ Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete);
+ String value = inputValue.getValue();
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
+
+ resetInputName(mappedToscaTemplate, inputForDelete.getName());
+
+ value = "";
+ if(!mappedToscaTemplate.isEmpty()){
+ Either result = cleanNestedMap(mappedToscaTemplate , true);
+ Map modifiedMappedToscaTemplate = mappedToscaTemplate;
+ if (result.isLeft())
+ modifiedMappedToscaTemplate = (Map)result.left().value();
+ else
+ log.warn("Map cleanup failed -> " +result.right().value().toString()); //continue, don't break operation
+ value = gson.toJson(modifiedMappedToscaTemplate);
+ }
+ inputValue.setValue(value);
+
+
+ List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues();
+ if(getInputsValues != null && !getInputsValues.isEmpty()){
+ Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId())).findAny();
+ if(op.isPresent()){
+ getInputsValues.remove(op.get());
+ }
+ }
+ inputValue.setGetInputValues(getInputsValues);
+
+ Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), inputValue.getDefaultValue());
+ if (findDefaultValue.isRight()) {
+ deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()))));
+ return deleteEither;
+
+ }
+ String defaultValue = findDefaultValue.left().value();
+ inputValue.setDefaultValue(defaultValue);
+ log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
+ return deleteEither;
+ }
+
+ private void resetInputName(Map<String, Object> lhm1, String inputName){
+ for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
+ value = "";
+ lhm1.remove(key);
+ } else if (value instanceof Map) {
+ Map<String, Object> subMap = (Map<String, Object>)value;
+ resetInputName(subMap, inputName);
+ } else {
+ continue;
+ }
+
+ }
+ }
+
+ private Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone ){
+ if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){
+ if (deepClone){
+ if (!(mappedToscaTemplate instanceof HashMap))
+ return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() );
+ else
+ mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone();
+ }
+ return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , LOOP_PROTECTION_LEVEL ) );
+ }
+ else {
+ log.debug("mappedToscaTemplate is empty ");
+ return Either.right("mappedToscaTemplate is empty ");
+ }
+ }
+
+ /* Mutates the object
+ * Tail recurse -> traverse the tosca elements and remove nested empty map properties
+ * this only handles nested maps, other objects are left untouched (even a Set containing a map) since behaviour is unexpected
+ *
+ * @param toscaElement - expected map of tosca values
+ * @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
+ **/
+ private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){
+ //region - Stop if map is empty
+ if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof Map))
+ return toscaElement;
+ //endregion
+ //region - Remove empty map entries & return null iff empty map
+ if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) {
+ Object ret;
+ Set<Object> keysToRemove = new HashSet<>(); // use different set to avoid ConcurrentModificationException
+ for( Object key : ((Map)toscaElement).keySet() ) {
+ Object value = ((Map) toscaElement).get(key);
+ ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel );
+ if ( ret == null )
+ keysToRemove.add(key);
+ }
+ Collection set = ((Map) toscaElement).keySet();
+ if (CollectionUtils.isNotEmpty(set))
+ set.removeAll(keysToRemove);
+
+ if ( isEmptyNestedMap(toscaElement) ) // similar to < if ( MapUtils.isEmpty( (Map)toscaElement ) ) > ,but adds nested map check
+ return null;
+ }
+ //endregion
+ else
+ return null;
+ return toscaElement;
+ }
+
+ //@returns true iff map nested maps are all empty
+ //ignores other collection objects
+ private boolean isEmptyNestedMap(Object element){
+ boolean isEmpty = true;
+ if (element != null){
+ if ( element instanceof Map ){
+ if (MapUtils.isEmpty((Map)element))
+ isEmpty = true;
+ else
+ {
+ for( Object key : ((Map)(element)).keySet() ){
+ Object value = ((Map)(element)).get(key);
+ isEmpty &= isEmptyNestedMap( value );
+ }
+ }
+ } else {
+ isEmpty = false;
+ }
+ }
+ return isEmpty;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java
new file mode 100644
index 0000000000..e77287de9f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.components.property;
+
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+
+public class GetInputUtils {
+
+ private GetInputUtils() {
+ }
+
+ public static boolean isGetInputValueForInput(GetInputValueDataDefinition inputData, String inputId) {
+ return inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java
new file mode 100644
index 0000000000..be3c82fa09
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDecelerator.java
@@ -0,0 +1,130 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
+
+@org.springframework.stereotype.Component
+public class PolicyPropertyDecelerator extends DefaultPropertyDecelerator<PolicyDefinition, PropertyDataDefinition> {
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyPropertyDecelerator.class);
+ private PolicyOperation policyOperation;
+
+ public PolicyPropertyDecelerator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, PolicyOperation policyOperation) {
+ super(componentsUtils, propertyOperation);
+ this.policyOperation = policyOperation;
+ }
+
+ @Override
+ PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) {
+ return new PropertyDataDefinition(prop);
+ }
+
+ @Override
+ Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId, List<PropertyDataDefinition> properties) {
+ log.debug("#updatePropertiesValues - updating policies properties for policy {} on component {}", policyId, component.getUniqueId());
+ StorageOperationStatus updateStatus = policyOperation.updatePolicyProperties(component, policyId, properties);
+ return updateStatus == StorageOperationStatus.OK ? Either.left(updateStatus) : Either.right(updateStatus);
+ }
+
+ @Override
+ Optional<PolicyDefinition> resolvePropertiesOwner(Component component, String policyId) {
+ log.debug("#resolvePropertiesOwner - fetching policy {} of component {}", policyId, component.getUniqueId());
+ return Optional.ofNullable(component.getPolicyById(policyId));
+ }
+
+ @Override
+ void addPropertiesListToInput(PropertyDataDefinition declaredProp, PropertyDataDefinition originalProp, InputDefinition input) {
+ List<ComponentInstanceProperty> propertiesList = input.getProperties();
+ if(propertiesList == null) {
+ propertiesList = new ArrayList<>(); // adding the property with the new value for UI
+ }
+ propertiesList.add(new ComponentInstanceProperty(declaredProp));
+ input.setProperties(propertiesList);
+
+ }
+
+ @Override
+ public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputForDelete) {
+ return getPolicyPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId())
+ .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties))
+ .orElse(StorageOperationStatus.OK);
+ }
+
+ private StorageOperationStatus unDeclarePolicyProperties(Component container, InputDefinition input, PolicyProperties policyProperties) {
+ String policyId = policyProperties.getPolicyId();
+ List<PropertyDataDefinition> propsDeclaredAsInput = policyProperties.getProperties();
+ propsDeclaredAsInput.forEach(policyProp -> prepareValueBeforeDelete(input, policyProp, Collections.emptyList()));
+ return policyOperation.updatePolicyProperties(container, policyId, propsDeclaredAsInput);
+ }
+
+ private Optional<PolicyProperties> getPolicyPropertiesDeclaredAsInput(Component container, String inputId) {
+ if (container.getPolicies() == null) {
+ return Optional.empty();
+ }
+ return container.getPolicies().values()
+ .stream()
+ .filter(policy -> Objects.nonNull(policy.getProperties()))
+ .collect(Collectors.toMap(PolicyDataDefinition::getUniqueId,
+ p -> getPolicyPropertiesDeclaredAsInput(p, inputId)))
+ .entrySet()
+ .stream()
+ .filter(entry -> !entry.getValue().isEmpty())
+ .map(entry -> new PolicyProperties(entry.getKey(), entry.getValue()))
+ .findFirst();
+ }
+
+ private boolean isPropertyDeclaredAsInputByInputId(PropertyDataDefinition property, String inputId) {
+ if (CollectionUtils.isEmpty(property.getGetInputValues())) {
+ return false;
+ }
+ return property.getGetInputValues().stream()
+ .filter(Objects::nonNull)
+ .anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId));
+ }
+
+ private List<PropertyDataDefinition> getPolicyPropertiesDeclaredAsInput(PolicyDefinition policy, String inputId) {
+ return policy.getProperties()
+ .stream()
+ .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId))
+ .collect(Collectors.toList());
+ }
+
+ private class PolicyProperties {
+ private String policyId;
+ private List<PropertyDataDefinition> properties;
+
+ PolicyProperties(String policyId, List<PropertyDataDefinition> properties) {
+ this.policyId = policyId;
+ this.properties = properties;
+ }
+
+ String getPolicyId() {
+ return policyId;
+ }
+
+ public List<PropertyDataDefinition> getProperties() {
+ return properties;
+ }
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java
new file mode 100644
index 0000000000..ea311cebb5
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerationOrchestrator.java
@@ -0,0 +1,66 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.Pair;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstInputsMap;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.List;
+
+@org.springframework.stereotype.Component
+public class PropertyDecelerationOrchestrator {
+
+ private static final Logger log = LoggerFactory.getLogger(PropertyDecelerationOrchestrator.class);
+ private ComponentInstanceInputPropertyDecelerator componentInstanceInputPropertyDecelerator;
+ private ComponentInstancePropertyDecelerator componentInstancePropertyDecelerator;
+ private PolicyPropertyDecelerator policyPropertyDecelerator;
+ private List<PropertyDecelerator> propertyDecelerators;
+
+ public PropertyDecelerationOrchestrator(ComponentInstanceInputPropertyDecelerator componentInstanceInputPropertyDecelerator, ComponentInstancePropertyDecelerator componentInstancePropertyDecelerator, PolicyPropertyDecelerator policyPropertyDecelerator) {
+ this.componentInstanceInputPropertyDecelerator = componentInstanceInputPropertyDecelerator;
+ this.componentInstancePropertyDecelerator = componentInstancePropertyDecelerator;
+ this.policyPropertyDecelerator = policyPropertyDecelerator;
+ propertyDecelerators = Arrays.asList(componentInstanceInputPropertyDecelerator, componentInstancePropertyDecelerator, policyPropertyDecelerator);
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) {
+ PropertyDecelerator propertyDecelerator = getPropertyDecelerator(componentInstInputsMap);
+ Pair<String, List<ComponentInstancePropInput>> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare();
+ return propertyDecelerator.declarePropertiesAsInputs(component, propsToDeclare.getLeft(), propsToDeclare.getRight());
+ }
+
+ public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputToDelete) {
+ log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId());
+ for (PropertyDecelerator propertyDecelerator : propertyDecelerators) {
+ StorageOperationStatus storageOperationStatus = propertyDecelerator.unDeclarePropertiesAsInputs(component, inputToDelete);
+ if (StorageOperationStatus.OK != storageOperationStatus) {
+ log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus);
+ return storageOperationStatus;
+ }
+ }
+ return StorageOperationStatus.OK;
+
+ }
+
+ private PropertyDecelerator getPropertyDecelerator(ComponentInstInputsMap componentInstInputsMap) {
+ if (!MapUtils.isEmpty(componentInstInputsMap.getComponentInstanceInputsMap())) {
+ return componentInstanceInputPropertyDecelerator;
+ }
+ if (!MapUtils.isEmpty(componentInstInputsMap.getComponentInstanceProperties())) {
+ return componentInstancePropertyDecelerator;
+ }
+ if (!MapUtils.isEmpty(componentInstInputsMap.getPolicyProperties())) {
+ return policyPropertyDecelerator;
+ }
+ throw new IllegalStateException("there are no properties selected for deceleration");
+
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java
new file mode 100644
index 0000000000..9255763f2c
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDecelerator.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.List;
+
+public interface PropertyDecelerator {
+
+ /**
+ * creates a list of inputs from the given list of properties and updates the properties accordingly
+ * @param component the container
+ * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc)
+ * @param propsToDeclare the list of properties that are being declared as inputs
+ * @return the list of inputs that were created from the given properties
+ */
+ Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare);
+
+ /**
+ * returns the values of declared properties to each original state before it was declared as an input.
+ * this function is to be called when an input, that was created by declaring a property, is deleted.
+ * @param component the container of the input to be deleted
+ * @param input the input to be deleted
+ */
+ StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input);
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java
new file mode 100644
index 0000000000..df6cb3f6b9
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.be.components.scheduledtasks;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+
+public abstract class AbstractScheduleTaskRunner {
+ private static final Logger log = LoggerFactory.getLogger(AbstractScheduleTaskRunner.class);
+ public abstract ExecutorService getExecutorService();
+
+ protected void shutdownExecutor() {
+ ExecutorService executorService = getExecutorService();
+ if (executorService == null)
+ return;
+
+ executorService.shutdown(); // Disable new tasks from being submitted
+ try {
+ // Wait a while for existing tasks to terminate
+ if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
+ executorService.shutdownNow(); // Cancel currently executing
+ // tasks
+ // Wait a while for tasks to respond to being cancelled
+ if (!executorService.awaitTermination(60, TimeUnit.SECONDS))
+ log.debug("Pool did not terminate");
+ }
+ } catch (InterruptedException ie) {
+ // (Re-)Cancel if current thread also interrupted
+ executorService.shutdownNow();
+ // Preserve interrupt status
+ Thread.currentThread().interrupt();
+ }
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java
new file mode 100644
index 0000000000..a2659f4559
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java
@@ -0,0 +1,150 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.components.scheduledtasks;
+
+import org.apache.commons.lang3.concurrent.BasicThreadFactory;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.CleanComponentsConfiguration;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+@Component("asdcComponentsCleaner")
+public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implements Runnable {
+
+ private static final Logger log = LoggerFactory.getLogger(AsdcComponentsCleanerTask.class);
+
+ @javax.annotation.Resource
+ private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null;
+
+ private List<NodeTypeEnum> componentsToClean;
+ private long cleaningIntervalInMinutes;
+
+ private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1,
+ new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build());
+ ScheduledFuture<?> scheduledFuture = null;
+
+ @PostConstruct
+ public void init() {
+ log.info("Enter init method of AsdcComponentsCleaner");
+ Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
+ CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration();
+
+ if (cleanComponentsConfiguration == null) {
+ log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration");
+ BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init",
+ "fecth configuration");
+ return;
+
+ }
+ componentsToClean = new ArrayList<NodeTypeEnum>();
+ List<String> components = cleanComponentsConfiguration.getComponentsToClean();
+ if (components == null) {
+ log.info("no component were configured for cleaning");
+ }
+ for (String component : components) {
+ NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component);
+ if (typeEnum != null)
+ componentsToClean.add(typeEnum);
+ }
+
+ long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes();
+
+ if (intervalInMinutes < 1) {
+ log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default");
+ intervalInMinutes = 60;
+ }
+ cleaningIntervalInMinutes = intervalInMinutes;
+
+ startTask();
+
+ log.info("End init method of AsdcComponentsCleaner");
+ }
+
+ @PreDestroy
+ public void destroy() {
+ this.stopTask();
+ shutdownExecutor();
+ }
+
+ public void startTask() {
+
+ log.debug("start task for cleaning components");
+
+ try {
+
+ if (scheduledService != null) {
+ log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes);
+ scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes,
+ TimeUnit.MINUTES);
+
+ }
+ } catch (Exception e) {
+ log.debug("unexpected error occured", e);
+ BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask",
+ e.getMessage());
+
+ }
+ }
+
+ private void stopTask() {
+ if (scheduledFuture != null) {
+ boolean cancelTaskSuccessfully = scheduledFuture.cancel(true);
+ log.debug("Stop cleaning task. result = {}", cancelTaskSuccessfully);
+ if (!cancelTaskSuccessfully) {
+ BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask",
+ "try to stop the polling task");
+ }
+ scheduledFuture = null;
+ }
+
+ }
+
+ @Override
+ public void run() {
+ try {
+ componentsCleanBusinessLogic.cleanComponents(componentsToClean);
+ } catch (Exception e) {
+ log.error("unexpected error occured", e);
+ BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run",
+ e.getMessage());
+ }
+
+ }
+
+ @Override
+ public ExecutorService getExecutorService() {
+ return scheduledService;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java
new file mode 100644
index 0000000000..a09a78165e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.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.be.components.scheduledtasks;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Component("componentsCleanBusinessLogic")
+public class ComponentsCleanBusinessLogic extends BaseBusinessLogic {
+
+ @Autowired
+ private ResourceBusinessLogic resourceBusinessLogic;
+
+ @Autowired
+ private ServiceBusinessLogic serviceBusinessLogic;
+
+ private static final Logger log = LoggerFactory.getLogger(ComponentsCleanBusinessLogic.class);
+
+ public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean) {
+
+ Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents = new HashMap<NodeTypeEnum, Either<List<String>, ResponseFormat>>();
+
+ log.trace("start cleanComponents");
+ for (NodeTypeEnum type : componentsToClean) {
+ switch (type) {
+ case Resource:
+ processDeletionForType(cleanedComponents, NodeTypeEnum.Resource, resourceBusinessLogic);
+ break;
+ case Service:
+ processDeletionForType(cleanedComponents, NodeTypeEnum.Service, serviceBusinessLogic);
+ break;
+ default:
+ log.debug("{} component type does not have cleaning method defined", type);
+ break;
+ }
+ }
+
+ log.trace("end cleanComponents");
+ return cleanedComponents;
+ }
+
+ private void processDeletionForType(Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) {
+ Either<List<String>, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents();
+ if (deleteMarkedResources.isRight()) {
+ log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage());
+ } else {
+ if (log.isDebugEnabled()) {
+ StringBuilder sb = new StringBuilder("list of deleted components - type " + type + ": ");
+ for (String id : deleteMarkedResources.left().value()) {
+ sb.append(id).append(", ");
+ }
+ log.debug(sb.toString());
+ }
+ }
+ cleanedComponents.put(type, deleteMarkedResources);
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java
new file mode 100644
index 0000000000..eac4ecf813
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java
@@ -0,0 +1,163 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.components.scheduledtasks;
+
+import com.google.common.annotations.VisibleForTesting;
+import fj.data.Either;
+import org.apache.commons.lang.math.NumberUtils;
+import org.apache.commons.lang3.concurrent.BasicThreadFactory;
+import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.convertToFunction;
+
+@Component("recoveryThreadManager")
+public class RecoveryThreadManager extends AbstractScheduleTaskRunner {
+
+ private static final Logger log = LoggerFactory.getLogger(RecoveryThreadManager.class);
+ @VisibleForTesting
+ FixEnvironmentTask task = new FixEnvironmentTask();
+
+ @Resource
+ private OperationalEnvironmentDao operationalEnvironmentDao;
+
+ @Autowired
+ private EnvironmentsEngine environmentsEngine;
+
+ private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(NumberUtils.INTEGER_ONE,
+ new BasicThreadFactory.Builder().namingPattern("EnvironmentCleanThread-%d").build());
+ @VisibleForTesting
+ Integer allowedTimeBeforeStaleSec;
+
+ @PostConstruct
+ public void init() {
+ log.debug("Enter init method of RecoveryThreadManager");
+ final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager
+ .getConfigurationManager().getDistributionEngineConfiguration();
+ Integer opEnvRecoveryIntervalSec = distributionEngineConfiguration.getOpEnvRecoveryIntervalSec();
+ scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec,
+ TimeUnit.SECONDS);
+ this.allowedTimeBeforeStaleSec = distributionEngineConfiguration.getAllowedTimeBeforeStaleSec();
+ log.debug("End init method of AsdcComponentsCleaner");
+ }
+
+ @PreDestroy
+ public void destroy() {
+ shutdownExecutor();
+ }
+
+ protected class FixEnvironmentTask implements Runnable {
+ @Override
+ public void run() {
+ try {
+ // Failed Envs
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherFailedEnv = operationalEnvironmentDao
+ .getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED);
+ eitherFailedEnv.bimap(convertToFunction(this::handleFailedeEnvironmentsRecords), convertToFunction(
+ cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.FAILED, cassandraError)));
+
+ // In-Progress Envs
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherInProgressEnv = operationalEnvironmentDao
+ .getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS);
+ eitherInProgressEnv.bimap(convertToFunction(this::handleInProgressEnvironmentsRecords),
+ convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.IN_PROGRESS,
+ cassandraError)));
+
+ // Envs To Connect to UEB topics
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherCompleteEnv = operationalEnvironmentDao
+ .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED);
+ eitherCompleteEnv.bimap(convertToFunction(this::handleCompleteEnvironmentsRecords), convertToFunction(
+ cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.COMPLETED, cassandraError)));
+
+ } catch (Exception e) {
+ log.debug("error while handling operational environments to be fixed :{}", e.getMessage(), e);
+ }
+ }
+
+ private void handleCompleteEnvironmentsRecords(List<OperationalEnvironmentEntry> completeEnvironmentsRecords) {
+ if (!isEmpty(completeEnvironmentsRecords)) {
+ completeEnvironmentsRecords.stream().filter(env -> !environmentsEngine.isInMap(env))
+ .forEach(opEnvEntry -> {
+ environmentsEngine.createUebTopicsForEnvironment(opEnvEntry);
+ environmentsEngine.addToMap(opEnvEntry);
+ });
+ }
+
+ }
+
+ private void handleFailedeEnvironmentsRecords(List<OperationalEnvironmentEntry> failedEnvironmentsRecords) {
+ if (!isEmpty(failedEnvironmentsRecords)) {
+ failedEnvironmentsRecords.parallelStream()
+ .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env));
+ }
+
+ }
+
+ private void handleInProgressEnvironmentsRecords(List<OperationalEnvironmentEntry> inProgressEnvList) {
+ if (!isEmpty(inProgressEnvList)) {
+
+ long currentTimeMillis = System.currentTimeMillis();
+ if (!isEmpty(inProgressEnvList)) {
+ List<OperationalEnvironmentEntry> staleInProgressEnvList = inProgressEnvList.stream()
+ .filter(record -> (record.getLastModified().getTime() + (allowedTimeBeforeStaleSec * 1000)) < currentTimeMillis)
+ .collect(Collectors.toList());
+ staleInProgressEnvList.parallelStream()
+ .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env));
+ }
+
+ }
+
+ }
+
+ private void logFailedRetrieveRecord(EnvironmentStatusEnum recordStatus, CassandraOperationStatus error) {
+ log.debug("error: {} while retrieving operational environments with status: {}", error, recordStatus);
+ }
+
+
+ }
+
+ @Override
+ public ExecutorService getExecutorService() {
+ return scheduledService;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java
new file mode 100644
index 0000000000..83f5a5de95
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java
@@ -0,0 +1,42 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.apache.tinkerpop.shaded.minlog.Log;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.validation.constraints.NotNull;
+import java.security.SecureRandom;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Utils {
+
+ private static final Logger log = LoggerFactory.getLogger(Utils.class);
+ private static final Pattern COUNTER_PATTERN = Pattern.compile("\\d+$");
+ private static final SecureRandom random = new SecureRandom();
+
+
+ private Utils() {}
+
+ public static int getNextCounter(@NotNull List<String> existingValues) {
+ if (existingValues.isEmpty()) {
+ return 0;
+ }
+ int maxCurrentCounter = 0;
+ try {
+ maxCurrentCounter = existingValues.stream()
+ .map(COUNTER_PATTERN::matcher)
+ .filter(Matcher::find)
+ .map(matcher -> matcher.group(0))
+ .mapToInt(Integer::parseInt)
+ .max()
+ .orElse(0);
+ }
+ catch (Exception e) {
+ Log.warn("Failed in retrieivng counter from existing value: ", e);
+ maxCurrentCounter = random.nextInt(100) + 50;
+ }
+ return ++maxCurrentCounter;
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java
new file mode 100644
index 0000000000..da098acb13
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.be.components.validation;
+
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+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.exception.ResponseFormat;
+
+@org.springframework.stereotype.Component
+public class AccessValidations {
+
+ private final UserValidations userValidations;
+ private final ComponentValidations componentValidations;
+
+
+ public AccessValidations(UserValidations userValidations, ComponentValidations componentValidations) {
+ this.userValidations = userValidations;
+ this.componentValidations = componentValidations;
+ }
+
+ public Component validateUserCanWorkOnComponentAndLockIt(ComponentTypeEnum componentTypeEnum, String componentId, String userId, String actionContext) {
+ userValidations.validateUserExists(userId, actionContext, false)
+ .left()
+ .on(this::onUserError);
+
+ return componentValidations.validateComponentIsCheckedOutByUserAndLockIt(componentTypeEnum, componentId, userId);
+ }
+
+ private User onUserError(ResponseFormat responseFormat) {
+ throw new ComponentException(responseFormat);
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java
new file mode 100644
index 0000000000..c626e29f21
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java
@@ -0,0 +1,22 @@
+package org.openecomp.sdc.be.components.validation;
+
+/**
+ * Created by chaya on 11/14/2017.
+ */
+public enum ApiResourceEnum {
+
+ ENVIRONMENT_ID("Environment ID"),
+ RESOURCE_ID("Resource ID"),
+ SERVICE_ID("Service ID");
+
+ private String value;
+
+ ApiResourceEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java
index 15fff52ab9..002ae50cde 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java
@@ -20,19 +20,126 @@
package org.openecomp.sdc.be.components.validation;
+import org.apache.commons.collections.CollectionUtils;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+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.tosca.ToscaDataDefinition;
+import java.util.List;
import java.util.Optional;
-import java.util.stream.Collectors;
+import java.util.Set;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
+import org.openecomp.sdc.common.util.ValidationUtils;
-public class ComponentValidations {
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static java.util.stream.Collectors.toList;
+
+
+@org.springframework.stereotype.Component
+public final class ComponentValidations {
+
+ private final ToscaOperationFacade toscaOperationFacade;
+ private final IGraphLockOperation graphLockOperation;
+
+ public ComponentValidations(ToscaOperationFacade toscaOperationFacade, IGraphLockOperation graphLockOperation) {
+ this.toscaOperationFacade = toscaOperationFacade;
+ this.graphLockOperation = graphLockOperation;
+ }
public static boolean validateComponentInstanceExist(Component component, String instanceId) {
return Optional.ofNullable(component.getComponentInstances())
- .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(Collectors.toList()))
+ .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList()))
.filter(instancesIds -> instancesIds.contains(instanceId))
.isPresent();
}
+ public static String getNormalizedName(ToscaDataDefinition toscaDataDefinition) {
+ String name = (String) toscaDataDefinition.getToscaPresentationValue(JsonPresentationFields.NAME);
+ return org.openecomp.sdc.common.util.ValidationUtils.normalizeComponentInstanceName(name);
+ }
+
+ /**
+ * The following logic is applied:
+ * For each name new or existing name we look at the normalized name which is used in Tosca representation
+ * @param currentName
+ * @param newName
+ * @param component
+ * @return True is new name can be used in this component, false otherwise
+ */
+ public static boolean validateNameIsUniqueInComponent(String currentName, String newName, Component component) {
+ String normalizedCurrentName = ValidationUtils.normalizeComponentInstanceName(currentName);
+ String normalizedNewName = ValidationUtils.normalizeComponentInstanceName(newName);
+
+ if (normalizedCurrentName.equals(normalizedNewName)) {
+ return true; //As it's same entity, still considered unique
+ }
+ List<GroupDefinition> groups = component.getGroups();
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ Set<String> existingNames = new HashSet<>();
+ if (CollectionUtils.isNotEmpty(groups)) {
+ List<String> existingGroupNames = groups
+ .stream()
+ .map(ComponentValidations::getNormalizedName)
+ .collect(toList());
+ existingNames.addAll(existingGroupNames);
+ }
+ if (CollectionUtils.isNotEmpty(componentInstances)) {
+ List<String> existingInstanceNames = componentInstances
+ .stream()
+ .map(ComponentValidations::getNormalizedName)
+ .collect(toList());
+ existingNames.addAll(existingInstanceNames);
+ }
+ return !existingNames.contains(normalizedNewName);
+ }
+
+ public Component validateComponentIsCheckedOutByUserAndLockIt(ComponentTypeEnum componentTypeEnum, String componentId, String userId) {
+ Component component = getComponent(componentId, componentTypeEnum);
+
+ if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
+ throw new ComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getName());
+ }
+
+ lockComponent(component);
+
+ return component;
+ }
+
+ private Component getComponent(String componentId, ComponentTypeEnum componentType) {
+ Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView())
+ .left()
+ .on(this::onToscaOperationError);
+
+ if (componentType!=component.getComponentType()) {
+ throw new ComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
+ }
+
+ return component;
+ }
+
+ private void lockComponent(Component component) {
+ StorageOperationStatus lockComponentStatus = graphLockOperation.lockComponent(component.getUniqueId(),
+ component.getComponentType().getNodeType());
+ if (!StorageOperationStatus.OK.equals(lockComponentStatus)) {
+ throw new StorageException(lockComponentStatus);
+ }
+ }
+
+ private Component onToscaOperationError(StorageOperationStatus storageOperationStatus) {
+ throw new StorageException(storageOperationStatus);
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java
new file mode 100644
index 0000000000..c1934ae1c4
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java
@@ -0,0 +1,216 @@
+package org.openecomp.sdc.be.components.validation;
+
+import fj.data.Either;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Provides specific functionality for policy
+ */
+public class PolicyUtils {
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyUtils.class);
+
+ private PolicyUtils() {
+ // No instances allowed
+ }
+
+ /**
+ * Calculates the next integer counter according to the found max counter existing in the provided policies map
+ *
+ * @param policies the map of the policies
+ * @return the integer counter
+ */
+ public static int getNextPolicyCounter(Map<String, PolicyDefinition> policies) {
+ int nextCounter = 0;
+ if (MapUtils.isNotEmpty(policies)) {
+ int nextCounterFromIds = policies.values()
+ .stream()
+ .map(p -> extractNextPolicyCounterFromUniqueId(p.getUniqueId()))
+ .max(Integer::compareTo)
+ .orElse(0);
+ int nextCounterFromNames = policies.values()
+ .stream()
+ .map(p -> extractNextPolicyCounterFromName(p.getName()))
+ .max(Integer::compareTo)
+ .orElse(0);
+ nextCounter = nextCounterFromIds > nextCounterFromNames ? nextCounterFromIds : nextCounterFromNames;
+ }
+ return nextCounter;
+ }
+
+ /**
+ * Validates policy fields on policy update. Updates mutable fields
+ *
+ * @param recievedPolicy the policy parsed from the HTTP request
+ * @param validPolicy the copy of the existing policy found on the component
+ * @param policies all the polices related to the component
+ * @return validated and updated policy or an error as action status
+ */
+ public static Either<PolicyDefinition, ActionStatus> validatePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) {
+ validateImmutablePolicyFields(recievedPolicy, validPolicy);
+ return validateUpdateMutablePolicyFields(recievedPolicy, validPolicy, policies);
+ }
+
+ /**
+ * Retrieves the set of the excluded policy types for the specified component
+ *
+ * @param the component
+ * @return the set of the policies
+ */
+ public static Set<String> getExcludedPolicyTypesByComponent(Component component) {
+ if (MapUtils.isEmpty(ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getExcludedPolicyTypesMapping())) {
+ return Collections.emptySet();
+ }
+ if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
+ return ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getExcludedPolicyTypesMapping()
+ .get(component.getComponentType().name());
+ }
+ return ConfigurationManager.getConfigurationManager()
+ .getConfiguration()
+ .getExcludedPolicyTypesMapping()
+ .get(((Resource) component).getResourceType().getValue());
+ }
+
+ private static int extractNextPolicyCounterFromUniqueId(String uniqueId) {
+ int counter = 0;
+ if (StringUtils.isNotEmpty(uniqueId)) {
+ counter = extractNextPolicyCounter(uniqueId, uniqueId.lastIndexOf(Constants.POLICY_UID_POSTFIX));
+ }
+ return counter;
+ }
+
+ private static int extractNextPolicyCounterFromName(String policyName) {
+ int counter = 0;
+ if (StringUtils.isNotEmpty(policyName)) {
+ counter = extractNextPolicyCounter(policyName, policyName.length());
+ }
+ return counter;
+ }
+
+ private static int extractNextPolicyCounter(String policyName, int endIndex) {
+ int counter = 0;
+ try {
+ counter = Integer.valueOf(policyName.substring(policyName.lastIndexOf(Constants.GROUP_POLICY_NAME_DELIMETER) + Constants.GROUP_POLICY_NAME_DELIMETER
+ .length(), endIndex)) + 1;
+ }
+ catch (NumberFormatException | IndexOutOfBoundsException e) {
+ log.error("The exception {} occurred upon extraction counter from the srting value {}. ", e, policyName);
+ }
+ return counter;
+ }
+
+ private static Either<PolicyDefinition, ActionStatus> validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) {
+ return validateUpdatePolicyName(recievedPolicy, validPolicy, policies);
+ }
+
+ private static void validateImmutablePolicyFields(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy) {
+ boolean isUpdatedField = isUpdatedField(receivedPolicy.getUniqueId(), validPolicy.getUniqueId());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getUniqueId(), validPolicy.getUniqueId(), JsonPresentationFields.UNIQUE_ID);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getComponentName(), validPolicy.getComponentName());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getComponentName(), validPolicy.getComponentName(), JsonPresentationFields.CI_COMPONENT_NAME);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getDerivedFrom(), validPolicy.getDerivedFrom());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getDerivedFrom(), validPolicy.getDerivedFrom(), JsonPresentationFields.DERIVED_FROM);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getDescription(), validPolicy.getDescription());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getDescription(), validPolicy.getDescription(), JsonPresentationFields.DESCRIPTION);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getInvariantName(), validPolicy.getInvariantName());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getInvariantName(), validPolicy.getInvariantName(), JsonPresentationFields.CI_INVARIANT_NAME);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getInvariantUUID(), validPolicy.getInvariantUUID());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getInvariantUUID(), validPolicy.getInvariantUUID(), JsonPresentationFields.INVARIANT_UUID);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getPolicyTypeName(), validPolicy.getPolicyTypeName());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeName(), validPolicy.getPolicyTypeName(), JsonPresentationFields.TYPE);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid(), JsonPresentationFields.TYPE_UNIQUE_ID);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID(), JsonPresentationFields.UUID);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getVersion(), validPolicy.getVersion());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getVersion(), validPolicy.getVersion(), JsonPresentationFields.VERSION);
+ }
+ isUpdatedField = isUpdatedField(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar()
+ .toString());
+ if (isUpdatedField) {
+ logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar()
+ .toString(), JsonPresentationFields.IS_FROM_CSAR);
+ }
+ }
+
+ private static boolean isUpdatedField(String oldField, String newField) {
+ boolean isUpdatedField = false;
+ if (StringUtils.isEmpty(oldField) && StringUtils.isNotEmpty(newField)) {
+ isUpdatedField = true;
+ }
+ if (StringUtils.isNotEmpty(oldField) && StringUtils.isNotEmpty(newField) && !oldField.equals(newField)) {
+ isUpdatedField = true;
+ }
+ return isUpdatedField;
+ }
+
+ private static void logImmutableFieldUpdateWarning(String oldValue, String newValue, JsonPresentationFields field) {
+ log.warn("Update of the field {} of a policy not allowed. The change will be ignored. The old value is {} , the new value is {}. ", field, oldValue, newValue);
+ }
+
+ private static Either<PolicyDefinition, ActionStatus> validateUpdatePolicyName(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) {
+ Either<PolicyDefinition, ActionStatus> result = null;
+ Optional<PolicyDefinition> sameNamePolicy = Optional.empty();
+ if (StringUtils.isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy
+ .getName()).matches()) {
+ log.error("Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(), receivedPolicy.getUniqueId());
+ result = Either.right(ActionStatus.INVALID_POLICY_NAME);
+ }
+ if (result == null && MapUtils.isNotEmpty(policies)) {
+ sameNamePolicy = policies.values()
+ .stream()
+ .filter(p -> p.getName().equals(receivedPolicy.getName()))
+ .findFirst();
+ }
+ if (sameNamePolicy.isPresent()) {
+ log.error("Failed to validate the name {} of the policy {}. The policy {} with the same name already exists. ", receivedPolicy
+ .getName(), receivedPolicy.getUniqueId(), sameNamePolicy.get().getUniqueId());
+ result = Either.right(ActionStatus.POLICY_NAME_ALREADY_EXIST);
+ }
+ if (result == null) {
+ validPolicy.setName(receivedPolicy.getName());
+ result = Either.left(validPolicy);
+ }
+ return result;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java
new file mode 100644
index 0000000000..ec5a1c3078
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java
@@ -0,0 +1,118 @@
+package org.openecomp.sdc.be.components.validation;
+
+import fj.data.Either;
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
+import org.openecomp.sdc.be.components.impl.ActivationRequestInformation;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Created by chaya on 10/18/2017.
+ */
+@org.springframework.stereotype.Component("serviceDistributionValidation")
+public class ServiceDistributionValidation {
+ private static final Logger log = LoggerFactory.getLogger(ServiceDistributionValidation.class);
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Resource
+ private ToscaOperationFacade toscaOperationFacade;
+ @Resource
+ private UserValidations userValidations;
+ @Resource
+ private IDistributionEngine distributionEngine;
+
+ public Either<ActivationRequestInformation, ResponseFormat> validateActivateServiceRequest(String serviceUUID, String opEnvId, User modifier, ServiceDistributionReqInfo data) {
+ try {
+ validateUserExists(modifier.getUserId());
+ Service serviceToActivate = validateServiceExists(serviceUUID);
+ validateDistributionServiceLifeCycleState(serviceToActivate);
+ OperationalEnvironmentEntry operationalEnvironmentEntry = validateOperationalEnvExists(opEnvId);
+ String workloadContext = validateWorkloadContext(data);
+ ActivationRequestInformation activationRequestInformation = new ActivationRequestInformation(serviceToActivate, workloadContext, operationalEnvironmentEntry.getTenant());
+ return Either.left(activationRequestInformation);
+ } catch (ValidationException e) {
+ log.error("failed while validating activate service UUID {} request. error {}", serviceUUID, e.getExceptionResponseFormat(), e);
+ return Either.right(e.getExceptionResponseFormat());
+ }
+ }
+
+ private Service validateServiceExists(String serviceUUID) {
+ if (StringUtils.isEmpty(serviceUUID.trim())) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE);
+ throw new ValidationException(responseFormat);
+ }
+ Either<Component, StorageOperationStatus> latestComponentByUuid = toscaOperationFacade.getLatestServiceByUuid(serviceUUID);
+ if (latestComponentByUuid.isRight()) {
+ log.error("failed retrieving service {}", serviceUUID);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue());
+ throw new ValidationException(responseFormat);
+ }
+ return (Service)latestComponentByUuid.left().value();
+ }
+
+ private String validateWorkloadContext(ServiceDistributionReqInfo data) {
+ String workloadContext = data.getWorkloadContext();
+ if (workloadContext == null || workloadContext.isEmpty()) {
+ log.error("workload context does not exist on data to distribute");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_BODY);
+ throw new ValidationException(responseFormat);
+ }
+ return workloadContext;
+ }
+
+ private OperationalEnvironmentEntry validateOperationalEnvExists(String opEnvId) {
+ if (StringUtils.isEmpty(opEnvId.trim())) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE);
+ throw new ValidationException(responseFormat);
+ }
+ OperationalEnvironmentEntry operationalEnvironment = distributionEngine.getEnvironmentById(opEnvId);
+ if (operationalEnvironment == null) {
+ return failOnEnvNotExist(opEnvId);
+ }
+ if (!operationalEnvironment.getStatus().equals(EnvironmentStatusEnum.COMPLETED.getName())) {
+ log.error("the operational environment is not ready to receive distributions. environment status: {}", operationalEnvironment.getStatus());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND , ApiResourceEnum.ENVIRONMENT_ID.getValue());
+ throw new ValidationException(responseFormat);
+ }
+ return operationalEnvironment;
+ }
+
+ private OperationalEnvironmentEntry failOnEnvNotExist(String opEnvId) {
+ return ValidationUtils.throwValidationException(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.ENVIRONMENT_ID.getValue()), "failed to get operational environment {}", opEnvId);
+ }
+
+ private void validateServiceState(Service service, List<LifecycleStateEnum> allowedStates) {
+ LifecycleStateEnum state = service.getLifecycleState();
+ if (!allowedStates.contains(state)) {
+ log.error("service {} life cycle state {} is not valid for distribution", service.getUniqueId(), service.getLifecycleState());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_STATE);
+ throw new ValidationException(responseFormat);
+ }
+ }
+ private void validateUserExists(String userId) {
+ userValidations.validateUserExists(userId, "activate Distribution", false)
+ .left().on(responseFormat -> ValidationUtils.throwValidationException(responseFormat, "user {} not exist", userId));
+ }
+
+ private void validateDistributionServiceLifeCycleState(Service serviceToActivate) {
+ validateServiceState(serviceToActivate,
+ Arrays.asList(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, LifecycleStateEnum.CERTIFIED));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java
new file mode 100644
index 0000000000..e2e671f872
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java
@@ -0,0 +1,110 @@
+package org.openecomp.sdc.be.components.validation;
+
+import fj.data.Either;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.user.IUserBusinessLogic;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+@org.springframework.stereotype.Component
+public class UserValidations {
+
+ private static final Logger log = LoggerFactory.getLogger(UserValidations.class);
+ private final IUserBusinessLogic userAdmin;
+ private final ComponentsUtils componentsUtils;
+
+ public UserValidations(IUserBusinessLogic userAdmin, ComponentsUtils componentsUtils) {
+ this.userAdmin = userAdmin;
+ this.componentsUtils = componentsUtils;
+ }
+
+ public Either<User, ResponseFormat> validateUserExists(String userId, String ecompErrorContext, boolean inTransaction) {
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, inTransaction);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ ResponseFormat responseFormat;
+ if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
+ if (log.isDebugEnabled()) {
+ log.debug("validateUserExists - not authorized user, userId {}", userId);
+ }
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.AUTH_FAILED);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("validateUserExists - failed to authorize user, userId {}", userId);
+ }
+ responseFormat = componentsUtils.getResponseFormat(eitherCreator.right().value());
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("User is not listed. userId {}", userId);
+ }
+ BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
+ return Either.right(responseFormat);
+ }
+ return Either.left(eitherCreator.left().value());
+ }
+
+ public Either<Boolean, ResponseFormat> validateUserRole(User user, List<Role> roles) {
+ Role userRole = Role.valueOf(user.getRole());
+ if (roles != null) {
+ if (!roles.contains(userRole)) {
+ if (log.isDebugEnabled()) {
+ log.debug("user is not in appropriate role to perform action");
+ }
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ return Either.right(responseFormat);
+ }
+ return Either.left(Boolean.TRUE);
+ }
+ return Either.left(Boolean.FALSE);
+ }
+
+ public Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) {
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userId, false);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ if (eitherCreator.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
+ log.debug("validateUserExists - not authorized user, userId {}", userId);
+ Either.right(ActionStatus.RESTRICTED_OPERATION);
+ } else {
+ log.debug("validateUserExists - failed to authorize user, userId {}", userId);
+ }
+ log.debug("User is not listed. userId {}", userId);
+ BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, userId);
+ return Either.right(eitherCreator.right().value());
+ }
+ return Either.left(eitherCreator.left().value());
+ }
+
+ public Either<User, ResponseFormat> validateUserNotEmpty(User user, String ecompErrorContext) {
+ String userId = user.getUserId();
+
+ if (StringUtils.isEmpty(userId)) {
+ log.debug("User header is missing ");
+ BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ return Either.right(responseFormat);
+ }
+ return Either.left(user);
+ }
+
+ public Either<User, ResponseFormat> validateUserExists(User user, String ecompErrorContext, boolean inTransaction) {
+ return validateUserExists(user.getUserId(), ecompErrorContext, inTransaction);
+ }
+
+ public void validateUserExist(String userId, String ecompErrorContext, Wrapper<ResponseFormat> errorWrapper) {
+ Either<User, ResponseFormat> resp = validateUserExists(userId, ecompErrorContext, false);
+ if (resp.isRight()) {
+ errorWrapper.setInnerElement(resp.right().value());
+ }
+ }
+
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java
new file mode 100644
index 0000000000..8abf2f7d63
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.be.components.validation;
+
+import org.openecomp.sdc.exception.ResponseFormat;
+
+/**
+ * Created by chaya on 10/18/2017.
+ */
+public class ValidationException extends RuntimeException {
+
+ private transient ResponseFormat exceptionResponseFormat;
+
+ public ValidationException(ResponseFormat exceptionResponseFormat) {
+ super();
+ this.exceptionResponseFormat = exceptionResponseFormat;
+ }
+
+ public ResponseFormat getExceptionResponseFormat() {
+ return exceptionResponseFormat;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java
new file mode 100644
index 0000000000..07505a2adb
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.components.validation;
+
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ValidationUtils {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ValidationUtils.class);
+
+ public static <T> T throwValidationException(ResponseFormat responseFormat, String logMessage, Object ... logParams){
+ LOGGER.error(logMessage, logParams);
+ throw new ValidationException(responseFormat);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java
new file mode 100644
index 0000000000..967232ac86
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.be.datamodel;
+
+import java.io.Serializable;
+import java.util.Set;
+
+public class ForwardingPaths implements Serializable{
+
+ private static final long serialVersionUID=1L;
+
+ public ForwardingPaths() {
+ }
+
+ private Set<String> forwardingPathToDelete;
+ public Set<String> getForwardingPathToDelete() {
+ return forwardingPathToDelete;
+ }
+
+ public void setForwardingPathToDelete(Set<String> forwardingPathToDelete) {
+ this.forwardingPathToDelete = forwardingPathToDelete;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java
new file mode 100644
index 0000000000..a033cec86f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java
@@ -0,0 +1,89 @@
+package org.openecomp.sdc.be.datamodel;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.Set;
+
+public class NameIdPair extends HashMap<String, Object> implements java.io.Serializable {
+ public static final String OPTIONS = "options";
+ public static final String NAME = "name";
+ public static final String ID = "id";
+ public static final String OWNER_ID = "ownerId";
+
+ public NameIdPair(String name, String id) {
+ this(name, id, null);
+ }
+
+ public NameIdPair(String name, String id, String ownerId) {
+ super();
+ setId(id);
+ setName(name);
+ if (!Objects.isNull(ownerId)) {
+ setOwnerId(ownerId);
+ }
+
+ }
+
+ public NameIdPair(NameIdPair nameIdPair) {
+ super(nameIdPair);
+ }
+
+ public String getName() {
+ return get(NAME).toString();
+ }
+
+ public void setName(String name) {
+ super.put(NAME, name);
+ }
+
+ public String getId() {
+ return get(ID).toString();
+ }
+
+ public void setId(String id) {
+ super.put(ID, id);
+ }
+
+ public String getOwnerId() {
+ return get(OWNER_ID).toString();
+ }
+
+ public void setOwnerId(String ownerId) {
+ put(OWNER_ID, ownerId);
+ }
+
+ public Set<NameIdPairWrapper> getWrappedData() {
+ return (Set<NameIdPairWrapper>) super.get(OPTIONS);
+ }
+
+ public void setWrappedData(Set<NameIdPairWrapper> data) {
+ super.put(OPTIONS, data);
+ }
+
+ public void addWrappedData(NameIdPairWrapper nameIdPairWrapper) {
+ if (get(OPTIONS) == null) {
+ setWrappedData(new HashSet<>());
+ }
+ getWrappedData().add(nameIdPairWrapper);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof NameIdPair)) return false;
+ NameIdPair that = (NameIdPair) o;
+ return Objects.equals(getId(), that.getId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getId());
+ }
+
+ public static final NameIdPair create(String name, String id) {
+ return new NameIdPair(name, id);
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java
new file mode 100644
index 0000000000..e46e57705e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java
@@ -0,0 +1,43 @@
+package org.openecomp.sdc.be.datamodel;
+
+import java.io.Serializable;
+import java.util.HashMap;
+
+public class NameIdPairWrapper extends HashMap<String, Object> implements Serializable {
+ public static final String ID = "id";
+ public static final String DATA = "data";
+
+ public NameIdPairWrapper() {
+ }
+
+ public NameIdPairWrapper(NameIdPair nameIdPair) {
+ super();
+ init(nameIdPair);
+ }
+ public void init(NameIdPair nameIdPair) {
+ setId(nameIdPair.getId());
+ setData(new NameIdPair(nameIdPair));
+ }
+
+ public String getId() {
+ return get(ID).toString();
+ }
+
+ public void setId(String id) {
+ super.put(ID, id);
+ }
+
+ public NameIdPair getData() {
+ return (NameIdPair) get(DATA);
+ }
+
+ public void setData(NameIdPair data) {
+ put(DATA, data);
+ }
+
+ public NameIdPair getNameIdPair(){
+ return new NameIdPair(getData().getName(),getData().getId());
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java
new file mode 100644
index 0000000000..d05ddafed9
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.datamodel;
+
+import java.io.Serializable;
+import java.util.Set;
+
+public class ServiceRelations extends java.util.HashSet<NameIdPairWrapper> implements Serializable {
+
+
+
+ public ServiceRelations() {
+ }
+
+ public ServiceRelations(Set<NameIdPairWrapper> relations) {
+ super();
+ addAll(relations);
+ }
+
+ public Set<NameIdPairWrapper> getRelations() {
+ return this;
+ }
+
+ public void setRelations(Set<NameIdPairWrapper> relations) {
+ clear();
+ this.addAll(relations);
+ }
+
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
index 921aefaa8e..855f20aba2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
@@ -24,16 +24,16 @@ import java.io.Serializable;
public enum CategoryTypeEnum implements Serializable {
- CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping");
+ CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping");
- private String value;
+ private String value;
- CategoryTypeEnum(String value) {
- this.value = value;
- }
+ CategoryTypeEnum(String value) {
+ this.value = value;
+ }
- public String getValue() {
- return value;
- }
+ public String getValue() {
+ return value;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java
index 42ff4c900a..fc98400dd1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java
@@ -22,6 +22,6 @@ package org.openecomp.sdc.be.datamodel.api;
public enum HighestFilterEnum {
- ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY;
+ ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java
index 9f66911461..9f0d7a3281 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java
@@ -20,39 +20,121 @@
package org.openecomp.sdc.be.datamodel.utils;
+import org.apache.commons.codec.binary.Base64;
+import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.ValidationUtils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.stream.Collectors;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.ValidationUtils;
public class ArtifactUtils {
- public static ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) {
- for (String artifactUid : artifactsList) {
- for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
- ArtifactDefinition artifact = entry.getValue();
- if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) {
- artifacts.add(artifact);
- }
-
- }
- }
- if (artifacts.size() == 1) {
- return artifacts.get(0);
- }
- 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;
- }
+
+ public static ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) {
+ for (String artifactUid : artifactsList) {
+ for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
+ ArtifactDefinition artifact = entry.getValue();
+ if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) {
+ artifacts.add(artifact);
+ }
+
+ }
+ }
+ if (artifacts.size() == 1) {
+ return artifacts.get(0);
+ }
+ 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;
+ }
+
+ public static Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description,
+ byte[] artifactContentent, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean isFromCsar) {
+
+ Map<String, Object> json = new HashMap<String, Object>();
+ if (artifactId != null && !artifactId.isEmpty())
+ json.put(Constants.ARTIFACT_ID, artifactId);
+
+ json.put(Constants.ARTIFACT_NAME, artifactName);
+ json.put(Constants.ARTIFACT_TYPE, artifactType);
+ json.put(Constants.ARTIFACT_DESCRIPTION, description);
+ json.put(Constants.IS_FROM_CSAR, isFromCsar);
+
+ String encodedPayload = new String(artifactContentent);
+
+
+ encodedPayload = Base64.encodeBase64String(artifactContentent);
+ // }
+
+ json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
+ json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
+ json.put(Constants.ARTIFACT_LABEL, label);
+ json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
+ json.put(Constants.REQUIRED_ARTIFACTS,
+ (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
+ : updatedRequiredArtifacts.stream()
+ .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())
+ || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
+ .map(e -> e.getFileName()).collect(Collectors.toList()));
+ return json;
+ }
+
+ public static Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo,
+ byte[] artifactContentent, int atrifactLabelCounter) {
+
+ Map<String, Object> json = new HashMap<String, Object>();
+ String artifactName = artifactTemplateInfo.getFileName();
+
+ json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
+ json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
+ json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
+
+ String encodedPayload = Base64.encodeBase64String(artifactContentent);
+
+ json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
+ String displayName = artifactName;
+ if (artifactName.lastIndexOf(".") > 0)
+ displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
+ json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
+ String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
+ json.put(Constants.ARTIFACT_LABEL, label);
+ json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
+ List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
+ json.put(Constants.REQUIRED_ARTIFACTS,
+ (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
+ : requiredArtifacts.stream()
+ .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())
+ || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
+ .map(e -> e.getFileName()).collect(Collectors.toList()));
+ return json;
+ }
+
+ public static ArtifactDefinition findArtifactInList(List<ArtifactDefinition> createdArtifacts, String artifactId) {
+ for (ArtifactDefinition artifact : createdArtifacts) {
+ if (artifact.getUniqueId().equals(artifactId)) {
+ return artifact;
+ }
+ }
+ return null;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java
index ab71508e62..cd6351cf9e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java
@@ -25,52 +25,52 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
public class NodeTypeConvertUtils {
- public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) {
- NodeTypeEnum res = null;
- if (componentTypeEnum != null) {
- switch (componentTypeEnum) {
- case SERVICE:
- switch (categoryType) {
- case CATEGORY:
- res = NodeTypeEnum.ServiceNewCategory;
- break;
+ public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) {
+ NodeTypeEnum res = null;
+ if (componentTypeEnum != null) {
+ switch (componentTypeEnum) {
+ case SERVICE:
+ switch (categoryType) {
+ case CATEGORY:
+ res = NodeTypeEnum.ServiceNewCategory;
+ break;
- default:
- // doesn't support subcategories or grouping
- break;
- }
- break;
- case RESOURCE:
- switch (categoryType) {
- case CATEGORY:
- res = NodeTypeEnum.ResourceNewCategory;
- break;
- case SUBCATEGORY:
- res = NodeTypeEnum.ResourceSubcategory;
- break;
- default:
- // doesn't support grouping
- break;
- }
- break;
- case PRODUCT:
- switch (categoryType) {
- case CATEGORY:
- res = NodeTypeEnum.ProductCategory;
- break;
- case SUBCATEGORY:
- res = NodeTypeEnum.ProductSubcategory;
- break;
- case GROUPING:
- res = NodeTypeEnum.ProductGrouping;
- break;
- }
- break;
- default:
- break;
- }
- }
- return res;
- }
+ default:
+ // doesn't support subcategories or grouping
+ break;
+ }
+ break;
+ case RESOURCE:
+ switch (categoryType) {
+ case CATEGORY:
+ res = NodeTypeEnum.ResourceNewCategory;
+ break;
+ case SUBCATEGORY:
+ res = NodeTypeEnum.ResourceSubcategory;
+ break;
+ default:
+ // doesn't support grouping
+ break;
+ }
+ break;
+ case PRODUCT:
+ switch (categoryType) {
+ case CATEGORY:
+ res = NodeTypeEnum.ProductCategory;
+ break;
+ case SUBCATEGORY:
+ res = NodeTypeEnum.ProductSubcategory;
+ break;
+ case GROUPING:
+ res = NodeTypeEnum.ProductGrouping;
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ return res;
+ }
}
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 f2a5b35562..624a8b623a 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
@@ -20,236 +20,243 @@
package org.openecomp.sdc.be.datamodel.utils;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
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;
-import org.openecomp.sdc.be.ui.model.UiServiceMetadata;
+import org.openecomp.sdc.be.ui.model.*;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
public class UiComponentDataConverter {
-
- public static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) {
-
- switch (ComponentFieldsEnum.findByValue(fieldName)) {
-
- case INPUTS:
- if(component.getInputs() == null){
- dataTransfer.setInputs(new ArrayList<>());
- } else {
- dataTransfer.setInputs(component.getInputs());
- }
- break;
-
- case COMPONENT_INSTANCE_RELATION:
- if(component.getComponentInstancesRelations() == null){
- dataTransfer.setComponentInstancesRelations(new ArrayList<>());
- } else {
- dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations());
- }
-
- break;
-
- case GROUPS:
- if(component.getGroups() == null){
- dataTransfer.setGroups(new ArrayList<>());
- } else {
- dataTransfer.setGroups(component.getGroups());
- }
- break;
-
- case COMPONENT_INSTANCES:
- if(component.getComponentInstances() == null) {
- dataTransfer.setComponentInstances(new ArrayList<>());
- } else {
- dataTransfer.setComponentInstances(component.getComponentInstances());
- }
- break;
-
- case COMPONENT_INSTANCES_PROPERTIES:
- if(component.getComponentInstancesProperties() == null) {
- dataTransfer.setComponentInstancesProperties(new HashMap<>());
- } else {
- dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties());
- }
- break;
-
- case CAPABILITIES:
- if(component.getCapabilities() == null) {
- dataTransfer.setCapabilities(new HashMap<>());
- } else {
- dataTransfer.setCapabilities(component.getCapabilities());
- }
- break;
-
- case REQUIREMENTS:
- if(component.getRequirements() == null) {
- dataTransfer.setRequirements(new HashMap<>());
- } else {
- dataTransfer.setRequirements(component.getRequirements());
- }
- break;
-
- case DEPLOYMENT_ARTIFACTS:
- if(component.getDeploymentArtifacts() == null) {
- dataTransfer.setDeploymentArtifacts(new HashMap<>());
- } else {
- dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts());
- }
- break;
-
- case TOSCA_ARTIFACTS:
- if(component.getToscaArtifacts() == null) {
- dataTransfer.setToscaArtifacts(new HashMap<>());
- } else {
- dataTransfer.setToscaArtifacts(component.getToscaArtifacts());
- }
- break;
-
- case ARTIFACTS:
- if(component.getArtifacts() == null) {
- dataTransfer.setArtifacts(new HashMap<>());
- } else {
- dataTransfer.setArtifacts(component.getArtifacts());
- }
- break;
-
- case COMPONENT_INSTANCES_ATTRIBUTES:
- if(component.getComponentInstancesAttributes() == null) {
- dataTransfer.setComponentInstancesAttributes(new HashMap<>());
- } else {
- dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes());
- }
- break;
-
- case COMPONENT_INSTANCE_INPUTS:
- if(component.getComponentInstancesInputs() == null) {
- dataTransfer.setComponentInstancesInputs(new HashMap<>());
- } else {
- dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs());
- }
-
- break;
-
-
- default:
- break;
- }
-
- }
-
-
- public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List<String> paramsToReturn) {
- UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer();
-
- for(String fieldName: paramsToReturn){
-
- switch (ComponentFieldsEnum.findByValue(fieldName)) {
-
- case PROPERTIES:
- if(resource.getProperties() == null) {
- dataTransfer.setProperties(new ArrayList<>());
- } else {
- dataTransfer.setProperties(resource.getProperties());
- }
- break;
-
- case INTERFACES:
- if(resource.getInterfaces() == null) {
- dataTransfer.setInterfaces(new HashMap<>());
- } else {
- dataTransfer.setInterfaces(resource.getInterfaces());
- }
- break;
-
- case DERIVED_FROM:
- if(resource.getDerivedFrom() == null) {
- dataTransfer.setDerivedFrom(new ArrayList<>());
- } else {
- dataTransfer.setDerivedFrom(resource.getDerivedFrom());
- }
- break;
-
- case ATTRIBUTES:
- if(resource.getAttributes() == null) {
- dataTransfer.setAttributes(new ArrayList<>());
- } else {
- dataTransfer.setAttributes(resource.getAttributes());
- }
- break;
-
- case ADDITIONAL_INFORMATION:
- if(resource.getAdditionalInformation() == null) {
- dataTransfer.setAdditionalInformation(new ArrayList<>());
- } else {
- dataTransfer.setAdditionalInformation(resource.getAdditionalInformation());
- }
- break;
- case METADATA:
- UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition());
- dataTransfer.setMetadata(metadata);
- break;
-
- default:
- setUiTranferDataByFieldName(dataTransfer, resource, fieldName);
- }
- }
-
- return dataTransfer;
- }
-
- public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List<String> paramsToReturn) {
- UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer();
-
- for(String fieldName: paramsToReturn){
-
- switch (ComponentFieldsEnum.findByValue(fieldName)) {
-
- case SERVICE_API_ARTIFACTS:
- if(service.getServiceApiArtifacts() == null) {
- dataTransfer.setServiceApiArtifacts(new HashMap<>());
- } else {
- dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts());
- }
-
- break;
-
- case METADATA:
- UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
- dataTransfer.setMetadata(metadata);
- break;
- default:
- setUiTranferDataByFieldName(dataTransfer, service, fieldName);
- }
- }
-
- 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;
- }
+
+ private static void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) {
+
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+
+ case INPUTS:
+ if(component.getInputs() == null){
+ dataTransfer.setInputs(new ArrayList<>());
+ } else {
+ dataTransfer.setInputs(component.getInputs());
+ }
+ break;
+
+ case COMPONENT_INSTANCE_RELATION:
+ if(component.getComponentInstancesRelations() == null){
+ dataTransfer.setComponentInstancesRelations(new ArrayList<>());
+ } else {
+ dataTransfer.setComponentInstancesRelations(component.getComponentInstancesRelations());
+ }
+
+ break;
+
+ case GROUPS:
+ if(component.getGroups() == null){
+ dataTransfer.setGroups(new ArrayList<>());
+ } else {
+ dataTransfer.setGroups(component.getGroups());
+ }
+ break;
+
+ case COMPONENT_INSTANCES:
+ if(component.getComponentInstances() == null) {
+ dataTransfer.setComponentInstances(new ArrayList<>());
+ } else {
+ dataTransfer.setComponentInstances(component.getComponentInstances());
+ }
+ break;
+
+ case COMPONENT_INSTANCES_PROPERTIES:
+ if(component.getComponentInstancesProperties() == null) {
+ dataTransfer.setComponentInstancesProperties(new HashMap<>());
+ } else {
+ dataTransfer.setComponentInstancesProperties(component.getComponentInstancesProperties());
+ }
+ break;
+
+ case CAPABILITIES:
+ if(component.getCapabilities() == null) {
+ dataTransfer.setCapabilities(new HashMap<>());
+ } else {
+ dataTransfer.setCapabilities(component.getCapabilities());
+ }
+ break;
+
+ case POLICIES:
+ dataTransfer.setPolicies(component.resolvePoliciesList());
+ break;
+
+ case REQUIREMENTS:
+ if(component.getRequirements() == null) {
+ dataTransfer.setRequirements(new HashMap<>());
+ } else {
+ dataTransfer.setRequirements(component.getRequirements());
+ }
+ break;
+
+ case DEPLOYMENT_ARTIFACTS:
+ if(component.getDeploymentArtifacts() == null) {
+ dataTransfer.setDeploymentArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setDeploymentArtifacts(component.getDeploymentArtifacts());
+ }
+ break;
+
+ case TOSCA_ARTIFACTS:
+ if(component.getToscaArtifacts() == null) {
+ dataTransfer.setToscaArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setToscaArtifacts(component.getToscaArtifacts());
+ }
+ break;
+
+ case ARTIFACTS:
+ if(component.getArtifacts() == null) {
+ dataTransfer.setArtifacts(new HashMap<>());
+ } else {
+ dataTransfer.setArtifacts(component.getArtifacts());
+ }
+ break;
+
+ case COMPONENT_INSTANCES_ATTRIBUTES:
+ if(component.getComponentInstancesAttributes() == null) {
+ dataTransfer.setComponentInstancesAttributes(new HashMap<>());
+ } else {
+ dataTransfer.setComponentInstancesAttributes(component.getComponentInstancesAttributes());
+ }
+ break;
+
+ case COMPONENT_INSTANCE_INPUTS:
+ if(component.getComponentInstancesInputs() == null) {
+ dataTransfer.setComponentInstancesInputs(new HashMap<>());
+ } else {
+ dataTransfer.setComponentInstancesInputs(component.getComponentInstancesInputs());
+ }
+
+ break;
+
+
+ default:
+ break;
+ }
+
+ }
+
+
+ public static UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List<String> paramsToReturn) {
+ UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer();
+
+ for(String fieldName: paramsToReturn){
+
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+
+ case PROPERTIES:
+ if(resource.getProperties() == null) {
+ dataTransfer.setProperties(new ArrayList<>());
+ } else {
+ dataTransfer.setProperties(resource.getProperties());
+ }
+ break;
+
+ case INTERFACES:
+ if(resource.getInterfaces() == null) {
+ dataTransfer.setInterfaces(new HashMap<>());
+ } else {
+ dataTransfer.setInterfaces(resource.getInterfaces());
+ }
+ break;
+
+ case DERIVED_FROM:
+ if(resource.getDerivedFrom() == null) {
+ dataTransfer.setDerivedFrom(new ArrayList<>());
+ } else {
+ dataTransfer.setDerivedFrom(resource.getDerivedFrom());
+ }
+ break;
+
+ case ATTRIBUTES:
+ if(resource.getAttributes() == null) {
+ dataTransfer.setAttributes(new ArrayList<>());
+ } else {
+ dataTransfer.setAttributes(resource.getAttributes());
+ }
+ break;
+
+ case ADDITIONAL_INFORMATION:
+ if(resource.getAdditionalInformation() == null) {
+ dataTransfer.setAdditionalInformation(new ArrayList<>());
+ } else {
+ dataTransfer.setAdditionalInformation(resource.getAdditionalInformation());
+ }
+ break;
+ case METADATA:
+ UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(), (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition());
+ dataTransfer.setMetadata(metadata);
+ break;
+
+ default:
+ setUiTranferDataByFieldName(dataTransfer, resource, fieldName);
+ }
+ }
+
+ return dataTransfer;
+ }
+
+ public static UiComponentDataTransfer getUiDataTransferFromServiceByParams(Service service, List<String> paramsToReturn) {
+ UiServiceDataTransfer dataTransfer = new UiServiceDataTransfer();
+
+ for(String fieldName: paramsToReturn){
+
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
+
+ case SERVICE_API_ARTIFACTS:
+ if(service.getServiceApiArtifacts() == null) {
+ dataTransfer.setServiceApiArtifacts(new org.openecomp.sdc.be.ui.model.SerializedHashMap<>());
+ } else {
+ dataTransfer.setServiceApiArtifacts(service.getServiceApiArtifacts());
+ }
+
+ break;
+ case FORWARDING_PATHS:
+ if(service.getForwardingPaths() == null) {
+ dataTransfer.setForwardingPaths(new org.openecomp.sdc.be.ui.model.SerializedHashMap<>());
+ } else {
+ dataTransfer.setForwardingPaths(service.getForwardingPaths());
+ }
+
+ break;
+ case METADATA:
+ UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
+ dataTransfer.setMetadata(metadata);
+ break;
+ default:
+ setUiTranferDataByFieldName(dataTransfer, service, fieldName);
+ }
+ }
+
+ 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());
+ break;
+ default:
+ break;
+ }
+ return uiComponentMetadata;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java
index 0cc415c80d..0aa8d5afa6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java
@@ -27,39 +27,34 @@ import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
public class AuditHandler {
- ComponentsUtils componentsUtils;
- String instanceID;
- private RegistrationRequest registrationRequest;
+ ComponentsUtils componentsUtils;
+ String instanceID;
+ private RegistrationRequest registrationRequest;
- public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) {
- super();
- this.componentsUtils = componentsUtils;
- this.instanceID = instanceID;
- this.registrationRequest = registrationRequest;
- }
+ public AuditHandler(ComponentsUtils componentsUtils, String instanceID, RegistrationRequest registrationRequest) {
+ super();
+ this.componentsUtils = componentsUtils;
+ this.instanceID = instanceID;
+ this.registrationRequest = registrationRequest;
+ }
- public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) {
- String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName())
- : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName());
- componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
- }
+ public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , String topicName) {
+ componentsUtils.auditTopicACLKeys(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
+ }
- public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole) {
- String topicName = (subscriberRole == SubscriberTypeEnum.CONSUMER) ? DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName())
- : DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName());
- componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
+ public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, String topicName) {
+ componentsUtils.auditTopicACLKeys(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), topicName, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
+ }
- }
+ public void auditRegisterRequest(CambriaErrorResponse registerResponse) {
+ componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
+ registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
- public void auditRegisterRequest(CambriaErrorResponse registerResponse) {
- componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
- registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
+ }
- }
-
- public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) {
- componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
- registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
- }
+ public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) {
+ componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
+ registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java
index ae1de21ea8..2c2adaa970 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java
@@ -20,224 +20,275 @@
package org.openecomp.sdc.be.distribution;
-import java.util.List;
-
-import javax.annotation.Resource;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse;
-import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler;
-import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine;
-import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask;
-import org.openecomp.sdc.be.components.distribution.engine.SubscriberTypeEnum;
+import org.openecomp.sdc.be.components.distribution.engine.*;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;
-import org.openecomp.sdc.be.distribution.api.client.ServerListResponse;
-import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse;
-import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse;
-import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.be.distribution.api.client.*;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.annotation.Resource;
+import javax.ws.rs.core.Response;
+import java.util.List;
-import fj.data.Either;
+import static org.apache.commons.lang.BooleanUtils.isTrue;
+import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;
+import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;
@Component("distributionBusinessLogic")
public class DistributionBusinessLogic {
- public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine";
- public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine";
- private Gson gson = new GsonBuilder().setPrettyPrinting().create();
- private static Logger log = LoggerFactory.getLogger(DistributionBusinessLogic.class.getName());
- @Resource
- private DistributionEngine distributionEngine;
-
- private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();
- private CambriaHandler cambriaHandler;
-
- public Either<ServerListResponse, ResponseFormat> getUebServerList() {
-
- DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
-
- List<String> serverList = distributionEngineConfiguration.getUebServers();
-
- if (serverList != null && !serverList.isEmpty()) {
-
- ServerListResponse serverListResponse = new ServerListResponse();
-
- serverListResponse.setUebServerList(serverList);
-
- return Either.left(serverListResponse);
- } else {
- ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return Either.right(errorResponseWrapper);
- }
-
- }
-
- public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, AuditHandler auditHandler) {
- CambriaErrorResponse registerResponse = null;
- try {
- registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER);
- auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER);
-
- if (responseWrapper.isEmpty()) {
- registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER);
- auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER);
- // Second Register failed - unregister the first
- if (!responseWrapper.isEmpty()) {
- CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER);
- auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER);
- }
- }
-
- if (responseWrapper.isEmpty()) {
- TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest);
- responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
- }
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic");
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic");
- Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
- responseWrapper.setInnerElement(errorResponse);
- } finally {
- auditHandler.auditRegisterRequest(registerResponse);
- }
- }
-
- public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest, AuditHandler auditHandler) {
- Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>();
- try {
- CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.PRODUCER);
- auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER);
- updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse);
-
- CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest, SubscriberTypeEnum.CONSUMER);
- auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER);
- updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse);
-
- // Success unregister both topics
- TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), getStatusTopicName(unRegistrationRequest.getDistrEnvName()),
- unregisterClientConsumerTopicResponse.getOperationStatus(), unregisterClientProducerTopicResponse.getOperationStatus());
-
- if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) {
- responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build());
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed");
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed");
- responseWrapper.setInnerElement(Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration of subscriber to topic");
- Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
- responseWrapper.setInnerElement(errorResponse);
-
- } finally {
- auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement());
- }
- }
-
- private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper, CambriaErrorResponse currentResponse) {
- if (cambriaResponseWrapper.isEmpty()) {
- cambriaResponseWrapper.setInnerElement(currentResponse);
- } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) {
- cambriaResponseWrapper.setInnerElement(currentResponse);
-
- }
-
- }
-
- public static String getNotificationTopicName(String envName) {
- DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
- return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);
-
- }
-
- public static String getStatusTopicName(String envName) {
- DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
- return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);
-
- }
-
- protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, SubscriberTypeEnum subscriberType) {
- DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
- String topicName;
- if (subscriberType == SubscriberTypeEnum.PRODUCER) {
- topicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName());
- } else {
- topicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName());
-
- }
- log.debug("unregistering client as {} , from topic: {}", subscriberType.name(), topicName);
- return getCambriaHandler().unRegisterFromTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType);
- }
-
- private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) {
- DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
- String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
-
- TopicRegistrationResponse topicResponse = new TopicRegistrationResponse();
- topicResponse.setDistrNotificationTopicName(notificationTopicName);
- topicResponse.setDistrStatusTopicName(statusTopicName);
- return topicResponse;
- }
-
- protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType) {
- DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
- String topicName, errorMsg;
-
- // Register for notifications as consumer
- if (subscriberType == SubscriberTypeEnum.CONSUMER) {
- topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
- errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed";
- }
- // Register for status as producer
- else {
- topicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed";
- }
- log.debug("registering client as {} , from topic: {}", subscriberType.name(), topicName);
- CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(config.getUebServers(), topicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), subscriberType);
-
- if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) {
- Response failedRegistrationResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg);
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg);
- responseWrapper.setInnerElement(failedRegistrationResponse);
- }
- return registerToTopic;
- }
-
- protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
- Response response = Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
- return response;
- }
-
- public ResponseFormatManager getResponseFormatManager() {
- return responseFormatManager;
- }
-
- public DistributionEngine getDistributionEngine() {
- return distributionEngine;
- }
-
- public CambriaHandler getCambriaHandler() {
- if (cambriaHandler == null) {
- cambriaHandler = new CambriaHandler();
- }
- return cambriaHandler;
- }
+ public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine";
+ public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine";
+ private Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ private static final Logger LOGGER = LoggerFactory.getLogger(DistributionBusinessLogic.class);
+ @Resource
+ private IDistributionEngine distributionEngine;
+
+ private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();
+ private CambriaHandler cambriaHandler;
+
+ private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) {
+ if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){
+ registrationRequest.setDistEnvEndPoints(config.getUebServers());
+ }
+ }
+ public Either<ServerListResponse, ResponseFormat> getUebServerList() {
+
+ DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+
+ List<String> serverList = distributionEngineConfiguration.getUebServers();
+
+ if (serverList != null && !serverList.isEmpty()) {
+
+ ServerListResponse serverListResponse = new ServerListResponse();
+
+ serverListResponse.setUebServerList(serverList);
+
+ return Either.left(serverListResponse);
+ } else {
+ ResponseFormat errorResponseWrapper = getResponseFormatManager()
+ .getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(errorResponseWrapper);
+ }
+
+ }
+
+ public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest,
+ AuditHandler auditHandler) {
+ CambriaErrorResponse registerResponse = null;
+ try {
+ DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration();
+ String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(),
+ registrationRequest.getDistrEnvName());
+ registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
+ SubscriberTypeEnum.PRODUCER, statusTopicName);
+
+ auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER, statusTopicName);
+ boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty();
+
+ // Story [347698] Distribution Client Get Indication from
+ // component whether to register as consumer and producer on
+ // status topic
+ boolean registeredAsConsumerOnStatus = false;
+ if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) {
+ registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
+ SubscriberTypeEnum.CONSUMER, statusTopicName);
+ auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, statusTopicName);
+ registeredAsConsumerOnStatus = responseWrapper.isEmpty();
+
+ }
+
+ if (responseWrapper.isEmpty()) {
+ String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(),
+ registrationRequest.getDistrEnvName());
+ registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
+ SubscriberTypeEnum.CONSUMER, notificationTopicName);
+ auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, notificationTopicName);
+ }
+ // Unregister Rollback
+ if (!responseWrapper.isEmpty()) {
+ if (isRegisteredAsProducerOnStatusSuccess) {
+ CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
+ SubscriberTypeEnum.PRODUCER, statusTopicName);
+ auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER, statusTopicName);
+ }
+ if (registeredAsConsumerOnStatus) {
+ CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
+ SubscriberTypeEnum.CONSUMER, statusTopicName);
+ auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER, statusTopicName);
+ }
+ }
+
+ if (responseWrapper.isEmpty()) {
+ TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest);
+ responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
+ }
+
+ } catch (Exception e) {
+ LOGGER.error("registration to topic failed", e);
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
+ "registration of subscriber to topic");
+ Response errorResponse = buildErrorResponse(
+ getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(errorResponse);
+ } finally {
+ auditHandler.auditRegisterRequest(registerResponse);
+ }
+ }
+
+ public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest,
+ AuditHandler auditHandler) {
+ Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>();
+ try {
+ String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName());
+ CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(
+ unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName);
+ auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER,
+ statusTopicName);
+ updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse);
+
+ String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName());
+ CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(
+ unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName);
+ auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER,
+ notificationTopicName);
+ updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse);
+
+ // Success unregister both topics
+ TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(
+ getNotificationTopicName(unRegistrationRequest.getDistrEnvName()),
+ getStatusTopicName(unRegistrationRequest.getDistrEnvName()),
+ unregisterClientConsumerTopicResponse.getOperationStatus(),
+ unregisterClientProducerTopicResponse.getOperationStatus());
+
+ if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) {
+ responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build());
+ } else {
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE,
+ "unregistration failed");
+ responseWrapper.setInnerElement(
+ Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());
+ }
+ } catch (Exception e) {
+ LOGGER.error("unregistered to topic failed", e);
+ Response errorResponse = buildErrorResponse(
+ getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(errorResponse);
+
+ } finally {
+ auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement());
+ }
+ }
+
+ private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper,
+ CambriaErrorResponse currentResponse) {
+ if (cambriaResponseWrapper.isEmpty()) {
+ cambriaResponseWrapper.setInnerElement(currentResponse);
+ } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) {
+ cambriaResponseWrapper.setInnerElement(currentResponse);
+
+ }
+
+ }
+
+ public static String getNotificationTopicName(String envName) {
+ DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+ return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);
+
+ }
+
+ public static String getStatusTopicName(String envName) {
+ DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+ return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);
+
+ }
+
+ protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest,
+ SubscriberTypeEnum subscriberType, String topicName) {
+ DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+ initRequestEnvEndPoints(unRegistrationRequest, config);
+
+ LOGGER.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints());
+ return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(),
+ config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName);
+ }
+
+ private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) {
+ DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+ String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(),
+ registrationRequest.getDistrEnvName());
+ String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(),
+ registrationRequest.getDistrEnvName());
+
+ TopicRegistrationResponse topicResponse = new TopicRegistrationResponse();
+ topicResponse.setDistrNotificationTopicName(notificationTopicName);
+ topicResponse.setDistrStatusTopicName(statusTopicName);
+ return topicResponse;
+ }
+
+ protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper,
+ RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) {
+ DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
+ .getDistributionEngineConfiguration();
+ initRequestEnvEndPoints(registrationRequest, config);
+ String errorMsg;
+
+ // Register for notifications as consumer
+ if (subscriberType == SubscriberTypeEnum.CONSUMER) {
+ errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed";
+ }
+ // Register for status as producer
+ else {
+ errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed";
+ }
+ LOGGER.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints());
+ CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ subscriberType, topicName);
+
+ if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) {
+ Response failedRegistrationResponse = buildErrorResponse(
+ getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
+ errorMsg);
+ responseWrapper.setInnerElement(failedRegistrationResponse);
+ }
+ return registerToTopic;
+ }
+
+ protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
+ return Response.status(requestErrorWrapper.getStatus())
+ .entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
+ }
+
+ public ResponseFormatManager getResponseFormatManager() {
+ return responseFormatManager;
+ }
+
+ public IDistributionEngine getDistributionEngine() {
+ return distributionEngine;
+ }
+
+ public CambriaHandler getCambriaHandler() {
+ if (cambriaHandler == null) {
+ cambriaHandler = new CambriaHandler();
+ }
+ return cambriaHandler;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java
index a6a6602cb0..3edb3d8f69 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java
@@ -21,5 +21,5 @@
package org.openecomp.sdc.be.distribution.api.client;
public enum CambriaOperationStatus {
- OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR,
+ OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR,
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java
index ef14efe4f8..1dfbdb538d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java
@@ -20,21 +20,43 @@
package org.openecomp.sdc.be.distribution.api.client;
+import java.util.List;
+
public class RegistrationRequest {
- String apiPublicKey;
- String distrEnvName;
+ String apiPublicKey;
+ String distrEnvName;
+ Boolean isConsumerToSdcDistrStatusTopic;
+ List<String> distEnvEndPoints;
+
+ public RegistrationRequest(String apiPublicKey, String distrEnvName, boolean isConsumerToSdcDistrStatusTopic) {
+ this.apiPublicKey = apiPublicKey;
+ this.distrEnvName = distrEnvName;
+ this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic;
+ }
+ public RegistrationRequest(String apiPublicKey, String distrEnvName, List<String> distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic){
+ this.apiPublicKey = apiPublicKey;
+ this.distrEnvName = distrEnvName;
+ this.distEnvEndPoints = distEnvEndPoints;
+ this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic;
+ }
+
+ public String getApiPublicKey() {
+ return apiPublicKey;
+ }
- public RegistrationRequest(String apiPublicKey, String distrEnvName) {
- this.apiPublicKey = apiPublicKey;
- this.distrEnvName = distrEnvName;
- }
+ public String getDistrEnvName() {
+ return distrEnvName;
+ }
- public String getApiPublicKey() {
- return apiPublicKey;
- }
+ public Boolean getIsConsumerToSdcDistrStatusTopic() {
+ return isConsumerToSdcDistrStatusTopic;
+ }
+ public List<String> getDistEnvEndPoints() {
+ return distEnvEndPoints;
+ }
- public String getDistrEnvName() {
- return distrEnvName;
- }
+ public void setDistEnvEndPoints(List<String> distEnvEndPoints) {
+ this.distEnvEndPoints = distEnvEndPoints;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java
index 267a691e29..2eebedfd7c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java
@@ -24,13 +24,13 @@ import java.util.List;
public class ServerListResponse {
- private List<String> uebServerList;
+ private List<String> uebServerList;
- public List<String> getUebServerList() {
- return uebServerList;
- }
+ public List<String> getUebServerList() {
+ return uebServerList;
+ }
- public void setUebServerList(List<String> uebServerList) {
- this.uebServerList = uebServerList;
- }
+ public void setUebServerList(List<String> uebServerList) {
+ this.uebServerList = uebServerList;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java
index e2a34a19d5..5d1b0657c6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java
@@ -21,22 +21,22 @@
package org.openecomp.sdc.be.distribution.api.client;
public class TopicRegistrationResponse {
- String distrNotificationTopicName;
- String distrStatusTopicName;
+ String distrNotificationTopicName;
+ String distrStatusTopicName;
- public void setDistrNotificationTopicName(String distrNotificationTopicName) {
- this.distrNotificationTopicName = distrNotificationTopicName;
- }
+ public void setDistrNotificationTopicName(String distrNotificationTopicName) {
+ this.distrNotificationTopicName = distrNotificationTopicName;
+ }
- public void setDistrStatusTopicName(String distrStatusTopicName) {
- this.distrStatusTopicName = distrStatusTopicName;
- }
+ public void setDistrStatusTopicName(String distrStatusTopicName) {
+ this.distrStatusTopicName = distrStatusTopicName;
+ }
- public String getDistrNotificationTopicName() {
- return distrNotificationTopicName;
- }
+ public String getDistrNotificationTopicName() {
+ return distrNotificationTopicName;
+ }
- public String getDistrStatusTopicName() {
- return distrStatusTopicName;
- }
+ public String getDistrStatusTopicName() {
+ return distrStatusTopicName;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java
index ffb9f9352f..621cd37a54 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java
@@ -21,32 +21,32 @@
package org.openecomp.sdc.be.distribution.api.client;
public class TopicUnregistrationResponse {
- String distrNotificationTopicName;
- String distrStatusTopicName;
- CambriaOperationStatus notificationUnregisterResult;
- CambriaOperationStatus statusUnregisterResult;
+ String distrNotificationTopicName;
+ String distrStatusTopicName;
+ CambriaOperationStatus notificationUnregisterResult;
+ CambriaOperationStatus statusUnregisterResult;
- public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) {
- super();
- this.distrNotificationTopicName = distrNotificationTopicName;
- this.distrStatusTopicName = distrStatusTopicName;
- this.notificationUnregisterResult = notificationUnregisterResult;
- this.statusUnregisterResult = statusUnregisterResult;
- }
+ public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) {
+ super();
+ this.distrNotificationTopicName = distrNotificationTopicName;
+ this.distrStatusTopicName = distrStatusTopicName;
+ this.notificationUnregisterResult = notificationUnregisterResult;
+ this.statusUnregisterResult = statusUnregisterResult;
+ }
- public String getDistrNotificationTopicName() {
- return distrNotificationTopicName;
- }
+ public String getDistrNotificationTopicName() {
+ return distrNotificationTopicName;
+ }
- public String getDistrStatusTopicName() {
- return distrStatusTopicName;
- }
+ public String getDistrStatusTopicName() {
+ return distrStatusTopicName;
+ }
- public CambriaOperationStatus getNotificationUnregisterResult() {
- return notificationUnregisterResult;
- }
+ public CambriaOperationStatus getNotificationUnregisterResult() {
+ return notificationUnregisterResult;
+ }
- public CambriaOperationStatus getStatusUnregisterResult() {
- return statusUnregisterResult;
- }
+ public CambriaOperationStatus getStatusUnregisterResult() {
+ return statusUnregisterResult;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java
index 125c1012b2..984a831c8e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java
@@ -20,45 +20,33 @@
package org.openecomp.sdc.be.distribution.servlet;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
import org.openecomp.sdc.be.servlets.BeGenericServlet;
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.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.Map;
/**
* This Servlet serves external users to download artifacts.
@@ -73,249 +61,233 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class DistributionCatalogServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName());
- @Context
- private HttpServletRequest request;
+ private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class);
+ @Context
+ private HttpServletRequest request;
+
+ // *******************************************************
+ // Download (GET) artifacts
+ // **********************************************************/
+ /**
+ *
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param serviceName
+ * @param serviceVersion
+ * @param artifactName
+ * @return
+ */
+ @GET
+ @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
+ @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"),
+ @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response downloadServiceArtifact(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @PathParam("serviceName") final String serviceName,
+ @PathParam("serviceVersion") final String serviceVersion,
+ @PathParam("artifactName") final String artifactName) {
+
+ Response response = null;
+ String requestURI = request.getRequestURI();
+ if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
+ log.debug("Missing X-ECOMP-InstanceID header");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ return buildErrorResponse(responseFormat);
+ }
+
+ try {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
+ if (downloadRsrcArtifactEither.isRight()) {
+ ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ response = buildErrorResponse(responseFormat);
+ } else {
+ byte[] value = downloadRsrcArtifactEither.left().value();
+ InputStream is = new ByteArrayInputStream(value);
- // *******************************************************
- // Download (GET) artifacts
- // **********************************************************/
- /**
- *
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param serviceName
- * @param serviceVersion
- * @param artifactName
- * @return
- */
- @GET
- @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
- @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"),
- @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response downloadServiceArtifact(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @PathParam("serviceName") final String serviceName,
- @PathParam("serviceVersion") final String serviceVersion,
- @PathParam("artifactName") final String artifactName) {
-
- Response response = null;
- String requestURI = request.getRequestURI();
- AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ response = buildOkResponse(responseFormat, is, headers);
+ }
+ return response;
- if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
- log.debug("Missing X-ECOMP-InstanceID header");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API");
+ log.debug("download artifact failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
- try {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
- if (downloadRsrcArtifactEither.isRight()) {
- ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- response = buildErrorResponse(responseFormat);
- } else {
- byte[] value = downloadRsrcArtifactEither.left().value();
- InputStream is = new ByteArrayInputStream(value);
+ /**
+ *
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param serviceName
+ * @param serviceVersion
+ * @param resourceName
+ * @param resourceVersion
+ * @param artifactName
+ * @return
+ */
+ @GET
+ @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
+ @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"),
+ @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"),
+ @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response downloadResourceArtifact(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @PathParam("serviceName") final String serviceName,
+ @PathParam("serviceVersion") final String serviceVersion,
+ @PathParam("resourceName") final String resourceName,
+ @PathParam("resourceVersion") final String resourceVersion,
+ @PathParam("artifactName") final String artifactName) {
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- response = buildOkResponse(responseFormat, is, headers);
- }
- return response;
+ Response response = null;
+ String requestURI = request.getRequestURI();
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download Murano package artifact for service - external API");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API");
- log.debug("download artifact failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /**
- *
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param serviceName
- * @param serviceVersion
- * @param resourceName
- * @param resourceVersion
- * @param artifactName
- * @return
- */
- @GET
- @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
- @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"),
- @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"),
- @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response downloadResourceArtifact(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @PathParam("serviceName") final String serviceName,
- @PathParam("serviceVersion") final String serviceVersion,
- @PathParam("resourceName") final String resourceName,
- @PathParam("resourceVersion") final String resourceVersion,
- @PathParam("artifactName") final String artifactName) {
-
- Response response = null;
- String requestURI = request.getRequestURI();
- AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
+ if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
+ log.debug("Missing X-ECOMP-InstanceID header");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ return buildErrorResponse(responseFormat);
+ }
- if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
- log.debug("Missing X-ECOMP-InstanceID header");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
+ try {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);
+ if (downloadRsrcArtifactEither.isRight()) {
+ ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ response = buildErrorResponse(responseFormat);
+ } else {
+ byte[] value = downloadRsrcArtifactEither.left().value();
+ // Returning 64-encoded as it was received during upload
+ InputStream is = new ByteArrayInputStream(value);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ response = buildOkResponse(responseFormat, is, headers);
+ }
+ return response;
- try {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);
- if (downloadRsrcArtifactEither.isRight()) {
- ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- response = buildErrorResponse(responseFormat);
- } else {
- byte[] value = downloadRsrcArtifactEither.left().value();
- // Returning 64-encoded as it was received during upload
- InputStream is = new ByteArrayInputStream(value);
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- response = buildOkResponse(responseFormat, is, headers);
- }
- return response;
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
+ log.debug("download artifact failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
- log.debug("download artifact failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
+ /**
+ *
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param serviceName
+ * @param serviceVersion
+ * @param resourceInstanceName
+ * @param artifactName
+ * @return
+ */
+ @GET
+ @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
+ @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"),
+ @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"),
+ @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response downloadResourceInstanceArtifact(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @PathParam("serviceName") final String serviceName,
+ @PathParam("serviceVersion") final String serviceVersion,
+ @PathParam("resourceInstanceName") final String resourceInstanceName,
+ @PathParam("artifactName") final String artifactName) {
- /**
- *
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param serviceName
- * @param serviceVersion
- * @param resourceInstanceName
- * @param artifactName
- * @return
- */
- @GET
- @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(nickname = "downloadResourceInstanceArtifactByName",value = "Download resource instance artifact by artifact name", httpMethod = "GET", notes = "Returns downloaded artifact", response = String.class)
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "The artifact is found and streamed.", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified Service is not found - SVC4503"),
- @ApiResponse(code = 404, message = "Specified Resource Instance is not found - SVC4526"),
- @ApiResponse(code = 404, message = "Specified Service Version is not found - SVC4504"),
- @ApiResponse(code = 404, message = "Specified artifact is not found - SVC4505"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response downloadResourceInstanceArtifact(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @PathParam("serviceName") final String serviceName,
- @PathParam("serviceVersion") final String serviceVersion,
- @PathParam("resourceInstanceName") final String resourceInstanceName,
- @PathParam("artifactName") final String artifactName) {
-
- Response response = null;
- String requestURI = request.getRequestURI();
- AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
+ Response response = null;
+ String requestURI = request.getRequestURI();
- if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
- log.debug("Missing X-ECOMP-InstanceID header");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
+ if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
+ log.debug("Missing X-ECOMP-InstanceID header");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ return buildErrorResponse(responseFormat);
+ }
- try {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);
- if (downloadRsrcArtifactEither.isRight()) {
- ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- response = buildErrorResponse(responseFormat);
- } else {
- byte[] value = downloadRsrcArtifactEither.left().value();
- // Returning 64-encoded as it was received during upload
- InputStream is = new ByteArrayInputStream(value);
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
- response = buildOkResponse(responseFormat, is, headers);
- }
- return response;
+ try {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);
+ if (downloadRsrcArtifactEither.isRight()) {
+ ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ response = buildErrorResponse(responseFormat);
+ } else {
+ byte[] value = downloadRsrcArtifactEither.left().value();
+ // Returning 64-encoded as it was received during upload
+ InputStream is = new ByteArrayInputStream(value);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
+ response = buildOkResponse(responseFormat, is, headers);
+ }
+ return response;
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
- log.debug("download artifact failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
+ log.debug("download artifact failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java
index 6add877fe0..b5c322f90b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java
@@ -20,20 +20,9 @@
package org.openecomp.sdc.be.distribution.servlet;
-import javax.annotation.Resource;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.distribution.AuditHandler;
@@ -56,17 +45,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-import io.swagger.annotations.ResponseHeader;
+import javax.annotation.Resource;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
/**
* This Servlet serves external users for distribution purposes.
@@ -81,321 +67,315 @@ import io.swagger.annotations.ResponseHeader;
@Singleton
public class DistributionServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(DistributionServlet.class.getName());
- @Resource
- private DistributionBusinessLogic distributionLogic;
- @Context
- private HttpServletRequest request;
-
- /**
- *
- * @param requestId
- * @param instanceId
- * @param accept
- * @param authorization
- * @return
- */
- @GET
- @Path("/distributionUebCluster")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List",
- //TODO Tal G fix response headers
- responseHeaders = {
- @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class),
- @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)})
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response getUebServerList(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {
-
- init(request);
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- Response response = null;
- ResponseFormat responseFormat = null;
-
- if (instanceId == null) {
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- response = buildErrorResponse(responseFormat);
- getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
- return response;
- }
-
- try {
- Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();
-
- if (actionResponse.isRight()) {
- responseFormat = actionResponse.right().value();
- response = buildErrorResponse(responseFormat);
- } else {
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- response = buildOkResponse(responseFormat, actionResponse.left().value());
- }
-
- getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "failed to get ueb serbver list from cofiguration");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration");
- log.debug("failed to get ueb serbver list from cofiguration", e);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
- response = buildErrorResponse(responseFormat);
- return response;
- }
-
- }
-
- /**
- *
- * @param requestId
- * @param instanceId
- * @param accept
- * @param contenType
- * @param contenLength
- * @param authorization
- * @param requestJson
- * @return
- */
- @POST
- @Path("/registerForDistribution")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 400, message = "Missing Body - POL4500"),
- @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"),
- @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"),
- @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")})
- //TODO Tal G fix response headers and to check missing header validations with Michael L
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")
- public Response registerForDistribution(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- String requestJson) {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- init(request);
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();
-
- validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);
-
- if (responseWrapper.isEmpty()) {
- validateJson(responseWrapper, registrationRequestWrapper, requestJson);
- }
- if (responseWrapper.isEmpty()) {
- validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName());
- }
-
- if (responseWrapper.isEmpty()) {
- distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
- }
-
- return responseWrapper.getInnerElement();
- }
-
- /**
- * Returns list of valid artifact types for validation done in the distribution client.<br>
- * The list is the representation of the values of the enum ArtifactTypeEnum.
- *
- * @param requestId
- * @param instanceId
- * @param authorization
- * @param accept
- * @return
- */
- @GET
- @Path("/artifactTypes")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")})
- public Response getValidArtifactTypes(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {
- init(request);
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- Response response = null;
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
-
- validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES);
- if (responseWrapper.isEmpty()) {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values());
- } else {
- response = responseWrapper.getInnerElement();
- }
- return response;
- }
-
- /**
- * Removes from subscription for distribution notifications
- *
- * @param requestId
- * @param instanceId
- * @param accept
- * @param contenType
- * @param contenLength
- * @param authorization
- * @param requestJson
- * @return
- */
- @POST
- @Path("/unRegisterForDistribution")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications")
- //TODO Edit the responses
- @ApiResponses(value = {
- @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 400, message = "Missing Body - POL4500"),
- @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"),
- @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"),
- @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")
- public Response unRegisterForDistribution(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- String requestJson) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- init(request);
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();
-
- validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);
-
- if (responseWrapper.isEmpty()) {
- validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);
- }
- if (responseWrapper.isEmpty()) {
- validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName());
- }
- if (responseWrapper.isEmpty()) {
- distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionEngineSystemError, DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
- BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
- }
-
- return responseWrapper.getInnerElement();
- }
-
- private void validateEnv(Wrapper<Response> responseWrapper, String distrEnvName) {
-
- // DE194021
- StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable();
- // DE194021
- // StorageOperationStatus environmentStatus =
- // distributionLogic.getDistributionEngine().isEnvironmentAvailable(distrEnvName);
- if (environmentStatus != StorageOperationStatus.OK) {
- if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) {
- Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));
- responseWrapper.setInnerElement(missingHeaderResponse);
- } else {
- Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
- responseWrapper.setInnerElement(missingHeaderResponse);
- }
- }
-
- }
-
- private void init(HttpServletRequest request) {
- if (distributionLogic == null) {
- distributionLogic = getDistributionBL(request.getSession().getServletContext());
- }
- }
-
- private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) {
- if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) {
- Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));
- responseWrapper.setInnerElement(missingHeaderResponse);
- // Audit
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
-
- }
-
- }
-
- private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) {
- if (requestJson == null || requestJson.isEmpty()) {
- Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
- responseWrapper.setInnerElement(missingBodyResponse);
- } else {
- Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class);
- if (eitherRegistration.isLeft()) {
- RegistrationRequest registrationRequest = eitherRegistration.left().value();
- if (registrationRequest.getApiPublicKey() == null) {
- Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));
- responseWrapper.setInnerElement(missingBodyResponse);
-
- } else if (registrationRequest.getDistrEnvName() == null) {
- Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
- responseWrapper.setInnerElement(missingBodyResponse);
- } else {
- registrationRequestWrapper.setInnerElement(registrationRequest);
- }
- } else {
- Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
- responseWrapper.setInnerElement(missingBodyResponse);
- }
- }
-
- }
-
- private DistributionBusinessLogic getDistributionBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- return webApplicationContext.getBean(DistributionBusinessLogic.class);
- }
-
- private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {
- return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest);
- }
+ private static final Logger log = LoggerFactory.getLogger(DistributionServlet.class);
+ @Resource
+ private DistributionBusinessLogic distributionLogic;
+ @Context
+ private HttpServletRequest request;
+
+ /**
+ *
+ * @param requestId
+ * @param instanceId
+ * @param accept
+ * @param authorization
+ * @return
+ */
+ @GET
+ @Path("/distributionUebCluster")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "UEB Server List", httpMethod = "GET", notes = "return the available UEB Server List",
+ //TODO Tal G fix response headers
+ responseHeaders = {
+ @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class),
+ @ResponseHeader(name = "Content-Length", description = "Length of the response body", response = String.class)})
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", response = ServerListResponse.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its credentials for Basic Authentication - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response getUebServerList(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {
+
+ init(request);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ Response response = null;
+ ResponseFormat responseFormat = null;
+
+ if (instanceId == null) {
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ response = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditMissingInstanceId(AuditingActionEnum.GET_UEB_CLUSTER, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
+ return response;
+ }
+
+ try {
+ Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();
+
+ if (actionResponse.isRight()) {
+ responseFormat = actionResponse.right().value();
+ response = buildErrorResponse(responseFormat);
+ } else {
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ response = buildOkResponse(responseFormat, actionResponse.left().value());
+ }
+
+ getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration");
+ log.debug("failed to get ueb serbver list from cofiguration", e);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ getComponentsUtils().auditGetUebCluster(AuditingActionEnum.GET_UEB_CLUSTER, instanceId, null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
+ response = buildErrorResponse(responseFormat);
+ return response;
+ }
+
+ }
+
+ /**
+ *
+ * @param requestId
+ * @param instanceId
+ * @param accept
+ * @param contenType
+ * @param contenLength
+ * @param authorization
+ * @param requestJson
+ * @return
+ */
+ @POST
+ @Path("/registerForDistribution")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Subscribes for distribution notifications")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "ECOMP component is successfully registered for distribution", response = TopicRegistrationResponse.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 400, message = "Missing Body - POL4500"),
+ @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"),
+ @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - POL4502"),
+ @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")})
+ //TODO Tal G fix response headers and to check missing header validations with Michael L
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})
+ public Response registerForDistribution(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ String requestJson) {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ init(request);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();
+
+ validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);
+
+ if (responseWrapper.isEmpty()) {
+ validateJson(responseWrapper, registrationRequestWrapper, requestJson);
+ }
+ if (responseWrapper.isEmpty()) {
+ validateEnv(responseWrapper, registrationRequestWrapper.getInnerElement().getDistrEnvName());
+ }
+
+ if (responseWrapper.isEmpty()) {
+ distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
+ } else {
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
+ }
+
+ return responseWrapper.getInnerElement();
+ }
+
+ /**
+ * Returns list of valid artifact types for validation done in the distribution client.<br>
+ * The list is the representation of the values of the enum ArtifactTypeEnum.
+ *
+ * @param requestId
+ * @param instanceId
+ * @param authorization
+ * @param accept
+ * @return
+ */
+ @GET
+ @Path("/artifactTypes")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Artifact types list", httpMethod = "GET", notes = "Fetches available artifact types list")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact types list fetched successfully", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( POST,PUT,DELETE will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")})
+ public Response getValidArtifactTypes(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {
+ init(request);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ Response response = null;
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+
+ validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES);
+ if (responseWrapper.isEmpty()) {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ArtifactTypeEnum.values());
+ } else {
+ response = responseWrapper.getInnerElement();
+ }
+ return response;
+ }
+
+ /**
+ * Removes from subscription for distribution notifications
+ *
+ * @param requestId
+ * @param instanceId
+ * @param accept
+ * @param contenType
+ * @param contenLength
+ * @param authorization
+ * @param requestJson
+ * @return
+ */
+ @POST
+ @Path("/unRegisterForDistribution")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Subscription status", httpMethod = "POST", notes = "Removes from subscription for distribution notifications")
+ //TODO Edit the responses
+ @ApiResponses(value = {
+ @ApiResponse(code = 204, message = "ECOMP component is successfully unregistered", response = TopicUnregistrationResponse.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 400, message = "Missing Body - POL4500"),
+ @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'apiPublicKey' - POL4501"),
+ @ApiResponse(code = 400, message = "Invalid Body : missing mandatory parameter 'distrEnvName' - SVC4506"),
+ @ApiResponse(code = 400, message = "Invalid Body : Specified 'distrEnvName' doesn’t exist - POL4137"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used to register for distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component should continue the attempts to register for distribution - POL5000")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.distribution.api.client.RegistrationRequest", paramType = "body", value = "json describe the artifact")})
+ public Response unRegisterForDistribution(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "Length of the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ String requestJson) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ init(request);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();
+
+ validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);
+
+ if (responseWrapper.isEmpty()) {
+ validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);
+ }
+ if (responseWrapper.isEmpty()) {
+ validateEnv(responseWrapper, unRegistrationRequestWrapper.getInnerElement().getDistrEnvName());
+ }
+ if (responseWrapper.isEmpty()) {
+ distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
+ } else {
+ BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
+ }
+
+ return responseWrapper.getInnerElement();
+ }
+
+ private void validateEnv(Wrapper<Response> responseWrapper, String distrEnvName) {
+
+ // DE194021
+ StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable();
+ if (environmentStatus != StorageOperationStatus.OK) {
+ if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) {
+ Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));
+ responseWrapper.setInnerElement(missingHeaderResponse);
+ } else {
+ Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(missingHeaderResponse);
+ }
+ }
+
+ }
+
+ private void init(HttpServletRequest request) {
+ if (distributionLogic == null) {
+ distributionLogic = getDistributionBL(request.getSession().getServletContext());
+ }
+ }
+
+ private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) {
+ if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) {
+ Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));
+ responseWrapper.setInnerElement(missingHeaderResponse);
+ // Audit
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditMissingInstanceId(auditingAction, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
+
+ }
+
+ }
+
+ private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) {
+ if (requestJson == null || requestJson.isEmpty()) {
+ Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
+ responseWrapper.setInnerElement(missingBodyResponse);
+ } else {
+ Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class);
+ if (eitherRegistration.isLeft()) {
+ RegistrationRequest registrationRequest = eitherRegistration.left().value();
+ if (registrationRequest.getApiPublicKey() == null) {
+ Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));
+ responseWrapper.setInnerElement(missingBodyResponse);
+
+ } else if (registrationRequest.getDistrEnvName() == null) {
+ Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
+ responseWrapper.setInnerElement(missingBodyResponse);
+ } else {
+ registrationRequestWrapper.setInnerElement(registrationRequest);
+ }
+ } else {
+ Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
+ responseWrapper.setInnerElement(missingBodyResponse);
+ }
+ }
+
+ }
+
+ private DistributionBusinessLogic getDistributionBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(DistributionBusinessLogic.class);
+ }
+
+ private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {
+ return new AuditHandler(getComponentsUtils(), request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), registrationRequest);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java b/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java
new file mode 100644
index 0000000000..28621bcb41
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.dto;
+
+/**
+ * Created by yavivi on 18/02/2018.
+ */
+public class ExternalRefDTO {
+ private String referenceUUID;
+
+ public ExternalRefDTO(){
+ //Empty constructor for serialization purposes
+ }
+
+ public ExternalRefDTO(String ref){
+ this.referenceUUID = ref;
+ }
+
+ public String getReferenceUUID() {
+ return referenceUUID;
+ }
+
+ public void setReferenceUUID(String referenceUUID) {
+ this.referenceUUID = referenceUUID;
+ }
+
+ @Override
+ public String toString() {
+ return this.referenceUUID;
+ }
+}
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 c88ec87d58..6ffa3a7c34 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
@@ -20,11 +20,7 @@
package org.openecomp.sdc.be.ecomp;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
+import fj.data.Either;
import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
import org.openecomp.portalsdk.core.restful.domain.EcompRole;
@@ -44,343 +40,342 @@ import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
-import fj.data.Either;
+import javax.servlet.http.HttpServletRequest;
+import java.util.LinkedList;
+import java.util.List;
+
-/*
- * PortalAPIException(String message, Throwable cause);
- */
public class EcompIntImpl implements IPortalRestAPIService {
- private static Logger log = LoggerFactory.getLogger(EcompIntImpl.class.getName());
-
- public EcompIntImpl() {
- log.debug("EcompIntImpl Class Instantiated");
- }
-
- @Override
- public void pushUser(EcompUser user) throws PortalAPIException {
- log.debug("Start handle request of ECOMP pushUser");
- try {
- if (user == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Recieved null for argument user", ErrorSeverity.INFO);
- log.debug("Recieved null for argument user");
- throw new PortalAPIException("Recieved null for argument user");
- }
-
- UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
- final String modifierAttId = "jh0003";
- User modifier = new User();
- modifier.setUserId(modifierAttId);
- log.debug("modifier id is {}", modifierAttId);
-
- Either<User, String> newASDCUser = EcompUserConverter.convertEcompUserToUser(user);
- if (newASDCUser.isRight()) {
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO);
- log.debug("Failed to create user {}", user.toString());
- throw new PortalAPIException("Failed to create user " + newASDCUser.right().value());
- } else if (newASDCUser.left().value() == null) {
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO);
- log.debug("Failed to create user {}", user.toString());
- throw new PortalAPIException("Failed to create user " + newASDCUser.right().value());
- }
-
- User convertedAsdcUser = newASDCUser.left().value();
- Either<User, ResponseFormat> createUserResponse = userBusinessLogic.createUser(modifier, convertedAsdcUser);
-
- // ALREADY EXIST ResponseFormat
- final String ALREADY_EXISTS_RESPONSE_ID = "SVC4006";
-
- if (createUserResponse.isRight()) {
- if (!createUserResponse.right().value().getMessageId().equals(ALREADY_EXISTS_RESPONSE_ID)) {
- log.debug("Failed to create user {}", user.toString());
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR);
- throw new PortalAPIException("Failed to create user" + createUserResponse.right());
- }
- log.debug("User already exist {}", user.toString());
- }
- log.debug("User created {}", user.toString());
- } catch (Exception e) {
- log.debug("Failed to create user {}", user, e);
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR);
- throw new PortalAPIException("Failed to create user", e);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- *
- * loginId - equals to userId
- *
- */
- @Override
- public void editUser(String loginId, EcompUser user) throws PortalAPIException {
- log.debug("Start handle request of ECOMP editUser");
-
- try {
- if (user == null) {
- log.debug("Recieved null for argument user");
- BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument user", ErrorSeverity.INFO);
- throw new PortalAPIException("Recieved null for argument user");
- } else if (loginId == null) {
- log.debug("Recieved null for argument loginId");
- BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument loginId", ErrorSeverity.INFO);
- throw new PortalAPIException("Recieved null for argument loginId");
- }
-
- UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
- if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) {
- log.debug("loginId and user loginId not equal");
- BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "loginId and user loginId not equal", ErrorSeverity.INFO);
- throw new PortalAPIException("loginId not equals to the user loginId field");
- } else if (user.getLoginId() == null) {
- user.setLoginId(loginId);
- }
-
- Either<User, String> asdcUser = EcompUserConverter.convertEcompUserToUser(user);
- if (asdcUser.isRight()) {
- log.debug("Failed to convert user");
- BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to convert user", ErrorSeverity.INFO);
- throw new PortalAPIException(asdcUser.right().value());
- } else if (asdcUser.left().value() == null) {
- log.debug("NULL pointer returned from user converter");
- BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "NULL pointer returned from user converter", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to edit user");
- }
-
- Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser.left().value());
-
- if (updateUserCredentialsResponse.isRight()) {
- log.debug("Failed to updateUserCredentials");
- BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to updateUserCredentials", ErrorSeverity.ERROR);
- throw new PortalAPIException("Failed to edit user" + updateUserCredentialsResponse.right().value());
- }
- } catch (Exception e) {
- log.debug("Failed to updateUserCredentials");
- throw new PortalAPIException("Failed to edit user", e);
- }
-
- }
-
- @Override
- public EcompUser getUser(String loginId) throws PortalAPIException {
- log.debug("Start handle request of ECOMP getUser");
-
- try {
-
- if (loginId == null) {
- log.debug("Recieved null for argument loginId");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Recieved null for argument loginId", ErrorSeverity.INFO);
- throw new PortalAPIException("Recieved null for argument loginId");
- }
-
- UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
- Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false);
-
- if (getUserResponse.isRight()) {
- log.debug("Failed to get User");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get User" + getUserResponse.right());
- } else {
- if (getUserResponse.left().value() != null) {
- Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value());
- if (ecompUser.isLeft() && ecompUser.left().value() != null) {
- return ecompUser.left().value();
- } else {
- log.debug("Failed to get User");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO);
- throw new PortalAPIException(ecompUser.right().value());
- }
- } else {
- log.debug("Failed to get User");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get User" + getUserResponse.right());
- }
- }
- } catch (Exception e) {
- log.debug("Failed to get User");
- throw new PortalAPIException("Failed to get User", e);
- }
- }
-
- @Override
- public List<EcompUser> getUsers() throws PortalAPIException {
- log.debug("Start handle request of ECOMP getUsers");
-
- try {
- UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
- final String modifierAttId = "jh0003";
-
- Either<List<User>, ResponseFormat> getUsersResponse = userBusinessLogic.getUsersList(modifierAttId, null, null);
-
- if (getUsersResponse.isRight()) {
- log.debug("Failed to get Users");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get Users" + getUsersResponse.right());
- } else {
- if (getUsersResponse.left().value() != null) {
- List<EcompUser> ecompUserList = new LinkedList<>();
- for (User user : getUsersResponse.left().value()) {
- Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(user);
- if (ecompUser.isRight()) {
- log.debug("Failed to convert User {}", user);
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING);
- continue;
- } else if (ecompUser.left().value() == null) {
- log.debug("Failed to convert User {}", user);
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING);
- continue;
- }
- ecompUserList.add(ecompUser.left().value());
- }
- return ecompUserList;
- } else {
- log.debug("Failed to get users");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get Users" + getUsersResponse.right());
- }
- }
- } catch (Exception e) {
- log.debug("Failed to get users");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get Users", e);
- }
- }
-
- @Override
- public List<EcompRole> getAvailableRoles() throws PortalAPIException {
- log.debug("Start handle request of ECOMP getAvailableRoles");
- try {
- List<EcompRole> ecompRolesList = new LinkedList<>();
- for (Role role : Role.values()) {
- EcompRole ecompRole = new EcompRole();
- ecompRole.setId(new Long(role.ordinal()));
- ecompRole.setName(role.name());
- ecompRolesList.add(ecompRole);
- }
-
- if (ecompRolesList.isEmpty()) {
- throw new PortalAPIException();
- }
-
- return ecompRolesList;
- } catch (Exception e) {
- log.debug("Failed to fetch roles");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", "Failed to fetch roles", ErrorSeverity.INFO);
- throw new PortalAPIException("Roles fetching failed", e);
- }
-
- }
-
- /**
- * The user role updated through this method only
- */
- @Override
- public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
- log.debug("Start handle request of ECOMP pushUserRole");
-
- final String modifierAttId = "jh0003";
- User modifier = new User();
- modifier.setUserId(modifierAttId);
- log.debug("modifier id is {}", modifierAttId);
-
- UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
- String updatedRole = null;
-
- if (roles == null) {
- throw new PortalAPIException("Error: Recieved null for roles");
- } else if (roles.iterator().hasNext()) {
- EcompRole ecompRole = roles.iterator().next();
- updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole);
- log.debug("pushing role: {} to user: {}", updatedRole, loginId);
- Either<User, ResponseFormat> updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole);
- if (updateUserRoleResponse.isRight()) {
- log.debug("Error: Failed to update role");
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString());
- }
- } else {
- log.debug("Error: No roles in List");
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO);
- //throw new PortalAPIException("Error: No roles in List");
- //in this cases we want to deactivate the user
- Either<User, ResponseFormat> deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId);
- if (deActivateUserResponse.isRight()) {
- log.debug("Error: Failed to deactivate user {}",loginId);
- BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO);
- throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage());
- }
- }
- }
-
- @Override
- public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
- try {
- log.debug("Start handle request of ECOMP getUserRoles");
-
- UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
- Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false);
-
- if (getUserResponse.isRight()) {
- log.debug("Error: Failed to get Roles");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get Roles" + getUserResponse.right());
- } else {
- if (getUserResponse.left().value() != null) {
- Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value());
- if (ecompUser.isRight()) {
- log.debug("Error: Failed to convert Roles");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR);
- throw new PortalAPIException(ecompUser.right().value());
- } else if (ecompUser.left().value() == null) {
- log.debug("Error: Failed to convert Roles");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR);
- throw new PortalAPIException();
- }
-
- return new LinkedList<>(ecompUser.left().value().getRoles());
- } else {
- log.debug("Error: Failed to get Roles");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.ERROR);
- throw new PortalAPIException("Failed to get Roles" + getUserResponse.right());
- }
- }
- } catch (Exception e) {
- log.debug("Error: Failed to get Roles");
- BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO);
- throw new PortalAPIException("Failed to get Roles", e);
- }
- }
-
- @Override
- public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
- // TODO Validation should be changed completely
- final String USERNAME = request.getHeader("username");
- final String PASSWORD = request.getHeader("password");
-
- if (USERNAME != null && PASSWORD != null) {
- if (!USERNAME.equals("") && !PASSWORD.equals("")) {
- log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD);
- return true;
- }
- }
-
- log.debug("User authentication failed");
- return false;
- }
-
- private UserBusinessLogic getUserBusinessLogic() {
- ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
- UserBusinessLogic userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic");
- return userBusinessLogic;
- }
-
- /**
+ private static final Logger log = LoggerFactory.getLogger(EcompIntImpl.class);
+
+ public EcompIntImpl() {
+ log.debug("EcompIntImpl Class Instantiated");
+ }
+
+ @Override
+ public void pushUser(EcompUser user) throws PortalAPIException {
+ log.debug("Start handle request of ECOMP pushUser");
+ try {
+ if (user == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Recieved null for argument user", ErrorSeverity.INFO);
+ log.debug("Recieved null for argument user");
+ throw new PortalAPIException("Recieved null for argument user");
+ }
+
+ UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
+
+ final String modifierAttId = "jh0003";
+ User modifier = new User();
+ modifier.setUserId(modifierAttId);
+ log.debug("modifier id is {}", modifierAttId);
+
+ Either<User, String> newASDCUser = EcompUserConverter.convertEcompUserToUser(user);
+ if (newASDCUser.isRight()) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to convert user", ErrorSeverity.INFO);
+ log.debug("Failed to create user {}", user);
+ throw new PortalAPIException("Failed to create user " + newASDCUser.right().value());
+ } else if (newASDCUser.left().value() == null) {
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "NULL pointer returned from user converter", ErrorSeverity.INFO);
+ log.debug("Failed to create user {}", user);
+ throw new PortalAPIException("Failed to create user " + newASDCUser.right().value());
+ }
+
+ User convertedAsdcUser = newASDCUser.left().value();
+ Either<User, ResponseFormat> createUserResponse = userBusinessLogic.createUser(modifier, convertedAsdcUser);
+
+ // ALREADY EXIST ResponseFormat
+ final String ALREADY_EXISTS_RESPONSE_ID = "SVC4006";
+
+ if (createUserResponse.isRight()) {
+ if (!createUserResponse.right().value().getMessageId().equals(ALREADY_EXISTS_RESPONSE_ID)) {
+ log.debug("Failed to create user {}", user);
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR);
+ throw new PortalAPIException("Failed to create user" + createUserResponse.right());
+ }
+ log.debug("User already exist {}", user);
+ }
+ log.debug("User created {}", user);
+ } catch (Exception e) {
+ log.debug("Failed to create user {}", user, e);
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUser", "Failed to create user", ErrorSeverity.ERROR);
+ throw new PortalAPIException("Failed to create user", e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ *
+ * loginId - equals to userId
+ *
+ */
+ @Override
+ public void editUser(String loginId, EcompUser user) throws PortalAPIException {
+ log.debug("Start handle request of ECOMP editUser");
+
+ try {
+ if (user == null) {
+ log.debug("Recieved null for argument user");
+ BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument user", ErrorSeverity.INFO);
+ throw new PortalAPIException("Recieved null for argument user");
+ } else if (loginId == null) {
+ log.debug("Recieved null for argument loginId");
+ BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Recieved null for argument loginId", ErrorSeverity.INFO);
+ throw new PortalAPIException("Recieved null for argument loginId");
+ }
+
+ UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
+
+ if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) {
+ log.debug("loginId and user loginId not equal");
+ BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "loginId and user loginId not equal", ErrorSeverity.INFO);
+ throw new PortalAPIException("loginId not equals to the user loginId field");
+ } else if (user.getLoginId() == null) {
+ user.setLoginId(loginId);
+ }
+
+ Either<User, String> asdcUser = EcompUserConverter.convertEcompUserToUser(user);
+ if (asdcUser.isRight()) {
+ log.debug("Failed to convert user");
+ BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to convert user", ErrorSeverity.INFO);
+ throw new PortalAPIException(asdcUser.right().value());
+ } else if (asdcUser.left().value() == null) {
+ log.debug("NULL pointer returned from user converter");
+ BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "NULL pointer returned from user converter", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to edit user");
+ }
+
+ Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser.left().value());
+
+ if (updateUserCredentialsResponse.isRight()) {
+ log.debug("Failed to updateUserCredentials");
+ BeEcompErrorManager.getInstance().logInvalidInputError("EditUser", "Failed to updateUserCredentials", ErrorSeverity.ERROR);
+ throw new PortalAPIException("Failed to edit user" + updateUserCredentialsResponse.right().value());
+ }
+ } catch (Exception e) {
+ log.debug("Failed to updateUserCredentials");
+ throw new PortalAPIException("Failed to edit user", e);
+ }
+
+ }
+
+ @Override
+ public EcompUser getUser(String loginId) throws PortalAPIException {
+ log.debug("Start handle request of ECOMP getUser");
+
+ try {
+
+ if (loginId == null) {
+ log.debug("Recieved null for argument loginId");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Recieved null for argument loginId", ErrorSeverity.INFO);
+ throw new PortalAPIException("Recieved null for argument loginId");
+ }
+
+ UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
+
+ Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false);
+
+ if (getUserResponse.isRight()) {
+ log.debug("Failed to get User");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get User" + getUserResponse.right());
+ } else {
+ if (getUserResponse.left().value() != null) {
+ Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value());
+ if (ecompUser.isLeft() && ecompUser.left().value() != null) {
+ return ecompUser.left().value();
+ } else {
+ log.debug("Failed to get User");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO);
+ throw new PortalAPIException(ecompUser.right().value());
+ }
+ } else {
+ log.debug("Failed to get User");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUser", "Failed to get User", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get User" + getUserResponse.right());
+ }
+ }
+ } catch (Exception e) {
+ log.debug("Failed to get User");
+ throw new PortalAPIException("Failed to get User", e);
+ }
+ }
+
+ @Override
+ public List<EcompUser> getUsers() throws PortalAPIException {
+ log.debug("Start handle request of ECOMP getUsers");
+
+ try {
+ UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
+
+ final String modifierAttId = "jh0003";
+
+ Either<List<User>, ResponseFormat> getUsersResponse = userBusinessLogic.getUsersList(modifierAttId, null, null);
+
+ if (getUsersResponse.isRight()) {
+ log.debug("Failed to get Users");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get Users" + getUsersResponse.right());
+ } else {
+ if (getUsersResponse.left().value() != null) {
+ List<EcompUser> ecompUserList = new LinkedList<>();
+ for (User user : getUsersResponse.left().value()) {
+ Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(user);
+ if (ecompUser.isRight()) {
+ log.debug("Failed to convert User {}", user);
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING);
+ continue;
+ } else if (ecompUser.left().value() == null) {
+ log.debug("Failed to convert User {}", user);
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to convert User" + user.toString(), ErrorSeverity.WARNING);
+ continue;
+ }
+ ecompUserList.add(ecompUser.left().value());
+ }
+ return ecompUserList;
+ } else {
+ log.debug("Failed to get users");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get Users" + getUsersResponse.right());
+ }
+ }
+ } catch (Exception e) {
+ log.debug("Failed to get users");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUsers", "Failed to get users", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get Users", e);
+ }
+ }
+
+ @Override
+ public List<EcompRole> getAvailableRoles() throws PortalAPIException {
+ log.debug("Start handle request of ECOMP getAvailableRoles");
+ try {
+ List<EcompRole> ecompRolesList = new LinkedList<>();
+ for (Role role : Role.values()) {
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(new Long(role.ordinal()));
+ ecompRole.setName(role.name());
+ ecompRolesList.add(ecompRole);
+ }
+
+ if (ecompRolesList.isEmpty()) {
+ throw new PortalAPIException();
+ }
+
+ return ecompRolesList;
+ } catch (Exception e) {
+ log.debug("Failed to fetch roles");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", "Failed to fetch roles", ErrorSeverity.INFO);
+ throw new PortalAPIException("Roles fetching failed", e);
+ }
+
+ }
+
+ /**
+ * The user role updated through this method only
+ */
+ @Override
+ public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
+ log.debug("Start handle request of ECOMP pushUserRole");
+
+ final String modifierAttId = "jh0003";
+ User modifier = new User();
+ modifier.setUserId(modifierAttId);
+ log.debug("modifier id is {}", modifierAttId);
+
+ UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
+
+ String updatedRole = null;
+
+ if (roles == null) {
+ throw new PortalAPIException("Error: Recieved null for roles");
+ } else if (roles.iterator().hasNext()) {
+ EcompRole ecompRole = roles.iterator().next();
+ updatedRole = EcompRoleConverter.convertEcompRoleToRole(ecompRole);
+ log.debug("pushing role: {} to user: {}", updatedRole, loginId);
+ Either<User, ResponseFormat> updateUserRoleResponse = userBusinessLogic.updateUserRole(modifier, loginId, updatedRole);
+ if (updateUserRoleResponse.isRight()) {
+ log.debug("Error: Failed to update role");
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to update role", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to update role" + updateUserRoleResponse.right().value().toString());
+ }
+ } else {
+ log.debug("Error: No roles in List");
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to fetch roles", ErrorSeverity.INFO);
+ //in this cases we want to deactivate the user
+ Either<User, ResponseFormat> deActivateUserResponse = userBusinessLogic.deActivateUser(modifier, loginId);
+ if (deActivateUserResponse.isRight()) {
+ log.debug("Error: Failed to deactivate user {}",loginId);
+ BeEcompErrorManager.getInstance().logInvalidInputError("PushUserRole", "Failed to deactivate user", ErrorSeverity.INFO);
+ throw new PortalAPIException(deActivateUserResponse.right().value().getFormattedMessage());
+ }
+ }
+ }
+
+ @Override
+ public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
+ try {
+ log.debug("Start handle request of ECOMP getUserRoles");
+
+ UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
+
+ Either<User, ActionStatus> getUserResponse = userBusinessLogic.getUser(loginId, false);
+
+ if (getUserResponse.isRight()) {
+ log.debug("Error: Failed to get Roles");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get Roles" + getUserResponse.right());
+ } else {
+ if (getUserResponse.left().value() != null) {
+ Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(getUserResponse.left().value());
+ if (ecompUser.isRight()) {
+ log.debug("Error: Failed to convert Roles");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR);
+ throw new PortalAPIException(ecompUser.right().value());
+ } else if (ecompUser.left().value() == null) {
+ log.debug("Error: Failed to convert Roles");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to convert Roles", ErrorSeverity.ERROR);
+ throw new PortalAPIException();
+ }
+
+ return new LinkedList<>(ecompUser.left().value().getRoles());
+ } else {
+ log.debug("Error: Failed to get Roles");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.ERROR);
+ throw new PortalAPIException("Failed to get Roles" + getUserResponse.right());
+ }
+ }
+ } catch (Exception e) {
+ log.debug("Error: Failed to get Roles");
+ BeEcompErrorManager.getInstance().logInvalidInputError("GetUserRoles", "Failed to get Roles", ErrorSeverity.INFO);
+ throw new PortalAPIException("Failed to get Roles", e);
+ }
+ }
+
+ @Override
+ public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
+ // TODO Validation should be changed completely
+ final String USERNAME = request.getHeader("username");
+ final String PASSWORD = request.getHeader("password");
+
+ if (USERNAME != null && PASSWORD != null) {
+ if (!USERNAME.equals("") && !PASSWORD.equals("")) {
+ log.debug("User authenticated - Username: ,Password: {}", USERNAME, PASSWORD);
+ return true;
+ }
+ }
+
+ log.debug("User authentication failed");
+ return false;
+ }
+
+ private UserBusinessLogic getUserBusinessLogic() {
+ ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
+ 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
@@ -399,8 +394,8 @@ public class EcompIntImpl implements IPortalRestAPIService {
* @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);
- }
+ @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
index 93de8fed2c..b02a4a52cd 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java
@@ -20,30 +20,15 @@
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 fj.data.Either;
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.externalapi.servlet.representation.*;
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.*;
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;
@@ -52,341 +37,339 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
@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<List<? extends AssetMetadata>, ResponseFormat> convertToAssetMetadata(List<? extends Component> componentList, String serverBaseURL, boolean detailed) {
- if (componentList == null || componentList.isEmpty()) {
- return Either.left(new LinkedList<>());
- }
- List<AssetMetadata> retResList = new LinkedList<>();
-
- for (Component curr : componentList) {
- Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed);
- if (resMetaData.isRight()) {
- return Either.right(resMetaData.right().value());
- }
- retResList.add(resMetaData.left().value());
- }
-
- return Either.left(retResList);
-
- }
-
- public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) {
- ComponentTypeEnum componentType = component.getComponentType();
- Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component);
-
- if (resMetaData.isRight()) {
- return Either.right(resMetaData.right().value());
- }
- else{
- return Either.left(resMetaData.left().value());
- }
-
- }
-
- private Either<? extends AssetMetadata, ResponseFormat> 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<ProductAssetMetadata> 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<? extends AssetMetadata, ResponseFormat> 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<ResourceAssetDetailedMetadata, StorageOperationStatus> 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<? extends AssetMetadata, ResponseFormat> generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) {
- AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType());
-
- metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed);
-
- if (detailed) {
- Either<ServiceAssetDetailedMetadata, StorageOperationStatus> 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 extends AssetMetadata, T extends Component> 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 extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) {
- assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed);
- if(resource.getCategories() != null && !resource.getCategories().isEmpty()){
- CategoryDefinition categoryDefinition = resource.getCategories().get(0);
- assetToPopulate.setCategory(categoryDefinition.getName());
- assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName());
- }
- assetToPopulate.setResourceType(resource.getResourceType().name());
- assetToPopulate.setLifecycleState(resource.getLifecycleState().name());
- assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId());
-
- return (T) assetToPopulate;
- }
-
- private <T extends ServiceAssetMetadata> T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) {
- assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed);
-
- if(service.getCategories() != null && !service.getCategories().isEmpty()){
- CategoryDefinition categoryDefinition = service.getCategories().get(0);
- assetToPopulate.setCategory(categoryDefinition.getName());
- }
-
- assetToPopulate.setLifecycleState(service.getLifecycleState().name());
- assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId());
- assetToPopulate.setDistributionStatus(service.getDistributionStatus().name());
-
- return (T) assetToPopulate;
- }
-
- private <T extends ResourceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) {
-
- List<ComponentInstance> componentInstances = resource.getComponentInstances();
-
- if (componentInstances != null) {
- Either<List<ResourceInstanceMetadata>, 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<String, ArtifactDefinition> 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 <T extends ServiceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) {
-
- List<ComponentInstance> componentInstances = service.getComponentInstances();
-
- if (componentInstances != null) {
- Either<List<ResourceInstanceMetadata>, 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<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts();
- assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts);
-
- assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName());
-
- return Either.left(assetToPopulate);
- }
-
- private <T extends ResourceAssetDetailedMetadata> T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map<String, ArtifactDefinition> artifacts) {
-
- List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(resource, artifacts);
-
- asset.setArtifacts(artifactMetaList);
-
- return asset;
- }
-
- private <T extends ServiceAssetDetailedMetadata> T populateServiceWithArtifacts(T asset, Service service, Map<String, ArtifactDefinition> artifacts) {
-
- List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(service, artifacts);
-
- asset.setArtifacts(artifactMetaList);
-
- return asset;
- }
-
- private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) {
- List<ArtifactMetadata> artifactMetaList = new LinkedList<>();
- if (artifacts != null) {
- Collection<ArtifactDefinition> 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<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(List<ComponentInstance> componentInstances, String componentType, String componentUUID) {
- List<ResourceInstanceMetadata> retList = new LinkedList<>();
- Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
-
- for (ComponentInstance componentInstance : componentInstances) {
- ResourceInstanceMetadata metadata = new ResourceInstanceMetadata();
- String componentUid = componentInstance.getComponentUid();
- String invariantUUID, resourceUUID;
-
- if (!uuidDuplicatesMap.containsKey(componentUid)) {
- Either<Resource, StorageOperationStatus> 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<String, String> 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<ArtifactMetadata> artifactMetaList = new LinkedList<>();
- Collection<ArtifactDefinition> 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<CategoryDefinition> categories = product.getCategories(); List<ProductCategoryGroupMetadata> categoryMetadataList = new LinkedList<>();
- *
- * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List<SubCategoryDefinition> subcategories =
- * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List<GroupDefinition> groups = product.getGroups(); for (GroupDefinition
- * groupDefinition : groups) { String groupName = groupDefinition.getName(); categoryMetadataList.add(new ProductCategoryGroupMetadata(categoryName, subCategoryName, groupName)); } } } retProdAsset.setProductGroupings(categoryMetadataList);
- * return retProdAsset; } }
- */
+ private static final Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class);
+
+ @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<List<? extends AssetMetadata>, ResponseFormat> convertToAssetMetadata(List<? extends Component> componentList, String serverBaseURL, boolean detailed) {
+ if (componentList == null || componentList.isEmpty()) {
+ return Either.left(new LinkedList<>());
+ }
+ List<AssetMetadata> retResList = new LinkedList<>();
+
+ for (Component curr : componentList) {
+ Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed);
+ if (resMetaData.isRight()) {
+ return Either.right(resMetaData.right().value());
+ }
+ retResList.add(resMetaData.left().value());
+ }
+
+ return Either.left(retResList);
+
+ }
+
+ public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) {
+ ComponentTypeEnum componentType = component.getComponentType();
+ Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component);
+
+ if (resMetaData.isRight()) {
+ return Either.right(resMetaData.right().value());
+ }
+ else{
+ return Either.left(resMetaData.left().value());
+ }
+
+ }
+
+ private Either<? extends AssetMetadata, ResponseFormat> 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<ProductAssetMetadata> 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<? extends AssetMetadata, ResponseFormat> 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<ResourceAssetDetailedMetadata, StorageOperationStatus> 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<? extends AssetMetadata, ResponseFormat> generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) {
+ AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType());
+
+ metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed);
+
+ if (detailed) {
+ Either<ServiceAssetDetailedMetadata, StorageOperationStatus> 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 extends AssetMetadata, T extends Component> 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 extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) {
+ assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed);
+ if(resource.getCategories() != null && !resource.getCategories().isEmpty()){
+ CategoryDefinition categoryDefinition = resource.getCategories().get(0);
+ assetToPopulate.setCategory(categoryDefinition.getName());
+ assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName());
+ }
+ assetToPopulate.setResourceType(resource.getResourceType().name());
+ assetToPopulate.setLifecycleState(resource.getLifecycleState().name());
+ assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId());
+
+ return (T) assetToPopulate;
+ }
+
+ private <T extends ServiceAssetMetadata> T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) {
+ assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed);
+
+ if(service.getCategories() != null && !service.getCategories().isEmpty()){
+ CategoryDefinition categoryDefinition = service.getCategories().get(0);
+ assetToPopulate.setCategory(categoryDefinition.getName());
+ }
+
+ assetToPopulate.setLifecycleState(service.getLifecycleState().name());
+ assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId());
+ assetToPopulate.setDistributionStatus(service.getDistributionStatus().name());
+
+ return (T) assetToPopulate;
+ }
+
+ private <T extends ResourceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) {
+
+ List<ComponentInstance> componentInstances = resource.getComponentInstances();
+
+ if (componentInstances != null) {
+ Either<List<ResourceInstanceMetadata>, 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<String, ArtifactDefinition> 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 <T extends ServiceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToServiceDetailedMetadata(T assetToPopulate, Service service, String serverBaseURL) {
+
+ List<ComponentInstance> componentInstances = service.getComponentInstances();
+
+ if (componentInstances != null) {
+ Either<List<ResourceInstanceMetadata>, 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<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts();
+ assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts);
+
+ assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName());
+
+ return Either.left(assetToPopulate);
+ }
+
+ private <T extends ResourceAssetDetailedMetadata> T populateResourceWithArtifacts(T asset, Resource resource, String serverBaseURL, Map<String, ArtifactDefinition> artifacts) {
+
+ List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(resource, artifacts);
+
+ asset.setArtifacts(artifactMetaList);
+
+ return asset;
+ }
+
+ private <T extends ServiceAssetDetailedMetadata> T populateServiceWithArtifacts(T asset, Service service, Map<String, ArtifactDefinition> artifacts) {
+
+ List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(service, artifacts);
+
+ asset.setArtifacts(artifactMetaList);
+
+ return asset;
+ }
+
+ private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) {
+ List<ArtifactMetadata> artifactMetaList = new LinkedList<>();
+ if (artifacts != null) {
+ Collection<ArtifactDefinition> 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) {
+ final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
+
+ 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<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(List<ComponentInstance> componentInstances, String componentType, String componentUUID) {
+ List<ResourceInstanceMetadata> retList = new LinkedList<>();
+ Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
+
+ for (ComponentInstance componentInstance : componentInstances) {
+ ResourceInstanceMetadata metadata = new ResourceInstanceMetadata();
+ String componentUid = componentInstance.getComponentUid();
+ String invariantUUID, resourceUUID;
+
+ if (!uuidDuplicatesMap.containsKey(componentUid)) {
+ Either<Resource, StorageOperationStatus> 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<String, String> 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<ArtifactMetadata> artifactMetaList = new LinkedList<>();
+ Collection<ArtifactDefinition> 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<CategoryDefinition> categories = product.getCategories(); List<ProductCategoryGroupMetadata> categoryMetadataList = new LinkedList<>();
+ *
+ * if (categories == null || categories.isEmpty()) { return retProdAsset; } else { for (CategoryDefinition categoryDefinition : categories) { String categoryName = categoryDefinition.getName(); List<SubCategoryDefinition> subcategories =
+ * categoryDefinition.getSubcategories(); for (SubCategoryDefinition subCategoryDefinition : subcategories) { String subCategoryName = subCategoryDefinition.getName(); List<GroupDefinition> 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/ecomp/converters/EcompRoleConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
index 4ee3605703..6b0c85bb3e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
@@ -27,26 +27,26 @@ import org.slf4j.LoggerFactory;
public final class EcompRoleConverter {
- private static Logger log = LoggerFactory.getLogger(EcompRoleConverter.class.getName());
-
- private EcompRoleConverter() {
- }
-
- // TODO Add Either or Exception in case of convertation failure
- public static String convertEcompRoleToRole(EcompRole ecompRole) {
-
- log.debug("converting role");
- if (ecompRole == null) {
- log.debug("recieved null for roles");
- return null;
- }
-
- for (Role role : Role.values()) {
- if (role.ordinal() == ecompRole.getId()) {
- return role.name();
- }
- }
- log.debug("no roles converted");
- return null;
- }
+ private static final Logger log = LoggerFactory.getLogger(EcompRoleConverter.class);
+
+ private EcompRoleConverter() {
+ }
+
+ // TODO Add Either or Exception in case of convertation failure
+ public static String convertEcompRoleToRole(EcompRole ecompRole) {
+
+ log.debug("converting role");
+ if (ecompRole == null) {
+ log.debug("recieved null for roles");
+ return null;
+ }
+
+ for (Role role : Role.values()) {
+ if (role.ordinal() == ecompRole.getId()) {
+ return role.name();
+ }
+ }
+ log.debug("no roles converted");
+ return null;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
index 19ef31feaf..590be72f1f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
@@ -20,91 +20,90 @@
package org.openecomp.sdc.be.ecomp.converters;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
+import fj.data.Either;
import org.openecomp.portalsdk.core.restful.domain.EcompRole;
import org.openecomp.portalsdk.core.restful.domain.EcompUser;
import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
-import fj.data.Either;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
public final class EcompUserConverter {
- private EcompUserConverter() {
- }
-
- public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) {
- EcompUser convertedUser = new EcompUser();
-
- if (asdcUser == null) {
- return Either.right("User is null");
- }
-
- convertedUser.setFirstName(asdcUser.getFirstName());
- convertedUser.setLastName(asdcUser.getLastName());
- convertedUser.setLoginId(asdcUser.getUserId());
- convertedUser.setOrgUserId(asdcUser.getUserId());
- convertedUser.setEmail(asdcUser.getEmail());
-
- if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) {
- convertedUser.setActive(true);
- } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) {
- convertedUser.setActive(false);
- }
-
- EcompRole convertedRole = new EcompRole();
- for (Role role : Role.values()) {
- if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) {
- convertedRole.setName(role.name());
- convertedRole.setId(new Long(role.ordinal()));
- break;
- }
- }
-
- Set<EcompRole> convertedRoleSet = new HashSet<>();
- convertedRoleSet.add(convertedRole);
- convertedUser.setRoles(convertedRoleSet);
-
- return Either.left(convertedUser);
- }
-
- public static Either<User, String> convertEcompUserToUser(EcompUser ecompUser) {
- User convertedUser = new User();
-
- if (ecompUser == null) {
- return Either.right("EcompUser is null");
- }
-
- convertedUser.setFirstName(ecompUser.getFirstName());
- convertedUser.setLastName(ecompUser.getLastName());
-
- if (!ecompUser.getLoginId().isEmpty()) {
- convertedUser.setUserId(ecompUser.getLoginId());
- } else {
- convertedUser.setUserId(ecompUser.getOrgUserId());
- }
-
- convertedUser.setEmail(ecompUser.getEmail());
-
- if (ecompUser.getRoles() != null) {
- Iterator<EcompRole> iter = ecompUser.getRoles().iterator();
-
- if (iter.hasNext()) {
- String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next());
- convertedUser.setRole(updatedRole);
- }
- }
-
- if (ecompUser.isActive()) {
- convertedUser.setStatus(UserStatusEnum.ACTIVE);
- } else {
- convertedUser.setStatus(UserStatusEnum.INACTIVE);
- }
-
- return Either.left(convertedUser);
- }
+ private EcompUserConverter() {
+ }
+
+ public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) {
+ EcompUser convertedUser = new EcompUser();
+
+ if (asdcUser == null) {
+ return Either.right("User is null");
+ }
+
+ convertedUser.setFirstName(asdcUser.getFirstName());
+ convertedUser.setLastName(asdcUser.getLastName());
+ convertedUser.setLoginId(asdcUser.getUserId());
+ convertedUser.setOrgUserId(asdcUser.getUserId());
+ convertedUser.setEmail(asdcUser.getEmail());
+
+ if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) {
+ convertedUser.setActive(true);
+ } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) {
+ convertedUser.setActive(false);
+ }
+
+ EcompRole convertedRole = new EcompRole();
+ for (Role role : Role.values()) {
+ if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) {
+ convertedRole.setName(role.name());
+ convertedRole.setId(new Long(role.ordinal()));
+ break;
+ }
+ }
+
+ Set<EcompRole> convertedRoleSet = new HashSet<>();
+ convertedRoleSet.add(convertedRole);
+ convertedUser.setRoles(convertedRoleSet);
+
+ return Either.left(convertedUser);
+ }
+
+ public static Either<User, String> convertEcompUserToUser(EcompUser ecompUser) {
+ User convertedUser = new User();
+
+ if (ecompUser == null) {
+ return Either.right("EcompUser is null");
+ }
+
+ convertedUser.setFirstName(ecompUser.getFirstName());
+ convertedUser.setLastName(ecompUser.getLastName());
+
+ if (!ecompUser.getLoginId().isEmpty()) {
+ convertedUser.setUserId(ecompUser.getLoginId());
+ } else {
+ convertedUser.setUserId(ecompUser.getOrgUserId());
+ }
+
+ convertedUser.setEmail(ecompUser.getEmail());
+
+ if (ecompUser.getRoles() != null) {
+ Iterator<EcompRole> iter = ecompUser.getRoles().iterator();
+
+ if (iter.hasNext()) {
+ String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next());
+ convertedUser.setRole(updatedRole);
+ }
+ }
+
+ if (ecompUser.isActive()) {
+ convertedUser.setStatus(UserStatusEnum.ACTIVE);
+ } else {
+ convertedUser.setStatus(UserStatusEnum.INACTIVE);
+ }
+
+ return Either.left(convertedUser);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
index 1408459470..70225c0dd2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
@@ -20,26 +20,15 @@
package org.openecomp.sdc.be.externalapi.servlet;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -56,16 +45,24 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.Map;
/**
* This Servlet serves external users operations on artifacts.
*
@@ -78,740 +75,740 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class ArtifactExternalServlet extends AbstractValidationsServlet {
- @Context
- private HttpServletRequest request;
+ @Context
+ private HttpServletRequest request;
+
+ private static final Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class);
+
+ private static String startLog = "Start handle request of ";
+
+ /**
+ * Uploads an artifact to resource or service
+ *
+ * @param contenType
+ * @param checksum
+ * @param userId
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param assetType
+ * @param uuid
+ * @param data
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/artifacts")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
+ @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
+ @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
+ @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
+ @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
+ @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+ @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
+ public Response uploadArtifact(
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ String data) {
+
+ init(log);
- private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName());
-
- private static String startLog = "Start handle request of ";
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- /**
- * Uploads an artifact to resource or service
- *
- * @param contenType
- * @param checksum
- * @param userId
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param assetType
- * @param uuid
- * @param data
- * @return
- */
- @POST
- @Path("/{assetType}/{uuid}/artifacts")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
- @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
- @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
- @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
- @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
- @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
- @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")
- public Response uploadArtifact(
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- String data) {
-
- init(log);
-
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
- if (componentType == null) {
- log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- if (responseWrapper.isEmpty()) {
- validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
- }
- if (responseWrapper.isEmpty() ) {
- validateHttpCspUserIdHeader(userId, responseWrapper);
- }
- Response response = null;
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,
- additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create));
- if (uploadArtifactEither.isRight()) {
- log.debug("failed to upload artifact");
- responseWrapper.setInnerElement(uploadArtifactEither.right().value());
- } else {
- Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
- }
- }
- if( response == null ){
- response = buildErrorResponse(responseWrapper.getInnerElement());
- }
- return response;
- } catch (Exception e) {
- final String message = "failed to upload artifact to a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- } finally {
- getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams);
- }
- }
+ if (componentType == null) {
+ log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
+ }
+ if (responseWrapper.isEmpty() ) {
+ validateHttpCspUserIdHeader(userId, responseWrapper);
+ }
+ Response response = null;
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
+ if (uploadArtifactEither.isRight()) {
+ log.debug("failed to upload artifact");
+ responseWrapper.setInnerElement(uploadArtifactEither.right().value());
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
+ }
+ }
+ if( response == null ){
+ response = buildErrorResponse(responseWrapper.getInnerElement());
+ }
+ return response;
+ } catch (Exception e) {
+ final String message = "failed to upload artifact to a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } finally {
+ getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams);
+ }
+ }
- /**
- * Uploads an artifact to resource instance
- *
- * @param assetType
- * @param uuid
- * @param resourceInstanceName
- * @return
- */
- @POST
- @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
- @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
- @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
- @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
- @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
- @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
- @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")
- public Response uploadArtifactToInstance(
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
- String data) {
+ /**
+ * Uploads an artifact to resource instance
+ *
+ * @param assetType
+ * @param uuid
+ * @param resourceInstanceName
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
+ @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
+ @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
+ @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
+ @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
+ @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+ @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
+ public Response uploadArtifactToInstance(
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
+ String data) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- if (componentType == null) {
- log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("uploadArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
- additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create));
- if (uploadArtifactEither.isRight()) {
- log.debug("failed to upload artifact");
- responseFormat = uploadArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
- }
- }
- }catch (Exception e) {
- final String message = "failed to upload artifact to a resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ if (componentType == null) {
+ log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
+ log.debug("uploadArtifact: Missing USER_ID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
+ if (uploadArtifactEither.isRight()) {
+ log.debug("failed to upload artifact");
+ responseFormat = uploadArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ }
+ }
+ }catch (Exception e) {
+ final String message = "failed to upload artifact to a resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
- /**
- *
- * @param contenType
- * @param checksum
- * @param userId
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param assetType
- * @param uuid
- * @param artifactUUID
- * @param data
- * @return
- */
- @POST
- @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
- @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
- @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
- @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
- @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
- @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")
- public Response updateArtifact(
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
- String data) {
+ /**
+ *
+ * @param contenType
+ * @param checksum
+ * @param userId
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param assetType
+ * @param uuid
+ * @param artifactUUID
+ * @param data
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
+ @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
+ @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
+ @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
+ @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+ @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
+ public Response updateArtifact(
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
+ String data) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
- if (componentType == null) {
- log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("updateArtifact: Missing USER_ID");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
- additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update));
- if (uploadArtifactEither.isRight()) {
- log.debug("failed to update artifact");
- responseFormat = uploadArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
- }
- }
- } catch (Exception e) {
- final String message = "failed to update artifact on a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
+ if (componentType == null) {
+ log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
+ log.debug("updateArtifact: Missing USER_ID");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
+ if (uploadArtifactEither.isRight()) {
+ log.debug("failed to update artifact");
+ responseFormat = uploadArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ }
+ }
+ } catch (Exception e) {
+ final String message = "failed to update artifact on a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
- /**
- * updates an artifact on a resource instance
- *
- * @param assetType
- * @param uuid
- * @param resourceInstanceName
- * @param artifactUUID
- * @return
- */
- @POST
- @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
- @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
- @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
- @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
- @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
- @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")
- public Response updateArtifactOnResourceInstance(
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
- @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
- String data) {
+ /**
+ * updates an artifact on a resource instance
+ *
+ * @param assetType
+ * @param uuid
+ * @param resourceInstanceName
+ * @param artifactUUID
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
+ @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
+ @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
+ @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
+ @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+ @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
+ public Response updateArtifactOnResourceInstance(
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
+ @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
+ String data) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
- if (componentType == null) {
- log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
- additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update));
- if (uploadArtifactEither.isRight()) {
- log.debug("failed to update artifact");
- responseFormat = uploadArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
- }
- }
- } catch (Exception e) {
- final String message = "failed to update artifact on resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
+ if (componentType == null) {
+ log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
+ log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
+ if (uploadArtifactEither.isRight()) {
+ log.debug("failed to update artifact");
+ responseFormat = uploadArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ }
+ }
+ } catch (Exception e) {
+ final String message = "failed to update artifact on resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
- /**
- * deletes an artifact of a resource or service
- *
- * @param assetType
- * @param uuid
- * @param artifactUUID
- * @return
- */
- @DELETE
- @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class)
- /*@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
- @ApiResponse(code = 404, message = "Asset not found") })*/
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
- @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
- @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
- @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
- @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
- @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
- public Response deleteArtifact(
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
+ /**
+ * deletes an artifact of a resource or service
+ *
+ * @param assetType
+ * @param uuid
+ * @param artifactUUID
+ * @return
+ */
+ @DELETE
+ @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class)
+ /*@ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 404, message = "Asset not found") })*/
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
+ @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
+ @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
+ @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
+ @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+ @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+ public Response deleteArtifact(
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
- if (componentType == null) {
- log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("deleteArtifact: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
- additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete));
- if (uploadArtifactEither.isRight()) {
- log.debug("failed to delete artifact");
- responseFormat = uploadArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
- }
- }
- } catch (Exception e) {
- final String message = "failed to delete an artifact of a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
+ if (componentType == null) {
+ log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
+ log.debug("deleteArtifact: Missing USER_ID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
+ if (uploadArtifactEither.isRight()) {
+ log.debug("failed to delete artifact");
+ responseFormat = uploadArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ }
+ }
+ } catch (Exception e) {
+ final String message = "failed to delete an artifact of a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
- /**
- * deletes an artifact of a resource instance
- *
- * @param assetType
- * @param uuid
- * @param resourceInstanceName
- * @return
- */
- @DELETE
- @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class)
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
- @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
- @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
- @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
- @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
- @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
- public Response deleteArtifactOnResourceInstance(
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
- @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
+ /**
+ * deletes an artifact of a resource instance
+ *
+ * @param assetType
+ * @param uuid
+ * @param resourceInstanceName
+ * @return
+ */
+ @DELETE
+ @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
+ @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
+ @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
+ @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
+ @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+ @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+ public Response deleteArtifactOnResourceInstance(
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
+ @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
- if (componentType == null) {
- log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
- log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
- additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete));
- if (uploadArtifactEither.isRight()) {
- log.debug("failed to delete artifact");
- responseFormat = uploadArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
- }
- }
- } catch (Exception e) {
- final String message = "failed to delete an artifact of a resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
+ if (componentType == null) {
+ log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
+ log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
+ additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
+ if (uploadArtifactEither.isRight()) {
+ log.debug("failed to delete artifact");
+ responseFormat = uploadArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+ }
+ }
+ } catch (Exception e) {
+ final String message = "failed to delete an artifact of a resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
- /**
- * downloads an artifact of a component (either a service or a resource) by artifactUUID
- *
- * @param assetType
- * @param uuid
- * @param artifactUUID
- * @return
- */
- @GET
- @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
- public Response downloadComponentArtifact(
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
+ /**
+ * downloads an artifact of a component (either a service or a resource) by artifactUUID
+ *
+ * @param assetType
+ * @param uuid
+ * @param artifactUUID
+ * @return
+ */
+ @GET
+ @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
+ public Response downloadComponentArtifact(
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
- if (componentType == null) {
- log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams);
- if (downloadComponentArtifactEither.isRight()) {
- responseFormat = downloadComponentArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- byte[] value = downloadComponentArtifactEither.left().value();
- InputStream is = new ByteArrayInputStream(value);
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
- }
- }
- } catch (Exception e) {
- final String message = "failed to download an artifact of a resource or service";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
+ if (componentType == null) {
+ log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams);
+ if (downloadComponentArtifactEither.isRight()) {
+ responseFormat = downloadComponentArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ byte[] value = downloadComponentArtifactEither.left().value();
+ InputStream is = new ByteArrayInputStream(value);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
+ }
+ }
+ } catch (Exception e) {
+ final String message = "failed to download an artifact of a resource or service";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
- /**
- * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID
- *
- * @param assetType
- * @param uuid
- * @param resourceInstanceName
- * @param artifactUUID
- * @return
- */
- @GET
- @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(nickname = "downloadResourceInstanceArtifactByUUID",value = "Download resource instance artifact by artifact UUID", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
- public Response downloadResourceInstanceArtifact(
- @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
- @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
- @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
+ /**
+ * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID
+ *
+ * @param assetType
+ * @param uuid
+ * @param resourceInstanceName
+ * @param artifactUUID
+ * @return
+ */
+ @GET
+ @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
+ public Response downloadResourceInstanceArtifact(
+ @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
+ @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
+ @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- ResponseFormat responseFormat = null;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("{} {}", startLog, url);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- String componentTypeValue = componentType == null ? null : componentType.getValue();
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
- if (componentType == null) {
- log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
- log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- }
- try {
- if (responseWrapper.isEmpty()) {
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
- if (downloadResourceArtifactEither.isRight()) {
- responseFormat = downloadResourceArtifactEither.right().value();
- responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
- } else {
- byte[] value = downloadResourceArtifactEither.left().value();
- InputStream is = new ByteArrayInputStream(value);
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
- }
- }
- } catch (Exception e) {
- final String message = "failed to download an artifact of a resource instance";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
- } finally {
- getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
- }
- return responseWrapper.getInnerElement();
- }
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("{} {}", startLog, url);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ String componentTypeValue = componentType == null ? null : componentType.getValue();
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
+ if (componentType == null) {
+ log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
+ log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ }
+ try {
+ if (responseWrapper.isEmpty()) {
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
+ if (downloadResourceArtifactEither.isRight()) {
+ responseFormat = downloadResourceArtifactEither.right().value();
+ responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
+ } else {
+ byte[] value = downloadResourceArtifactEither.left().value();
+ InputStream is = new ByteArrayInputStream(value);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
+ }
+ }
+ } catch (Exception e) {
+ final String message = "failed to download an artifact of a resource instance";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ } finally {
+ getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
+ }
+ return responseWrapper.getInnerElement();
+ }
}
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 b9956063d6..27f82dfda3 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
@@ -20,26 +20,9 @@
package org.openecomp.sdc.be.externalapi.servlet;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
@@ -61,14 +44,19 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
/**
* This Servlet serves external users for retrieving component metadata.
@@ -83,311 +71,299 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class AssetsDataServlet extends AbstractValidationsServlet {
- @Context
- private HttpServletRequest request;
-
- private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName());
-
- /**
- *
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param assetType
- * @param category
- * @param subCategory
- * @param distributionStatus
- * @param resourceType
- * @return
- */
- @GET
- @Path("/{assetType}")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response getAssetListExternal(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category,
- @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory,
- @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus,
- @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) {
-
- Response response = null;
- ResponseFormat responseFormat = null;
- String query = request.getQueryString();
- String requestURI = request.getRequestURI().endsWith("/")?
- removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
- AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
-
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query);
-
- // Mandatory
- if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
- log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
-
- try {
- ServletContext context = request.getSession().getServletContext();
- ElementBusinessLogic elementLogic = getElementBL(context);
-
- AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
- Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
-
- if (category != null) {
- filters.put(FilterKeyEnum.CATEGORY, category);
- }
- if (subCategory != null) {
- filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
- }
- if (distributionStatus != null) {
- filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
- }
- if (resourceType != null) {
- ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
- if (resourceTypeEnum == null) {
- log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
- filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
- }
-
- Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
-
- if (assetTypeData.isRight()) {
- log.debug("getAssetList: Asset Fetching Failed");
- responseFormat = assetTypeData.right().value();
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- } else {
- log.debug("getAssetList: Asset Fetching Success");
- Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
- if (resMetadata.isRight()) {
- log.debug("getAssetList: Asset conversion Failed");
- responseFormat = resMetadata.right().value();
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
- Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
-
- response = buildOkResponse(responseFormat, result);
- return response;
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
- log.debug("getAssetList: Fetch list of assets failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /**
- *
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param assetType
- * @param uuid
- * @return
- */
- @GET
- @Path("/{assetType}/{uuid}/metadata")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response getAssetSpecificMetadataByUuidExternal(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
-
- Response response = null;
- ResponseFormat responseFormat = null;
- AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
- if (componentType == null) {
- log.debug("getMetaData: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- return buildErrorResponse(responseFormat);
- }
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
-
- // Mandatory
- if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
- log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
-
- try {
- ServletContext context = request.getSession().getServletContext();
- ElementBusinessLogic elementLogic = getElementBL(context);
- AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
-
- Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
-
- if (assetTypeData.isRight()) {
- log.debug("getAssetList: Asset Fetching Failed");
- responseFormat = assetTypeData.right().value();
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
-
- return buildErrorResponse(responseFormat);
- } else {
- log.debug("getAssetList: Asset Fetching Success");
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName());
- Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
- if (resMetadata.isRight()) {
- log.debug("getAssetList: Asset conversion Failed");
- responseFormat = resMetadata.right().value();
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
- Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
-
- response = buildOkResponse(responseFormat, result);
- return response;
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
- log.debug("getAssetList: Fetch list of assets failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /**
- *
- * @param requestId
- * @param instanceIdHeader
- * @param accept
- * @param authorization
- * @param assetType
- * @param uuid
- * @return
- */
- @GET
- @Path("/{assetType}/{uuid}/toscaModel")
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class)
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
- public Response getToscaModelExternal(
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
-
- String url = request.getRequestURI();
- log.debug("Start handle request of {} {}", request.getMethod(), url);
- Response response = null;
- ResponseFormat responseFormat = null;
- ServletContext context = request.getSession().getServletContext();
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
-
- if (componentType == null) {
- log.debug("getToscaModel: assetType parameter {} is not valid", assetType);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- return buildErrorResponse(responseFormat);
- }
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
-
-
- if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
- log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return buildErrorResponse(responseFormat);
- }
-
- try {
- ComponentBusinessLogic componentBL = getComponentBL(componentType, context);
-
- Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam);
- if (csarArtifact.isRight()) {
- responseFormat = csarArtifact.right().value();
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- response = buildErrorResponse(responseFormat);
- } else {
- byte[] value = csarArtifact.left().value().getRight();
- InputStream is = new ByteArrayInputStream(value);
- String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
- Map<String, String> headers = new HashMap<>();
- headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
- headers.put(Constants.MD5_HEADER, contenetMD5);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- response = buildOkResponse(responseFormat, is, headers);
- }
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
- log.debug("falied to get asset tosca model", e);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- response = buildErrorResponse(responseFormat);
- getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
- return response;
- }
- }
-
-
- private String removeDuplicateSlashSeparator(String requestUri) {
- return requestUri.substring(0, requestUri.length()-1);
- }
+ @Context
+ private HttpServletRequest request;
+
+ private static final Logger log = LoggerFactory.getLogger(AssetsDataServlet.class);
+
+ /**
+ *
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param assetType
+ * @param category
+ * @param subCategory
+ * @param distributionStatus
+ * @param resourceType
+ * @return
+ */
+ @GET
+ @Path("/{assetType}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response getAssetListExternal(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category,
+ @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory,
+ @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus,
+ @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) {
+
+ Response response = null;
+ ResponseFormat responseFormat = null;
+ String query = request.getQueryString();
+ String requestURI = request.getRequestURI().endsWith("/")?
+ removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("Start handle request of {}", url);
+
+ AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
+
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query);
+
+ // Mandatory
+ if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
+ log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+
+ try {
+ ServletContext context = request.getSession().getServletContext();
+ ElementBusinessLogic elementLogic = getElementBL(context);
+
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
+ Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
+
+ if (category != null) {
+ filters.put(FilterKeyEnum.CATEGORY, category);
+ }
+ if (subCategory != null) {
+ filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
+ }
+ if (distributionStatus != null) {
+ filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
+ }
+ if (resourceType != null) {
+ ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
+ if (resourceTypeEnum == null) {
+ log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+ filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
+ }
+
+ Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
+
+ if (assetTypeData.isRight()) {
+ log.debug("getAssetList: Asset Fetching Failed");
+ responseFormat = assetTypeData.right().value();
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ } else {
+ log.debug("getAssetList: Asset Fetching Success");
+ Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
+ if (resMetadata.isRight()) {
+ log.debug("getAssetList: Asset conversion Failed");
+ responseFormat = resMetadata.right().value();
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+ Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+
+ response = buildOkResponse(responseFormat, result);
+ return response;
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
+ log.debug("getAssetList: Fetch list of assets failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /**
+ *
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param assetType
+ * @param uuid
+ * @return
+ */
+ @GET
+ @Path("/{assetType}/{uuid}/metadata")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response getAssetSpecificMetadataByUuidExternal(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
+
+ Response response = null;
+ ResponseFormat responseFormat = null;
+ AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("Start handle request of {}", url);
+
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
+
+ // Mandatory
+ if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
+ log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+
+ try {
+ ServletContext context = request.getSession().getServletContext();
+ ElementBusinessLogic elementLogic = getElementBL(context);
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
+
+ Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
+
+ if (assetTypeData.isRight()) {
+ log.debug("getAssetList: Asset Fetching Failed");
+ responseFormat = assetTypeData.right().value();
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+
+ return buildErrorResponse(responseFormat);
+ } else {
+ log.debug("getAssetList: Asset Fetching Success");
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName());
+ Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
+ if (resMetadata.isRight()) {
+ log.debug("getAssetList: Asset conversion Failed");
+ responseFormat = resMetadata.right().value();
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+ Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+
+ response = buildOkResponse(responseFormat, result);
+ return response;
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
+ log.debug("getAssetList: Fetch list of assets failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /**
+ *
+ * @param requestId
+ * @param instanceIdHeader
+ * @param accept
+ * @param authorization
+ * @param assetType
+ * @param uuid
+ * @return
+ */
+ @GET
+ @Path("/{assetType}/{uuid}/toscaModel")
+ @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class),
+ @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+ public Response getToscaModelExternal(
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
+
+ String url = request.getRequestURI();
+ log.debug("Start handle request of {} {}", request.getMethod(), url);
+ Response response = null;
+ ResponseFormat responseFormat = null;
+ ServletContext context = request.getSession().getServletContext();
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url);
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
+ additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
+
+ if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
+ log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return buildErrorResponse(responseFormat);
+ }
+
+ try {
+ ComponentBusinessLogic componentBL = getComponentBL(componentType, context);
+
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam);
+ if (csarArtifact.isRight()) {
+ responseFormat = csarArtifact.right().value();
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ response = buildErrorResponse(responseFormat);
+ } else {
+ byte[] value = csarArtifact.left().value().getRight();
+ InputStream is = new ByteArrayInputStream(value);
+ String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
+ Map<String, String> headers = new HashMap<>();
+ headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
+ headers.put(Constants.MD5_HEADER, contenetMD5);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ response = buildOkResponse(responseFormat, is, headers);
+ }
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
+ log.debug("falied to get asset tosca model", e);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ response = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
+ return response;
+ }
+ }
+
+
+ private String removeDuplicateSlashSeparator(String requestUri) {
+ return requestUri.substring(0, requestUri.length()-1);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
index 18422f53a1..0651291fc4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
@@ -20,30 +20,11 @@
package org.openecomp.sdc.be.externalapi.servlet;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.common.Strings;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@@ -62,11 +43,7 @@ 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;
-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.*;
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;
@@ -82,508 +59,509 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "CRUD External Servlet", description = "This Servlet serves external users for creating assets and changing their lifecycle state")
@Singleton
public class CrudExternalServlet extends AbstractValidationsServlet {
-
- @Context
- private HttpServletRequest request;
-
- private static Logger log = LoggerFactory.getLogger(CrudExternalServlet.class.getName());
-
- /**
- * Creates a new Resource
- *
- * @param assetType
- * @param data
- * @param userId
- * @param instanceIdHeader
- * @return
- */
- @POST
- @Path("/{assetType}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class),
- @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"),
- @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
- @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"),
- @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"),
- @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource")
- public Response createResourceExternal(
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
- String data) {
-
- init(log);
-
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
- Resource resource = null;
- User modifier = null;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
- ServletContext context = request.getSession().getServletContext();
- ResourceBusinessLogic resourceBL = getResourceBL(context);
- try {
- // Validate X-ECOMP-InstanceID Header
- if (responseWrapper.isEmpty()) {
- validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
- }
- // Validate USER_ID Header
- if (responseWrapper.isEmpty()) {
- validateHttpCspUserIdHeader(userId, responseWrapper);
- }
- // Validate assetType
- if (responseWrapper.isEmpty()) {
- if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- }
- //Validate resource type
- if(responseWrapper.isEmpty()){
- JSONParser parser = new JSONParser();
- JSONObject jsonObj = (JSONObject) parser.parse(data);
- String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName());
- if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name"));
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- }
- // Convert the user json to a resource
- if (responseWrapper.isEmpty()) {
- modifier = new User();
- modifier.setUserId(userId);
- Either<Resource, ResponseFormat> eitherResource = getComponentsUtils()
- .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class,
- null, ComponentTypeEnum.RESOURCE);
- if( eitherResource.isRight() ){
- responseWrapper.setInnerElement(eitherResource.right().value());
- }
- else{
- resource = eitherResource.left().value();
- }
-
- }
- //validate name exist
- if(responseWrapper.isEmpty()){
- if( Strings.isEmpty(resource.getName())){
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
- ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));
-
- }
- }
-
- if(responseWrapper.isEmpty()){
- resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root"));
- resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName()));
- resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(),
- resource.getSystemName()));
- handleCategories(context, data, resource, responseWrapper);
- }
- // Create the resource in the dataModel
- if (responseWrapper.isEmpty()) {
- Either<Resource, ResponseFormat> eitherCreateResponse = resourceBL.createResource(resource, null,
- modifier, null, null);
- if (eitherCreateResponse.isRight()) {
- responseWrapper.setInnerElement(eitherCreateResponse.right().value());
- } else {
- resource = eitherCreateResponse.left().value();
- }
- }
- Response response;
- //Build Response and store it in the response Wrapper
- if (responseWrapper.isEmpty()) {
- response = buildCreatedResourceResponse(resource, context, responseWrapper);
- }
- else{
- response = buildErrorResponse(responseWrapper.getInnerElement());
- }
- return response;
-
- } catch (Exception e) {
- final String message = "failed to create vfc monitoring template resource";
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
- log.debug(message, e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- finally{
- prepareAdditionalAudit(resource, additionalParams);
-
- getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),
- ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request,
- additionalParams);
- }
- }
-
- /**
- * Changing the lifecycle of an asset
- * @param jsonChangeInfo The description - request body
- * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources")
- * @param uuid The uuid of the desired resource to be changed
- * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST
- * @param userId
- * @return
- */
- @POST
- @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST")
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class),
- @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
- @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
- @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
- @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
- @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
- @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
- @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"),
- @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")})
- @ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed")
- public Response changeResourceStateExternal(
- @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
- @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
- @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
- @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType,
- String jsonChangeInfo) {
-
- Response response = null;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
-
- init(log);
-
- String requestURI = request.getRequestURI();
- String url = request.getMethod() + " " + requestURI;
- log.debug("Start handle request of {}", url);
-
- //get the business logic
- ServletContext context = request.getSession().getServletContext();
- LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
-
- Wrapper<ResponseFormat> responseWrapper = runValidations(assetType);
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
- Component component = null;
- Component responseObject = null;
- User modifier = null;
-
- try{
- // Validate X-ECOMP-InstanceID Header
- if (responseWrapper.isEmpty()) {
- validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
- }
-
- if (responseWrapper.isEmpty()) {
- //get user
- Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
- if (eitherGetUser.isRight()) {
- ResponseFormat responseFormat = eitherGetUser.right().value();
- responseWrapper.setInnerElement(responseFormat);
- return buildErrorResponse(responseFormat);
- }
- modifier = eitherGetUser.left().value();
-
- //get the component id from the uuid
- Either<Component, ResponseFormat> latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid);
- if (latestVersion.isRight()) {
- ResponseFormat responseFormat = latestVersion.right().value();
- responseWrapper.setInnerElement(responseFormat);
- return buildErrorResponse(responseFormat);
- }
- component = latestVersion.left().value();
- String componentId = component.getUniqueId();
-
- //validate the transition is valid
- Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier);
- if (validateEnum.isRight()) {
- ResponseFormat responseFormat = validateEnum.right().value();
- responseWrapper.setInnerElement(responseFormat);
- return buildErrorResponse(responseFormat);
- }
- LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
-
- //create changeInfo
- LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
- try {
- if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
- ObjectMapper mapper = new ObjectMapper();
- changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
- }
- }
- catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("failed to convert from json {}", jsonChangeInfo, e);
- ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, AuditingActionEnum.CHECKOUT_RESOURCE);
- responseWrapper.setInnerElement(responseFormat);
- return buildErrorResponse(responseFormat);
- }
-
- //execute business logic
- Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);
- if (actionResponse.isRight()) {
- log.info("failed to change resource state");
- ResponseFormat responseFormat = actionResponse.right().value();
- responseWrapper.setInnerElement(responseFormat);
- return buildErrorResponse(responseFormat);
- }
-
- log.debug("change state successful !!!");
- responseObject = actionResponse.left().value();
- response = buildCreatedResourceResponse(responseObject, context, responseWrapper);
- } else {
- response = buildErrorResponse(responseWrapper.getInnerElement());
- }
-
- return response;
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
- log.debug("change lifecycle state failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- responseWrapper.setInnerElement(responseFormat);
- return buildErrorResponse(responseFormat);
- } finally{
- auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId);
- }
- }
-
- private void prepareAdditionalAudit(Resource resource, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY);
-
- if( resource != null ){
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID());
- } else {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY);
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY);
- }
- }
-
- private Response buildCreatedResourceResponse(Component resource, ServletContext context,
- Wrapper<ResponseFormat> responseWrapper) throws IOException, JsonGenerationException, JsonMappingException {
- ResponseFormat responseFormat;
- Response response;
- AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
- Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils
- .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(),
- true);
- if (resMetadata.isRight()) {
- log.debug("Asset conversion Failed");
- responseFormat = resMetadata.right().value();
- responseWrapper.setInnerElement(responseFormat);
- response = buildErrorResponse(responseFormat);
- }else{
- final AssetMetadata assetData = resMetadata.left().value();
- assetData.setToscaModelURL(null);
-
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));
- Object representation = RepresentationUtils.toRepresentation(assetData);
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
- }
- return response;
- }
-
- private void handleCategories(ServletContext context, String data, Resource resource,
- Wrapper<ResponseFormat> responseWrapper) {
- try {
- JSONParser parser = new JSONParser();
- JSONObject jsonObj = (JSONObject) parser.parse(data);
- String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue());
- String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue());
- if (Strings.isEmpty(category)) {
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
- ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
- }
- else if (Strings.isEmpty(subcategory)) {
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
- ActionStatus.COMPONENT_MISSING_SUBCATEGORY));
- }
- if (responseWrapper.isEmpty()) {
- ElementBusinessLogic elementLogic = getElementBL(context);
- // get All Categories
- Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementLogic
- .getAllResourceCategories();
- // Error fetching categories
- if (allResourceCategories.isRight()) {
- responseWrapper.setInnerElement(
- getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));
- } else {
- addCategories(resource, category, subcategory, allResourceCategories, responseWrapper);
- }
- }
- } catch (Exception e) {
- log.debug("Exception occured in addCategories: {}", e.getMessage(), e);
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- private void addCategories(Resource resource, String category, String subcategory,
- Either<List<CategoryDefinition>, ActionStatus> allResourceCategories,
- Wrapper<ResponseFormat> responseWrapper) {
- Optional<CategoryDefinition> optionalCategory =
- // Stream of all the categories
- allResourceCategories.left().value().stream()
- // filter in only relevant category
- .filter(e -> e.getName().equals(category))
- // get the result
- .findAny();
- if (!optionalCategory.isPresent()) {
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
- ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
- } else {
- CategoryDefinition categoryDefinition = optionalCategory.get();
-
- List<SubCategoryDefinition> subCaregories =
- // Stream of all sub-categories of the relevant
- // category
- categoryDefinition.getSubcategories().stream()
- // filter in only relevant sub-category
- .filter(e -> e.getName().equals(subcategory))
- // get the result
- .collect(Collectors.toList());
-
- if( subCaregories.isEmpty() ){
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
- ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
- }
- else{
- categoryDefinition.setSubcategories(subCaregories);
- resource.setCategories(Arrays.asList(categoryDefinition));
- }
-
- }
- }
-
-
-
-
- private void auditChnageLifecycleAction(EnumMap<AuditingFieldsKeysEnum, Object> additionalParams,
- Wrapper<ResponseFormat> responseWrapper, ComponentTypeEnum componentType, Component component,
- Component responseObject, User modifier, String userId) {
- if (modifier!=null){
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- } else {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId);
- }
-
- if (component!=null){
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name());
- } else {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
- }
-
- if (responseObject!=null){
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name());
- } else {
- if (component!=null){
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID());
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name());
- } else {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,"");
- }
- }
-
- getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),
- componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request,
- additionalParams);
- }
-
- private Wrapper<ResponseFormat> runValidations(final String assetType) {
- Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-
- // Validate X-ECOMP-InstanceID Header
- if (responseWrapper.isEmpty()) {
- String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
- validateXECOMPInstanceIDHeader(instanceId,responseWrapper);
- }
- // Validate USER_ID Header
- if (responseWrapper.isEmpty()) {
- validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper);
- }
- // Validate assetType
- if (responseWrapper.isEmpty()) {
- if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){
- responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
- }
-
- return responseWrapper;
- }
-
- private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) {
- LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
- try {
- transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
- } catch (IllegalArgumentException e) {
- log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
- ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
- return Either.right(error);
- }
- return Either.left(transitionEnum);
- }
+
+ @Context
+ private HttpServletRequest request;
+
+ private static final Logger log = LoggerFactory.getLogger(CrudExternalServlet.class);
+
+ /**
+ * Creates a new Resource
+ *
+ * @param assetType
+ * @param data
+ * @param userId
+ * @param instanceIdHeader
+ * @return
+ */
+ @POST
+ @Path("/{assetType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"),
+ @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
+ @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"),
+ @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format - SVC4064"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name has wrong format - SVC4070"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"),
+ @ApiResponse(code = 400, message = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.Resource", paramType = "body", value = "json describe the created resource")})
+ public Response createResourceExternal(
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
+ String data) {
+
+ init(log);
+
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("Start handle request of {}", url);
+ Resource resource = null;
+ User modifier = null;
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ ServletContext context = request.getSession().getServletContext();
+ ResourceBusinessLogic resourceBL = getResourceBL(context);
+ try {
+ // Validate X-ECOMP-InstanceID Header
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
+ }
+ // Validate USER_ID Header
+ if (responseWrapper.isEmpty()) {
+ validateHttpCspUserIdHeader(userId, responseWrapper);
+ }
+ // Validate assetType
+ if (responseWrapper.isEmpty()) {
+ if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) ){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+ //Validate resource type
+ if(responseWrapper.isEmpty()){
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj = (JSONObject) parser.parse(data);
+ String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName());
+ if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, (String) jsonObj.get("name"));
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ }
+ // Convert the user json to a resource
+ if (responseWrapper.isEmpty()) {
+ modifier = new User();
+ modifier.setUserId(userId);
+ Either<Resource, ResponseFormat> eitherResource = getComponentsUtils()
+ .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class,
+ null, ComponentTypeEnum.RESOURCE);
+ if( eitherResource.isRight() ){
+ responseWrapper.setInnerElement(eitherResource.right().value());
+ }
+ else{
+ resource = eitherResource.left().value();
+ }
+
+ }
+ //validate name exist
+ if(responseWrapper.isEmpty()){
+ if( Strings.isEmpty(resource.getName())){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));
+
+ }
+ }
+
+ if(responseWrapper.isEmpty()){
+ resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root"));
+ resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName()));
+ resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(),
+ resource.getSystemName()));
+ handleCategories(context, data, resource, responseWrapper);
+ }
+ // Create the resource in the dataModel
+ if (responseWrapper.isEmpty()) {
+ Either<Resource, ResponseFormat> eitherCreateResponse = resourceBL.createResource(resource, null,
+ modifier, null, null);
+ if (eitherCreateResponse.isRight()) {
+ responseWrapper.setInnerElement(eitherCreateResponse.right().value());
+ } else {
+ resource = eitherCreateResponse.left().value();
+ }
+ }
+ Response response;
+ //Build Response and store it in the response Wrapper
+ if (responseWrapper.isEmpty()) {
+ response = buildCreatedResourceResponse(resource, context, responseWrapper);
+ }
+ else{
+ response = buildErrorResponse(responseWrapper.getInnerElement());
+ }
+ return response;
+
+ } catch (Exception e) {
+ final String message = "failed to create vfc monitoring template resource";
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
+ log.debug(message, e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ finally{
+ prepareAdditionalAudit(resource, additionalParams);
+
+ getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),
+ ComponentTypeEnum.RESOURCE.getValue(), AuditingActionEnum.CREATE_RESOURCE_BY_API.getName(), request,
+ additionalParams);
+ }
+ }
+
+ /**
+ * Changing the lifecycle of an asset
+ * @param jsonChangeInfo The description - request body
+ * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT – use "resources")
+ * @param uuid The uuid of the desired resource to be changed
+ * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout / CERTIFICATION_REQUEST
+ * @param userId
+ * @return
+ */
+ @POST
+ @Path("/{assetType}/{uuid}/lifecycleState/{lifecycleOperation}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 403, message = "Asset is already checked-out by another user - SVC4085"),
+ @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")})
+ @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction", paramType = "body", value = "userRemarks - Short description (free text) about the asset version being changed")})
+ public Response changeResourceStateExternal(
+ @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The user id", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(allowableValues = "checkout, checkin", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
+ @ApiParam(value = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
+ @ApiParam(value = "validValues: resources / services ", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam(value = "assetType") final String assetType,
+ String jsonChangeInfo) {
+
+ Response response = null;
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+
+ init(log);
+
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ log.debug("Start handle request of {}", url);
+
+ //get the business logic
+ ServletContext context = request.getSession().getServletContext();
+ LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
+
+ Wrapper<ResponseFormat> responseWrapper = runValidations(assetType);
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
+ Component component = null;
+ Component responseObject = null;
+ User modifier = null;
+
+ try{
+ // Validate X-ECOMP-InstanceID Header
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ //get user
+ Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
+ if (eitherGetUser.isRight()) {
+ ResponseFormat responseFormat = eitherGetUser.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+ modifier = eitherGetUser.left().value();
+
+ //get the component id from the uuid
+ Either<Component, ResponseFormat> latestVersion = businessLogic.getLatestComponentByUuid(componentType, uuid);
+ if (latestVersion.isRight()) {
+ ResponseFormat responseFormat = latestVersion.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+ component = latestVersion.left().value();
+ String componentId = component.getUniqueId();
+
+ //validate the transition is valid
+ Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier);
+ if (validateEnum.isRight()) {
+ ResponseFormat responseFormat = validateEnum.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+ LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
+
+ //create changeInfo
+ LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
+ try {
+ if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
+ ObjectMapper mapper = new ObjectMapper();
+ changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
+ }
+ }
+ catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json {}", jsonChangeInfo, e);
+ ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+
+ //execute business logic
+ Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);
+ if (actionResponse.isRight()) {
+ log.info("failed to change resource state");
+ ResponseFormat responseFormat = actionResponse.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+
+ log.debug("change state successful !!!");
+ responseObject = actionResponse.left().value();
+ response = buildCreatedResourceResponse(responseObject, context, responseWrapper);
+ } else {
+ response = buildErrorResponse(responseWrapper.getInnerElement());
+ }
+
+ return response;
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
+ log.debug("change lifecycle state failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ responseWrapper.setInnerElement(responseFormat);
+ return buildErrorResponse(responseFormat);
+ } finally{
+ auditChnageLifecycleAction(additionalParams, responseWrapper, componentType, component, responseObject, modifier, userId);
+ }
+ }
+
+ private void prepareAdditionalAudit(Resource resource, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, StringUtils.EMPTY);
+
+ if( resource != null ){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resource.getUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, resource.getInvariantUUID());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, StringUtils.EMPTY);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, StringUtils.EMPTY);
+ }
+ }
+
+ private Response buildCreatedResourceResponse(Component resource, ServletContext context,
+ Wrapper<ResponseFormat> responseWrapper) throws IOException {
+ ResponseFormat responseFormat;
+ Response response;
+ AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
+ Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils
+ .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(),
+ true);
+ if (resMetadata.isRight()) {
+ log.debug("Asset conversion Failed");
+ responseFormat = resMetadata.right().value();
+ responseWrapper.setInnerElement(responseFormat);
+ response = buildErrorResponse(responseFormat);
+ }else{
+ final AssetMetadata assetData = resMetadata.left().value();
+ assetData.setToscaModelURL(null);
+
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));
+ Object representation = RepresentationUtils.toRepresentation(assetData);
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
+ }
+ return response;
+ }
+
+ private void handleCategories(ServletContext context, String data, Resource resource,
+ Wrapper<ResponseFormat> responseWrapper) {
+ try {
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj = (JSONObject) parser.parse(data);
+ String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue());
+ String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue());
+ if (Strings.isEmpty(category)) {
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ else if (Strings.isEmpty(subcategory)) {
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_MISSING_SUBCATEGORY));
+ }
+ if (responseWrapper.isEmpty()) {
+ ElementBusinessLogic elementLogic = getElementBL(context);
+ // get All Categories
+ Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementLogic
+ .getAllResourceCategories();
+ // Error fetching categories
+ if (allResourceCategories.isRight()) {
+ responseWrapper.setInnerElement(
+ getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));
+ } else {
+ addCategories(resource, category, subcategory, allResourceCategories, responseWrapper);
+ }
+ }
+ } catch (Exception e) {
+ log.debug("Exception occured in addCategories: {}", e.getMessage(), e);
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ private void addCategories(Resource resource, String category, String subcategory,
+ Either<List<CategoryDefinition>, ActionStatus> allResourceCategories,
+ Wrapper<ResponseFormat> responseWrapper) {
+ Optional<CategoryDefinition> optionalCategory =
+ // Stream of all the categories
+ allResourceCategories.left().value().stream()
+ // filter in only relevant category
+ .filter(e -> e.getName().equals(category))
+ // get the result
+ .findAny();
+ if (!optionalCategory.isPresent()) {
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+ } else {
+ CategoryDefinition categoryDefinition = optionalCategory.get();
+
+ List<SubCategoryDefinition> subCaregories =
+ // Stream of all sub-categories of the relevant
+ // category
+ categoryDefinition.getSubcategories().stream()
+ // filter in only relevant sub-category
+ .filter(e -> e.getName().equals(subcategory))
+ // get the result
+ .collect(Collectors.toList());
+
+ if( subCaregories.isEmpty() ){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
+ ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+ }
+ else{
+ categoryDefinition.setSubcategories(subCaregories);
+ resource.setCategories(Arrays.asList(categoryDefinition));
+ }
+
+ }
+ }
+
+
+
+
+ private void auditChnageLifecycleAction(EnumMap<AuditingFieldsKeysEnum, Object> additionalParams,
+ Wrapper<ResponseFormat> responseWrapper, ComponentTypeEnum componentType, Component component,
+ Component responseObject, User modifier, String userId) {
+ if (modifier!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFullName());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, userId);
+ }
+
+ if (component!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, component.getVersion());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, component.getLifecycleState().name());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, "");
+ }
+
+ if (responseObject!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, responseObject.getVersion());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, responseObject.getUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, responseObject.getInvariantUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,responseObject.getLifecycleState().name());
+ } else {
+ if (component!=null){
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, component.getVersion());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, component.getUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, component.getInvariantUUID());
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,component.getLifecycleState().name());
+ } else {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE,"");
+ }
+ }
+
+ getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(),
+ componentType.getValue(), AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName(), request,
+ additionalParams);
+ }
+
+ private Wrapper<ResponseFormat> runValidations(final String assetType) {
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+
+ // Validate X-ECOMP-InstanceID Header
+ if (responseWrapper.isEmpty()) {
+ String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
+ validateXECOMPInstanceIDHeader(instanceId,responseWrapper);
+ }
+ // Validate USER_ID Header
+ if (responseWrapper.isEmpty()) {
+ validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper);
+ }
+ // Validate assetType
+ if (responseWrapper.isEmpty()) {
+ if( !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue().equals(assetType)){
+ responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+ }
+ }
+
+ return responseWrapper;
+ }
+
+ private Either<LifeCycleTransitionEnum, ResponseFormat> validateTransitionEnum(final String lifecycleTransition, User user) {
+ LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
+ try {
+ transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
+ } catch (IllegalArgumentException e) {
+ log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
+ ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
+ return Either.right(error);
+ }
+ return Either.left(transitionEnum);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java
new file mode 100644
index 0000000000..7e48890c7d
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java
@@ -0,0 +1,214 @@
+package org.openecomp.sdc.be.externalapi.servlet;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dto.ExternalRefDTO;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Controller;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.List;
+import java.util.Map;
+
+
+@Path("/v1/catalog")
+@Controller
+public class ExternalRefsServlet extends AbstractValidationsServlet {
+
+ private static final Logger log = LoggerFactory.getLogger(ExternalRefsServlet.class);
+
+ private ExternalRefsBusinessLogic businessLogic;
+
+ public ExternalRefsServlet(ExternalRefsBusinessLogic businessLogic, ComponentsUtils componentsUtils){
+ this.businessLogic = businessLogic;
+ this.componentsUtils = componentsUtils;
+ }
+
+ @GET
+ @Path("/{assetType}/{uuid}/version/{version}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getComponentInstanceExternalRef(
+ @Context final HttpServletRequest request,
+ @PathParam("assetType") String assetType,
+ @PathParam("uuid") String uuid,
+ @PathParam("version") String version,
+ @PathParam("componentInstanceName") String componentInstanceName,
+ @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId) {
+
+ log.debug("GET component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType);
+
+ Response r = authorizeAndValidateRequest(request, userId);
+ if (r != null){
+ return r;
+ }
+
+ Either<List<String>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, componentInstanceName, objectType);
+ if (refsResult.isLeft()){
+ return this.buildOkResponse(refsResult.left().value());
+ } else {
+ return this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, componentInstanceName, objectType, "");
+ }
+ }
+
+ @GET
+ @Path("/{assetType}/{uuid}/version/{version}/externalReferences/{objectType}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Map<String, List<String>> getAssetExternalRefByObjectType(
+ @Context final HttpServletRequest request,
+ @PathParam("assetType") String assetType,
+ @PathParam("uuid") String uuid,
+ @PathParam("version") String version,
+ @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId) {
+
+ log.debug("GET asset external references {} {} {}", assetType, uuid, objectType);
+
+ Response r = authorizeAndValidateRequest(request, userId);
+ if (r != null){
+ throw new WebApplicationException(r);
+ }
+
+ Either<Map<String, List<String>>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, objectType);
+ if (refsResult.isLeft()){
+ return refsResult.left().value();
+ } else {
+ throw new WebApplicationException(this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, "", objectType, ""));
+ }
+ }
+
+ @POST
+ @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response addComponentInstanceExternalRef(
+ @Context final HttpServletRequest request,
+ @PathParam("assetType") String assetType,
+ @PathParam("uuid") String uuid,
+ @PathParam("componentInstanceName") String componentInstanceName,
+ @PathParam("objectType") String objectType, ExternalRefDTO ref, @HeaderParam("USER_ID") String userId) {
+
+ log.debug("POST component instance external interfaces {} {} {} {} {}", assetType, uuid, componentInstanceName, objectType, ref);
+
+ Response r = authorizeAndValidateRequest(request, userId);
+ if (r != null){
+ return r;
+ }
+
+ Either<String, ActionStatus> addResult = this.businessLogic.addExternalReference(uuid, componentInstanceName, objectType, ref);
+ if (addResult.isLeft()) {
+ return Response.status(Response.Status.CREATED)
+ .entity(ref)
+ .build();
+ } else {
+ return this.buildExtRefErrorResponse(addResult.right().value(), uuid, "", componentInstanceName, objectType, ref.getReferenceUUID());
+ }
+
+ }
+
+ @DELETE
+ @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{reference}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response deleteComponentInstanceReference(
+ @Context final HttpServletRequest request,
+ @PathParam("assetType") String assetType,
+ @PathParam("uuid") String uuid,
+ @PathParam("componentInstanceName") String componentInstanceName,
+ @PathParam("objectType") String objectType,
+ @PathParam("reference") String reference, @HeaderParam("USER_ID") String userId) {
+
+ log.debug("DELETE component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType);
+
+ Response r = authorizeAndValidateRequest(request, userId);
+ if (r != null){
+ return r;
+ }
+
+ Either<String, ActionStatus> deleteStatus = this.businessLogic.deleteExternalReference(uuid, componentInstanceName, objectType, reference);
+ if (deleteStatus.isLeft()){
+ return this.buildOkResponse(new ExternalRefDTO(reference));
+ } else {
+ return this.buildExtRefErrorResponse(deleteStatus.right().value(), uuid, "", componentInstanceName, objectType, reference);
+ }
+ }
+
+ @PUT
+ @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{oldRefValue}")
+ @Produces(MediaType.APPLICATION_JSON)
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response updateComponentInstanceReference(
+ @Context final HttpServletRequest request,
+ @PathParam("assetType") String assetType,
+ @PathParam("uuid") String uuid,
+ @PathParam("componentInstanceName") String componentInstanceName,
+ @PathParam("objectType") String objectType,
+ @PathParam("oldRefValue") String oldRefValue,
+ ExternalRefDTO newRefValueDTO, @HeaderParam("USER_ID") String userId) {
+
+ log.debug("PUT component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType);
+
+ Response r = authorizeAndValidateRequest(request, userId);
+ if (r != null){
+ return r;
+ }
+
+ String newRefValue = newRefValueDTO.getReferenceUUID();
+ Either<String, ActionStatus> updateResult = this.businessLogic.updateExternalReference(uuid, componentInstanceName, objectType, oldRefValue, newRefValue);
+ if (updateResult.isLeft()){
+ return this.buildOkResponse(new ExternalRefDTO(newRefValue));
+ } else {
+ return this.buildExtRefErrorResponse(updateResult.right().value(), uuid, "", componentInstanceName, objectType, oldRefValue);
+ }
+
+ }
+
+ private Response authorizeAndValidateRequest(final HttpServletRequest request, String userId) {
+ init(log);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ Wrapper<User> userWrapper = new Wrapper<>();
+
+ //Validate X-ECOMP_INSTANCE_ID_HEADER
+ if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null || request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER).isEmpty()){
+ return this.buildExtRefErrorResponse(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID, "", "", "", "", "");
+ }
+
+ String method = request.getMethod();
+ if (responseWrapper.isEmpty() && !"GET".equals(method)) {
+ validateUserExist(responseWrapper, userWrapper, userId);
+ validateUserRole(responseWrapper, userWrapper.getInnerElement());
+ }
+
+ return responseWrapper.getInnerElement();
+ }
+
+ private Response buildExtRefErrorResponse(ActionStatus status, String uuid, String version, String componentInstanceName, String objectType, String ref){
+ switch (status) {
+ case RESOURCE_NOT_FOUND:
+ return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid));
+ case COMPONENT_VERSION_NOT_FOUND:
+ return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid, version));
+ case COMPONENT_INSTANCE_NOT_FOUND:
+ return buildErrorResponse(componentsUtils.getResponseFormat(status, componentInstanceName, uuid));
+ case EXT_REF_ALREADY_EXIST:
+ return Response.status(Response.Status.OK)
+ .entity(new ExternalRefDTO(ref))
+ .build();
+ case EXT_REF_NOT_FOUND:
+ return buildErrorResponse(componentsUtils.getResponseFormat(status, objectType + "/" + ref));
+ case MISSING_X_ECOMP_INSTANCE_ID:
+ return buildErrorResponse(componentsUtils.getResponseFormat(status));
+ default:
+ return this.buildGeneralErrorResponse();
+ }
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java
new file mode 100644
index 0000000000..3f1bf18edb
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java
@@ -0,0 +1,167 @@
+package org.openecomp.sdc.be.externalapi.servlet;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionRespInfo;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
+import org.openecomp.sdc.be.servlets.RepresentationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.util.EnumMap;
+
+/**
+ * Created by chaya on 10/17/2017.
+ */
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
+@Path("/v1/catalog")
+@Api(value = "Service Activation External Servlet", description = "This Servlet serves external users for activating a specific service")
+@Singleton
+public class ServiceActivationServlet extends AbstractValidationsServlet {
+
+ @Context
+ private HttpServletRequest request;
+
+ private static final Logger log = LoggerFactory.getLogger(ServiceActivationServlet.class);
+
+ /**
+ * Activates a service on a specific environment
+ *
+ * @param serviceUUID
+ * @param opEnvId
+ * @param userId
+ * @param instanceIdHeader
+ * @return
+ */
+ @POST
+ @Path("/services/{serviceUUID}/distribution/{opEnvId}/activate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "activate a service", httpMethod = "POST", notes = "Activates a service")
+ @ApiResponses(value = {
+ @ApiResponse(code = 202, message = "ECOMP component is authenticated and required service may be distributed"),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
+ @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
+ @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
+ @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+ @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+ @ApiResponse(code = 500, message = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+ @ApiResponse(code = 400, message = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
+ @ApiResponse(code = 400, message = "Missing request body. The post request did not contain the expected body - SVC4500"),
+ @ApiResponse(code = 400, message = "The resource name is missing in the request body - SVC4062"),
+ @ApiResponse(code = 409, message = "Service state is invalid for this action"),
+ @ApiResponse(code = 502, message = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})
+ public Response activateServiceExternal(
+ @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
+ @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @ApiParam(value = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID,
+ @ApiParam(value = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId,
+ String data) {
+
+ init(log);
+
+ ResponseFormat responseFormat = null;
+ String requestURI = request.getRequestURI();
+ String url = request.getMethod() + " " + requestURI;
+ EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID);
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
+ log.debug("Start handle request of {}", url);
+
+ ServletContext context = request.getSession().getServletContext();
+ try {
+
+ Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId);
+
+ if (responseWrapper.isEmpty()) {
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data);
+ Either<String, ResponseFormat> distResponse = businessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);
+
+ if (distResponse.isRight()) {
+ log.debug("failed to activate service distribution");
+ responseFormat = distResponse.right().value();
+ return buildErrorResponse(responseFormat);
+ }
+ String distributionId = distResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(new ServiceDistributionRespInfo(distributionId));
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.ACCEPTED);
+ return buildOkResponse(responseFormat, result);
+ } else {
+ log.debug("request instanceId/userId header validation failed");
+ responseFormat = responseWrapper.getInnerElement();
+ return buildErrorResponse(responseFormat);
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
+ log.debug("activate distribution failed with exception", e);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ } finally {
+ getComponentsUtils().auditExternalActivateService(responseFormat, ComponentTypeEnum.SERVICE.name(), request, additionalParams);
+ }
+ }
+
+ private Wrapper<ResponseFormat> validateRequestHeaders(String instanceIdHeader, String userId) {
+ Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+ if (responseWrapper.isEmpty()) {
+ validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
+ }
+ if (responseWrapper.isEmpty()) {
+ validateHttpCspUserIdHeader(userId, responseWrapper);
+ }
+ return responseWrapper;
+ }
+
+ private ServiceDistributionReqInfo convertJsonToActivationMetadata(String data) {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ return mapper.readValue(data, ServiceDistributionReqInfo.class);
+ } catch (IOException e) {
+ log.error("#convertJsonToActivationMetadata - json deserialization failed with error: ", e);
+ return new ServiceDistributionReqInfo(null);
+ }
+ }
+
+ @Override
+ protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
+ ResponseFormat responseFormat;
+ if( StringUtils.isEmpty(header)){
+ log.debug("MissingUSER_ID");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
+ responseWrapper.setInnerElement(responseFormat);
+ }
+ }
+}
+
+
+
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
index 15ebceaa5d..e41d8d7548 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
@@ -21,104 +21,104 @@
package org.openecomp.sdc.be.externalapi.servlet.representation;
public class ArtifactMetadata {
- private String artifactName;
- private String artifactType;
- private String artifactURL;
- private String artifactDescription;
- private Integer artifactTimeout;
- private String artifactChecksum;
- private String artifactUUID;
- private String artifactVersion;
- private String generatedFromUUID;
- private String artifactLabel;
- private String artifactGroupType;
-
- 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 Integer getArtifactTimeout() {
- return artifactTimeout;
- }
-
- public void setArtifactTimeout(Integer 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;
- }
-
- public String getArtifactLabel() {
- return artifactLabel;
- }
-
- public void setArtifactLabel(String artifactLabel) {
- this.artifactLabel = artifactLabel;
- }
-
- public String getArtifactGroupType() {
- return artifactGroupType;
- }
-
- public void setArtifactGroupType(String artifactGroupType) {
- this.artifactGroupType = artifactGroupType;
- }
+ private String artifactName;
+ private String artifactType;
+ private String artifactURL;
+ private String artifactDescription;
+ private Integer artifactTimeout;
+ private String artifactChecksum;
+ private String artifactUUID;
+ private String artifactVersion;
+ private String generatedFromUUID;
+ private String artifactLabel;
+ private String artifactGroupType;
+
+ 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 Integer getArtifactTimeout() {
+ return artifactTimeout;
+ }
+
+ public void setArtifactTimeout(Integer 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;
+ }
+
+ public String getArtifactLabel() {
+ return artifactLabel;
+ }
+
+ public void setArtifactLabel(String artifactLabel) {
+ this.artifactLabel = artifactLabel;
+ }
+
+ public String getArtifactGroupType() {
+ return artifactGroupType;
+ }
+
+ public void setArtifactGroupType(String artifactGroupType) {
+ this.artifactGroupType = artifactGroupType;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java
index cb14f76aff..b12411a7b3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java
@@ -21,109 +21,109 @@
package org.openecomp.sdc.be.externalapi.servlet.representation;
public abstract class AssetMetadata implements IAssetMetadata {
- private String uuid;
- private String invariantUUID;
- private String name;
- private String version;
- private String toscaModelURL;
+ private String uuid;
+ private String invariantUUID;
+ private String name;
+ private String version;
+ private String toscaModelURL;
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getUuid()
- */
- @Override
- public String getUuid() {
- return uuid;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getUuid()
+ */
+ @Override
+ public String getUuid() {
+ return uuid;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setUuid(java.lang.String)
- */
- @Override
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setUuid(java.lang.String)
+ */
+ @Override
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getInvariantUUID()
- */
- @Override
- public String getInvariantUUID() {
- return invariantUUID;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getInvariantUUID()
+ */
+ @Override
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setInvariantUUID(java.lang.String)
- */
- @Override
- public void setInvariantUUID(String invariantUUID) {
- this.invariantUUID = invariantUUID;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setInvariantUUID(java.lang.String)
+ */
+ @Override
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getName()
- */
- @Override
- public String getName() {
- return name;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getName()
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setName(java.lang.String)
- */
- @Override
- public void setName(String name) {
- this.name = name;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setName(java.lang.String)
+ */
+ @Override
+ public void setName(String name) {
+ this.name = name;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getVersion()
- */
- @Override
- public String getVersion() {
- return version;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# getVersion()
+ */
+ @Override
+ public String getVersion() {
+ return version;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setVersion(java.lang.String)
- */
- @Override
- public void setVersion(String version) {
- this.version = version;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# setVersion(java.lang.String)
+ */
+ @Override
+ public void setVersion(String version) {
+ this.version = version;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL()
- */
- @Override
- public String getToscaModelURL() {
- return toscaModelURL;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL()
+ */
+ @Override
+ public String getToscaModelURL() {
+ return toscaModelURL;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL(java.lang.String)
- */
- @Override
- public void setToscaModelURL(String toscaModelURL) {
- this.toscaModelURL = toscaModelURL;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.sdc.be.distribution.servlet.representation.IAssetMetadata# toscaModelURL(java.lang.String)
+ */
+ @Override
+ public void setToscaModelURL(String toscaModelURL) {
+ this.toscaModelURL = toscaModelURL;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java
index f95a8e9684..319e16a294 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java
@@ -22,24 +22,24 @@ package org.openecomp.sdc.be.externalapi.servlet.representation;
public interface IAssetMetadata {
- String getUuid();
+ String getUuid();
- void setUuid(String uuid);
+ void setUuid(String uuid);
- String getInvariantUUID();
+ String getInvariantUUID();
- void setInvariantUUID(String invariantUUID);
+ void setInvariantUUID(String invariantUUID);
- String getName();
+ String getName();
- void setName(String name);
+ void setName(String name);
- String getVersion();
+ String getVersion();
- void setVersion(String version);
+ void setVersion(String version);
- String getToscaModelURL();
+ String getToscaModelURL();
- void setToscaModelURL(String toscaModelURL);
+ void setToscaModelURL(String toscaModelURL);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java
index d2d9c2c902..40b78c12d3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java
@@ -23,50 +23,50 @@ package org.openecomp.sdc.be.externalapi.servlet.representation;
import java.util.List;
public class ProductAssetMetadata extends AssetMetadata {
- private String lifecycleState;
- private String lastUpdaterUserId;
- private boolean isActive;
- private List<String> contacts;
- private List<ProductCategoryGroupMetadata> productGroupings;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
+ private boolean isActive;
+ private List<String> contacts;
+ private List<ProductCategoryGroupMetadata> productGroupings;
- public String getLifecycleState() {
- return lifecycleState;
- }
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
- public void setLifecycleState(String lifecycleState) {
- this.lifecycleState = lifecycleState;
- }
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
- public String getLastUpdaterUserId() {
- return lastUpdaterUserId;
- }
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
- public void setLastUpdaterUserId(String lastUpdaterUserId) {
- this.lastUpdaterUserId = lastUpdaterUserId;
- }
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
- public boolean isActive() {
- return isActive;
- }
+ public boolean isActive() {
+ return isActive;
+ }
- public void setActive(boolean isActive) {
- this.isActive = isActive;
- }
+ public void setActive(boolean isActive) {
+ this.isActive = isActive;
+ }
- public List<String> getContacts() {
- return contacts;
- }
+ public List<String> getContacts() {
+ return contacts;
+ }
- public void setContacts(List<String> contacts) {
- this.contacts = contacts;
- }
+ public void setContacts(List<String> contacts) {
+ this.contacts = contacts;
+ }
- public List<ProductCategoryGroupMetadata> getProductGroupings() {
- return productGroupings;
- }
+ public List<ProductCategoryGroupMetadata> getProductGroupings() {
+ return productGroupings;
+ }
- public void setProductGroupings(List<ProductCategoryGroupMetadata> productGroupings) {
- this.productGroupings = productGroupings;
- }
+ public void setProductGroupings(List<ProductCategoryGroupMetadata> productGroupings) {
+ this.productGroupings = productGroupings;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java
index 047f9d6a2c..7d666df703 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java
@@ -21,37 +21,37 @@
package org.openecomp.sdc.be.externalapi.servlet.representation;
public class ProductCategoryGroupMetadata {
- private String category;
- private String subCategory;
- private String group;
-
- public ProductCategoryGroupMetadata(String category, String subCategory, String group) {
- this.category = category;
- this.subCategory = subCategory;
- this.group = group;
- }
-
- 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;
- }
-
- public String getGroup() {
- return group;
- }
-
- public void setGroup(String group) {
- this.group = group;
- }
+ private String category;
+ private String subCategory;
+ private String group;
+
+ public ProductCategoryGroupMetadata(String category, String subCategory, String group) {
+ this.category = category;
+ this.subCategory = subCategory;
+ this.group = group;
+ }
+
+ 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;
+ }
+
+ public String getGroup() {
+ return group;
+ }
+
+ public void setGroup(String group) {
+ this.group = group;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
index 0952feea05..eb15e077de 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
@@ -24,50 +24,50 @@ import java.util.List;
public class ResourceAssetDetailedMetadata extends ResourceAssetMetadata {
- private String lastUpdaterFullName;
- private String toscaResourceName;
- private List<ResourceInstanceMetadata> resources;
- private List<ArtifactMetadata> artifacts;
- private String description;
+ private String lastUpdaterFullName;
+ private String toscaResourceName;
+ private List<ResourceInstanceMetadata> resources;
+ private List<ArtifactMetadata> artifacts;
+ private String description;
- public String getLastUpdaterFullName() {
- return lastUpdaterFullName;
- }
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
- public void setLastUpdaterFullName(String lastUpdaterFullName) {
- this.lastUpdaterFullName = lastUpdaterFullName;
- }
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
- public String getToscaResourceName() {
- return toscaResourceName;
- }
+ public String getToscaResourceName() {
+ return toscaResourceName;
+ }
- public void setToscaResourceName(String toscaResourceName) {
- this.toscaResourceName = toscaResourceName;
- }
+ public void setToscaResourceName(String toscaResourceName) {
+ this.toscaResourceName = toscaResourceName;
+ }
- public List<ResourceInstanceMetadata> getResources() {
- return resources;
- }
+ public List<ResourceInstanceMetadata> getResources() {
+ return resources;
+ }
- public void setResources(List<ResourceInstanceMetadata> resources) {
- this.resources = resources;
- }
+ public void setResources(List<ResourceInstanceMetadata> resources) {
+ this.resources = resources;
+ }
- public List<ArtifactMetadata> getArtifacts() {
- return artifacts;
- }
+ public List<ArtifactMetadata> getArtifacts() {
+ return artifacts;
+ }
- public void setArtifacts(List<ArtifactMetadata> artifactMetaList) {
- this.artifacts = artifactMetaList;
- }
+ public void setArtifacts(List<ArtifactMetadata> artifactMetaList) {
+ this.artifacts = artifactMetaList;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
-
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java
index 2b75facc6c..455e125ffc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java
@@ -21,49 +21,49 @@
package org.openecomp.sdc.be.externalapi.servlet.representation;
public class ResourceAssetMetadata extends AssetMetadata {
- private String category;
- private String subCategory;
- private String resourceType;
- private String lifecycleState;
- private String lastUpdaterUserId;
+ private String category;
+ private String subCategory;
+ private String resourceType;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
- public String getCategory() {
- return category;
- }
+ public String getCategory() {
+ return category;
+ }
- public void setCategory(String category) {
- this.category = category;
- }
+ public void setCategory(String category) {
+ this.category = category;
+ }
- public String getSubCategory() {
- return subCategory;
- }
+ public String getSubCategory() {
+ return subCategory;
+ }
- public void setSubCategory(String subCategory) {
- this.subCategory = subCategory;
- }
+ public void setSubCategory(String subCategory) {
+ this.subCategory = subCategory;
+ }
- public String getResourceType() {
- return resourceType;
- }
+ public String getResourceType() {
+ return resourceType;
+ }
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
- public String getLifecycleState() {
- return lifecycleState;
- }
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
- public void setLifecycleState(String lifecycleState) {
- this.lifecycleState = lifecycleState;
- }
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
- public String getLastUpdaterUserId() {
- return lastUpdaterUserId;
- }
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
- public void setLastUpdaterUserId(String lastUpdaterUserId) {
- this.lastUpdaterUserId = lastUpdaterUserId;
- }
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
index a53422f311..1023f82249 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
@@ -23,67 +23,67 @@ package org.openecomp.sdc.be.externalapi.servlet.representation;
import java.util.List;
public class ResourceInstanceMetadata {
- private String resourceInstanceName;
- private String resourceName;
- private String resourceInvariantUUID;
- private String resourceVersion;
- private String resoucreType;
- private String resourceUUID;
- private List<ArtifactMetadata> 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<ArtifactMetadata> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<ArtifactMetadata> artifacts) {
- this.artifacts = artifacts;
- }
+ private String resourceInstanceName;
+ private String resourceName;
+ private String resourceInvariantUUID;
+ private String resourceVersion;
+ private String resoucreType;
+ private String resourceUUID;
+ private List<ArtifactMetadata> 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<ArtifactMetadata> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<ArtifactMetadata> artifacts) {
+ this.artifacts = artifacts;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java
index edd88b495d..e677fdc190 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java
@@ -23,31 +23,31 @@ package org.openecomp.sdc.be.externalapi.servlet.representation;
import java.util.List;
public class ServiceAssetDetailedMetadata extends ServiceAssetMetadata {
- private String lastUpdaterFullName;
- private List<ResourceInstanceMetadata> resources;
- private List<ArtifactMetadata> artifacts;
+ private String lastUpdaterFullName;
+ private List<ResourceInstanceMetadata> resources;
+ private List<ArtifactMetadata> artifacts;
- public String getLastUpdaterFullName() {
- return lastUpdaterFullName;
- }
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
- public void setLastUpdaterFullName(String lastUpdaterFullName) {
- this.lastUpdaterFullName = lastUpdaterFullName;
- }
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
- public List<ResourceInstanceMetadata> getResources() {
- return resources;
- }
+ public List<ResourceInstanceMetadata> getResources() {
+ return resources;
+ }
- public void setResources(List<ResourceInstanceMetadata> resources) {
- this.resources = resources;
- }
+ public void setResources(List<ResourceInstanceMetadata> resources) {
+ this.resources = resources;
+ }
- public List<ArtifactMetadata> getArtifacts() {
- return artifacts;
- }
+ public List<ArtifactMetadata> getArtifacts() {
+ return artifacts;
+ }
- public void setArtifacts(List<ArtifactMetadata> artifacts) {
- this.artifacts = artifacts;
- }
+ public void setArtifacts(List<ArtifactMetadata> artifacts) {
+ this.artifacts = artifacts;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java
index 094f973553..6e5ac8426c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java
@@ -21,40 +21,40 @@
package org.openecomp.sdc.be.externalapi.servlet.representation;
public class ServiceAssetMetadata extends AssetMetadata {
- private String category;
- private String lifecycleState;
- private String lastUpdaterUserId;
- private String distributionStatus;
-
- 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;
- }
-
- public String getDistributionStatus() {
- return distributionStatus;
- }
-
- public void setDistributionStatus(String distributionStatus) {
- this.distributionStatus = distributionStatus;
- }
+ private String category;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
+ private String distributionStatus;
+
+ 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;
+ }
+
+ public String getDistributionStatus() {
+ return distributionStatus;
+ }
+
+ public void setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java
new file mode 100644
index 0000000000..5557c7a609
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.externalapi.servlet.representation;
+
+/**
+ * Created by chaya on 10/26/2017.
+ */
+public class ServiceDistributionReqInfo {
+
+ private String workloadContext;
+
+ public ServiceDistributionReqInfo() {
+ }
+ public ServiceDistributionReqInfo(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java
new file mode 100644
index 0000000000..3fa54c3654
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java
@@ -0,0 +1,24 @@
+package org.openecomp.sdc.be.externalapi.servlet.representation;
+
+/**
+ * Created by chaya on 10/26/2017.
+ */
+public class ServiceDistributionRespInfo {
+
+ private String distributionId;
+
+ public ServiceDistributionRespInfo() {
+ }
+
+ public ServiceDistributionRespInfo(String distributionId) {
+ this.distributionId = distributionId;
+ }
+
+ public String getDistributionId() {
+ return distributionId;
+ }
+
+ public void setDistributionId(String distributionId) {
+ this.distributionId = distributionId;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
index de95790f4e..841cd3225d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
@@ -20,27 +20,15 @@
package org.openecomp.sdc.be.filters;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.StringTokenizer;
-
-import javax.annotation.Priority;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ConsumerDefinition;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.exception.ResponseFormat;
import org.openecomp.sdc.security.Passwords;
@@ -48,178 +36,186 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
+import javax.annotation.Priority;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.StringTokenizer;
@Priority(10)
public class BasicAuthenticationFilter implements ContainerRequestFilter {
- @Context
- private HttpServletRequest sr;
-
- protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- private String realm = "ASDC";
-
- private static Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class.getName());
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
-
- String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER);
- if (authHeader != null) {
- StringTokenizer st = new StringTokenizer(authHeader);
- if (st.hasMoreTokens()) {
- String basic = st.nextToken();
-
- if (basic.equalsIgnoreCase("Basic")) {
- try {
- String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
- log.debug("Credentials: {}" , credentials);
- checkUserCredentiles(requestContext, credentials);
- } catch (UnsupportedEncodingException e) {
- log.error("Authentication Filter Failed Couldn't retrieve authentication", e);
- authInvalidHeaderError(requestContext);
- }
- } else {
- log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication.");
- authInvalidHeaderError(requestContext);
- }
- } else {
- log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication.");
- authInvalidHeaderError(requestContext);
- }
-
- } else {
- log.error("Authentication Filter Failed no autharization header");
- authRequiredError(requestContext);
- }
- }
-
- private void checkUserCredentiles(ContainerRequestContext requestContext, String credentials) {
- int p = credentials.indexOf(":");
- if (p != -1) {
- String _username = credentials.substring(0, p).trim();
- String _password = credentials.substring(p + 1).trim();
-
- ConsumerBusinessLogic consumerBL = getConsumerBusinessLogic();
- if (consumerBL == null) {
- log.error("Authentication Filter Failed to get consumerBL.");
- requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
- } else {
- Either<ConsumerDefinition, ResponseFormat> result = consumerBL.getConsumer(_username);
- validatePassword(requestContext, _username, _password, result);
- }
- } else {
- log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication.");
- authInvalidHeaderError(requestContext);
-
- }
- }
-
- private void validatePassword(ContainerRequestContext requestContext, String _username, String _password, Either<ConsumerDefinition, ResponseFormat> result) {
- if (result.isRight()) {
- Integer status = result.right().value().getStatus();
- if (status == Status.NOT_FOUND.getStatusCode()) {
- log.error("Authentication Filter Failed Couldn't find user");
- authUserNotFoundError(requestContext, _username);
- } else {
- log.error("Authentication Filter Failed to get consumerBL.");
- requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
- }
- } else {
- ConsumerDefinition consumerCredentials = result.left().value();
- if (!Passwords.isExpectedPassword(_password, consumerCredentials.getConsumerSalt(), consumerCredentials.getConsumerPassword())) {
- log.error("Authentication Filter Failed invalide password");
- authInvalidePasswordError(requestContext, _username);
- } else {
- authSuccesessful(requestContext, _username);
- }
- }
- }
-
- private void authSuccesessful(ContainerRequestContext requestContext, String _username) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- log.error("Authentication Filter Failed to get component utils.");
- requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
- }
- componentUtils.auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_SUCCESS.toString(), realm);
- }
-
- private void authInvalidePasswordError(ContainerRequestContext requestContext, String _username) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- log.error("Authentication Filter Failed to get component utils.");
- requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
- }
- componentUtils.auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
- requestContext.abortWith(buildErrorResponse(responseFormat, false));
- }
-
- private void authUserNotFoundError(ContainerRequestContext requestContext, String _username) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- log.error("Authentication Filter Failed to get component utils.");
- requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
- }
- getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_USER_NOT_FOUND.toString(), realm);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
- requestContext.abortWith(buildErrorResponse(responseFormat, false));
- }
-
- private void authInvalidHeaderError(ContainerRequestContext requestContext) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- log.error("Authentication Filter Failed to get component utils.");
- requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
- }
- getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER);
- requestContext.abortWith(buildErrorResponse(responseFormat, false));
- }
-
- private void authRequiredError(ContainerRequestContext requestContext) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- log.error("Authentication Filter Failed to get component utils.");
- requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
- }
- getComponentsUtils().auditAuthEvent(AuditingActionEnum.AUTH_REQUEST, requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED);
- requestContext.abortWith(buildErrorResponse(responseFormat, true));
- }
-
- private ComponentsUtils getComponentsUtils() {
- ServletContext context = sr.getSession().getServletContext();
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class);
- return componentsUtils;
- }
-
- private ConsumerBusinessLogic getConsumerBusinessLogic() {
- ServletContext context = sr.getSession().getServletContext();
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class);
- return consumerBusinessLogic;
- }
-
- public enum AuthStatus {
- AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS
- }
-
- protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) {
- ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus());
- if (addWwwAuthenticationHeader) {
- responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
- }
- Response response = responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
- return response;
- }
+ @Context
+ private HttpServletRequest sr;
+
+ protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ private String realm = "ASDC";
+
+ private static final Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class);
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+
+ String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER);
+ if (authHeader != null) {
+ StringTokenizer st = new StringTokenizer(authHeader);
+ if (st.hasMoreTokens()) {
+ String basic = st.nextToken();
+
+ if (basic.equalsIgnoreCase("Basic")) {
+ try {
+ String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
+ log.debug("Credentials: {}" , credentials);
+ checkUserCredentiles(requestContext, credentials);
+ } catch (UnsupportedEncodingException e) {
+ log.error("Authentication Filter Failed Couldn't retrieve authentication", e);
+ authInvalidHeaderError(requestContext);
+ }
+ } else {
+ log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication.");
+ authInvalidHeaderError(requestContext);
+ }
+ } else {
+ log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication.");
+ authInvalidHeaderError(requestContext);
+ }
+
+ } else {
+ log.error("Authentication Filter Failed no autharization header");
+ authRequiredError(requestContext);
+ }
+ }
+
+ private void checkUserCredentiles(ContainerRequestContext requestContext, String credentials) {
+ int p = credentials.indexOf(":");
+ if (p != -1) {
+ String _username = credentials.substring(0, p).trim();
+ String _password = credentials.substring(p + 1).trim();
+
+ ConsumerBusinessLogic consumerBL = getConsumerBusinessLogic();
+ if (consumerBL == null) {
+ log.error("Authentication Filter Failed to get consumerBL.");
+ requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
+ } else {
+ Either<ConsumerDefinition, ResponseFormat> result = consumerBL.getConsumer(_username);
+ validatePassword(requestContext, _username, _password, result);
+ }
+ } else {
+ log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic autantication.");
+ authInvalidHeaderError(requestContext);
+
+ }
+ }
+
+ private void validatePassword(ContainerRequestContext requestContext, String _username, String _password, Either<ConsumerDefinition, ResponseFormat> result) {
+ if (result.isRight()) {
+ Integer status = result.right().value().getStatus();
+ if (status == Status.NOT_FOUND.getStatusCode()) {
+ log.error("Authentication Filter Failed Couldn't find user");
+ authUserNotFoundError(requestContext, _username);
+ } else {
+ log.error("Authentication Filter Failed to get consumerBL.");
+ requestContext.abortWith(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ } else {
+ ConsumerDefinition consumerCredentials = result.left().value();
+ if (!Passwords.isExpectedPassword(_password, consumerCredentials.getConsumerSalt(), consumerCredentials.getConsumerPassword())) {
+ log.error("Authentication Filter Failed invalide password");
+ authInvalidePasswordError(requestContext, _username);
+ } else {
+ authSuccesessful(requestContext, _username);
+ }
+ }
+ }
+
+ private void authSuccesessful(ContainerRequestContext requestContext, String _username) {
+ ComponentsUtils componentUtils = getComponentsUtils();
+ if (componentUtils == null) {
+ log.error("Authentication Filter Failed to get component utils.");
+ requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_SUCCESS.toString(), realm);
+ }
+
+ private void authInvalidePasswordError(ContainerRequestContext requestContext, String _username) {
+ ComponentsUtils componentUtils = getComponentsUtils();
+ if (componentUtils == null) {
+ log.error("Authentication Filter Failed to get component utils.");
+ requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
+ requestContext.abortWith(buildErrorResponse(responseFormat, false));
+ }
+
+ private void authUserNotFoundError(ContainerRequestContext requestContext, String _username) {
+ ComponentsUtils componentUtils = getComponentsUtils();
+ if (componentUtils == null) {
+ log.error("Authentication Filter Failed to get component utils.");
+ requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), _username, AuthStatus.AUTH_FAILED_USER_NOT_FOUND.toString(), realm);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
+ requestContext.abortWith(buildErrorResponse(responseFormat, false));
+ }
+
+ private void authInvalidHeaderError(ContainerRequestContext requestContext) {
+ ComponentsUtils componentUtils = getComponentsUtils();
+ if (componentUtils == null) {
+ log.error("Authentication Filter Failed to get component utils.");
+ requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER);
+ requestContext.abortWith(buildErrorResponse(responseFormat, false));
+ }
+
+ private void authRequiredError(ContainerRequestContext requestContext) {
+ ComponentsUtils componentUtils = getComponentsUtils();
+ if (componentUtils == null) {
+ log.error("Authentication Filter Failed to get component utils.");
+ requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED);
+ requestContext.abortWith(buildErrorResponse(responseFormat, true));
+ }
+
+ private ComponentsUtils getComponentsUtils() {
+ ServletContext context = sr.getSession().getServletContext();
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class);
+ return componentsUtils;
+ }
+
+ private ConsumerBusinessLogic getConsumerBusinessLogic() {
+ ServletContext context = sr.getSession().getServletContext();
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class);
+ return consumerBusinessLogic;
+ }
+
+ public enum AuthStatus {
+ AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS
+ }
+
+ protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) {
+ ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus());
+ if (addWwwAuthenticationHeader) {
+ responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
+ }
+ Response response = responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
+ return response;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
index d24743534c..60409b3ee0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
@@ -20,20 +20,7 @@
package org.openecomp.sdc.be.filters;
-import java.io.IOException;
-import java.util.UUID;
-
-import javax.annotation.Priority;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.container.ContainerResponseFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.Provider;
-
+import com.google.gson.GsonBuilder;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -50,171 +37,180 @@ import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.GsonBuilder;
+import javax.annotation.Priority;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.Provider;
+import java.io.IOException;
+import java.util.UUID;
@Provider
@Priority(1)
public class BeServletFilter implements ContainerRequestFilter, ContainerResponseFilter {
- @Context
- private HttpServletRequest sr;
-
- private static Logger log = LoggerFactory.getLogger(BeServletFilter.class.getName());
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
- try {
-
- MDC.clear();
-
- // In case of 405 response code, this function is not entered, then
- // we'll process
- // the MDC fields and UUID during the response
- ThreadLocalsHolder.setMdcProcessed(true);
-
- // Timing HTTP request
- ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis());
-
- String uuid = processMdcFields(requestContext);
-
- ThreadLocalsHolder.setUuid(uuid);
-
- inHttpRequest();
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Error during request filter");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter");
- log.debug("Error during request filter: {} ", e);
- }
- }
-
- @Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
- try {
- // Formatting the response in case of 405
- if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED);
- responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError()));
- }
-
- if (ThreadLocalsHolder.isMdcProcessed()) {
- // filter() was executed during request - this is the regular
- // flow
- responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid());
- Long startTime = ThreadLocalsHolder.getRequestStartTime();
- if (startTime != null) {
- long endTime = System.currentTimeMillis();
- MDC.put("timer", Long.toString(endTime - startTime));
- }
- } else {
- // this is the 405 response code case
- // we have no MDC fields since filter() wasn't executed during
- // request
- String uuid = processMdcFields(requestContext);
- responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid);
- }
-
- outHttpResponse(responseContext);
-
- log.debug("Close transaction from filter");
- TitanDao titanDao = getTitanDao();
- if ( titanDao != null ){
- if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){
- titanDao.commit();
- log.debug("Doing commit from filter");
- }else{
- titanDao.rollback();
- log.debug("Doing rollback from filter");
- }
- }
- // Cleaning up
- MDC.clear();
- ThreadLocalsHolder.cleanup();
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Error during request filter");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter");
- log.debug("Error during response filter: {} ", e);
- }
- }
-
- private String processMdcFields(ContainerRequestContext requestContext) {
- // UserId for logging
- String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER);
- MDC.put("userId", userId);
-
- String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER);
- MDC.put("serviceInstanceID", serviceInstanceID);
-
- MDC.put("remoteAddr", sr.getRemoteAddr());
- MDC.put("localAddr", sr.getLocalAddr());
-
- // UUID
- String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER);
- if (uuid == null) {
- // Generate the UUID
- uuid = UUID.randomUUID().toString();
-
- // Add to MDC for logging
- MDC.put("uuid", uuid);
-
- // This log message should already be with the UUID
- uuidGeneration(uuid);
-
- } else {
- // According to Ella, in case this header exists, we don't have to
- // perform any validations
- // since it's not our responsibilty, so we log the UUID just as it
- // was received.
- MDC.put("uuid", uuid);
- }
- return uuid;
- }
-
- private ComponentsUtils getComponentsUtils() {
- ServletContext context = this.sr.getSession().getServletContext();
-
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- return webApplicationContext.getBean(ComponentsUtils.class);
- }
- private TitanDao getTitanDao() {
- ServletContext context = this.sr.getSession().getServletContext();
-
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- return webApplicationContext.getBean(TitanDao.class);
- }
- // Extracted for purpose of clear method name, for logback %M parameter
- private void inHttpRequest() {
- if (isInfoLog()) {
- log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol());
- } else {
- log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol());
- }
- }
-
- // Extracted for purpose of clear method name, for logback %M parameter
- private void outHttpResponse(ContainerResponseContext responseContext) {
- if (isInfoLog()) {
- log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus());
- } else {
- log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus());
- }
- }
-
- private boolean isInfoLog() {
- boolean logRequest = true;
- Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
- String requestURI = sr.getRequestURI();
- if (requestURI != null && configuration.getUnLoggedUrls() != null) {
- logRequest = !configuration.getUnLoggedUrls().contains(requestURI);
- }
-
- return logRequest;
- }
-
- // Extracted for purpose of clear method name, for logback %M parameter
- private void uuidGeneration(String uuid) {
- log.info("No requestID provided -> Generated UUID {}", uuid);
- }
+ @Context
+ private HttpServletRequest sr;
+
+ private static final Logger log = LoggerFactory.getLogger(BeServletFilter.class);
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+ try {
+
+ MDC.clear();
+
+ // In case of 405 response code, this function is not entered, then
+ // we'll process
+ // the MDC fields and UUID during the response
+ ThreadLocalsHolder.setMdcProcessed(true);
+
+ // Timing HTTP request
+ ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis());
+
+ String uuid = processMdcFields(requestContext);
+
+ ThreadLocalsHolder.setUuid(uuid);
+
+ inHttpRequest();
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter");
+ log.debug("Error during request filter: {} ", e);
+ }
+ }
+
+ @Override
+ public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
+ try {
+ // Formatting the response in case of 405
+ if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED);
+ responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError()));
+ }
+
+ if (ThreadLocalsHolder.isMdcProcessed()) {
+ // filter() was executed during request - this is the regular
+ // flow
+ responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid());
+ Long startTime = ThreadLocalsHolder.getRequestStartTime();
+ if (startTime != null) {
+ long endTime = System.currentTimeMillis();
+ MDC.put("timer", Long.toString(endTime - startTime));
+ }
+ } else {
+ // this is the 405 response code case
+ // we have no MDC fields since filter() wasn't executed during
+ // request
+ String uuid = processMdcFields(requestContext);
+ responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid);
+ }
+
+ outHttpResponse(responseContext);
+
+ log.debug("Close transaction from filter");
+ TitanDao titanDao = getTitanDao();
+ if ( titanDao != null ){
+ if (responseContext.getStatus() == Response.Status.OK.getStatusCode() || responseContext.getStatus() == Response.Status.CREATED.getStatusCode() ){
+ titanDao.commit();
+ log.debug("Doing commit from filter");
+ }else{
+ titanDao.rollback();
+ log.debug("Doing rollback from filter");
+ }
+ }
+ // Cleaning up
+ MDC.clear();
+ ThreadLocalsHolder.cleanup();
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter");
+ log.debug("Error during response filter: {} ", e);
+ }
+ }
+
+ private String processMdcFields(ContainerRequestContext requestContext) {
+ // UserId for logging
+ String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER);
+ MDC.put("userId", userId);
+
+ String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER);
+ MDC.put("serviceInstanceID", serviceInstanceID);
+
+ MDC.put("remoteAddr", sr.getRemoteAddr());
+ MDC.put("localAddr", sr.getLocalAddr());
+
+ // UUID
+ String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER);
+ if (uuid == null) {
+ // Generate the UUID
+ uuid = UUID.randomUUID().toString();
+
+ // Add to MDC for logging
+ MDC.put("uuid", uuid);
+
+ // This log message should already be with the UUID
+ uuidGeneration(uuid);
+
+ } else {
+ // According to Ella, in case this header exists, we don't have to
+ // perform any validations
+ // since it's not our responsibilty, so we log the UUID just as it
+ // was received.
+ MDC.put("uuid", uuid);
+ }
+ return uuid;
+ }
+
+ private ComponentsUtils getComponentsUtils() {
+ ServletContext context = this.sr.getSession().getServletContext();
+
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(ComponentsUtils.class);
+ }
+ private TitanDao getTitanDao() {
+ ServletContext context = this.sr.getSession().getServletContext();
+
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(TitanDao.class);
+ }
+ // Extracted for purpose of clear method name, for logback %M parameter
+ private void inHttpRequest() {
+ if (isInfoLog()) {
+ log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol());
+ } else {
+ log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol());
+ }
+ }
+
+ // Extracted for purpose of clear method name, for logback %M parameter
+ private void outHttpResponse(ContainerResponseContext responseContext) {
+ if (isInfoLog()) {
+ log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus());
+ } else {
+ log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus());
+ }
+ }
+
+ private boolean isInfoLog() {
+ boolean logRequest = true;
+ Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
+ String requestURI = sr.getRequestURI();
+ if (requestURI != null && configuration.getUnLoggedUrls() != null) {
+ logRequest = !configuration.getUnLoggedUrls().contains(requestURI);
+ }
+
+ return logRequest;
+ }
+
+ // Extracted for purpose of clear method name, for logback %M parameter
+ private void uuidGeneration(String uuid) {
+ log.info("No requestID provided -> Generated UUID {}", uuid);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java
index c572e2e552..b80ee4c324 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java
@@ -20,21 +20,9 @@
package org.openecomp.sdc.be.filters;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.annotation.Priority;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-
-import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
@@ -46,77 +34,87 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.annotation.Priority;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
@Priority(11)
public class ComponentsAvailabilityFilter implements ContainerRequestFilter {
- @Context
- protected HttpServletRequest sr;
- protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
- private static Logger log = LoggerFactory.getLogger(ComponentsAvailabilityFilter.class.getName());
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
-
- String requestUrl = requestContext.getUriInfo().getPath();
- if (!requestUrl.equals("healthCheck")) {
- List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext());
- ActionStatus status = getAggregateBeStatus(beHealthCheckInfos);
-
- if (!status.equals(ActionStatus.OK)) {
- log.error("Components Availability Filter Failed - ES/Cassandra is DOWN");
- availabilityError(requestContext);
- }
- }
-
- }
-
- protected ActionStatus getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
- ActionStatus status = ActionStatus.OK;
- for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
- if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) {
- status = ActionStatus.GENERAL_ERROR;
- break;
- }
- }
- return status;
- }
-
- protected List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) {
-
- List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>();
- HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext);
- healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan
- return healthCheckInfos;
- }
-
- protected ComponentsUtils getComponentsUtils() {
- ServletContext context = sr.getSession().getServletContext();
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class);
- return componentsUtils;
- }
-
- protected void availabilityError(ContainerRequestContext requestContext) {
- ComponentsUtils componentUtils = getComponentsUtils();
- if (componentUtils == null) {
- log.error("Components Availability Filter Failed to get component utils.");
- requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
- }
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus());
- Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build();
- requestContext.abortWith(response);
- }
-
- private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
- return healthCheckBl;
- }
+ @Context
+ protected HttpServletRequest sr;
+ protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ private static final Logger log = LoggerFactory.getLogger(ComponentsAvailabilityFilter.class);
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+
+ String requestUrl = requestContext.getUriInfo().getPath();
+ if (!requestUrl.equals("healthCheck")) {
+ List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext());
+ ActionStatus status = getAggregateBeStatus(beHealthCheckInfos);
+
+ if (!status.equals(ActionStatus.OK)) {
+ log.error("Components Availability Filter Failed - ES/Cassandra is DOWN");
+ availabilityError(requestContext);
+ }
+ }
+
+ }
+
+ protected ActionStatus getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
+ ActionStatus status = ActionStatus.OK;
+ for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
+ if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) {
+ status = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ }
+ return status;
+ }
+
+ protected List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) {
+
+ List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>();
+ HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext);
+ healthCheckBusinessLogic.getTitanHealthCheck(healthCheckInfos); // Titan
+ return healthCheckInfos;
+ }
+
+ protected ComponentsUtils getComponentsUtils() {
+ ServletContext context = sr.getSession().getServletContext();
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class);
+ return componentsUtils;
+ }
+
+ protected void availabilityError(ContainerRequestContext requestContext) {
+ ComponentsUtils componentUtils = getComponentsUtils();
+ if (componentUtils == null) {
+ log.error("Components Availability Filter Failed to get component utils.");
+ requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build());
+ }
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus());
+ Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build();
+ requestContext.abortWith(response);
+ }
+
+ private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
+ return healthCheckBl;
+ }
}
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 910521c8dc..566daec5e7 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
@@ -20,23 +20,24 @@
package org.openecomp.sdc.be.impl;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import javax.annotation.PostConstruct;
-import javax.servlet.http.HttpServletRequest;
-
-import org.codehaus.jackson.Version;
-import org.codehaus.jackson.map.DeserializationConfig;
-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 com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditAuthRequestEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditConsumerEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditEcompOpEnvEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditResourceEventFactoryMananger;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.auditing.impl.distribution.AuditDistribDownloadEventFactory;
+import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAccessEventFactory;
+import org.openecomp.sdc.be.auditing.impl.usersadmin.AuditUserAdminEventFactory;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -46,7 +47,6 @@ 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;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ConsumerDefinition;
@@ -56,12 +56,14 @@ import org.openecomp.sdc.be.model.PolicyTypeDefinition;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
@@ -71,1451 +73,1370 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import javax.servlet.http.HttpServletRequest;
+import java.lang.reflect.Type;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
@org.springframework.stereotype.Component("componentUtils")
public class ComponentsUtils {
- @javax.annotation.Resource
- private IAuditingManager auditingManager;
-
- private ResponseFormatManager responseFormatManager;
-
- private static Logger log = LoggerFactory.getLogger(ComponentsUtils.class.getName());
-
- @PostConstruct
- public void Init() {
- this.responseFormatManager = ResponseFormatManager.getInstance();
- }
-
- public IAuditingManager getAuditingManager() {
- return auditingManager;
- }
-
- public void setAuditingManager(IAuditingManager auditingManager) {
- this.auditingManager = auditingManager;
- }
-
- public <T> Either<T, ResponseFormat> convertJsonToObject(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum) {
- if (data == null) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("object is null after converting from json");
- ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum);
- return Either.right(responseFormat);
- }
- try {
- T obj = parseJsonToObject(data, clazz);
- return Either.left(obj);
- } catch (Exception e) {
- // INVALID JSON
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("failed to convert from json {}", data, e);
- ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum);
- return Either.right(responseFormat);
- }
- }
-
- public static <T> T parseJsonToObject(String data, Class<T> clazz) {
- Type constraintType = new TypeToken<PropertyConstraint>() {
- }.getType();
- Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
- log.trace("convert json to object. json=\n{}", data);
- T resource = gson.fromJson(data, clazz);
- return resource;
- }
-
- public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
- T component = null;
- ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- try {
- log.trace("convert json to object. json=\n{}", data);
-
- final SimpleModule module = new SimpleModule("customerSerializationModule", new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
- //
- mapper.registerModule(module);
-
- component = mapper.readValue(data, clazz);
- if (component == null) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("object is null after converting from json");
- ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum);
- return Either.right(responseFormat);
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("failed to convert from json {}", data, e);
- ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum);
- return Either.right(responseFormat);
- }
- return Either.left(component);
- }
-
- public <T> void addDeserializer(SimpleModule module, Class<T> clazz, final JsonDeserializer<T> deserializer) {
- module.addDeserializer(clazz, deserializer);
- }
-
- // Error response
-
- public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) {
- return responseFormatManager.getResponseFormat(actionStatus, params);
- }
-
- public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) {
- return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params);
- }
-
- /**
- * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he
- * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields.
- *
- * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service.
- *
- * @param actionStatus
- * @param resource
- * @return
- */
- public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) {
- if (resource == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case COMPONENT_VERSION_ALREADY_EXIST:
- responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion());
- break;
- case RESOURCE_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName());
- break;
- case COMPONENT_NAME_ALREADY_EXIST:
- responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- break;
- case COMPONENT_IN_USE:
- responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId());
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) {
- if (resourceName == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case RESOURCE_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName);
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) {
- if (capabilityType == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case CAPABILITY_TYPE_ALREADY_EXIST:
- responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType());
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public <T> ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) {
- if (obj == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat = null;
-
- switch (actionStatus) {
- case MISSING_CAPABILITY_TYPE:
- if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List<?>) obj)){
- List<?> list = (List<?>)obj;
- if ( list.get(0) instanceof RequirementDefinition ) {
- responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object
- return responseFormat;
- }
- }
- log.debug("UNKNOWN TYPE : expecting obj as a non empty List<RequirmentsDefinitions>");
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- /**
- * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he
- * received. It's caller's responisibility to fill the passed resource object with needed fields.
- *
- * @param actionStatus
- * @param user
- * @return
- */
- public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) {
- if (user == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat requestErrorWrapper;
- switch (actionStatus) {
- case INVALID_USER_ID:
- requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId());
- break;
- case INVALID_EMAIL_ADDRESS:
- requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail());
- break;
- case INVALID_ROLE:
- requestErrorWrapper = getResponseFormat(actionStatus, user.getRole());
- break;
- case USER_NOT_FOUND:
- case USER_ALREADY_EXIST:
- case USER_INACTIVE:
- case USER_HAS_ACTIVE_ELEMENTS:
- requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId());
- break;
- default:
- requestErrorWrapper = getResponseFormat(actionStatus);
- break;
- }
- return requestErrorWrapper;
- }
-
- public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) {
- User user = new User();
- user.setUserId(userId);
- return getResponseFormatByUser(actionStatus, user);
- }
-
- public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String serviceId, String envName) {
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE:
- responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName);
- break;
- case DISTRIBUTION_ENVIRONMENT_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName);
- break;
- case DISTRIBUTION_ARTIFACT_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND, serviceId);
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) {
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case RESOURCE_NOT_FOUND:
- case ARTIFACT_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) {
- ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
- log.debug("audit before sending response");
- auditResource(responseFormat, user, null, "", "", actionEnum, null);
- return responseFormat;
- }
-
- public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
- ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
- log.debug("audit before sending response");
- auditComponentAdmin(responseFormat, user, null, "", "", actionEnum, typeEnum);
- return responseFormat;
- }
-
- public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String prevState, String prevVersion, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- if (actionEnum != null) {
- log.trace("Inside auditing for audit action {}", actionEnum.name());
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
-
- updateUserFields(modifier, auditingFields);
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, ComponentTypeEnum.RESOURCE.getValue());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState);
- if (resource != null) {
- // fields that are filled during creation and might still be
- // empty
- String resourceCurrVersion = (resource.getVersion() != null) ? resource.getVersion() : "";
- String resourceCurrState = (resource.getLifecycleState() != null) ? resource.getLifecycleState().name() : "";
- String uuid = (resource.getUUID() != null) ? resource.getUUID() : "";
- String invariantUUID = (resource.getInvariantUUID() != null) ? resource.getInvariantUUID() : "";
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, resourceCurrVersion);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, resourceCurrState);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, invariantUUID);
-
- } else {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- // In those specific cases we want some specific fields from
- // resource object
- switch (actionEnum) {
- case IMPORT_RESOURCE:
- if (resource != null) {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, resource.getToscaResourceName());
- } else {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, "");
- }
- break;
- default:
- break;
- }
-
- // This is to add/overwrite anything set in this function if some
- // params were passed from above,
- // for example resourceName of resource import
- if (additionalParams != null) {
- auditingFields.putAll(additionalParams);
- }
-
- getAuditingManager().auditEvent(auditingFields);
- }
- }
-
- private void updateUserFields(User modifier, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- if (modifier != null) {
- String firstName = modifier.getFirstName();
- String lastName = modifier.getLastName();
- if (firstName != null || lastName != null) {// to prevent "null
- // null" names
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, firstName + " " + lastName);
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- }
- }
-
- public void auditDistributionDownload(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- log.trace("Inside auditing for audit action {}", actionEnum.name());
- int status = responseFormat.getStatus();
- String message = "";
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- // This is to add/overwrite anything set in this function if some params
- // were passed from above,
- // for example resourceName of resource import
- if (additionalParams != null) {
- auditingFields.putAll(additionalParams);
- }
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- log.trace("Inside auditing for audit action {}", actionEnum.name());
- int status = responseFormat.getStatus();
- String message = "";
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- if (additionalParams != null) {
- auditingFields.putAll(additionalParams);
- }
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- log.trace("Inside auditing for audit action {}", actionEnum);
- String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
- String requestURI = request.getRequestURI();
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- int status = 0;
- String message = "";
- if(responseFormat != null){
- status = responseFormat.getStatus();
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- if (additionalParams != null) {
- auditingFields.putAll(additionalParams);
- if(!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)){
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
- }
- }
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams);
- }
-
- public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
- auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams);
- }
-
- public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
- auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams);
- }
-
- public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
- additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
- auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams);
- }
-
- public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) {
- log.trace("Inside auditing for audit action {}", actionEnum.name());
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- updateUserFields(modifier, auditingFields);
- // String componentTypeStr = (componentTypeEnum != null ?
- // componentTypeEnum.getValue() : null);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType);
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, categoryName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, subCategoryName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, groupingName);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) {
-
- return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE);
- }
-
- public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) {
-
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
- if (storageResponse == null) {
- return responseEnum;
- }
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case CONNECTION_FAILURE:
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
- break;
- case PARENT_RESOURCE_NOT_FOUND:
- responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND;
- break;
- case MULTIPLE_PARENT_RESOURCE_FOUND:
- responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND;
- break;
- case NOT_FOUND:
- if (ComponentTypeEnum.RESOURCE == type) {
- responseEnum = ActionStatus.RESOURCE_NOT_FOUND;
- } else if (ComponentTypeEnum.PRODUCT == type) {
- responseEnum = ActionStatus.PRODUCT_NOT_FOUND;
- } else {
- responseEnum = ActionStatus.SERVICE_NOT_FOUND;
- }
- break;
- case FAILED_TO_LOCK_ELEMENT:
- responseEnum = ActionStatus.COMPONENT_IN_USE;
- break;
- case ARTIFACT_NOT_FOUND:
- responseEnum = ActionStatus.ARTIFACT_NOT_FOUND;
- break;
- case DISTR_ENVIRONMENT_NOT_AVAILABLE:
- responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE;
- break;
- case DISTR_ENVIRONMENT_NOT_FOUND:
- responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND;
- break;
- case DISTR_ENVIRONMENT_SENT_IS_INVALID:
- responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID;
- break;
- case DISTR_ARTIFACT_NOT_FOUND:
- responseEnum = ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND;
- break;
- case INVALID_TYPE:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case INVALID_VALUE:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case CSAR_NOT_FOUND:
- responseEnum = ActionStatus.CSAR_NOT_FOUND;
- break;
- case PROPERTY_NAME_ALREADY_EXISTS:
- responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS;
- break;
- case MATCH_NOT_FOUND:
- responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY;
- break;
- case CATEGORY_NOT_FOUND:
- responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
- break;
- case INVALID_PROPERTY:
- responseEnum = ActionStatus.INVALID_PROPERTY;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ActionStatus convertFromToscaError(ToscaError toscaError) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
- if (toscaError == null) {
- return responseEnum;
- }
- switch (toscaError) {// TODO match errors
- case NODE_TYPE_CAPABILITY_ERROR:
- case NOT_SUPPORTED_TOSCA_TYPE:
- case NODE_TYPE_REQUIREMENT_ERROR:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- return responseEnum;
- }
-
- public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case CONNECTION_FAILURE:
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case CONNECTION_FAILURE:
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case INVALID_ID:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
- break;
- case INVALID_PROPERTY:
- responseEnum = ActionStatus.INVALID_PROPERTY;
- break;
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case MATCH_NOT_FOUND:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
- break;
- case NOT_FOUND:
- if (isRelation) {
- responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND;
- } else {
- responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
- }
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) {
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case RESOURCE_INSTANCE_NOT_FOUND:
- responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
- break;
- default:
- responseFormat = getResponseFormat(actionStatus, serviceName);
- break;
- }
- return responseFormat;
- }
-
- public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) {
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case RESOURCE_INSTANCE_NOT_FOUND:
- responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case INVALID_ID:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
- break;
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case MATCH_NOT_FOUND:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
- break;
- case NOT_FOUND:
- responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, String prevState, String prevVersion, AuditingActionEnum actionEnum, ComponentTypeEnum type) {
- auditComponent(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type, null);
- }
-
- public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, String prevState, String prevVersion, AuditingActionEnum actionEnum, ComponentTypeEnum type, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
- if (actionEnum != null) {
- log.trace("Inside auditing for audit action {}", actionEnum.name());
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
-
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
-
- updateUserFields(modifier, auditingFields);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, type.getValue().replace(" ", ""));
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, prevVersion);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, prevState);
- if (component != null) {
- // fields that are filled during creation and might still be
- // empty
- String resourceCurrVersion = component.getVersion();
- String resourceCurrState = (component.getLifecycleState() != null) ? component.getLifecycleState().name() : "";
- String resourceUuid = (component.getUUID() != null) ? component.getUUID() : "";
- String invariantUUID = (component.getInvariantUUID() != null) ? component.getInvariantUUID() : "";
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, resourceCurrVersion);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, resourceCurrState);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, resourceUuid);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, invariantUUID);
- } else {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, "");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, "");
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- // This is meant to overwrite anything set in this function if some
- // params were passed from above,
- // for example resourceName of resource import
- if (additionalParams != null) {
- auditingFields.putAll(additionalParams);
- }
-
- getAuditingManager().auditEvent(auditingFields);
- }
- }
-
- public void auditDistributionEngine(AuditingActionEnum actionEnum, String environmentName, String topicName, String role, String apiKey, String status) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, environmentName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiKey);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditDistributionNotification(AuditingActionEnum actionEnum, String serviceUUID, String resourceName, String resourceType, String currVersion, String modifierUid, String modifierName, String environmentName, String currState,
- String topicName, String distributionId, String description, String status) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID);
-
- // auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME,
- // environmentName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditAuthEvent(AuditingActionEnum actionEnum, String url, String user, String authStatus, String realm) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL, url);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER, user);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, authStatus);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM, realm);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditDistributionStatusNotification(AuditingActionEnum actionEnum, String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, distributionId);
- ThreadLocalsHolder.setUuid(distributionId);
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, errorReason);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditGetUebCluster(AuditingActionEnum actionEnum, String consumerId, String statusTime, String status, String description) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, description);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditMissingInstanceId(AuditingActionEnum actionEnum, String status, String description) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, null);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, null);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditTopicACLKeys(AuditingActionEnum actionEnum, String envName, String topicName, String role, String apiPublicKey, String status) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditRegisterOrUnRegisterEvent(AuditingActionEnum actionEnum, String consumerId, String apiPublicKey, String envName, String status, String statusDesc, String notifTopicName, String statusTopicName) {
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, statusDesc);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, notifTopicName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, statusTopicName);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditServiceDistributionDeployed(AuditingActionEnum actionEnum, String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID);
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, "Service");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, serviceName);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, serviceVersion);
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- if (modifier != null) {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- }
- StringBuilder ecompUser = new StringBuilder();
- if (consumer != null) {
- if (consumer.getConsumerName() != null && !consumer.getConsumerName().trim().isEmpty()) {
- ecompUser.append(consumer.getConsumerName());
- }
- if (consumer.getConsumerSalt() != null && !consumer.getConsumerSalt().trim().isEmpty()) {
- if (ecompUser.length() > 0) {
- ecompUser.append(",");
- }
- ecompUser.append(consumer.getConsumerSalt());
- }
- if (consumer.getConsumerPassword() != null && !consumer.getConsumerPassword().trim().isEmpty()) {
- if (ecompUser.length() > 0) {
- ecompUser.append(",");
- }
- ecompUser.append(consumer.getConsumerPassword());
- }
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, ecompUser.toString());
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
-
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditGetUsersList(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- if (modifier != null) {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- }
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, details);
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- if (modifier != null) {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- } else {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, "");
- }
- if (userBefore != null) {
- String userBeforeUserId = (userBefore.getUserId() != null) ? userBefore.getUserId() : "";
- String userBeforFirstName = (userBefore.getFirstName() != null) ? ", " + userBefore.getFirstName() + " " : "";
- String userBeforLastName = (userBefore.getLastName() != null) ? userBefore.getLastName() : "";
- String userBeforEmail = (userBefore.getEmail() != null) ? ", " + userBefore.getEmail() : "";
- String userBeforRloe = (userBefore.getRole() != null) ? ", " + userBefore.getRole() : "";
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, userBeforeUserId + userBeforFirstName + userBeforLastName + userBeforEmail + userBeforRloe);
- } else {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, "");
- }
- if (userAfter != null) {
- String userAfterUserId = (userAfter.getUserId() != null) ? userAfter.getUserId() : "";
- String userAfterFirstName = (userAfter.getFirstName() != null) ? ", " + userAfter.getFirstName() + " " : "";
- String userAfterLastName = (userAfter.getLastName() != null) ? userAfter.getLastName() : "";
- String userAfterEmail = (userAfter.getEmail() != null) ? ", " + userAfter.getEmail() : "";
- String userAfterRloe = (userAfter.getRole() != null) ? ", " + userAfter.getRole() : "";
-
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, userAfterUserId + userAfterFirstName + userAfterLastName + userAfterEmail + userAfterRloe);
- } else {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, "");
- }
-
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditUserAccess(AuditingActionEnum actionEnum, User user, ResponseFormat responseFormat) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user.getFirstName() + " " + user.getLastName() + '(' + user.getUserId() + ')');
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public void auditGetCategoryHierarchy(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) {
-
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
- if (modifier != null) {
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
- }
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS, details);
- int status = responseFormat.getStatus();
- String message = "";
-
- if (responseFormat.getMessageId() != null) {
- message = responseFormat.getMessageId() + ": ";
- }
- message += responseFormat.getFormattedMessage();
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
- getAuditingManager().auditEvent(auditingFields);
- }
-
- public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) {
- if (component == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case COMPONENT_VERSION_ALREADY_EXIST:
- responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion());
- break;
- case RESOURCE_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- break;
- case COMPONENT_NAME_ALREADY_EXIST:
- responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- break;
- case COMPONENT_IN_USE:
- responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId());
- break;
- case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND:
- responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
-
- public Either<Boolean, ResponseFormat> validateStringNotEmpty(User user, Component component, String value, ActionStatus badResult, AuditingActionEnum actionEnum) {
- if ((value == null) || (value.trim().isEmpty())) {
- log.info(badResult.name());
- ResponseFormat errorResponse = getResponseFormat(badResult);
- if (actionEnum != null) {
- log.debug("audit before sending response");
- auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, getComponentType(component));
- }
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
-
- public Boolean validateStringNotEmpty(String value) {
- if ((value == null) || (value.trim().isEmpty())) {
- return false;
- }
- return true;
- }
-
- private ComponentTypeEnum getComponentType(Component component) {
- if (component instanceof Service) {
- return ComponentTypeEnum.SERVICE;
- } // else if(component instanceof Resource){
- return null;
- }
-
- public Either<Boolean, ResponseFormat> validateStringMatchesPattern(User user, Component component, String value, Pattern pattern, ActionStatus badResult, AuditingActionEnum actionEnum) {
- if (!pattern.matcher(value).matches()) {
- log.error(badResult.name());
- ResponseFormat errorResponse = getResponseFormat(badResult);
- if (actionEnum != null) {
- log.debug("audit before sending response");
- auditComponentAdmin(errorResponse, user, component, "", "", actionEnum, getComponentType(component));
- }
- return Either.right(errorResponse);
- }
- return Either.left(true);
- }
-
- /**
- *
- * " Error: Missing Mandatory Informational %s1 %s2 : %s3 " where %s1 - "resource"/"service" %s2 - "artifact"/ "artifacts" %s3 - Comma separated list of missing informational artifact types
- *
- * @param resource
- * @param componentMissingMandatoryArtifacts
- * @param value
- * @return
- */
- public ResponseFormat getResponseFormatByMissingArtifacts(ComponentTypeEnum componentType, Map<String, ArtifactDefinition> artifacts) {
-
- String artifactTitle = "artifact";
- if (artifacts.size() > 1) {
- artifactTitle = "artifacts";
- }
- Collection<ArtifactDefinition> artifactsLabels = artifacts.values();
- StringBuilder artifactsLabelBuilder = new StringBuilder();
-
- List<ArtifactDefinition> artifactsLabelsList = new ArrayList<ArtifactDefinition>();
- artifactsLabelsList.addAll(artifactsLabels);
- for (int i = 0; i < artifactsLabelsList.size(); i++) {
- ArtifactDefinition artifactDef = artifactsLabelsList.get(i);
- artifactsLabelBuilder.append(artifactDef.getArtifactDisplayName());
- if (i < artifactsLabelsList.size() - 1) {
- artifactsLabelBuilder.append(";");
- }
- }
- ResponseFormat responseFormat = getResponseFormat(ActionStatus.COMPONENT_MISSING_MANDATORY_ARTIFACTS, componentType.name().toLowerCase(), artifactTitle, artifactsLabelBuilder.toString());
-
- return responseFormat;
- }
-
- public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
- break;
- case INVALID_ID:
- responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- 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) {
-
- if (additionalInfoParameterInfo == null) {
- additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
- }
- if (labelOrValue == null) {
- labelOrValue = AdditionalInformationEnum.None;
- }
-
- ResponseFormat responseFormat = null;
- switch (actionStatus) {
- case COMPONENT_NAME_ALREADY_EXIST:
- responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey());
- break;
- case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT:
- responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString());
- break;
- case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED:
- responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase());
- break;
- case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED:
- responseFormat = getResponseFormat(actionStatus);
- break;
- case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS:
- responseFormat = getResponseFormat(actionStatus);
- break;
- case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS:
- responseFormat = getResponseFormat(actionStatus);
- break;
- case ADDITIONAL_INFORMATION_NOT_FOUND:
- responseFormat = getResponseFormat(actionStatus);
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
-
- return responseFormat;
- }
-
- public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) {
- return getResponseFormatAdditionalProperty(actionStatus, null, null, null);
- }
-
- public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case CONNECTION_FAILURE:
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
- break;
- case NOT_FOUND:
- responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case CONNECTION_FAILURE:
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) {
- ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
-
- switch (storageResponse) {
- case OK:
- responseEnum = ActionStatus.OK;
- break;
- case CONNECTION_FAILURE:
- case GRAPH_IS_LOCK:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- case BAD_REQUEST:
- responseEnum = ActionStatus.INVALID_CONTENT;
- break;
- case ENTITY_ALREADY_EXISTS:
- responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
- break;
- case SCHEMA_VIOLATION:
- responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
- break;
- case CANNOT_UPDATE_EXISTING_ENTITY:
- responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST;
- break;
- default:
- responseEnum = ActionStatus.GENERAL_ERROR;
- break;
- }
- log.debug("convert storage response {} to action response {}", storageResponse.name(), responseEnum.name());
- return responseEnum;
- }
-
- public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) {
- if (groupType == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case GROUP_MEMBER_EMPTY:
- case GROUP_TYPE_ALREADY_EXIST:
- responseFormat = getResponseFormat(actionStatus, groupType.getType());
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
-
- }
-
- public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) {
- if (policyType == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case POLICY_TYPE_ALREADY_EXIST:
- responseFormat = getResponseFormat(actionStatus, policyType.getType());
- break;
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
-
- }
-
- public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) {
- if (dataType == null) {
- return getResponseFormat(actionStatus);
- }
- ResponseFormat responseFormat;
-
- switch (actionStatus) {
- case DATA_TYPE_ALREADY_EXIST:
- responseFormat = getResponseFormat(actionStatus, dataType.getName());
- break;
- case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM:
- responseFormat = getResponseFormat(actionStatus, dataType.getName());
- break;
- case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY:
- responseFormat = getResponseFormat(actionStatus, dataType.getName());
- break;
- case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR:
- responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
- break;
- case DATA_TYPE_DERIVED_IS_MISSING:
- responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName());
- break;
- case DATA_TYPE_DUPLICATE_PROPERTY:
- responseFormat = getResponseFormat(actionStatus, dataType.getName());
- break;
- case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE:
- responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
- break;
- case DATA_TYPE_CANNOT_HAVE_PROPERTIES:
- responseFormat = getResponseFormat(actionStatus, dataType.getName());
- break;
- case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST:
- responseFormat = getResponseFormat(actionStatus, dataType.getName());
- break;
-
- default:
- responseFormat = getResponseFormat(actionStatus);
- break;
- }
- return responseFormat;
- }
+ private static final Logger log = LoggerFactory.getLogger(ComponentsUtils.class);
+ private final AuditingManager auditingManager;
+ private final ResponseFormatManager responseFormatManager;
+
+ public ComponentsUtils(AuditingManager auditingManager) {
+ this.auditingManager = auditingManager;
+ this.responseFormatManager = ResponseFormatManager.getInstance();
+ }
+
+ public AuditingManager getAuditingManager() {
+ return auditingManager;
+ }
+
+ public <T> Either<T, ResponseFormat> convertJsonToObject(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum) {
+ if (data == null) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("object is null after converting from json");
+ ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum);
+ return Either.right(responseFormat);
+ }
+ try {
+ T obj = parseJsonToObject(data, clazz);
+ return Either.left(obj);
+ } catch (Exception e) {
+ // INVALID JSON
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json {}", data, e);
+ ResponseFormat responseFormat = getInvalidContentErrorAndAudit(user, actionEnum);
+ return Either.right(responseFormat);
+ }
+ }
+
+ public static <T> T parseJsonToObject(String data, Class<T> clazz) {
+ Type constraintType = new TypeToken<PropertyConstraint>() {}.getType();
+ Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+ log.trace("convert json to object. json=\n{}", data);
+ return gson.fromJson(data, clazz);
+ }
+
+ public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
+ T component = null;
+ ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
+ try {
+ log.trace("convert json to object. json=\n{}", data);
+
+ SimpleModule module = new SimpleModule("customDeserializationModule");
+ module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
+ mapper.registerModule(module);
+
+ component = mapper.readValue(data, clazz);
+ if (component == null) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("object is null after converting from json");
+ ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum);
+ return Either.right(responseFormat);
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json {}", data, e);
+ ResponseFormat responseFormat = getInvalidContentErrorAndAuditComponent(user, actionEnum, typeEnum);
+ return Either.right(responseFormat);
+ }
+ return Either.left(component);
+ }
+
+ public ResponseFormat getResponseFormat(ActionStatus actionStatus, String... params) {
+ return responseFormatManager.getResponseFormat(actionStatus, params);
+ }
+
+ public ResponseFormat getResponseFormat(StorageOperationStatus storageStatus, String... params) {
+ return responseFormatManager.getResponseFormat(this.convertFromStorageResponse(storageStatus), params);
+ }
+
+ public <T> Either<List<T>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus storageOperationStatus) {
+ return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList()) :
+ Either.right(getResponseFormat(storageOperationStatus));
+ }
+
+ /**
+ * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he
+ * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields.
+ * <p>
+ * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service.
+ *
+ * @param actionStatus
+ * @param resource
+ * @return
+ */
+ public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, Resource resource) {
+ if (resource == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case COMPONENT_VERSION_ALREADY_EXIST:
+ responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion());
+ break;
+ case RESOURCE_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName());
+ break;
+ case COMPONENT_NAME_ALREADY_EXIST:
+ responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+ break;
+ case COMPONENT_IN_USE:
+ responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId());
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ public ResponseFormat getResponseFormatByResource(ActionStatus actionStatus, String resourceName) {
+ if (resourceName == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case RESOURCE_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName);
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ public ResponseFormat getResponseFormatByCapabilityType(ActionStatus actionStatus, CapabilityTypeDefinition capabilityType) {
+ if (capabilityType == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case CAPABILITY_TYPE_ALREADY_EXIST:
+ responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType());
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ public <T> ResponseFormat getResponseFormatByElement(ActionStatus actionStatus, T obj) {
+ if (obj == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat = null;
+
+ switch (actionStatus) {
+ case MISSING_CAPABILITY_TYPE:
+ if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)) {
+ List list = (List) obj;
+ if (list.get(0) instanceof RequirementDefinition) {
+ responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list.get(0)).getName()); //Arbitray index, all we need is single object
+ return responseFormat;
+ }
+ }
+ log.debug("UNKNOWN TYPE : expecting obj as a non empty List<RequirmentsDefinitions>");
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ /**
+ * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he
+ * received. It's caller's responisibility to fill the passed resource object with needed fields.
+ *
+ * @param actionStatus
+ * @param user
+ * @return
+ */
+ public ResponseFormat getResponseFormatByUser(ActionStatus actionStatus, User user) {
+ if (user == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat requestErrorWrapper;
+ switch (actionStatus) {
+ case INVALID_USER_ID:
+ requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId());
+ break;
+ case INVALID_EMAIL_ADDRESS:
+ requestErrorWrapper = getResponseFormat(actionStatus, user.getEmail());
+ break;
+ case INVALID_ROLE:
+ requestErrorWrapper = getResponseFormat(actionStatus, user.getRole());
+ break;
+ case USER_NOT_FOUND:
+ case USER_ALREADY_EXIST:
+ case USER_INACTIVE:
+ case USER_HAS_ACTIVE_ELEMENTS:
+ requestErrorWrapper = getResponseFormat(actionStatus, user.getUserId());
+ break;
+ default:
+ requestErrorWrapper = getResponseFormat(actionStatus);
+ break;
+ }
+ return requestErrorWrapper;
+ }
+
+ public ResponseFormat getResponseFormatByUserId(ActionStatus actionStatus, String userId) {
+ User user = new User();
+ user.setUserId(userId);
+ return getResponseFormatByUser(actionStatus, user);
+ }
+
+ public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String serviceId, String envName) {
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE:
+ responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName);
+ break;
+ case DISTRIBUTION_ENVIRONMENT_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND, envName);
+ break;
+ case DISTRIBUTION_ARTIFACT_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND, serviceId);
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) {
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case RESOURCE_NOT_FOUND:
+ case ARTIFACT_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ public ResponseFormat getInvalidContentErrorAndAudit(User user, String resourceName, AuditingActionEnum actionEnum) {
+ ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ log.debug("audit before sending response");
+ auditResource(responseFormat, user, resourceName, actionEnum);
+ return responseFormat;
+ }
+
+ public ResponseFormat getInvalidContentErrorAndAudit(User user, AuditingActionEnum actionEnum) {
+ ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ log.debug("audit before sending response");
+ auditAdminUserAction(actionEnum, user, null, null, responseFormat);
+ return responseFormat;
+ }
+
+ public ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
+ ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ log.debug("audit before sending response");
+ auditComponentAdmin(responseFormat, user, null, actionEnum, typeEnum);
+ return responseFormat;
+ }
+
+ public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, ResourceAuditData prevResFields) {
+ auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null);
+ }
+
+ public void auditResource(ResponseFormat responseFormat, User modifier, String resourceName, AuditingActionEnum actionEnum) {
+ auditResource(responseFormat, modifier, null, resourceName, actionEnum);
+ }
+
+ public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum) {
+ auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum);
+ }
+
+ public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum) {
+ auditResource(responseFormat, modifier, resource, resourceName, actionEnum, ResourceAuditData.newBuilder().build(), null, null);
+ }
+
+ public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, String resourceName, AuditingActionEnum actionEnum,
+ ResourceAuditData prevResFields, String currentArtifactUuid, String artifactData) {
+ if (actionEnum != null) {
+ int status = responseFormat.getStatus();
+ String message = "";
+ String uuid = null;
+ String resourceCurrVersion = null;
+ String resourceCurrState = null;
+ String invariantUUID = null;
+ String resourceType = ComponentTypeEnum.RESOURCE.getValue();
+ String toscaNodeType = null;
+
+ log.trace("Inside auditing for audit action {}", actionEnum);
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+ if (resource != null) {
+ resourceName = resource.getName();
+ resourceCurrVersion = resource.getVersion();
+ if (resource.getLifecycleState() != null) {
+ resourceCurrState = resource.getLifecycleState().name();
+ }
+ if (resource.getResourceType() != null) {
+ resourceType = resource.getResourceType().name();
+ }
+ invariantUUID = resource.getInvariantUUID();
+ uuid = resource.getUUID();
+ toscaNodeType = resource.getToscaResourceName();
+ }
+
+ AuditBaseEventFactory factory = AuditResourceEventFactoryMananger.createResourceEventFactory(
+ actionEnum,
+ CommonAuditData.newBuilder()
+ .status(status)
+ .description(message)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .serviceInstanceId(uuid)
+ .build(),
+ prevResFields,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(currentArtifactUuid)
+ .state(resourceCurrState)
+ .version(resourceCurrVersion)
+ .build(),
+ resourceType, resourceName, invariantUUID,
+ modifier, artifactData, null, null, toscaNodeType);
+
+ getAuditingManager().auditEvent(factory);
+ }
+ }
+
+ private void updateUserFields(User modifier, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ if (modifier != null) {
+ String firstName = modifier.getFirstName();
+ String lastName = modifier.getLastName();
+ if (firstName != null || lastName != null) {// to prevent "null
+ // null" names
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, firstName + " " + lastName);
+ }
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ }
+ }
+
+ public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) {
+ log.trace("Inside auditing");
+ int status = responseFormat.getStatus();
+ String message = "";
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+ getAuditingManager().auditEvent(auditingFields);
+ AuditDistribDownloadEventFactory factory = new AuditDistribDownloadEventFactory(
+ CommonAuditData.newBuilder()
+ .status(status)
+ .description(message)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ distributionData);
+ getAuditingManager().auditEvent(factory);
+ }
+
+ public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ log.trace("Inside auditing for audit action {}", actionEnum);
+ int status = responseFormat.getStatus();
+ String message = "";
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
+
+ if (additionalParams != null) {
+ auditingFields.putAll(additionalParams);
+ }
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditExternalCrudApi(ResponseFormat responseFormat, String componentType, String actionEnum, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ log.trace("Inside auditing for audit action {}", actionEnum);
+ String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
+ String requestURI = request.getRequestURI();
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ int status = 0;
+ String message = "";
+ if (responseFormat != null) {
+ status = responseFormat.getStatus();
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+ }
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
+
+ if (additionalParams != null) {
+ auditingFields.putAll(additionalParams);
+ if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME)) {
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
+ }
+ }
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditExternalActivateService(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName(), request, additionalParams);
+ }public void auditExternalDownloadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.DOWNLOAD_ARTIFACT.getName(), request, additionalParams);
+ }
+
+ public void auditExternalUploadArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), request, additionalParams);
+ }
+
+ public void auditExternalUpdateArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), request, additionalParams);
+ }
+
+ public void auditExternalDeleteArtifact(ResponseFormat responseFormat, String componentType, HttpServletRequest request, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, request.getHeader(Constants.USER_ID_HEADER));
+ additionalParams.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, "");
+ auditExternalCrudApi(responseFormat, componentType, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), request, additionalParams);
+ }
+
+ public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) {
+ log.trace("Inside auditing for audit action {}", actionEnum);
+ int status = responseFormat.getStatus();
+ String message = "";
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ updateUserFields(modifier, auditingFields);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, categoryName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, subCategoryName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, groupingName);
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) {
+
+ return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE);
+ }
+
+ public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) {
+
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+ if (storageResponse == null) {
+ return responseEnum;
+ }
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case CONNECTION_FAILURE:
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
+ break;
+ case PARENT_RESOURCE_NOT_FOUND:
+ responseEnum = ActionStatus.PARENT_RESOURCE_NOT_FOUND;
+ break;
+ case MULTIPLE_PARENT_RESOURCE_FOUND:
+ responseEnum = ActionStatus.MULTIPLE_PARENT_RESOURCE_FOUND;
+ break;
+ case NOT_FOUND:
+ if (ComponentTypeEnum.RESOURCE == type) {
+ responseEnum = ActionStatus.RESOURCE_NOT_FOUND;
+ } else if (ComponentTypeEnum.PRODUCT == type) {
+ responseEnum = ActionStatus.PRODUCT_NOT_FOUND;
+ } else {
+ responseEnum = ActionStatus.SERVICE_NOT_FOUND;
+ }
+ break;
+ case FAILED_TO_LOCK_ELEMENT:
+ responseEnum = ActionStatus.COMPONENT_IN_USE;
+ break;
+ case ARTIFACT_NOT_FOUND:
+ responseEnum = ActionStatus.ARTIFACT_NOT_FOUND;
+ break;
+ case DISTR_ENVIRONMENT_NOT_AVAILABLE:
+ responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE;
+ break;
+ case DISTR_ENVIRONMENT_NOT_FOUND:
+ responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_FOUND;
+ break;
+ case DISTR_ENVIRONMENT_SENT_IS_INVALID:
+ responseEnum = ActionStatus.DISTRIBUTION_ENVIRONMENT_INVALID;
+ break;
+ case DISTR_ARTIFACT_NOT_FOUND:
+ responseEnum = ActionStatus.DISTRIBUTION_ARTIFACT_NOT_FOUND;
+ break;
+ case INVALID_TYPE:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case INVALID_VALUE:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case CSAR_NOT_FOUND:
+ responseEnum = ActionStatus.CSAR_NOT_FOUND;
+ break;
+ case PROPERTY_NAME_ALREADY_EXISTS:
+ responseEnum = ActionStatus.PROPERTY_NAME_ALREADY_EXISTS;
+ break;
+ case MATCH_NOT_FOUND:
+ responseEnum = ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY;
+ break;
+ case CATEGORY_NOT_FOUND:
+ responseEnum = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
+ break;
+ case INVALID_PROPERTY:
+ responseEnum = ActionStatus.INVALID_PROPERTY;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ActionStatus convertFromToscaError(ToscaError toscaError) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+ if (toscaError == null) {
+ return responseEnum;
+ }
+ switch (toscaError) {// TODO match errors
+ case NODE_TYPE_CAPABILITY_ERROR:
+ case NOT_SUPPORTED_TOSCA_TYPE:
+ case NODE_TYPE_REQUIREMENT_ERROR:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ return responseEnum;
+ }
+
+ public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case CONNECTION_FAILURE:
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case CONNECTION_FAILURE:
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.LIFECYCLE_TYPE_ALREADY_EXIST;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case INVALID_ID:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
+ break;
+ case INVALID_PROPERTY:
+ responseEnum = ActionStatus.INVALID_PROPERTY;
+ break;
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case MATCH_NOT_FOUND:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
+ break;
+ case NOT_FOUND:
+ if (isRelation) {
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND;
+ } else {
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
+ }
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) {
+ ResponseFormat responseFormat;
+
+ if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
+ responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
+ }
+ else {
+ responseFormat = getResponseFormat(actionStatus, serviceName);
+ }
+ return responseFormat;
+ }
+
+ public ResponseFormat getResponseFormatForResourceInstanceProperty(ActionStatus actionStatus, String resourceInstanceName) {
+ ResponseFormat responseFormat;
+ if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
+ responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
+ }
+ else {
+ responseFormat = getResponseFormat(actionStatus);
+ }
+ return responseFormat;
+ }
+
+ public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case INVALID_ID:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST;
+ break;
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case MATCH_NOT_FOUND:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_ALREADY_EXIST;
+ break;
+ case NOT_FOUND:
+ responseEnum = ActionStatus.RESOURCE_INSTANCE_NOT_FOUND;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, String comment) {
+ auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, null, null, comment, null, null);
+ }
+
+ public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) {
+ auditComponent(responseFormat, modifier, component, actionEnum, type, ResourceAuditData.newBuilder().build());
+ }
+
+ public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent) {
+ auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent);
+ }
+
+ public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent) {
+ auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, null, null, null, null, null);
+ }
+
+
+ public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, String compName, ComponentTypeEnum type, String comment) {
+ auditComponent(responseFormat, modifier, null, actionEnum, type, ResourceAuditData.newBuilder().build(), null, compName, comment, null, null);
+ }
+
+ public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, ResourceAuditData currComponent) {
+ auditComponent(responseFormat, modifier, component, actionEnum, type, prevComponent, currComponent, null, null, null, null);
+ }
+
+ public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type, ResourceAuditData prevComponent, ResourceAuditData currComponent, String compName, String comment, String artifactData, String did) {
+ if (actionEnum != null) {
+ String uuid = null;
+ String currState = null;
+ String invariantUUID = null;
+ String currArtifactUid = null;
+ String currVersion = null;
+ String dcurrStatus = null;
+ String message = "";
+
+ int status = responseFormat.getStatus();
+
+ log.trace("Inside auditing for audit action {}", actionEnum);
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+
+ if (component != null) {
+ // fields that are filled during creation and might still be empty
+ if (component.getLifecycleState() != null) {
+ currState = component.getLifecycleState().name();
+ }
+ uuid = component.getUUID();
+ invariantUUID = component.getInvariantUUID();
+ currVersion = component.getVersion();
+ if (StringUtils.isEmpty(compName)) {
+ compName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ }
+ }
+ if (currComponent != null) {
+ currArtifactUid = currComponent.getArtifactUuid();
+ dcurrStatus = currComponent.getDistributionStatus();
+ if (currState == null) { //probably it was not set
+ currState = currComponent.getState();
+ }
+ if (currVersion == null) { //probably it was not set
+ currVersion = currComponent.getVersion();
+ }
+ }
+ AuditBaseEventFactory factory = AuditResourceEventFactoryMananger.createResourceEventFactory(
+ actionEnum,
+ CommonAuditData.newBuilder()
+ .status(status)
+ .description(message)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .serviceInstanceId(uuid)
+ .build(),
+ prevComponent,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(currArtifactUid)
+ .state(currState)
+ .version(currVersion)
+ .distributionStatus(dcurrStatus)
+ .build(),
+ type.getValue().replace(" ", ""), compName, invariantUUID,
+ modifier, artifactData, comment, did, null);
+
+ getAuditingManager().auditEvent(factory);
+ }
+ }
+
+ public void auditDistributionEngine(AuditingActionEnum actionEnum, String environmentName, String topicName, String role, String apiKey, String status) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, environmentName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiKey);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+
+ public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID,
+ String environmentType, String action, String environmentName, String tenantContext) {
+ getAuditingManager().auditEvent(new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName,
+ environmentType, action, tenantContext));
+ }
+
+ public void auditDistributionNotification(AuditingActionEnum actionEnum, String serviceUUID, String resourceName, String resourceType, String currVersion, String modifierUid, String modifierName, String environmentName, String currState,
+ String topicName, String distributionId, String description, String status, String workloadContext, String tenant) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID);
+
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, currVersion);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, currState);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, resourceType);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifierUid);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifierName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, tenant);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, workloadContext);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID, environmentName);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditAuthEvent(String url, String user, String authStatus, String realm) {
+ getAuditingManager().auditEvent(new AuditAuthRequestEventFactory(
+ CommonAuditData.newBuilder()
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ user, url, realm, authStatus));
+ }
+
+ public void auditDistributionStatusNotification(AuditingActionEnum actionEnum, String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime, String status, String errorReason) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, distributionId);
+ ThreadLocalsHolder.setUuid(distributionId);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, resourceUrl);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, errorReason);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditGetUebCluster(AuditingActionEnum actionEnum, String consumerId, String statusTime, String status, String description) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, statusTime);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, description);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditMissingInstanceId(AuditingActionEnum actionEnum, String status, String description) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, null);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP, null);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, description);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditTopicACLKeys(AuditingActionEnum actionEnum, String envName, String topicName, String role, String apiPublicKey, String status) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, topicName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, role);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditRegisterOrUnRegisterEvent(AuditingActionEnum actionEnum, String consumerId, String apiPublicKey, String envName, String status, String statusDesc, String notifTopicName, String statusTopicName) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, consumerId);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, apiPublicKey);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, envName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, statusDesc);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, notifTopicName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, statusTopicName);
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditServiceDistributionDeployed(AuditingActionEnum actionEnum, String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, serviceUUID);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, "Service");
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, serviceName);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, serviceVersion);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, distributionId);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, desc);
+
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) {
+ int status = responseFormat.getStatus();
+ String message = "";
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+ AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum,
+ CommonAuditData.newBuilder()
+ .description(message)
+ .status(status)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ modifier, consumer);
+
+ getAuditingManager().auditEvent(factory);
+ }
+
+ public void auditGetUsersList(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ if (modifier != null) {
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ }
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, details);
+ int status = responseFormat.getStatus();
+ String message = "";
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) {
+ int status = responseFormat.getStatus();
+ String message = "";
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+ AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum,
+ CommonAuditData.newBuilder()
+ .description(message)
+ .status(status)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ modifier, userBefore, userAfter);
+
+ getAuditingManager().auditEvent(factory);
+ }
+
+ public void auditUserAccess(AuditingActionEnum actionEnum, User user, ResponseFormat responseFormat) {
+
+ int status = responseFormat.getStatus();
+ String message = "";
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+
+ AuditEventFactory factory = new AuditUserAccessEventFactory(CommonAuditData.newBuilder()
+ .description(message)
+ .status(status)
+ .requestId(ThreadLocalsHolder.getUuid())
+ .build(),
+ user);
+
+ getAuditingManager().auditEvent(factory);
+ }
+
+ public void auditGetCategoryHierarchy(AuditingActionEnum actionEnum, User modifier, String details, ResponseFormat responseFormat) {
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, actionEnum.getName());
+ if (modifier != null) {
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ }
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS, details);
+ int status = responseFormat.getStatus();
+ String message = "";
+
+ if (responseFormat.getMessageId() != null) {
+ message = responseFormat.getMessageId() + ": ";
+ }
+ message += responseFormat.getFormattedMessage();
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, status);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, message);
+ getAuditingManager().auditEvent(auditingFields);
+ }
+
+ public ResponseFormat getResponseFormatByComponent(ActionStatus actionStatus, Component component, ComponentTypeEnum type) {
+ if (component == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case COMPONENT_VERSION_ALREADY_EXIST:
+ responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion());
+ break;
+ case RESOURCE_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+ break;
+ case COMPONENT_NAME_ALREADY_EXIST:
+ responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+ break;
+ case COMPONENT_IN_USE:
+ responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId());
+ break;
+ case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND:
+ responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+ public boolean validateStringNotEmpty(String value) {
+ return value != null && !value.trim().isEmpty();
+ }
+
+ public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.COMPONENT_NAME_ALREADY_EXIST;
+ break;
+ case INVALID_ID:
+ responseEnum = ActionStatus.ADDITIONAL_INFORMATION_NOT_FOUND;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ 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) {
+
+ if (additionalInfoParameterInfo == null) {
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
+ }
+ if (labelOrValue == null) {
+ labelOrValue = AdditionalInformationEnum.None;
+ }
+
+ ResponseFormat responseFormat = null;
+ switch (actionStatus) {
+ case COMPONENT_NAME_ALREADY_EXIST:
+ responseFormat = getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey());
+ break;
+ case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT:
+ responseFormat = getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString());
+ break;
+ case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED:
+ responseFormat = getResponseFormat(actionStatus, nodeType.name().toLowerCase());
+ break;
+ case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ case ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ case ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ case ADDITIONAL_INFORMATION_NOT_FOUND:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+
+ return responseFormat;
+ }
+
+ public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) {
+ return getResponseFormatAdditionalProperty(actionStatus, null, null, null);
+ }
+
+ public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case CONNECTION_FAILURE:
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.CONSUMER_ALREADY_EXISTS;
+ break;
+ case NOT_FOUND:
+ responseEnum = ActionStatus.ECOMP_USER_NOT_FOUND;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case CONNECTION_FAILURE:
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.GROUP_TYPE_ALREADY_EXIST;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) {
+ ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
+
+ switch (storageResponse) {
+ case OK:
+ responseEnum = ActionStatus.OK;
+ break;
+ case CONNECTION_FAILURE:
+ case GRAPH_IS_LOCK:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ case BAD_REQUEST:
+ responseEnum = ActionStatus.INVALID_CONTENT;
+ break;
+ case ENTITY_ALREADY_EXISTS:
+ responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
+ break;
+ case SCHEMA_VIOLATION:
+ responseEnum = ActionStatus.DATA_TYPE_ALREADY_EXIST;
+ break;
+ case CANNOT_UPDATE_EXISTING_ENTITY:
+ responseEnum = ActionStatus.DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST;
+ break;
+ default:
+ responseEnum = ActionStatus.GENERAL_ERROR;
+ break;
+ }
+ log.debug("convert storage response {} to action response {}", storageResponse, responseEnum);
+ return responseEnum;
+ }
+
+ public ResponseFormat getResponseFormatByGroupType(ActionStatus actionStatus, GroupTypeDefinition groupType) {
+ if (groupType == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case GROUP_MEMBER_EMPTY:
+ case GROUP_TYPE_ALREADY_EXIST:
+ responseFormat = getResponseFormat(actionStatus, groupType.getType());
+ break;
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+
+ }
+
+ public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) {
+ if (policyType == null) {
+ return getResponseFormat(actionStatus);
+ }
+
+ ResponseFormat responseFormat;
+ if (actionStatus == ActionStatus.POLICY_TYPE_ALREADY_EXIST) {
+ responseFormat = getResponseFormat(actionStatus, policyType.getType());
+ }
+ else {
+ responseFormat = getResponseFormat(actionStatus);
+ }
+ return responseFormat;
+
+ }
+
+ public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) {
+ if (dataType == null) {
+ return getResponseFormat(actionStatus);
+ }
+ ResponseFormat responseFormat;
+
+ switch (actionStatus) {
+ case DATA_TYPE_ALREADY_EXIST:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName());
+ break;
+ case DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName());
+ break;
+ case DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName());
+ break;
+ case DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
+ break;
+ case DATA_TYPE_DERIVED_IS_MISSING:
+ responseFormat = getResponseFormat(actionStatus, dataType.getDerivedFromName());
+ break;
+ case DATA_TYPE_DUPLICATE_PROPERTY:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName());
+ break;
+ case DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName(), properties == null ? "" : String.valueOf(properties));
+ break;
+ case DATA_TYPE_CANNOT_HAVE_PROPERTIES:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName());
+ break;
+ case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST:
+ responseFormat = getResponseFormat(actionStatus, dataType.getName());
+ break;
+
+ default:
+ responseFormat = getResponseFormat(actionStatus);
+ break;
+ }
+ return responseFormat;
+ }
+
+
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java
index ddc5ecabe7..b268554ee3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/DownloadArtifactLogic.java
@@ -20,143 +20,124 @@
package org.openecomp.sdc.be.impl;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.StreamingOutput;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.eclipse.jgit.util.Base64;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
import org.openecomp.sdc.be.info.ArtifactAccessInfo;
import org.openecomp.sdc.be.info.ArtifactAccessList;
import org.openecomp.sdc.be.info.ServletJsonResponse;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.StreamingOutput;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
public class DownloadArtifactLogic {
- private static Logger log = LoggerFactory.getLogger(DownloadArtifactLogic.class.getName());
-
- private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- public Response downloadArtifact(final String resourceName, final String resourceVersion, final String artifactName, Either<? extends ESArtifactData, ResourceUploadStatus> getArtifactStatus, String artifactId) {
- Response response = null;
-
- if (getArtifactStatus.isRight()) {
- log.debug("Could not find artifact for with id: {}", artifactId);
- ResourceUploadStatus status = getArtifactStatus.right().value();
- if (status == status.COMPONENT_NOT_EXIST)
- response = Response.status(HttpStatus.SC_NO_CONTENT).build();
- else
- response = Response.status(HttpStatus.SC_NOT_FOUND).build();
-
- return response;
- }
- // convert artifact to inputstream
- else {
- ESArtifactData artifactData = getArtifactStatus.left().value();
- byte[] artifactPayload = artifactData.getDataAsArray();
-
- String payloadStr = new String(artifactPayload);
- byte[] decodedPayload = artifactPayload;
- log.debug("payload is encoded. perform decode");
- decodedPayload = Base64.decode(new String(artifactPayload));
- final InputStream artifactStream = new ByteArrayInputStream(decodedPayload);
- log.debug("found artifact for with id: {}", artifactId);
- try {
-
- // outputstream for response
- StreamingOutput stream = new StreamingOutput() {
- public void write(OutputStream output) throws IOException, WebApplicationException {
- try {
- IOUtils.copy(artifactStream, output);
- } catch (Exception e) {
- throw new WebApplicationException(e);
- }
- }
- };
- artifactStream.close();
- return Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment; filename = " + artifactName)
- // .header(Constants.MD5_HEADER, new
- // String(artifactData.getArtifactChecksum()))
- .build();
-
- } catch (IOException e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Failed to stream artifact data on the response");
- BeEcompErrorManager.getInstance().logBeSystemError("Failed to stream artifact data on the response");
- log.debug("Failed to stream artifact data on the response: {}", e.getMessage(), e);
- response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Failed to stream artifact data on the response");
- return response;
- }
- }
- }
-
- public List<ArtifactAccessInfo> convertArtifactList(List<? extends ESArtifactData> artifactsList, String servletPath) {
-
- List<ArtifactAccessInfo> artifactAccessList = new ArrayList<ArtifactAccessInfo>();
- for (ESArtifactData artifact : artifactsList) {
- ArtifactAccessInfo accessInfo = new ArtifactAccessInfo(artifact, servletPath);
- artifactAccessList.add(accessInfo);
- }
- return artifactAccessList;
- }
-
- public Response createArtifactListResponse(final String serviceName, Either<List<ESArtifactData>, ResourceUploadStatus> getArtifactsStatus/*
- * List < ? extends IResourceData> artifactsList
- */, String servletPath) {
- Response response;
- List<ArtifactAccessInfo> artifactAccessInfos;
- if (getArtifactsStatus.isRight()) {
- // if there are no artifacts - return No-Content
- ResourceUploadStatus status = getArtifactsStatus.right().value();
- if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST || status == ResourceUploadStatus.SERVICE_NOT_EXIST) {
- log.debug("resource {} does not exist", serviceName);
- response = Response.status(HttpStatus.SC_NOT_FOUND).entity("[]").build();
-
- } else {
- log.debug("No content was found for {}", serviceName);
- response = Response.status(HttpStatus.SC_NO_CONTENT).entity("[]").build();
- }
- return response;
- } else {
- List<? extends ESArtifactData> artifactsList = getArtifactsStatus.left().value();
- log.debug("{} artifacts were found for {}", artifactsList.size(), serviceName);
- artifactAccessInfos = convertArtifactList(artifactsList, servletPath);
-
- String artifactDataJson = gson.toJson(new ArtifactAccessList(artifactAccessInfos));
- response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build();
-
- return response;
- }
- }
-
- public Response buildResponse(int status, String errorMessage) {
-
- ServletJsonResponse jsonResponse = new ServletJsonResponse();
- jsonResponse.setDescription(errorMessage);
- jsonResponse.setSource(Constants.CATALOG_BE);
-
- Response response = Response.status(status).entity(jsonResponse).build();
-
- return response;
- }
+ private static final Logger log = LoggerFactory.getLogger(DownloadArtifactLogic.class);
+
+ private Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ public Response downloadArtifact(final String artifactName, Either<? extends ESArtifactData, ResourceUploadStatus> getArtifactStatus, String artifactId) {
+ Response response = null;
+
+ if (getArtifactStatus.isRight()) {
+ log.debug("Could not find artifact for with id: {}", artifactId);
+ ResourceUploadStatus status = getArtifactStatus.right().value();
+ if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST)
+ response = Response.status(HttpStatus.SC_NO_CONTENT).build();
+ else
+ response = Response.status(HttpStatus.SC_NOT_FOUND).build();
+
+ return response;
+ }
+ // convert artifact to inputstream
+ else {
+ ESArtifactData artifactData = getArtifactStatus.left().value();
+ byte[] artifactPayload = artifactData.getDataAsArray();
+
+ log.debug("payload is encoded. perform decode");
+ byte[] decodedPayload = Base64.decode(new String(artifactPayload));
+ final InputStream artifactStream = new ByteArrayInputStream(decodedPayload);
+ log.debug("found artifact for with id: {}", artifactId);
+
+ // outputstream for response
+ StreamingOutput stream = output -> {
+ try {
+ IOUtils.copy(artifactStream, output);
+ } catch (IOException e) {
+ log.debug("failed to copy artifact payload into response");
+ throw new WebApplicationException(e);
+ }
+ };
+ return Response.ok(stream).type(MediaType.APPLICATION_OCTET_STREAM_TYPE)
+ .header("content-disposition", "attachment; filename = " + artifactName)
+ .build();
+
+ }
+ }
+
+ public List<ArtifactAccessInfo> convertArtifactList(List<? extends ESArtifactData> artifactsList, String servletPath) {
+
+ List<ArtifactAccessInfo> artifactAccessList = new ArrayList<ArtifactAccessInfo>();
+ for (ESArtifactData artifact : artifactsList) {
+ ArtifactAccessInfo accessInfo = new ArtifactAccessInfo(artifact, servletPath);
+ artifactAccessList.add(accessInfo);
+ }
+ return artifactAccessList;
+ }
+
+ public Response createArtifactListResponse(final String serviceName, Either<List<ESArtifactData>, ResourceUploadStatus> getArtifactsStatus/*
+ * List < ? extends IResourceData> artifactsList
+ */, String servletPath) {
+ Response response;
+ List<ArtifactAccessInfo> artifactAccessInfos;
+ if (getArtifactsStatus.isRight()) {
+ // if there are no artifacts - return No-Content
+ ResourceUploadStatus status = getArtifactsStatus.right().value();
+ if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST || status == ResourceUploadStatus.SERVICE_NOT_EXIST) {
+ log.debug("resource {} does not exist", serviceName);
+ response = Response.status(HttpStatus.SC_NOT_FOUND).entity("[]").build();
+
+ } else {
+ log.debug("No content was found for {}", serviceName);
+ response = Response.status(HttpStatus.SC_NO_CONTENT).entity("[]").build();
+ }
+ return response;
+ } else {
+ List<? extends ESArtifactData> artifactsList = getArtifactsStatus.left().value();
+ log.debug("{} artifacts were found for {}", artifactsList.size(), serviceName);
+ artifactAccessInfos = convertArtifactList(artifactsList, servletPath);
+
+ String artifactDataJson = gson.toJson(new ArtifactAccessList(artifactAccessInfos));
+ response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build();
+
+ return response;
+ }
+ }
+
+ public Response buildResponse(int status, String errorMessage) {
+
+ ServletJsonResponse jsonResponse = new ServletJsonResponse();
+ jsonResponse.setDescription(errorMessage);
+ jsonResponse.setSource(Constants.CATALOG_BE);
+
+ Response response = Response.status(status).entity(jsonResponse).build();
+
+ return response;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java
new file mode 100644
index 0000000000..2158508e56
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java
@@ -0,0 +1,244 @@
+package org.openecomp.sdc.be.impl;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.SetMultimap;
+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.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
+import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
+import org.openecomp.sdc.be.datamodel.NameIdPair;
+import org.openecomp.sdc.be.datamodel.NameIdPairWrapper;
+import org.openecomp.sdc.be.datamodel.ServiceRelations;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Service;
+
+public class ForwardingPathUtils {
+
+ public static final String FORWARDING_PATH_NODE_NAME = "Forwarding Path";
+ public static final String FORWARDER_CAPABILITY = "org.openecomp.capabilities.Forwarder";
+
+
+ public ServiceRelations convertServiceToServiceRelations(Service service) {
+ ServiceRelations serviceRelations = new ServiceRelations();
+ List<ComponentInstance> componentInstances = service.getComponentInstances();
+ if (componentInstances == null || componentInstances.isEmpty()) {
+ return serviceRelations;
+ }
+ Set<NameIdPairWrapper> relations = new HashSet<>();
+ //@todo get all capabilities and requirements.
+ SetMultimap<NameIdPair, NameIdPair> nodeToCP = HashMultimap.create();
+ componentInstances.forEach(ci -> initNodeToCP(ci, nodeToCP));
+ handleRelDef(relations, nodeToCP);
+ serviceRelations.setRelations(relations);
+ return serviceRelations;
+ }
+
+ private void initNodeToCP(ComponentInstance ci, SetMultimap<NameIdPair, NameIdPair> nodeToCP) {
+ Set<CapabilityDefinition> capabilities = ci.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream()).collect(Collectors.toSet());
+ if (!CollectionUtils.isNotEmpty(capabilities)) {
+ return;
+ }
+ Set<CapabilityDefinition> forwarderCapabilities = capabilities.stream().filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet());
+ if (!CollectionUtils.isNotEmpty(forwarderCapabilities)) {
+ return;
+ }
+ NameIdPair node = new NameIdPair(ci.getName(), ci.getUniqueId());
+ forwarderCapabilities.forEach(fc -> {
+ NameIdPair capability = new NameIdPair(fc.getName(), fc.getUniqueId(), fc.getOwnerId());
+ nodeToCP.put(node, capability);
+
+ });
+
+ }
+
+
+ private void handleRelDef(Set<NameIdPairWrapper> relations, SetMultimap<NameIdPair, NameIdPair> nodeToCP) {
+ nodeToCP.keySet().forEach(fromNode -> {
+ NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper();
+ nameIdPairWrapper.init(fromNode);
+ if (!relations.contains(nameIdPairWrapper)) {
+ relations.add(nameIdPairWrapper);
+ Collection<NameIdPair> fromCps = nodeToCP.get(fromNode);
+ fromCps.forEach(fromCP -> handleFromCp(nodeToCP, nameIdPairWrapper));
+ }
+ });
+
+ }
+
+ private void handleFromCp(SetMultimap<NameIdPair, NameIdPair> nodeToCP, NameIdPairWrapper wrapper) {
+ Map<NameIdPair, Set<NameIdPair>> options = toMap(nodeToCP);
+
+ Set<NameIdPair> cpOptions = options.get(wrapper.getNameIdPair());
+ List<NameIdPairWrapper> wrappers = cpOptions.stream().map(cpOption -> createWrapper(cpOption)).collect(Collectors.toList());
+ wrappers.forEach(cpOptionWrapper -> {
+ org.openecomp.sdc.be.datamodel.NameIdPair data = wrapper.getData();
+ data.addWrappedData(cpOptionWrapper);
+ });
+ addNodes(wrappers, options);
+ }
+
+ private void addNodes(List<NameIdPairWrapper> cpOptions, Map<NameIdPair, Set<NameIdPair>> options) {
+
+ cpOptions.forEach(cpOption -> {
+ Set<NameIdPairWrapper> wrappers = options.keySet().stream().map(option -> createWrapper(option)).collect(Collectors.toSet());
+ wrappers.forEach(wrapper -> {
+ cpOption.getData().addWrappedData(wrapper);
+ Collection<NameIdPair> cps = options.get(wrapper.getNameIdPair());
+ Set<NameIdPairWrapper> cpsWrappers = cps.stream().map(cp -> new NameIdPairWrapper(cp)).collect(Collectors.toSet());
+ cpsWrappers.forEach(cpw -> {
+ NameIdPair data = wrapper.getData();
+ if (!data.containsKey(cpw)) {
+ data.addWrappedData(cpw);
+ }
+ });
+ });
+
+ });
+ }
+
+ private NameIdPairWrapper createWrapper(NameIdPair cpOption) {
+ NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper();
+ nameIdPairWrapper.init(new NameIdPair(cpOption));
+ return nameIdPairWrapper;
+ }
+
+
+ private Map<NameIdPair, Set<NameIdPair>> toMap(SetMultimap<NameIdPair, NameIdPair> nodeToCP) {
+ Map<NameIdPair, Set<NameIdPair>> retVal = new HashMap<>();
+ nodeToCP.asMap().forEach((nameIdPair, nameIdPairs) -> retVal.put(nameIdPair, new HashSet<>(nameIdPairs)));
+ return retVal;
+ }
+
+
+ protected ResponseFormatManager getResponseFormatManager() {
+ return ResponseFormatManager.getInstance();
+ }
+
+ public Set<String> findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService,
+ String componentInstanceId) {
+ return findForwardingPathToDeleteOnCIDeletion(containerService, componentInstanceId).values().stream()
+ .map(ForwardingPathDataDefinition::getName).collect(Collectors.toSet());
+ }
+
+ private Map<String, ForwardingPathDataDefinition> findForwardingPathToDeleteOnCIDeletion(Service containerService,
+ String componentInstanceId) {
+ return containerService.getForwardingPaths().entrySet().stream()
+ .filter(entry -> elementContainsCI(entry, componentInstanceId))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ private boolean elementContainsCI(Map.Entry<String, ForwardingPathDataDefinition> fpEntry,
+ String componentInstanceId) {
+ return fpEntry.getValue().getPathElements()
+ .getListToscaDataDefinition().stream()
+ .anyMatch(element -> elementContainsCI(element, componentInstanceId));
+ }
+
+ private boolean elementContainsCI(ForwardingPathElementDataDefinition elementDataDefinitions,
+ String componentInstanceId) {
+ return elementDataDefinitions.getFromNode().equals(componentInstanceId)
+ || elementDataDefinitions.getToNode().equals(componentInstanceId);
+ }
+
+ public Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> updateForwardingPathOnVersionChange(
+ Service containerService, DataForMergeHolder dataHolder,
+ Component updatedContainerComponent, String newInstanceId) {
+ Map<String, ForwardingPathDataDefinition> updated = containerService.getForwardingPaths().entrySet().stream()
+ .filter(entry -> elementContainsCIAndForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent))
+ .collect(Collectors.toMap(Map.Entry::getKey,
+ entry -> updateCI(entry.getValue(), dataHolder.getOrigComponentInstId(),newInstanceId)));
+ Map<String, ForwardingPathDataDefinition> deleted = containerService.getForwardingPaths().entrySet().stream()
+ .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent))
+ .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
+ return new Pair<>(updated, deleted);
+ }
+
+ public Set<String> getForwardingPathsToBeDeletedOnVersionChange(
+ Service containerService, DataForMergeHolder dataHolder, Component updatedContainerComponent) {
+ return containerService.getForwardingPaths().entrySet().stream()
+ .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(),
+ dataHolder.getOrigComponentInstId(), updatedContainerComponent))
+ .map(entry -> entry.getValue().getUniqueId()).collect( Collectors.toSet());
+ }
+
+ private ForwardingPathDataDefinition updateCI(ForwardingPathDataDefinition inFP, String oldCI, String newCI) {
+ ForwardingPathDataDefinition retVal = new ForwardingPathDataDefinition(inFP);
+ List<ForwardingPathElementDataDefinition> fpList = retVal.getPathElements().getListToscaDataDefinition()
+ .stream().map(element -> updateElement(element, oldCI, newCI)).collect(Collectors.toList());
+ retVal.setPathElements(new ListDataDefinition<>(fpList));
+ return retVal;
+ }
+
+ private ForwardingPathElementDataDefinition updateElement(ForwardingPathElementDataDefinition element, String oldCI,
+ String newCI) {
+ ForwardingPathElementDataDefinition retVal = new ForwardingPathElementDataDefinition(element);
+ if (retVal.getFromNode().equals(oldCI)) {
+ retVal.setFromNode(newCI);
+ }
+ if (retVal.getToNode().equals(oldCI)) {
+ retVal.setToNode(newCI);
+ }
+ if (Objects.equals(retVal.getToCPOriginId(),oldCI )) {
+ retVal.setToCPOriginId(newCI);
+ }
+ if (Objects.equals(retVal.getFromCPOriginId(),oldCI)) {
+ retVal.setFromCPOriginId(newCI);
+ }
+ return retVal;
+ }
+
+ private boolean elementContainsCIAndForwarder(ForwardingPathDataDefinition forwardingPathDataDefinition,
+ String oldCIId, Component newCI) {
+ return forwardingPathDataDefinition.getPathElements()
+ .getListToscaDataDefinition().stream()
+ .anyMatch(element -> elementContainsCIAndForwarder(element, oldCIId, newCI));
+ }
+
+ private boolean elementContainsCIAndForwarder(ForwardingPathElementDataDefinition elementDataDefinitions,
+ String oldCIId, Component newCI) {
+ return (elementDataDefinitions.getFromNode().equals(oldCIId) && ciContainsForwarder(newCI,
+ elementDataDefinitions.getFromCP()))
+ || (elementDataDefinitions.getToNode().equals(oldCIId) && ciContainsForwarder(newCI,
+ elementDataDefinitions.getToCP()));
+ }
+
+ private boolean ciContainsForwarder(Component newCI, String capabilityID) {
+ if (newCI.getCapabilities() == null){
+ return false;
+ }
+ return newCI.getCapabilities().values()
+ .stream()
+ .flatMap(List::stream)
+ .anyMatch(c -> c.getUniqueId().equals(capabilityID));
+ }
+
+ private boolean elementContainsCIAndDoesNotContainForwarder(
+ ForwardingPathDataDefinition forwardingPathDataDefinition,
+ String oldCIId, Component newCI) {
+ return forwardingPathDataDefinition.getPathElements()
+ .getListToscaDataDefinition().stream()
+ .anyMatch(element -> elementContainsCIAndDoesNotContainForwarder(element, oldCIId, newCI));
+ }
+
+ private boolean elementContainsCIAndDoesNotContainForwarder(
+ ForwardingPathElementDataDefinition elementDataDefinitions,
+ String oldCIId, Component newCI) {
+ return (elementDataDefinitions.getFromNode().equals(oldCIId) && !ciContainsForwarder(newCI,
+ elementDataDefinitions.getFromCP()))
+ || (elementDataDefinitions.getToNode().equals(oldCIId) && !ciContainsForwarder(newCI,
+ elementDataDefinitions.getToCP()));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java
index 3a5d9bf85f..c8128a33fc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java
@@ -20,30 +20,29 @@
package org.openecomp.sdc.be.impl;
-import javax.annotation.Resource;
-
+import com.google.gson.Gson;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.springframework.stereotype.Component;
-import com.google.gson.Gson;
+import javax.annotation.Resource;
@Component("servletUtils")
public class ServletUtils {
- @Resource
- private ComponentsUtils componentsUtils;
- private Gson gson = new Gson();
- @Resource
- private IUserBusinessLogic adminManager;
-
- public ComponentsUtils getComponentsUtils() {
- return componentsUtils;
- }
-
- public Gson getGson() {
- return gson;
- }
-
- public IUserBusinessLogic getUserAdmin() {
- return adminManager;
- }
+ @Resource
+ private ComponentsUtils componentsUtils;
+ private Gson gson = new Gson();
+ @Resource
+ private IUserBusinessLogic adminManager;
+
+ public ComponentsUtils getComponentsUtils() {
+ return componentsUtils;
+ }
+
+ public Gson getGson() {
+ return gson;
+ }
+
+ public IUserBusinessLogic getUserAdmin() {
+ return adminManager;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java
index cb21984a7f..02759289b2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java
@@ -20,16 +20,16 @@
package org.openecomp.sdc.be.impl;
-import javax.servlet.ServletContext;
-
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
+import javax.servlet.ServletContext;
+
public class WebAppContextWrapper {
- public WebApplicationContext getWebAppContext(ServletContext context) {
+ public WebApplicationContext getWebAppContext(ServletContext context) {
- return WebApplicationContextUtils.getWebApplicationContext(context);
- }
+ return WebApplicationContextUtils.getWebApplicationContext(context);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java
index deb446e32f..d3fcf9f6c0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessInfo.java
@@ -17,143 +17,118 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
package org.openecomp.sdc.be.info;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
public class ArtifactAccessInfo {
- public ArtifactAccessInfo() {
- }
-
- public ArtifactAccessInfo(ESArtifactData artifactData) {
- // this.name = artifactData.getArtifactName();
- this.id = artifactData.getId();
- // this.type = artifactData.getArtifactType();
- // this.description = artifactData.getArtifactDescription();
- // this.creator = artifactData.getArtifactCreator();
- // DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
- // Date creationTimestamp = artifactData.getArtifactCreationTimestamp();
- // this.creationTime = (creationTimestamp !=
- // null)?dateFormat.format(creationTimestamp): null;
- // Date updateTimestamp = artifactData.getArtifactLastUpdateTimestamp();
- // this.lastUpdateTime = (updateTimestamp !=
- // null)?dateFormat.format(updateTimestamp):null;
- // this.lastUpdater = artifactData.getArtifactLastUpdater();
- // if (artifactData.getArtifactChecksum() != null){
- // this.checksum = new String(artifactData.getArtifactChecksum());
- // } else {
- // this.checksum = null;
- // }
- }
-
- public ArtifactAccessInfo(ESArtifactData artifactData, String servletContext) {
- // this.name = artifactData.getArtifactName();
- StringBuilder urlBuilder = new StringBuilder();
- urlBuilder = urlBuilder.append(servletContext).append("/");
- // if (ArtifactDataEnum.COMPONENT_ARTIFACT.equals(resource)){
- urlBuilder.append("resources/")
- // .append(artifactData.getResourceId()).append("/")
-
- .append("/artifacts/");
- /*
- * }else { ServiceArtifactData serviceArtifact = (ServiceArtifactData)artifactData; urlBuilder.append("services/") .append(serviceArtifact.getServiceName()).append("/") .append(serviceArtifact.getServiceVersion()) .append("/artifacts/")
- * .append(serviceArtifact.getNodeTemplateName()) .append("/"); }
- */
- // urlBuilder.append(artifactData.getArtifactName());
- this.url = urlBuilder.toString();
-
- }
-
- private String name;
- private String url;
- private String id;
- private String type;
- private String description;
- private String creator;
- private String creationTime;
- private String lastUpdater;
- private String lastUpdateTime;
- private String checksum;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- 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 getCreator() {
- return creator;
- }
-
- public void setCreator(String creator) {
- this.creator = creator;
- }
-
- public String getCreationTime() {
- return creationTime;
- }
-
- public void setCreationTime(String creationTime) {
- this.creationTime = creationTime;
- }
-
- public String getLastUpdater() {
- return lastUpdater;
- }
-
- public void setLastUpdater(String lastUpdater) {
- this.lastUpdater = lastUpdater;
- }
-
- public String getLastUpdateTime() {
- return lastUpdateTime;
- }
-
- public void setLastUpdateTime(String lastUpdateTime) {
- this.lastUpdateTime = lastUpdateTime;
- }
-
- public String getChecksum() {
- return checksum;
- }
-
- public void setChecksum(String checksum) {
- this.checksum = checksum;
- }
+ public ArtifactAccessInfo() {
+ }
+
+ public ArtifactAccessInfo(ESArtifactData artifactData) {
+ this.id = artifactData.getId();
+ }
+
+ public ArtifactAccessInfo(ESArtifactData artifactData, String servletContext) {
+ StringBuilder urlBuilder = new StringBuilder();
+ urlBuilder = urlBuilder.append(servletContext).append("/");
+ urlBuilder.append("resources/")
+ // .append(artifactData.getResourceId()).append("/")
+
+ .append("/artifacts/");
+ this.url = urlBuilder.toString();
+
+ }
+
+ private String name;
+ private String url;
+ private String id;
+ private String type;
+ private String description;
+ private String creator;
+ private String creationTime;
+ private String lastUpdater;
+ private String lastUpdateTime;
+ private String checksum;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ 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 getCreator() {
+ return creator;
+ }
+
+ public void setCreator(String creator) {
+ this.creator = creator;
+ }
+
+ public String getCreationTime() {
+ return creationTime;
+ }
+
+ public void setCreationTime(String creationTime) {
+ this.creationTime = creationTime;
+ }
+
+ public String getLastUpdater() {
+ return lastUpdater;
+ }
+
+ public void setLastUpdater(String lastUpdater) {
+ this.lastUpdater = lastUpdater;
+ }
+
+ public String getLastUpdateTime() {
+ return lastUpdateTime;
+ }
+
+ public void setLastUpdateTime(String lastUpdateTime) {
+ this.lastUpdateTime = lastUpdateTime;
+ }
+
+ public String getChecksum() {
+ return checksum;
+ }
+
+ public void setChecksum(String checksum) {
+ this.checksum = checksum;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java
index ddeb0505d9..635a082ad8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactAccessList.java
@@ -24,17 +24,17 @@ import java.util.List;
public class ArtifactAccessList {
- public ArtifactAccessList(List<ArtifactAccessInfo> artifacts) {
- this.artifacts = artifacts;
- }
+ public ArtifactAccessList(List<ArtifactAccessInfo> artifacts) {
+ this.artifacts = artifacts;
+ }
- private List<ArtifactAccessInfo> artifacts;
+ private List<ArtifactAccessInfo> artifacts;
- public List<ArtifactAccessInfo> getArtifacts() {
- return artifacts;
- }
+ public List<ArtifactAccessInfo> getArtifacts() {
+ return artifacts;
+ }
- public void setArtifacts(List<ArtifactAccessInfo> artifacts) {
- this.artifacts = artifacts;
- }
+ public void setArtifacts(List<ArtifactAccessInfo> artifacts) {
+ this.artifacts = artifacts;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java
index dfdfeac741..bf257ee4f2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java
@@ -24,60 +24,60 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
public class ArtifactDefinitionInfo {
- private String uniqueId;
- /** Specifies the display name of the artifact. */
- private String artifactName;
- private String artifactDisplayName;
- private String artifactVersion;
- private String artifactUUID;
-
- public ArtifactDefinitionInfo(ArtifactDefinition artifactDefinition) {
- uniqueId = artifactDefinition.getUniqueId();
- artifactName = artifactDefinition.getArtifactName();
- artifactDisplayName = artifactDefinition.getArtifactDisplayName();
- artifactVersion = artifactDefinition.getArtifactVersion();
- artifactUUID = artifactDefinition.getArtifactUUID();
-
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
-
- public String getArtifactName() {
- return artifactName;
- }
-
- public void setArtifactName(String artifactName) {
- this.artifactName = artifactName;
- }
-
- public String getArtifactDisplayName() {
- return artifactDisplayName;
- }
-
- public void setArtifactDisplayName(String artifactDisplayName) {
- this.artifactDisplayName = artifactDisplayName;
- }
-
- public String getArtifactVersion() {
- return artifactVersion;
- }
-
- public void setArtifactVersion(String artifactVersion) {
- this.artifactVersion = artifactVersion;
- }
-
- public String getArtifactUUID() {
- return artifactUUID;
- }
-
- public void setArtifactUUID(String artifactUUID) {
- this.artifactUUID = artifactUUID;
- }
+ private String uniqueId;
+ /** Specifies the display name of the artifact. */
+ private String artifactName;
+ private String artifactDisplayName;
+ private String artifactVersion;
+ private String artifactUUID;
+
+ public ArtifactDefinitionInfo(ArtifactDefinition artifactDefinition) {
+ uniqueId = artifactDefinition.getUniqueId();
+ artifactName = artifactDefinition.getArtifactName();
+ artifactDisplayName = artifactDefinition.getArtifactDisplayName();
+ artifactVersion = artifactDefinition.getArtifactVersion();
+ artifactUUID = artifactDefinition.getArtifactUUID();
+
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getArtifactDisplayName() {
+ return artifactDisplayName;
+ }
+
+ public void setArtifactDisplayName(String artifactDisplayName) {
+ this.artifactDisplayName = artifactDisplayName;
+ }
+
+ public String getArtifactVersion() {
+ return artifactVersion;
+ }
+
+ public void setArtifactVersion(String artifactVersion) {
+ this.artifactVersion = artifactVersion;
+ }
+
+ public String getArtifactUUID() {
+ return artifactUUID;
+ }
+
+ public void setArtifactUUID(String artifactUUID) {
+ this.artifactUUID = artifactUUID;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
index f78b7dfead..9b8e81cc7b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
@@ -20,12 +20,9 @@
package org.openecomp.sdc.be.info;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -38,319 +35,316 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.JsonObject;
-
-import fj.data.Either;
+import java.util.*;
public class ArtifactTemplateInfo {
- public static final String TYPE = "type";
- public static final String FILE_NAME = "fileName";
- public static final String ENV = "env";
- public static final String IS_BASE = "isBase";
-
- public static final String CSAR_HEAT = "HEAT";
- public static final String CSAR_ARTIFACT = "artifacts";
- public static final String CSAR_NETWORK = "network";
- public static final String CSAR_VOLUME = "volume";
- public static final String CSAR_NESTED = "nested";
- private static final Object DESC = "description";
- private static Logger log = LoggerFactory.getLogger(ArtifactTemplateInfo.class.getName());
- String type;
- String fileName;
- String env;
- boolean isBase;
- String groupName;
- String description;
-
- List<ArtifactTemplateInfo> relatedArtifactsInfo;
- private static Gson gson = new Gson();
-
- public ArtifactTemplateInfo() {
- super();
- }
-
- public ArtifactTemplateInfo(String type, String fileName, String env, List<ArtifactTemplateInfo> relatedArtifactsInfo) {
- super();
- this.type = type;
- this.fileName = fileName;
- this.env = env;
- this.relatedArtifactsInfo = relatedArtifactsInfo;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public String getFileName() {
- return fileName;
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public String getEnv() {
- return env;
- }
-
- public void setEnv(String env) {
- this.env = env;
- }
-
- public List<ArtifactTemplateInfo> getRelatedArtifactsInfo() {
- return relatedArtifactsInfo;
- }
-
- public void setRelatedArtifactsInfo(List<ArtifactTemplateInfo> relatedArtifactsInfo) {
- this.relatedArtifactsInfo = relatedArtifactsInfo;
- }
-
- public String getGroupName() {
- return groupName;
- }
-
- public void setGroupName(String groupName) {
- this.groupName = groupName;
- }
-
- public boolean isBase() {
- return isBase;
- }
-
- public void setBase(boolean isBase) {
- this.isBase = isBase;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @Override
- public String toString() {
- return "ArtifactTemplateInfo [type=" + type + ", fileName=" + fileName + ", env=" + env + ", isBase=" + isBase + ", groupName=" + groupName + ", description=" + description + ", relatedArtifactsInfo=" + relatedArtifactsInfo + "]";
- }
-
- public static Either<ArtifactTemplateInfo, ResponseFormat> createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map<String, Object> o, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList,
- ArtifactTemplateInfo parentArtifact) {
- String content = gson.toJson(o);
- JsonObject jsonElement = new JsonObject();
- ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo();
-
- jsonElement = gson.fromJson(content, jsonElement.getClass());
-
- Map<String, Object> artifactTemplateMap = componentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class);
- if (artifactTemplateMap.containsKey(TYPE))
- resourceInfo.setType((String) artifactTemplateMap.get(TYPE));
- if (artifactTemplateMap.containsKey(FILE_NAME))
- resourceInfo.setFileName((String) artifactTemplateMap.get(FILE_NAME));
- if (artifactTemplateMap.containsKey(IS_BASE))
- resourceInfo.setBase((Boolean) artifactTemplateMap.get(IS_BASE));
- if (artifactTemplateMap.containsKey(ENV)) {
- Object envObj = artifactTemplateMap.get(ENV);
- String envStr = "";
- if (envObj instanceof String) {
- envStr = (String) envObj;
- } else if (envObj instanceof Map) {
- Map envMap = (Map) envObj;
- if (envMap.containsKey(FILE_NAME)) {
- envStr = (String) envMap.get(FILE_NAME);
- }
- }
- resourceInfo.setEnv(envStr);
- }
- if (artifactTemplateMap.containsKey(DESC)) {
- resourceInfo.setDescription((String) artifactTemplateMap.get(DESC));
- } else {
- resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME));
- }
-
- boolean artifactTypeExist = false;
- String correctType = type;
- if (type.equalsIgnoreCase(CSAR_NESTED))
- correctType = ArtifactTypeEnum.HEAT_NESTED.getType();
- else if (type.equalsIgnoreCase(CSAR_VOLUME))
- correctType = ArtifactTypeEnum.HEAT_VOL.getType();
- else if (type.equalsIgnoreCase(CSAR_NETWORK))
- correctType = ArtifactTypeEnum.HEAT_NET.getType();
- else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){
- if( parentArtifact != null)
- correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType();
- else
- correctType = resourceInfo.type;
- }
- else if (type.equalsIgnoreCase(CSAR_HEAT))
- correctType = ArtifactTypeEnum.HEAT.getType();
- else
- correctType = ArtifactTypeEnum.OTHER.getType();
- Either<List<ArtifactType>, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource);
-
- if (allArtifactTypes.isRight()) {
- BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES));
- }
-
- for (ArtifactType artType : allArtifactTypes.left().value()) {
-
- if (artType.getName().contains(correctType)) {
- resourceInfo.type = artType.getName();
- artifactTypeExist = true;
- break;
- }
- }
-
- if (!artifactTypeExist) {
- BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType);
- log.debug("Not supported artifact type = {}" , correctType);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType));
- }
-
- Either<Boolean, ResponseFormat> eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo);
- if (eitherNeedToCreate.isRight())
- return Either.right(eitherNeedToCreate.right().value());
- eitherNeedToCreate = validateParentType(componentsUtils, resourceInfo, parentArtifact);
- if (eitherNeedToCreate.isRight())
- return Either.right(eitherNeedToCreate.right().value());
- eitherNeedToCreate = validateIsAlreadyExist(componentsUtils, resourceInfo, createdArtifactTemplateInfoList, parentArtifact);
- if (eitherNeedToCreate.isRight())
- return Either.right(eitherNeedToCreate.right().value());
- Set<String> keys = o.keySet();
- for (String key : keys) {
- if (o.get(key) instanceof List) {
- List<Map<String, Object>> artifList = (List<Map<String, Object>>) o.get(key);
- for (Map<String, Object> relatedArtifactsMap : artifList) {
- Either<ArtifactTemplateInfo, ResponseFormat> relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo);
- if (relatedArtifact.isRight())
- return relatedArtifact;
- if (resourceInfo.relatedArtifactsInfo == null)
- resourceInfo.relatedArtifactsInfo = new ArrayList<ArtifactTemplateInfo>();
- resourceInfo.relatedArtifactsInfo.add(relatedArtifact.left().value());
- }
- }
- }
- return Either.left(resourceInfo);
- }
-
- private static Either<Boolean, ResponseFormat> validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) {
-
- if (parentArtifact == null) {
- if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty())
- return Either.left(true);
- for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) {
- if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type));
- }
- }
- return Either.left(true);
- } else {
- List<ArtifactTemplateInfo> relatedArtifacts = parentArtifact.getRelatedArtifactsInfo();
- if (relatedArtifacts == null || relatedArtifacts.isEmpty())
- return Either.left(true);
- for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) {
- if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType())) {
- if (relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName()));
- }
- }
- }
- return Either.left(true);
- }
- }
-
- private static Either<Boolean, ResponseFormat> validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) {
-
- if (parentArtifact == null)
- return Either.left(true);
- if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()))
- return Either.left(true);
- if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && parentArtifact != null) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
- }
- if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))
- && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
- }
- if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
- if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
- return Either.left(true);
- }
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
- }
- if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
- }
-
- if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
- return Either.left(true);
- }
- return Either.left(true);
- }
-
- private static Either<Boolean, ResponseFormat> validateEnv(ComponentsUtils componentsUtils, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) {
-
- if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty())
- return Either.left(true);
- if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()))
- return Either.left(true);
- for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) {
- // check if artifact with this name already parsed. If parsed check
- // env name. it must be the same.
- if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) {
- if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) {
- log.debug("Artifact file with name {} type{} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
- }
- if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty()
- && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) {
- log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
- }
- if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) {
- log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
- }
- }
- List<ArtifactTemplateInfo> relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo();
- Either<Boolean, ResponseFormat> status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo);
- if (status.isRight())
- return status;
- }
- return Either.left(true);
- }
-
- private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
-
- Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
- List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
-
- if (parentType.equals(NodeTypeEnum.Service)) {
- deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
- } else {
- deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
- }
- if (deploymentArtifacts != null) {
- for (String artifactType : deploymentArtifacts.keySet()) {
- ArtifactType artifactT = new ArtifactType();
- artifactT.setName(artifactType);
- artifactTypes.add(artifactT);
- }
- return Either.left(artifactTypes);
- } else {
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
-
- }
-
- public static int compareByGroupName(ArtifactTemplateInfo art1, ArtifactTemplateInfo art2) {
- return art1.isBase ? (art2.isBase ? 0 : -1) : (art2.isBase ? 1 : 0);
- }
+ public static final String TYPE = "type";
+ public static final String FILE_NAME = "fileName";
+ public static final String ENV = "env";
+ public static final String IS_BASE = "isBase";
+
+ public static final String CSAR_HEAT = "HEAT";
+ public static final String CSAR_ARTIFACT = "artifacts";
+ public static final String CSAR_NETWORK = "network";
+ public static final String CSAR_VOLUME = "volume";
+ public static final String CSAR_NESTED = "nested";
+ private static final Object DESC = "description";
+ private static final Logger log = LoggerFactory.getLogger(ArtifactTemplateInfo.class);
+ String type;
+ String fileName;
+ String env;
+ boolean isBase;
+ String groupName;
+ String description;
+
+ List<ArtifactTemplateInfo> relatedArtifactsInfo;
+ private static Gson gson = new Gson();
+
+ public ArtifactTemplateInfo() {
+ super();
+ }
+
+ public ArtifactTemplateInfo(String type, String fileName, String env, List<ArtifactTemplateInfo> relatedArtifactsInfo) {
+ super();
+ this.type = type;
+ this.fileName = fileName;
+ this.env = env;
+ this.relatedArtifactsInfo = relatedArtifactsInfo;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public String getEnv() {
+ return env;
+ }
+
+ public void setEnv(String env) {
+ this.env = env;
+ }
+
+ public List<ArtifactTemplateInfo> getRelatedArtifactsInfo() {
+ return relatedArtifactsInfo;
+ }
+
+ public void setRelatedArtifactsInfo(List<ArtifactTemplateInfo> relatedArtifactsInfo) {
+ this.relatedArtifactsInfo = relatedArtifactsInfo;
+ }
+
+ public String getGroupName() {
+ return groupName;
+ }
+
+ public void setGroupName(String groupName) {
+ this.groupName = groupName;
+ }
+
+ public boolean isBase() {
+ return isBase;
+ }
+
+ public void setBase(boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @Override
+ public String toString() {
+ return "ArtifactTemplateInfo [type=" + type + ", fileName=" + fileName + ", env=" + env + ", isBase=" + isBase + ", groupName=" + groupName + ", description=" + description + ", relatedArtifactsInfo=" + relatedArtifactsInfo + "]";
+ }
+
+ public static Either<ArtifactTemplateInfo, ResponseFormat> createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map<String, Object> o, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList,
+ ArtifactTemplateInfo parentArtifact) {
+ String content = gson.toJson(o);
+ JsonObject jsonElement = new JsonObject();
+ ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo();
+
+ jsonElement = gson.fromJson(content, jsonElement.getClass());
+
+ Map<String, Object> artifactTemplateMap = componentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class);
+ if (artifactTemplateMap.containsKey(TYPE))
+ resourceInfo.setType((String) artifactTemplateMap.get(TYPE));
+ if (artifactTemplateMap.containsKey(FILE_NAME))
+ resourceInfo.setFileName((String) artifactTemplateMap.get(FILE_NAME));
+ if (artifactTemplateMap.containsKey(IS_BASE))
+ resourceInfo.setBase((Boolean) artifactTemplateMap.get(IS_BASE));
+ if (artifactTemplateMap.containsKey(ENV)) {
+ Object envObj = artifactTemplateMap.get(ENV);
+ String envStr = "";
+ if (envObj instanceof String) {
+ envStr = (String) envObj;
+ } else if (envObj instanceof Map) {
+ Map envMap = (Map) envObj;
+ if (envMap.containsKey(FILE_NAME)) {
+ envStr = (String) envMap.get(FILE_NAME);
+ }
+ }
+ resourceInfo.setEnv(envStr);
+ }
+ if (artifactTemplateMap.containsKey(DESC)) {
+ resourceInfo.setDescription((String) artifactTemplateMap.get(DESC));
+ } else {
+ resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME));
+ }
+
+ boolean artifactTypeExist = false;
+ String correctType = type;
+ if (type.equalsIgnoreCase(CSAR_NESTED))
+ correctType = ArtifactTypeEnum.HEAT_NESTED.getType();
+ else if (type.equalsIgnoreCase(CSAR_VOLUME))
+ correctType = ArtifactTypeEnum.HEAT_VOL.getType();
+ else if (type.equalsIgnoreCase(CSAR_NETWORK))
+ correctType = ArtifactTypeEnum.HEAT_NET.getType();
+ else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){
+ if( parentArtifact != null)
+ correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType();
+ else
+ correctType = resourceInfo.type;
+ }
+ else if (type.equalsIgnoreCase(CSAR_HEAT))
+ correctType = ArtifactTypeEnum.HEAT.getType();
+ else
+ correctType = ArtifactTypeEnum.OTHER.getType();
+ Either<List<ArtifactType>, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource);
+
+ if (allArtifactTypes.isRight()) {
+ BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES));
+ }
+
+ for (ArtifactType artType : allArtifactTypes.left().value()) {
+
+ if (artType.getName().contains(correctType)) {
+ resourceInfo.type = artType.getName();
+ artifactTypeExist = true;
+ break;
+ }
+ }
+
+ if (!artifactTypeExist) {
+ BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType);
+ log.debug("Not supported artifact type = {}" , correctType);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType));
+ }
+
+ Either<Boolean, ResponseFormat> eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo);
+ if (eitherNeedToCreate.isRight())
+ return Either.right(eitherNeedToCreate.right().value());
+ eitherNeedToCreate = validateParentType(componentsUtils, resourceInfo, parentArtifact);
+ if (eitherNeedToCreate.isRight())
+ return Either.right(eitherNeedToCreate.right().value());
+ eitherNeedToCreate = validateIsAlreadyExist(componentsUtils, resourceInfo, createdArtifactTemplateInfoList, parentArtifact);
+ if (eitherNeedToCreate.isRight())
+ return Either.right(eitherNeedToCreate.right().value());
+ Set<String> keys = o.keySet();
+ for (String key : keys) {
+ if (o.get(key) instanceof List) {
+ List<Map<String, Object>> artifList = (List<Map<String, Object>>) o.get(key);
+ for (Map<String, Object> relatedArtifactsMap : artifList) {
+ Either<ArtifactTemplateInfo, ResponseFormat> relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo);
+ if (relatedArtifact.isRight())
+ return relatedArtifact;
+ if (resourceInfo.relatedArtifactsInfo == null)
+ resourceInfo.relatedArtifactsInfo = new ArrayList<ArtifactTemplateInfo>();
+ resourceInfo.relatedArtifactsInfo.add(relatedArtifact.left().value());
+ }
+ }
+ }
+ return Either.left(resourceInfo);
+ }
+
+ private static Either<Boolean, ResponseFormat> validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) {
+
+ if (parentArtifact == null) {
+ if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty())
+ return Either.left(true);
+ for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) {
+ if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type));
+ }
+ }
+ return Either.left(true);
+ } else {
+ List<ArtifactTemplateInfo> relatedArtifacts = parentArtifact.getRelatedArtifactsInfo();
+ if (relatedArtifacts == null || relatedArtifacts.isEmpty())
+ return Either.left(true);
+ for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) {
+ if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType())) {
+ if (relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName()));
+ }
+ }
+ }
+ return Either.left(true);
+ }
+ }
+
+ private static Either<Boolean, ResponseFormat> validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) {
+
+ if (parentArtifact == null)
+ return Either.left(true);
+ if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()))
+ return Either.left(true);
+ if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && parentArtifact != null) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+ }
+ if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))
+ && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+ }
+ if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
+ if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
+ return Either.left(true);
+ }
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+ }
+ if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+ }
+
+ if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
+ return Either.left(true);
+ }
+ return Either.left(true);
+ }
+
+ private static Either<Boolean, ResponseFormat> validateEnv(ComponentsUtils componentsUtils, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) {
+
+ if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty())
+ return Either.left(true);
+ if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()))
+ return Either.left(true);
+ for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) {
+ // check if artifact with this name already parsed. If parsed check
+ // env name. it must be the same.
+ if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) {
+ if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) {
+ log.debug("Artifact file with name {} type{} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
+ }
+ if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty()
+ && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) {
+ log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
+ }
+ if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) {
+ log.debug("Artifact file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
+ }
+ }
+ List<ArtifactTemplateInfo> relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo();
+ Either<Boolean, ResponseFormat> status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo);
+ if (status.isRight())
+ return status;
+ }
+ return Either.left(true);
+ }
+
+ private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
+
+ Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
+ List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
+
+ if (parentType.equals(NodeTypeEnum.Service)) {
+ deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
+ } else {
+ deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
+ }
+ if (deploymentArtifacts != null) {
+ for (String artifactType : deploymentArtifacts.keySet()) {
+ ArtifactType artifactT = new ArtifactType();
+ artifactT.setName(artifactType);
+ artifactTypes.add(artifactT);
+ }
+ return Either.left(artifactTypes);
+ } else {
+ return Either.right(ActionStatus.GENERAL_ERROR);
+ }
+
+ }
+
+ public static int compareByGroupName(ArtifactTemplateInfo art1, ArtifactTemplateInfo art2) {
+ return art1.isBase ? (art2.isBase ? 0 : -1) : (art2.isBase ? 1 : 0);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java
index 249b420908..5d635f05ff 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java
@@ -20,29 +20,29 @@
package org.openecomp.sdc.be.info;
-import java.util.List;
-
import org.openecomp.sdc.be.model.ArtifactType;
+import java.util.List;
+
public class ArtifactTypesInfo {
- Integer heatDefaultTimeout = 60;
- List<ArtifactType> artifactTypes;
+ Integer heatDefaultTimeout = 60;
+ List<ArtifactType> artifactTypes;
- public List<ArtifactType> getArtifactTypes() {
- return artifactTypes;
- }
+ public List<ArtifactType> getArtifactTypes() {
+ return artifactTypes;
+ }
- public void setArtifactTypes(List<ArtifactType> artifactTypes) {
- this.artifactTypes = artifactTypes;
- }
+ public void setArtifactTypes(List<ArtifactType> artifactTypes) {
+ this.artifactTypes = artifactTypes;
+ }
- public Integer getHeatDefaultTimeout() {
- return heatDefaultTimeout;
- }
+ public Integer getHeatDefaultTimeout() {
+ return heatDefaultTimeout;
+ }
- public void setHeatDefaultTimeout(Integer heatDefaultTimeout) {
- this.heatDefaultTimeout = heatDefaultTimeout;
- }
+ public void setHeatDefaultTimeout(Integer heatDefaultTimeout) {
+ this.heatDefaultTimeout = heatDefaultTimeout;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java
index b2fa493443..a7847a164d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java
@@ -24,29 +24,29 @@ import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
public class CreateAndAssotiateInfo {
- private ComponentInstance node;
- private RequirementCapabilityRelDef associate;
-
- public CreateAndAssotiateInfo(ComponentInstance node, RequirementCapabilityRelDef associate) {
- super();
- this.node = node;
- this.associate = associate;
- }
-
- public ComponentInstance getNode() {
- return node;
- }
-
- public void setNode(ComponentInstance node) {
- this.node = node;
- }
-
- public RequirementCapabilityRelDef getAssociate() {
- return associate;
- }
-
- public void setAssociate(RequirementCapabilityRelDef associate) {
- this.associate = associate;
- }
+ private ComponentInstance node;
+ private RequirementCapabilityRelDef associate;
+
+ public CreateAndAssotiateInfo(ComponentInstance node, RequirementCapabilityRelDef associate) {
+ super();
+ this.node = node;
+ this.associate = associate;
+ }
+
+ public ComponentInstance getNode() {
+ return node;
+ }
+
+ public void setNode(ComponentInstance node) {
+ this.node = node;
+ }
+
+ public RequirementCapabilityRelDef getAssociate() {
+ return associate;
+ }
+
+ public void setAssociate(RequirementCapabilityRelDef associate) {
+ this.associate = associate;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java
index d0f3ff868e..795d5f6046 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java
@@ -24,39 +24,39 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public enum DistributionStatus {
- DEPLOYED("Deployed", "DEPLOYED");
-
- private String name;
- private String auditingStatus;
-
- private static Logger log = LoggerFactory.getLogger(DistributionStatus.class.getName());
-
- DistributionStatus(String name, String auditingStatus) {
- this.name = name;
- this.auditingStatus = auditingStatus;
- }
-
- public String getName() {
- return name;
- }
-
- public String getAuditingStatus() {
- return auditingStatus;
- }
-
- public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) {
- DistributionStatus res = null;
- DistributionStatus[] values = values();
- for (DistributionStatus value : values) {
- if (value.getAuditingStatus().equals(auditingStatus)) {
- res = value;
- break;
- }
- }
- if (res == null) {
- log.debug("No DistributionStatus is mapped to name {}", auditingStatus);
- }
- return res;
- }
+ DEPLOYED("Deployed", "DEPLOYED");
+
+ private String name;
+ private String auditingStatus;
+
+ private static final Logger log = LoggerFactory.getLogger(DistributionStatus.class);
+
+ DistributionStatus(String name, String auditingStatus) {
+ this.name = name;
+ this.auditingStatus = auditingStatus;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getAuditingStatus() {
+ return auditingStatus;
+ }
+
+ public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) {
+ DistributionStatus res = null;
+ DistributionStatus[] values = values();
+ for (DistributionStatus value : values) {
+ if (value.getAuditingStatus().equals(auditingStatus)) {
+ res = value;
+ break;
+ }
+ }
+ if (res == null) {
+ log.debug("No DistributionStatus is mapped to name {}", auditingStatus);
+ }
+ return res;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java
index 6f7596cd5f..dd8ef32124 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java
@@ -24,68 +24,68 @@ import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
public class DistributionStatusInfo {
- String omfComponentID;
- String timestamp;
- String url;
- String status;
- String errorReason;
-
- public DistributionStatusInfo(ESTimeBasedEvent distributionStatusEvent) {
- super();
- omfComponentID = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName());
- timestamp = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName());// distributionStatusEvent.getStatusTime();
- url = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName());// distributionStatusEvent.getResoureURL();
- status = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());// distributionStatusEvent.getStatus();
- errorReason = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName());
-
- }
-
- public DistributionStatusInfo(String omfComponentID, String timestamp, String url, String status) {
- super();
- this.omfComponentID = omfComponentID;
- this.timestamp = timestamp;
- this.url = url;
- this.status = status;
- }
-
- public String getOmfComponentID() {
- return omfComponentID;
- }
-
- public void setOmfComponentID(String omfComponentID) {
- this.omfComponentID = omfComponentID;
- }
-
- public String getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- public String getErrorReason() {
- return errorReason;
- }
-
- public void setErrorReason(String errorReason) {
- this.errorReason = errorReason;
- }
+ String omfComponentID;
+ String timestamp;
+ String url;
+ String status;
+ String errorReason;
+
+ public DistributionStatusInfo(ESTimeBasedEvent distributionStatusEvent) {
+ super();
+ omfComponentID = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName());
+ timestamp = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME.getDisplayName());// distributionStatusEvent.getStatusTime();
+ url = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName());// distributionStatusEvent.getResoureURL();
+ status = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName());// distributionStatusEvent.getStatus();
+ errorReason = (String) distributionStatusEvent.getFields().get(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName());
+
+ }
+
+ public DistributionStatusInfo(String omfComponentID, String timestamp, String url, String status) {
+ super();
+ this.omfComponentID = omfComponentID;
+ this.timestamp = timestamp;
+ this.url = url;
+ this.status = status;
+ }
+
+ public String getOmfComponentID() {
+ return omfComponentID;
+ }
+
+ public void setOmfComponentID(String omfComponentID) {
+ this.omfComponentID = omfComponentID;
+ }
+
+ public String getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getErrorReason() {
+ return errorReason;
+ }
+
+ public void setErrorReason(String errorReason) {
+ this.errorReason = errorReason;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java
index ab122efc74..1f3fb90f78 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java
@@ -24,14 +24,14 @@ import java.util.List;
public class DistributionStatusListResponse {
- private List<DistributionStatusInfo> distribStatusInfoList;
+ private List<DistributionStatusInfo> distribStatusInfoList;
- public List<DistributionStatusInfo> getDistributionStatusList() {
- return distribStatusInfoList;
- }
+ public List<DistributionStatusInfo> getDistributionStatusList() {
+ return distribStatusInfoList;
+ }
- public void setDistributionStatusList(List<DistributionStatusInfo> distribStatusInfoList) {
- this.distribStatusInfoList = distribStatusInfoList;
- }
+ public void setDistributionStatusList(List<DistributionStatusInfo> distribStatusInfoList) {
+ this.distribStatusInfoList = distribStatusInfoList;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java
index dfa481d34d..533ca7e99f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java
@@ -21,54 +21,54 @@
package org.openecomp.sdc.be.info;
public class DistributionStatusOfServiceInfo {
- String distributionID;
- String timestamp;
- String userId;
- String deployementStatus;
+ String distributionID;
+ String timestamp;
+ String userId;
+ String deployementStatus;
- public DistributionStatusOfServiceInfo() {
- super();
+ public DistributionStatusOfServiceInfo() {
+ super();
- }
+ }
- public DistributionStatusOfServiceInfo(String distributionID, String timestamp, String userId, String deployementStatus) {
- super();
- this.distributionID = distributionID;
- this.timestamp = timestamp;
- this.userId = userId;
- this.deployementStatus = deployementStatus;
- }
+ public DistributionStatusOfServiceInfo(String distributionID, String timestamp, String userId, String deployementStatus) {
+ super();
+ this.distributionID = distributionID;
+ this.timestamp = timestamp;
+ this.userId = userId;
+ this.deployementStatus = deployementStatus;
+ }
- public String getDistributionID() {
- return distributionID;
- }
+ public String getDistributionID() {
+ return distributionID;
+ }
- public void setDistributionID(String distributionID) {
- this.distributionID = distributionID;
- }
+ public void setDistributionID(String distributionID) {
+ this.distributionID = distributionID;
+ }
- public String getTimestamp() {
- return timestamp;
- }
+ public String getTimestamp() {
+ return timestamp;
+ }
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
- public String getUserId() {
- return userId;
- }
+ public String getUserId() {
+ return userId;
+ }
- public void setUserId(String userId) {
- this.userId = userId;
- }
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
- public String getDeployementStatus() {
- return deployementStatus;
- }
+ public String getDeployementStatus() {
+ return deployementStatus;
+ }
- public void setDeployementStatus(String deployementStatus) {
- this.deployementStatus = deployementStatus;
- }
+ public void setDeployementStatus(String deployementStatus) {
+ this.deployementStatus = deployementStatus;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java
index 8415736be1..023645fa2d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java
@@ -24,14 +24,14 @@ import java.util.List;
public class DistributionStatusOfServiceListResponce {
- private List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList;
+ private List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList;
- public List<DistributionStatusOfServiceInfo> getDistributionStatusOfServiceList() {
- return distribStatusOfServiceInfoList;
- }
+ public List<DistributionStatusOfServiceInfo> getDistributionStatusOfServiceList() {
+ return distribStatusOfServiceInfoList;
+ }
- public void setDistributionStatusOfServiceList(List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList) {
- this.distribStatusOfServiceInfoList = distribStatusOfServiceInfoList;
- }
+ public void setDistributionStatusOfServiceList(List<DistributionStatusOfServiceInfo> distribStatusOfServiceInfoList) {
+ this.distribStatusOfServiceInfoList = distribStatusOfServiceInfoList;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
index ea495267bd..f49315c0d0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
@@ -20,157 +20,157 @@
package org.openecomp.sdc.be.info;
-import java.util.List;
-
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupProperty;
+import java.util.List;
+
public class GroupDefinitionInfo {
- private String name;
-
- // the id is unique per group instance on graph.
- private String uniqueId;
-
- // the id is unique per group instance on graph.
- private String groupInstanceUniqueId;
-
- // the group UUID should be changed when one of the artifacts/component
- // instances has been changed.
- private String groupUUID;
-
- // version should be changed when there is a change to the group's metadata
- // or to the groups members
- // (not necessarily when the VF version is changed). This field cannot be
- // updated by user
- private String version;
-
- private String invariantUUID;
- private String customizationUUID;
-
- Boolean isBase = null;
-
- // artifacts - list of artifact uid. All artifacts in the group must already
- // be uploaded to the VF
- private List<ArtifactDefinitionInfo> artifacts;
-
- private List<? extends GroupProperty> properties;
-
- public GroupDefinitionInfo() {
- super();
- }
-
- public GroupDefinitionInfo(GroupDefinition other) {
- this.setName(other.getName());
- this.setUniqueId(other.getUniqueId());
- this.setVersion(other.getVersion());
- this.setGroupUUID(other.getGroupUUID());
- this.setInvariantUUID(other.getInvariantUUID());
- this.setProperties(other.convertToGroupProperties());
-
-
- }
-
- public GroupDefinitionInfo(GroupInstance other) {
- this.setName(other.getGroupName());
- this.setUniqueId(other.getGroupUid());
- this.setGroupInstanceUniqueId(other.getUniqueId());
- this.setVersion(other.getVersion());
- this.setGroupUUID(other.getGroupUUID());
- this.setCustomizationUUID(other.getCustomizationUUID());
- this.setInvariantUUID(other.getInvariantUUID());
- this.setProperties(other.convertToGroupInstancesProperties());
-
-
- }
-
- 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 getUniqueId() {
- return uniqueId;
- }
-
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
-
- public String getGroupUUID() {
- return groupUUID;
- }
-
- public void setGroupUUID(String groupUUID) {
- this.groupUUID = groupUUID;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
-
- public String getCustomizationUUID() {
- return customizationUUID;
- }
-
- public void setCustomizationUUID(String customizationUUID) {
- this.customizationUUID = customizationUUID;
- }
-
- public Boolean getIsBase() {
- return isBase;
- }
-
- public void setIsBase(Boolean isBase) {
- this.isBase = isBase;
- }
-
- public List<ArtifactDefinitionInfo> getArtifacts() {
- return artifacts;
- }
-
- public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) {
- this.artifacts = artifacts;
- }
-
- public List<? extends GroupProperty> getProperties() {
- return properties;
- }
-
- public void setProperties(List<? extends GroupProperty> properties) {
- this.properties = properties;
- }
-
-
-
- public String getGroupInstanceUniqueId() {
- return groupInstanceUniqueId;
- }
-
- public void setGroupInstanceUniqueId(String groupInstanceUniqueId) {
- this.groupInstanceUniqueId = groupInstanceUniqueId;
- }
-
- @Override
- public String toString() {
- return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]";
- }
-
+ private String name;
+
+ // the id is unique per group instance on graph.
+ private String uniqueId;
+
+ // the id is unique per group instance on graph.
+ private String groupInstanceUniqueId;
+
+ // the group UUID should be changed when one of the artifacts/component
+ // instances has been changed.
+ private String groupUUID;
+
+ // version should be changed when there is a change to the group's metadata
+ // or to the groups members
+ // (not necessarily when the VF version is changed). This field cannot be
+ // updated by user
+ private String version;
+
+ private String invariantUUID;
+ private String customizationUUID;
+
+ Boolean isBase = null;
+
+ // artifacts - list of artifact uid. All artifacts in the group must already
+ // be uploaded to the VF
+ private List<ArtifactDefinitionInfo> artifacts;
+
+ private List<? extends GroupProperty> properties;
+
+ public GroupDefinitionInfo() {
+ super();
+ }
+
+ public GroupDefinitionInfo(GroupDefinition other) {
+ this.setName(other.getName());
+ this.setUniqueId(other.getUniqueId());
+ this.setVersion(other.getVersion());
+ this.setGroupUUID(other.getGroupUUID());
+ this.setInvariantUUID(other.getInvariantUUID());
+ this.setProperties(other.convertToGroupProperties());
+
+
+ }
+
+ public GroupDefinitionInfo(GroupInstance other) {
+ this.setName(other.getGroupName());
+ this.setUniqueId(other.getGroupUid());
+ this.setGroupInstanceUniqueId(other.getUniqueId());
+ this.setVersion(other.getVersion());
+ this.setGroupUUID(other.getGroupUUID());
+ this.setCustomizationUUID(other.getCustomizationUUID());
+ this.setInvariantUUID(other.getInvariantUUID());
+ this.setProperties(other.convertToGroupInstancesProperties());
+
+
+ }
+
+ 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 getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getGroupUUID() {
+ return groupUUID;
+ }
+
+ public void setGroupUUID(String groupUUID) {
+ this.groupUUID = groupUUID;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+
+ public String getCustomizationUUID() {
+ return customizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.customizationUUID = customizationUUID;
+ }
+
+ public Boolean getIsBase() {
+ return isBase;
+ }
+
+ public void setIsBase(Boolean isBase) {
+ this.isBase = isBase;
+ }
+
+ public List<ArtifactDefinitionInfo> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public List<? extends GroupProperty> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<? extends GroupProperty> properties) {
+ this.properties = properties;
+ }
+
+
+
+ public String getGroupInstanceUniqueId() {
+ return groupInstanceUniqueId;
+ }
+
+ public void setGroupInstanceUniqueId(String groupInstanceUniqueId) {
+ this.groupInstanceUniqueId = groupInstanceUniqueId;
+ }
+
+ @Override
+ public String toString() {
+ return "GroupDefinitionInfo [" + super.toString() + ", isBase=" + isBase + ", artifacts=" + artifacts + "]";
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
index 4a7e925639..301cffafdc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
@@ -21,36 +21,36 @@
package org.openecomp.sdc.be.info;
public class GroupTemplateInfo {
- String groupName;
- boolean isBase;
- ArtifactTemplateInfo artifactTemplateInfo;
+ String groupName;
+ boolean isBase;
+ ArtifactTemplateInfo artifactTemplateInfo;
- public GroupTemplateInfo() {
- super();
- }
+ public GroupTemplateInfo() {
+ super();
+ }
- public String getGroupName() {
- return groupName;
- }
+ public String getGroupName() {
+ return groupName;
+ }
- public void setGroupName(String groupName) {
- this.groupName = groupName;
- }
+ public void setGroupName(String groupName) {
+ this.groupName = groupName;
+ }
- public boolean isBase() {
- return isBase;
- }
+ public boolean isBase() {
+ return isBase;
+ }
- public void setBase(boolean isBase) {
- this.isBase = isBase;
- }
+ public void setBase(boolean isBase) {
+ this.isBase = isBase;
+ }
- public ArtifactTemplateInfo getArtifactTemplateInfo() {
- return artifactTemplateInfo;
- }
+ public ArtifactTemplateInfo getArtifactTemplateInfo() {
+ return artifactTemplateInfo;
+ }
- public void setArtifactTemplateInfo(ArtifactTemplateInfo artifactTemplateInfo) {
- this.artifactTemplateInfo = artifactTemplateInfo;
- }
+ public void setArtifactTemplateInfo(ArtifactTemplateInfo artifactTemplateInfo) {
+ this.artifactTemplateInfo = artifactTemplateInfo;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
index 62ee5b6f81..e4b6f35cba 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
@@ -20,150 +20,145 @@
package org.openecomp.sdc.be.info;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import java.util.*;
public class MergedArtifactInfo {
- private List<ArtifactDefinition> createdArtifact;
- private ArtifactTemplateInfo jsonArtifactTemplate;
- private Set<String> parsetArtifactsNames;
-
- public List<ArtifactDefinition> getCreatedArtifact() {
- return createdArtifact;
- }
-
- public void setCreatedArtifact(List<ArtifactDefinition> createdArtifact) {
- this.createdArtifact = createdArtifact;
- parsetArtifactsNames = new HashSet<String>();
- parsetArtifactsNames.add(jsonArtifactTemplate.getFileName());
- List<ArtifactTemplateInfo> relatedGroupTemplateList = jsonArtifactTemplate.getRelatedArtifactsInfo();
- if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
- this.createArtifactsGroupSet(relatedGroupTemplateList, parsetArtifactsNames);
- }
-
- }
-
- public ArtifactTemplateInfo getJsonArtifactTemplate() {
- return jsonArtifactTemplate;
- }
-
- public void setJsonArtifactTemplate(ArtifactTemplateInfo jsonArtifactTemplate) {
- this.jsonArtifactTemplate = jsonArtifactTemplate;
- }
-
- public List<ArtifactTemplateInfo> getListToAssociateArtifactToGroup() {
- List<ArtifactTemplateInfo> resList = new ArrayList<ArtifactTemplateInfo>();
- List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo();
- if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
- getNewArtifactsInGroup(resList, relatedArtifacts);
- }
- return resList;
- }
-
- public List<ArtifactDefinition> getListToDissotiateArtifactFromGroup(List<ArtifactDefinition> deletedArtifacts) {
- List<ArtifactDefinition> resList = new ArrayList<ArtifactDefinition>();
- for (ArtifactDefinition artifactDefinition : createdArtifact) {
- boolean isDissotiate = true;
- if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){
- isDissotiate = false;
- }else{
- if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){
- Optional<ArtifactDefinition> op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
- if(op.isPresent()){
- ArtifactDefinition generatedFromArt = op.get();
- if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){
- isDissotiate = false;
- }
- }
- else{
- isDissotiate = true;
- }
-
- }
- }
- if (isDissotiate) {
- boolean isDeleted = false;
- for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
- if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) {
- isDeleted = true;
- break;
- }
-
- }
- if (!isDeleted)
- resList.add(artifactDefinition);
- }
-
- }
-
- return resList;
- }
-
- public List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> getListToUpdateArtifactInGroup() {
- List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList = new ArrayList<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>();
- for (ArtifactDefinition artifactDefinition : createdArtifact) {
- if (artifactDefinition.getArtifactName().equalsIgnoreCase(jsonArtifactTemplate.getFileName())) {
- resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, jsonArtifactTemplate));
- }
- }
- List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo();
- if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
- getUpdateArtifactsInGroup(resList, relatedArtifacts);
- }
- return resList;
- }
-
- private void getUpdateArtifactsInGroup(List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList, List<ArtifactTemplateInfo> jsonArtifacts) {
-
- for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) {
-
- for (ArtifactDefinition artifactDefinition : createdArtifact) {
- if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) {
- resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, artifactTemplateInfo));
- }
- }
-
- List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
- if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
- getUpdateArtifactsInGroup(resList, relatedArtifacts);
- }
- }
- }
-
- private void getNewArtifactsInGroup(List<ArtifactTemplateInfo> resList, List<ArtifactTemplateInfo> jsonArtifacts) {
-
- for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) {
- boolean isNewArtifact = true;
- for (ArtifactDefinition artifactDefinition : createdArtifact) {
- if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) {
- isNewArtifact = false;
- }
- }
- if (isNewArtifact)
- resList.add(artifactTemplateInfo);
- List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
- if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
- getNewArtifactsInGroup(resList, relatedArtifacts);
- }
- }
- }
-
- private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<String> parsedArtifactsName) {
-
- for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
- parsedArtifactsName.add(parsedGroupTemplate.getFileName());
- List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
- if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
- createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
- }
- }
- }
+ private List<ArtifactDefinition> createdArtifact;
+ private ArtifactTemplateInfo jsonArtifactTemplate;
+ private Set<String> parsetArtifactsNames;
+
+ public List<ArtifactDefinition> getCreatedArtifact() {
+ return createdArtifact;
+ }
+
+ public void setCreatedArtifact(List<ArtifactDefinition> createdArtifact) {
+ this.createdArtifact = createdArtifact;
+ parsetArtifactsNames = new HashSet<String>();
+ parsetArtifactsNames.add(jsonArtifactTemplate.getFileName());
+ List<ArtifactTemplateInfo> relatedGroupTemplateList = jsonArtifactTemplate.getRelatedArtifactsInfo();
+ if (relatedGroupTemplateList != null && !relatedGroupTemplateList.isEmpty()) {
+ this.createArtifactsGroupSet(relatedGroupTemplateList, parsetArtifactsNames);
+ }
+
+ }
+
+ public ArtifactTemplateInfo getJsonArtifactTemplate() {
+ return jsonArtifactTemplate;
+ }
+
+ public void setJsonArtifactTemplate(ArtifactTemplateInfo jsonArtifactTemplate) {
+ this.jsonArtifactTemplate = jsonArtifactTemplate;
+ }
+
+ public List<ArtifactTemplateInfo> getListToAssociateArtifactToGroup() {
+ List<ArtifactTemplateInfo> resList = new ArrayList<ArtifactTemplateInfo>();
+ List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
+ getNewArtifactsInGroup(resList, relatedArtifacts);
+ }
+ return resList;
+ }
+
+ public List<ArtifactDefinition> getListToDissotiateArtifactFromGroup(List<ArtifactDefinition> deletedArtifacts) {
+ List<ArtifactDefinition> resList = new ArrayList<ArtifactDefinition>();
+ for (ArtifactDefinition artifactDefinition : createdArtifact) {
+ boolean isDissotiate = true;
+ if(parsetArtifactsNames.contains(artifactDefinition.getArtifactName())){
+ isDissotiate = false;
+ }else{
+ if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){
+ Optional<ArtifactDefinition> op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
+ if(op.isPresent()){
+ ArtifactDefinition generatedFromArt = op.get();
+ if(parsetArtifactsNames.contains(generatedFromArt.getArtifactName())){
+ isDissotiate = false;
+ }
+ }
+ else{
+ isDissotiate = true;
+ }
+
+ }
+ }
+ if (isDissotiate) {
+ boolean isDeleted = false;
+ for (ArtifactDefinition deletedArtifact : deletedArtifacts) {
+ if (artifactDefinition.getUniqueId().equalsIgnoreCase(deletedArtifact.getUniqueId())) {
+ isDeleted = true;
+ break;
+ }
+
+ }
+ if (!isDeleted)
+ resList.add(artifactDefinition);
+ }
+
+ }
+
+ return resList;
+ }
+
+ public List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> getListToUpdateArtifactInGroup() {
+ List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList = new ArrayList<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>();
+ for (ArtifactDefinition artifactDefinition : createdArtifact) {
+ if (artifactDefinition.getArtifactName().equalsIgnoreCase(jsonArtifactTemplate.getFileName())) {
+ resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, jsonArtifactTemplate));
+ }
+ }
+ List<ArtifactTemplateInfo> relatedArtifacts = jsonArtifactTemplate.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
+ getUpdateArtifactsInGroup(resList, relatedArtifacts);
+ }
+ return resList;
+ }
+
+ private void getUpdateArtifactsInGroup(List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList, List<ArtifactTemplateInfo> jsonArtifacts) {
+
+ for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) {
+
+ for (ArtifactDefinition artifactDefinition : createdArtifact) {
+ if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) {
+ resList.add(new ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>(artifactDefinition, artifactTemplateInfo));
+ }
+ }
+
+ List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
+ getUpdateArtifactsInGroup(resList, relatedArtifacts);
+ }
+ }
+ }
+
+ private void getNewArtifactsInGroup(List<ArtifactTemplateInfo> resList, List<ArtifactTemplateInfo> jsonArtifacts) {
+
+ for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) {
+ boolean isNewArtifact = true;
+ for (ArtifactDefinition artifactDefinition : createdArtifact) {
+ if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) {
+ isNewArtifact = false;
+ }
+ }
+ if (isNewArtifact)
+ resList.add(artifactTemplateInfo);
+ List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
+ getNewArtifactsInGroup(resList, relatedArtifacts);
+ }
+ }
+ }
+
+ private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<String> parsedArtifactsName) {
+
+ for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
+ parsedArtifactsName.add(parsedGroupTemplate.getFileName());
+ List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
+ if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
+ createArtifactsGroupSet(relatedArtifacts, parsedArtifactsName);
+ }
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java
new file mode 100644
index 0000000000..766581bd62
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java
@@ -0,0 +1,41 @@
+package org.openecomp.sdc.be.info;
+
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+
+public class NodeTypeInfoToUpdateArtifacts {
+
+ private String nodeName;
+ private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle;
+
+
+ public NodeTypeInfoToUpdateArtifacts(String nodeName,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle) {
+ super();
+ this.nodeName = nodeName;
+ this.nodeTypesArtifactsToHandle = nodeTypesArtifactsToHandle;
+ }
+
+ public String getNodeName() {
+ return nodeName;
+ }
+
+ public void setNodeName(String nodeName) {
+ this.nodeName = nodeName;
+ }
+
+ public Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> getNodeTypesArtifactsToHandle() {
+ return nodeTypesArtifactsToHandle;
+ }
+
+ public void setNodeTypesArtifactsToHandle(
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle) {
+ this.nodeTypesArtifactsToHandle = nodeTypesArtifactsToHandle;
+ }
+
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java
new file mode 100644
index 0000000000..4d27713e22
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java
@@ -0,0 +1,123 @@
+package org.openecomp.sdc.be.info;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+public final class OperationalEnvInfo {
+ @JsonIgnore
+ private static ObjectMapper objectMapper = new ObjectMapper();
+
+ @JsonIgnore
+ private static final Logger logger = LoggerFactory.getLogger(OperationalEnvInfo.class);
+
+ @JsonProperty("operational-environment-id")
+ private String operationalEnvId;
+
+ @JsonProperty("operational-environment-name")
+ private String operationalEnvName;
+
+ @JsonProperty("operational-environment-type")
+ private String operationalEnvType;
+
+ @JsonProperty("operational-environment-status")
+ private String operationalEnvStatus;
+
+ @JsonProperty("tenant-context")
+ private String tenantContext;
+
+ @JsonProperty("workload-context")
+ private String workloadContext;
+
+ @JsonProperty("resource-version")
+ private String resourceVersion;
+
+ @JsonProperty("relationship-list")
+ private RelationshipList relationships;
+
+ public String getOperationalEnvId() {
+ return operationalEnvId;
+ }
+
+ public void setOperationalEnvId(String operationalEnvId) {
+ this.operationalEnvId = operationalEnvId;
+ }
+
+ public String getOperationalEnvName() {
+ return operationalEnvName;
+ }
+
+ public void setOperationalEnvName(String operationalEnvName) {
+ this.operationalEnvName = operationalEnvName;
+ }
+
+ public String getOperationalEnvType() {
+ return operationalEnvType;
+ }
+
+ public void setOperationalEnvType(String operationalEnvType) {
+ this.operationalEnvType = operationalEnvType;
+ }
+
+ public String getOperationalEnvStatus() {
+ return operationalEnvStatus;
+ }
+
+ public void setOperationalEnvStatus(String operationalEnvStatus) {
+ this.operationalEnvStatus = operationalEnvStatus;
+ }
+
+ public String getTenantContext() {
+ return tenantContext;
+ }
+
+ public void setTenantContext(String tenantContext) {
+ this.tenantContext = tenantContext;
+ }
+
+ public String getWorkloadContext() {
+ return workloadContext;
+ }
+
+ public void setWorkloadContext(String workloadContext) {
+ this.workloadContext = workloadContext;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ public RelationshipList getRelationships() {
+ return relationships;
+ }
+
+ public void setRelationships(RelationshipList relationships) {
+ this.relationships = relationships;
+ }
+
+ @Override
+ public String toString() {
+ try {
+ return objectMapper.writeValueAsString(this);
+ }
+ catch (JsonProcessingException e) {
+ logger.debug("Convert object to string failed with exception. ", e);
+ return StringUtils.EMPTY;
+ }
+ }
+
+ public static OperationalEnvInfo createFromJson(String json) throws IOException {
+ return objectMapper.readValue(json, OperationalEnvInfo.class);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java
new file mode 100644
index 0000000000..5684c9b57f
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java
@@ -0,0 +1,28 @@
+package org.openecomp.sdc.be.info;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public final class RelatedToProperty {
+
+ @JsonProperty("property-key")
+ private String propertyKey;
+
+ @JsonProperty("property-value")
+ private String propertyValue;
+
+ public String getPropertyKey() {
+ return propertyKey;
+ }
+
+ public void setPropertyKey(String propertyKey) {
+ this.propertyKey = propertyKey;
+ }
+
+ public String getPropertyValue() {
+ return propertyValue;
+ }
+
+ public void setPropertyValue(String propertyValue) {
+ this.propertyValue = propertyValue;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java
new file mode 100644
index 0000000000..fba6632698
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java
@@ -0,0 +1,70 @@
+package org.openecomp.sdc.be.info;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public final class Relationship {
+
+ @JsonProperty("related-to")
+ private String relatedTo;
+
+ @JsonProperty(value="relationship-label")
+ private String relationshipLabel;
+
+ @JsonProperty(value="related-link", required=false)
+ private String relatedLink;
+
+ @JsonProperty("relationship-data")
+ private List<RelationshipData> relationshipData;
+
+ @JsonProperty("related-to-property")
+ private List<RelatedToProperty> relatedToProperty;
+
+ public String getRelatedTo() {
+ return relatedTo;
+ }
+
+ public void setRelatedTo(String relatedTo) {
+ this.relatedTo = relatedTo;
+ }
+
+ public String getRelatedLink() {
+ return relatedLink;
+ }
+
+ public void setRelatedLink(String relatedLink) {
+ this.relatedLink = relatedLink;
+ }
+
+ public List<RelationshipData> getRelationshipData() {
+ if(relationshipData == null) {
+ relationshipData = new ArrayList<>();
+ }
+ return relationshipData;
+ }
+
+ public void setRelationshipData(List<RelationshipData> relationshipData) {
+ this.relationshipData = relationshipData;
+ }
+
+ public String getRelationshipLabel() {
+ return relationshipLabel;
+ }
+
+ public void setRelationshipLabel(String relationshipLabel) {
+ this.relationshipLabel = relationshipLabel;
+ }
+
+ public List<RelatedToProperty> getRelatedToProperty() {
+ if(relatedToProperty == null) {
+ relatedToProperty = new ArrayList<>();
+ }
+ return relatedToProperty;
+ }
+
+ public void setRelatedToProperty(List<RelatedToProperty> relatedToProperty) {
+ this.relatedToProperty = relatedToProperty;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java
new file mode 100644
index 0000000000..2b01daecd4
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java
@@ -0,0 +1,28 @@
+package org.openecomp.sdc.be.info;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public final class RelationshipData {
+
+ @JsonProperty("relationship-key")
+ private String relationshipKey;
+
+ @JsonProperty("relationship-value")
+ private String relationshipValue;
+
+ public void setRelationshipkey(String relationshipKey) {
+ this.relationshipKey = relationshipKey;
+ }
+
+ public String getRelationshipKey() {
+ return this.relationshipKey;
+ }
+
+ public void setRelationshipValue(String relationshipValue) {
+ this.relationshipValue = relationshipValue;
+ }
+
+ public String getRelationshipValue() {
+ return this.relationshipValue;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java
new file mode 100644
index 0000000000..6a09a84d6e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java
@@ -0,0 +1,20 @@
+package org.openecomp.sdc.be.info;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class RelationshipList {
+ private List<Relationship> relationship;
+
+ public List<Relationship> getRelationship() {
+ if(relationship == null) {
+ relationship = new ArrayList<>();
+ }
+ return relationship;
+ }
+
+ public void setRelationship(List<Relationship> relationship) {
+ this.relationship = relationship;
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java
index 457c49ee8e..99395350cb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java
@@ -24,28 +24,28 @@ import java.util.List;
public class ServiceInfo {
- private String name;
- private List<ServiceVersionInfo> versions;
+ private String name;
+ private List<ServiceVersionInfo> versions;
- public ServiceInfo(String serviceName, List<ServiceVersionInfo> list) {
- this.name = serviceName;
- this.versions = list;
- }
+ public ServiceInfo(String serviceName, List<ServiceVersionInfo> list) {
+ this.name = serviceName;
+ this.versions = list;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }
- public List<ServiceVersionInfo> getVersions() {
- return versions;
- }
+ public List<ServiceVersionInfo> getVersions() {
+ return versions;
+ }
- public void setVersions(List<ServiceVersionInfo> versions) {
- this.versions = versions;
- }
+ public void setVersions(List<ServiceVersionInfo> versions) {
+ this.versions = versions;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java
index 13f8a1307f..32c7c54528 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java
@@ -22,32 +22,30 @@ package org.openecomp.sdc.be.info;
public class ServiceVersionInfo {
- // private String serviceName;
- private String version;
- private String url;
-
- public ServiceVersionInfo(String serviceName, String serviceVersion, String context) {
- super();
- // this.serviceName = serviceName;
- this.version = serviceVersion;
- StringBuilder sb = new StringBuilder(context);
- sb.append("services/").append(serviceName).append("/").append(serviceVersion);
- url = sb.toString();
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setVersion(String serviceVersion) {
- this.version = serviceVersion;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
+ private String version;
+ private String url;
+
+ public ServiceVersionInfo(String serviceName, String serviceVersion, String context) {
+ super();
+ this.version = serviceVersion;
+ StringBuilder sb = new StringBuilder(context);
+ sb.append("services/").append(serviceName).append("/").append(serviceVersion);
+ url = sb.toString();
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String serviceVersion) {
+ this.version = serviceVersion;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java
index 9c26cf5959..00f41ad434 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java
@@ -23,13 +23,13 @@ package org.openecomp.sdc.be.info;
import java.util.List;
public class ServicesWrapper {
- private List<ServiceInfo> services;
+ private List<ServiceInfo> services;
- public List<ServiceInfo> getServices() {
- return services;
- }
+ public List<ServiceInfo> getServices() {
+ return services;
+ }
- public void setServices(List<ServiceInfo> services) {
- this.services = services;
- }
+ public void setServices(List<ServiceInfo> services) {
+ this.services = services;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java
index 5559311e9e..ae2032eb43 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java
@@ -22,23 +22,23 @@ package org.openecomp.sdc.be.info;
public class ServletJsonResponse {
- String source;
- String description;
+ String source;
+ String description;
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public String getSource() {
- return source;
- }
+ public String getSource() {
+ return source;
+ }
- public void setSource(String source) {
- this.source = source;
- }
+ public void setSource(String source) {
+ this.source = source;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java
index 11b27af7a1..031477cfe9 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java
@@ -24,46 +24,46 @@ import java.util.List;
public class ToscaNodeTypeInfo {
- private String nodeName;
- private String templateVersion;
- private List<ToscaNodeTypeInterface> interfaces;
- private String iconPath;
+ private String nodeName;
+ private String templateVersion;
+ private List<ToscaNodeTypeInterface> interfaces;
+ private String iconPath;
- public String getNodeName() {
- return nodeName;
- }
+ public String getNodeName() {
+ return nodeName;
+ }
- public void setNodeName(String nodeName) {
- this.nodeName = nodeName;
- }
+ public void setNodeName(String nodeName) {
+ this.nodeName = nodeName;
+ }
- public String getTemplateVersion() {
- return templateVersion;
- }
+ public String getTemplateVersion() {
+ return templateVersion;
+ }
- public void setTemplateVersion(String templateVersion) {
- this.templateVersion = templateVersion;
- }
+ public void setTemplateVersion(String templateVersion) {
+ this.templateVersion = templateVersion;
+ }
- public List<ToscaNodeTypeInterface> getInterfaces() {
- return interfaces;
- }
+ public List<ToscaNodeTypeInterface> getInterfaces() {
+ return interfaces;
+ }
- public void setInterfaces(List<ToscaNodeTypeInterface> interfaces) {
- this.interfaces = interfaces;
- }
+ public void setInterfaces(List<ToscaNodeTypeInterface> interfaces) {
+ this.interfaces = interfaces;
+ }
- public String getIconPath() {
- return iconPath;
- }
+ public String getIconPath() {
+ return iconPath;
+ }
- public void setIconPath(String iconPath) {
- this.iconPath = iconPath;
- }
+ public void setIconPath(String iconPath) {
+ this.iconPath = iconPath;
+ }
- @Override
- public String toString() {
- return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]";
- }
+ @Override
+ public String toString() {
+ return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]";
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java
index 25bab766bf..05fa3193c1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java
@@ -24,14 +24,14 @@ import java.util.List;
public class ToscaNodeTypeInterface {
- List<String> scripts;
+ List<String> scripts;
- public List<String> getScripts() {
- return scripts;
- }
+ public List<String> getScripts() {
+ return scripts;
+ }
- public void setScripts(List<String> scripts) {
- this.scripts = scripts;
- }
+ public void setScripts(List<String> scripts) {
+ this.scripts = scripts;
+ }
}
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 83cda6ef87..f895577c5d 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
@@ -41,54 +41,53 @@ import org.slf4j.LoggerFactory;
public class BEAppContextListener extends AppContextListener implements ServletContextListener {
- private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF";
- private static Logger log = LoggerFactory.getLogger(BEAppContextListener.class.getName());
-
- public void contextInitialized(ServletContextEvent context) {
+ private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF";
+ private static final Logger log = LoggerFactory.getLogger(BEAppContextListener.class);
- super.contextInitialized(context);
+ public void contextInitialized(ServletContextEvent context) {
- ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource());
- log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName());
+ super.contextInitialized(context);
- context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager);
+ ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource());
+ log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName());
- WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper();
- context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper);
+ context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager);
- DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic();
- context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic);
+ WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper();
+ context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper);
- context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
+ DownloadArtifactLogic downloadArtifactLogic = new DownloadArtifactLogic();
+ context.getServletContext().setAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR, downloadArtifactLogic);
- // Monitoring service
- BeMonitoringService bms = new BeMonitoringService(context.getServletContext());
- bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15));
+ context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
- log.debug("After executing {}", this.getClass());
+ // Monitoring service
+ BeMonitoringService bms = new BeMonitoringService(context.getServletContext());
+ bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15));
- }
-
- private String getVersionFromManifest(ServletContextEvent context) {
- ServletContext servletContext = context.getServletContext();
- InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME);
+ log.debug("After executing {}", this.getClass());
- String version = null;
- try {
- Manifest mf = new Manifest(inputStream);
- Attributes atts = mf.getMainAttributes();
- version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR);
- if (version == null || version.isEmpty()) {
- log.warn("failed to read ASDC version from MANIFEST.");
- } else {
- log.info("ASDC version from MANIFEST is {}", version);
- }
+ }
- } catch (IOException e) {
- log.warn("failed to read ASDC version from MANIFEST", e.getMessage());
- }
+ private String getVersionFromManifest(ServletContextEvent context) {
+ ServletContext servletContext = context.getServletContext();
+ InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME);
- return version;
- }
+ String version = null;
+ try {
+ Manifest mf = new Manifest(inputStream);
+ Attributes atts = mf.getMainAttributes();
+ version = atts.getValue(Constants.ASDC_RELEASE_VERSION_ATTR);
+ if (version == null || version.isEmpty()) {
+ log.warn("failed to read ASDC version from MANIFEST.");
+ } else {
+ log.info("ASDC version from MANIFEST is {}", version);
+ }
+
+ } catch (IOException e) {
+ log.warn("failed to read ASDC version from MANIFEST", e);
+ }
+ return version;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java
new file mode 100644
index 0000000000..216e55a2b1
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java
@@ -0,0 +1,20 @@
+package org.openecomp.sdc.be.mixin;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition;
+import org.openecomp.sdc.be.view.Mixin;
+import org.openecomp.sdc.be.view.MixinTarget;
+
+@MixinTarget(target = GroupTypeDataDefinition.class)
+public abstract class GroupTypeMixin extends Mixin {
+
+ @JsonProperty
+ abstract String getType();
+ @JsonProperty
+ abstract String getVersion();
+ @JsonProperty
+ abstract String getUniqueId();
+
+}
+
+
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java
new file mode 100644
index 0000000000..0fd86e1ced
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java
@@ -0,0 +1,20 @@
+package org.openecomp.sdc.be.mixin;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
+import org.openecomp.sdc.be.view.Mixin;
+import org.openecomp.sdc.be.view.MixinTarget;
+
+@MixinTarget(target = PolicyTypeDataDefinition.class)
+public abstract class PolicyTypeMixin extends Mixin {
+
+ @JsonProperty
+ abstract String getType();
+ @JsonProperty
+ abstract String getVersion();
+ @JsonProperty
+ abstract String getUniqueId();
+
+}
+
+
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java
index 6be300d6db..ba6596d1a2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java
@@ -20,12 +20,6 @@
package org.openecomp.sdc.be.monitoring;
-import java.net.URI;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.proxy.ProxyServlet;
@@ -36,75 +30,80 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.net.URI;
+
public class EsGateway extends ProxyServlet {
- private static final long serialVersionUID = 1L;
- private static Logger log = LoggerFactory.getLogger(EsGateway.class.getName());
+ private static final long serialVersionUID = 1L;
+ private static final Logger log = LoggerFactory.getLogger(EsGateway.class);
- @Override
- public URI rewriteURI(HttpServletRequest request) {
+ @Override
+ public URI rewriteURI(HttpServletRequest request) {
- String originalUrl = request.getRequestURI();
+ String originalUrl = request.getRequestURI();
- String redirectedUrl = getModifiedUrl(request);
+ String redirectedUrl = getModifiedUrl(request);
- log.debug("EsGateway Redirecting request from: {} , to: {}", originalUrl, redirectedUrl);
- return URI.create(redirectedUrl);
- }
+ log.debug("EsGateway Redirecting request from: {} , to: {}", originalUrl, redirectedUrl);
+ return URI.create(redirectedUrl);
+ }
- @Override
- public void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) {
- super.customizeProxyRequest(proxyRequest, request);
+ @Override
+ public void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) {
+ super.customizeProxyRequest(proxyRequest, request);
- }
+ }
- @Override
- protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
- super.onResponseSuccess(request, response, proxyResponse);
- }
+ @Override
+ protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
+ super.onResponseSuccess(request, response, proxyResponse);
+ }
- public String getModifiedUrl(HttpServletRequest request) {
- String esHost = null;
- String esPort = null;
- MonitoringBusinessLogic monitoringBL = getMonitoringBL(request.getSession().getServletContext());
- if (monitoringBL == null) {
- log.error("failed to retrive monitoringBL.");
- } else {
- esHost = monitoringBL.getEsHost();
- esPort = monitoringBL.getEsPort();
- }
+ public String getModifiedUrl(HttpServletRequest request) {
+ String esHost = null;
+ String esPort = null;
+ MonitoringBusinessLogic monitoringBL = getMonitoringBL(request.getSession().getServletContext());
+ if (monitoringBL == null) {
+ log.error("failed to retrive monitoringBL.");
+ } else {
+ esHost = monitoringBL.getEsHost();
+ esPort = monitoringBL.getEsPort();
+ }
- //String scheme = request.getScheme(); esGateway HTTP
- String scheme = "http";
- String contextPath = request.getContextPath(); // /mywebapp
- String servletPath = request.getServletPath(); // /servlet/MyServlet
- String pathInfo = request.getPathInfo(); // /a/b;c=123
- String queryString = request.getQueryString(); // d=789
+ //String scheme = request.getScheme(); esGateway HTTP
+ String scheme = "http";
+ String contextPath = request.getContextPath(); // /mywebapp
+ String servletPath = request.getServletPath(); // /servlet/MyServlet
+ String pathInfo = request.getPathInfo(); // /a/b;c=123
+ String queryString = request.getQueryString(); // d=789
- StringBuilder url = new StringBuilder();
- url.append(scheme).append("://").append(esHost);
- url.append(":").append(esPort);
- url.append(contextPath).append(servletPath);
+ StringBuilder url = new StringBuilder();
+ url.append(scheme).append("://").append(esHost);
+ url.append(":").append(esPort);
+ url.append(contextPath).append(servletPath);
- if (pathInfo != null) {
- url.append(pathInfo);
- }
- if (queryString != null) {
- url.append("?").append(queryString);
- }
+ if (pathInfo != null) {
+ url.append(pathInfo);
+ }
+ if (queryString != null) {
+ url.append("?").append(queryString);
+ }
- String redirectedUrl = url.toString().replace("/sdc2/esGateway/", "/");
- return redirectedUrl;
+ String redirectedUrl = url.toString().replace("/sdc2/esGateway/", "/");
+ return redirectedUrl;
- }
+ }
- protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
+ protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- MonitoringBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(MonitoringBusinessLogic.class);
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ MonitoringBusinessLogic monitoringBusinessLogic = webApplicationContext.getBean(MonitoringBusinessLogic.class);
- return monitoringBusinessLogic;
- }
+ return monitoringBusinessLogic;
+ }
}
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 1625b50bae..b67469d469 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
@@ -20,30 +20,14 @@
package org.openecomp.sdc.be.servlets;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Type;
-import java.nio.charset.StandardCharsets;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Supplier;
-import java.util.zip.ZipInputStream;
-
-import javax.annotation.Resource;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Response;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
import org.openecomp.sdc.be.components.impl.ImportUtils;
@@ -67,870 +51,830 @@ import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.UploadArtifactInfo;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.openecomp.sdc.common.util.ZipUtil;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.Yaml;
-import com.google.gson.Gson;
-import com.google.gson.JsonSyntaxException;
-
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Response;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Type;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import java.util.zip.ZipInputStream;
public abstract class AbstractValidationsServlet extends BeGenericServlet {
- @Resource
- private ServletUtils servletUtils;
-
- @Resource
- private ResourceImportManager resourceImportManager;
-
- @Autowired
- protected ComponentsUtils componentsUtils;
-
- private Logger log = null;
-
- protected void init(Logger log) {
- initLog(log);
- initSpringFromContext();
-
- }
-
- protected synchronized void initLog(Logger log) {
- if (this.log == null) {
- this.log = log;
- }
- }
-
- private synchronized void initSpringFromContext() {
- if (servletUtils == null) {
- ServletContext context = servletRequest.getSession().getServletContext();
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
- .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- servletUtils = webApplicationContext.getBean(ServletUtils.class);
- resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
- }
- }
-
- protected void validateResourceDoesNotExist(Wrapper<Response> responseWrapper, User user, String resourceName) {
- if (resourceImportManager.isResourceExist(resourceName)) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceName);
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
- }
-
- protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userUserId) {
- log.debug("get user {} from DB", userUserId);
- // get user details
- if (userUserId == null) {
- log.info("user userId is null");
- Response response = returnMissingInformation(new User());
- responseWrapper.setInnerElement(response);
- }
-
- else {
- IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin();
- Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userUserId, false);
- if (eitherCreator.isRight()) {
- log.info("user is not listed. userId={}", userUserId);
- User user = new User();
- user.setUserId(userUserId);
- Response response = returnMissingInformation(user);
- responseWrapper.setInnerElement(response);
- } else {
- userWrapper.setInnerElement(eitherCreator.left().value());
- }
- }
- }
-
- protected Response returnMissingInformation(User user) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return buildErrorResponse(responseFormat);
- }
-
- protected void validateDataNotNull(Wrapper<Response> responseWrapper, Object... dataParams) {
- for (Object dataElement : dataParams) {
- if (dataElement == null) {
- log.info("Invalid body was received.");
- Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- responseWrapper.setInnerElement(response);
- break;
- }
- }
-
- }
-
- protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user) {
- log.debug("validate user role");
- if (!user.getRole().equals(Role.ADMIN.name()) && !user.getRole().equals(Role.DESIGNER.name())) {
- log.info("user is not in appropriate role to perform action");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("audit before sending response");
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
-
- Response response = buildErrorResponse(responseFormat);
- errorResponseWrapper.setInnerElement(response);
- }
-
- }
-
- protected void validateZip(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException {
- InputStream fileInputStream = new FileInputStream(file);
- Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
- if (payloadName == null || payloadName.isEmpty() || !unzippedFolder.containsKey(payloadName)) {
- log.info("Invalid json was received. payloadName should be yml file name");
- Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
- protected void validateCsar(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException {
- InputStream fileInputStream = new FileInputStream(file);
- Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
- if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) {
- log.info("Invalid json was received. payloadName should be yml file name");
- Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
-
- protected void fillZipContents(Wrapper<String> yamlStringWrapper, File file) throws FileNotFoundException {
- InputStream fileInputStream = new FileInputStream(file);
- Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
- String ymlName = unzippedFolder.keySet().iterator().next();
- fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file);
- }
-
- protected void fillToscaTemplateFromZip(Wrapper<String> yamlStringWrapper, String payloadName, File file) throws FileNotFoundException {
- InputStream fileInputStream = new FileInputStream(file);
- Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
- byte[] yamlFileInBytes = unzippedFolder.get(payloadName);
- String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8);
- log.debug("received yaml: {}", yamlAsString);
- yamlStringWrapper.setInnerElement(yamlAsString);
- }
-
- protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) {
- try(InputStream fileInputStream = new FileInputStream(file);){
-
- byte [] data = new byte[(int)file.length()];
- if( fileInputStream.read(data) == -1){
- log.info("Invalid json was received.");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-
- Response errorResp = buildErrorResponse(responseFormat);
- responseWrapper.setInnerElement(errorResp);
- }
- String payloadData = Base64.encodeBase64String(data);
- uploadResourceInfoWrapper.setPayloadData(payloadData);
-
-
-
- } catch (IOException e) {
- log.info("Invalid json was received or Error while closing input Stream.");
- log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-
- Response errorResp = buildErrorResponse(responseFormat);
- responseWrapper.setInnerElement(errorResp);
-
- }
- }
-
- protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) {
- log.debug("validate user role");
- if (resourceAuthority == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE) {
- if (!user.getRole().equals(Role.ADMIN.name())) {
- log.info("user is not in appropriate role to perform action");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- log.debug("audit before sending response");
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
-
- Response response = buildErrorResponse(responseFormat);
- errorResponseWrapper.setInnerElement(response);
- }
- } else {
- validateUserRole(errorResponseWrapper, user);
- }
-
- }
-
- protected void validateAndFillResourceJson(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) {
- boolean isValid;
- try {
- log.debug("The received json is {}", resourceInfo);
- UploadResourceInfo resourceInfoObject = gson.fromJson(resourceInfo, UploadResourceInfo.class);
- if (resourceInfoObject == null) {
- isValid = false;
- } else {
- if (!resourceAuthorityEnum.isBackEndImport()) {
- isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty();
- //only resource name is checked
- } else {
- isValid = true;
- }
- uploadResourceInfoWrapper.setInnerElement(resourceInfoObject);
- }
-
- } catch (JsonSyntaxException e) {
- log.debug("Invalid json was received. {}", e.getMessage(), e);
- isValid = false;
-
- }
- if (!isValid) {
- log.info("Invalid json was received.");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- Response errorResp = buildErrorResponse(responseFormat);
- responseWrapper.setInnerElement(errorResp);
- }
- }
-
- protected void validateAuthorityType(Wrapper<Response> responseWrapper, String authorityType) {
- log.debug("The received authority type is {}", authorityType);
- ResourceAuthorityTypeEnum authorityTypeEnum = ResourceAuthorityTypeEnum.findByUrlPath(authorityType);
- if (authorityTypeEnum == null) {
- log.info("Invalid authority type was received.");
- Response errorResp = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- responseWrapper.setInnerElement(errorResp);
- }
- }
-
- public ServletUtils getServletUtils() {
- initSpringFromContext();
- return servletUtils;
- }
-
- public Gson getGson() {
- return getServletUtils().getGson();
- }
-
- public ComponentsUtils getComponentsUtils() {
- return getServletUtils().getComponentsUtils();
- }
-
- protected void validatePayloadIsTosca(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
- log.debug("checking payload is valid tosca");
- boolean isValid;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
- Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
-
- if (findFirstToscaStringElement.isRight()) {
- isValid = false;
- } else {
- String defenitionVersionFound = findFirstToscaStringElement.left().value();
- if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) {
- isValid = false;
- } else {
- isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
- }
- }
-
- if (!isValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
-
- protected void validatePayloadIsYml(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) {
- log.debug("checking tosca template is valid yml");
- YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
- boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes());
- if (!isYamlValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
- }
-
- protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) {
- boolean isValid;
- String nameSpace = "";
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
- Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
- if (toscaElement.isRight() || toscaElement.left().value().size() != 1) {
- isValid = false;
- } else {
- nameSpace = toscaElement.left().value().keySet().iterator().next();
- isValid = nameSpace.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
- }
- if (!isValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_NAMESPACE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- } else {
- String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
- String[] findTypes = str1.split("\\.");
- if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) {
- String type = findTypes[0].toUpperCase();
- resourceInfo.setResourceType(type);
- } else {
- resourceInfo.setResourceType(ResourceTypeEnum.VFC.name());
- }
- }
-
- }
-
- protected void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
- log.debug("checking payload contains single resource");
- boolean isValid;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
- Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
- if (toscaElement.isRight()) {
- isValid = false;
- } else {
- isValid = toscaElement.left().value().size() == 1;
- }
-
- if (!isValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
-
- protected void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
- log.debug("checking payload is not a tosca service");
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
- Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
-
- if (toscaElement.isLeft()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
-
- protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
- String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName();
- boolean isValidSuffix = false;
- if (toscaTemplatePayloadName != null && !toscaTemplatePayloadName.isEmpty()) {
- for (String validSuffix : ImportUtils.Constants.TOSCA_YML_CSAR_VALID_SUFFIX) {
- isValidSuffix = isValidSuffix || toscaTemplatePayloadName.toLowerCase().endsWith(validSuffix);
- }
- }
- if (!isValidSuffix) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
-
- }
-
- protected void validateMD5(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) {
- boolean isValid;
- String recievedMD5 = request.getHeader(Constants.MD5_HEADER);
- if (recievedMD5 == null) {
- isValid = false;
- } else {
- String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(resourceInfoJsonString);
- isValid = calculateMD5.equals(recievedMD5);
- }
- if (!isValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
- }
-
- protected void validateComponentType(Wrapper<Response> responseWrapper, Wrapper<ComponentTypeEnum> componentWrapper, String componentType) {
- boolean isValid;
- if (componentType == null) {
- isValid = false;
- } else {
- if (ComponentTypeEnum.RESOURCE_PARAM_NAME.equalsIgnoreCase(componentType)) {
- isValid = true;
- componentWrapper.setInnerElement(ComponentTypeEnum.RESOURCE);
- } else if (ComponentTypeEnum.SERVICE_PARAM_NAME.equalsIgnoreCase(componentType)) {
- isValid = true;
- componentWrapper.setInnerElement(ComponentTypeEnum.SERVICE);
- } else {
- isValid = false;
- }
- }
- if (!isValid) {
- log.debug("Invalid componentType:{}", componentType);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- Response errorResp = buildErrorResponse(responseFormat);
- responseWrapper.setInnerElement(errorResp);
- }
- }
-
- protected void fillToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo resourceInfo) {
- if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- } else {
- String toscaPayload = resourceInfo.getPayloadData();
- String decodedPayload = new String(Base64.decodeBase64(toscaPayload));
- yamlStringWrapper.setInnerElement(decodedPayload);
- }
-
- }
-
- protected void fillPayload(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum,
- File file) throws FileNotFoundException {
-
- if (responseWrapper.isEmpty()) {
- if (resourceAuthorityEnum.isBackEndImport()) {
- // PrePayload Validations
- if (responseWrapper.isEmpty()) {
- validateDataNotNull(responseWrapper, file, resourceInfoJsonString);
- }
- if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
- if (responseWrapper.isEmpty()) {
- validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
- }
-
- // Fill PayLoad From File
- if (responseWrapper.isEmpty()) {
- fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file);
- }
- }else{
-
- if (responseWrapper.isEmpty()) {
- validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
- }
-
- // Fill PayLoad From File
- if (responseWrapper.isEmpty()) {
- fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file);
- }
-
- }
-
- } else {
- // Fill PayLoad From JSON
- if (responseWrapper.isEmpty()) {
- fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement());
- }
- }
-
- }
-
- }
-
- protected void specificResourceAuthorityValidations(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, HttpServletRequest request, String resourceInfoJsonString,
- ResourceAuthorityTypeEnum resourceAuthorityEnum) throws FileNotFoundException {
-
- if (responseWrapper.isEmpty()) {
- // UI Only Validation
- if (!resourceAuthorityEnum.isBackEndImport()) {
- importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString);
- }
-
- // User Defined Type Resources
- if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
- if (responseWrapper.isEmpty()) {
- validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement());
- }
-
- }
- }
- }
-
- protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId,
- String resourceInfoJsonString) {
-
- if (responseWrapper.isEmpty()) {
- validateUserExist(responseWrapper, userWrapper, userUserId);
- }
-
- if (responseWrapper.isEmpty()) {
- validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum);
- }
-
- if (responseWrapper.isEmpty()) {
- validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString);
- }
-
- if (responseWrapper.isEmpty()) {
- validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement());
- }
- if (responseWrapper.isEmpty()) {
- validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement(), resourceAuthorityEnum);
- }
-
- }
-
- private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum) {
- String resourceType = uploadResourceInfo.getResourceType();
- if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
- if (resourceType.equals(ResourceTypeEnum.getTypeByName("VF").getValue()) && resourceAuthorityEnum == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE){
- log.debug("Import of VF resource type is forbidden - VF resource import can be done using onboarding flow only");
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_TYPE);
- Response errorResponse = buildErrorResponse(responseFormat);
- EnumMap additionalParam = new EnumMap(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, uploadResourceInfo.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- responseWrapper.setInnerElement(errorResponse);
- }
- }
-
- protected void importUIValidations(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) {
- if (responseWrapper.isEmpty()) {
- validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString);
- }
- if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) {
- validateResourceDoesNotExist(responseWrapper, user, resourceInfo.getName());
- }
- }
-
- protected void commonPayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
-
- if (responseWrapper.isEmpty()) {
- validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
- }
- if (responseWrapper.isEmpty()) {
- validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement());
- }
- if (responseWrapper.isEmpty()) {
- validatePayloadIsNotService(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
- }
- if (responseWrapper.isEmpty()) {
- validatePayloadIsSingleResource(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement());
- }
- }
-
- /*protected void topologyTemplatePayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
-
- if (responseWrapper.isEmpty()) {
- validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
- }
- if (responseWrapper.isEmpty()) {
- validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement());
- }
- if (responseWrapper.isEmpty()) {
- validatePayloadIsTopologyTemplate(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
- }
-
- }*/
-
- protected void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) {
- Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> createOrUpdateResponse;
- Response response;
- Object representation = null;
-
- if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) {
- log.debug("import resource from csar");
-
- createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId);
- //if (createOrUpdateResponse.isLeft()){
- // LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
- // lifecycleChangeInfo.setUserRemarks("certification on import");
- // Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceImportManager.getResourceBusinessLogic().validatePropertiesDefaultValues(createOrUpdateResponse.left().value().left);
- //}
-
- } else if (!authority.isUserTypeResource()) {
- log.debug("import normative type resource");
- createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true);
- } else {
- log.debug("import user resource (not normative type)");
- createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false, false);
- }
- if (createOrUpdateResponse.isRight()) {
- response = buildErrorResponse(createOrUpdateResponse.right().value());
- } else {
- try {
- representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft());
- } catch (IOException e) {
- log.debug("Error while building resource representation : {}", e.getMessage(), e);
- }
- ActionStatus successStatus = createOrUpdateResponse.left().value().right;
- response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation);
- }
- responseWrapper.setInnerElement(response);
- }
-
- private Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) {
-
- Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes;
- ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus> result = null;
- ActionStatus actionStatus;
- org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource();
- String payloadName = resourceInfoObject.getPayloadName();
- fillResourceFromResourceInfoObject(resource, resourceInfoObject);
-
- Either<Map<String, byte[]>, ResponseFormat> csarUIPayloadRes = getScarFromPayload(resourceInfoObject);
- if (csarUIPayloadRes.isRight()) {
- return Either.right(csarUIPayloadRes.right().value());
- }
- Map<String, byte[]> csarUIPayload = csarUIPayloadRes.left().value();
-
- createOrUpdateResourceRes = getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName);
- if (createOrUpdateResourceRes.isRight()) {
- return Either.right(createOrUpdateResourceRes.right().value());
- }
- if (resourceUniqueId == null || resourceUniqueId.isEmpty()) {
- createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName);
- if (createOrUpdateResourceRes.isRight()) {
- return Either.right(createOrUpdateResourceRes.right().value());
- }
- actionStatus = ActionStatus.CREATED;
- } else {
- createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId);
- if (createOrUpdateResourceRes.isRight()) {
- return Either.right(createOrUpdateResourceRes.right().value());
- }
- actionStatus = ActionStatus.OK;
- }
- result = new ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>(createOrUpdateResourceRes.left().value(), actionStatus);
- return Either.left(result);
- }
-
- private Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> getAndValidateCsarYaml(Map<String, byte[]> csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user, String csarUUID) {
-
- Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils());
-
- if (getToscaYamlRes.isRight()) {
- ResponseFormat responseFormat = getToscaYamlRes.right().value();
- log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
- getComponentsUtils().auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.CREATE_RESOURCE, null);
- return Either.right(responseFormat);
- }
- String toscaYaml = getToscaYamlRes.left().value().getValue();
-
- log.debug("checking tosca template is valid yml");
- YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
- boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes());
- if (!isValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- return Either.right(responseFormat);
- }
-
- log.debug("checking payload is valid tosca");
- String heatDecodedPayload = toscaYaml;
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
- Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
-
- if (findFirstToscaStringElement.isRight()) {
- isValid = false;
- } else {
- String defenitionVersionFound = findFirstToscaStringElement.left().value();
- if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) {
- isValid = false;
- } else {
- isValid = ImportUtils.Constants.TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
- }
- }
-
- if (!isValid) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
- additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resource.getName());
- getComponentsUtils().auditResource(responseFormat, user, null, "", "", AuditingActionEnum.IMPORT_RESOURCE, additionalParam);
- return Either.right(responseFormat);
- }
- return Either.left(resource);
- }
-
- private void fillResourceFromResourceInfoObject(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) {
- if (resource != null && resourceInfoObject != null) {
- resource.setDescription(resourceInfoObject.getDescription());
- resource.setTags(resourceInfoObject.getTags());
- resource.setCategories(resourceInfoObject.getCategories());
- resource.setContactId(resourceInfoObject.getContactId());
- resource.setName(resourceInfoObject.getName());
- resource.setIcon(resourceInfoObject.getResourceIconPath());
- resource.setVendorName(resourceInfoObject.getVendorName());
- resource.setVendorRelease(resourceInfoObject.getVendorRelease());
- resource.setResourceType(ResourceTypeEnum.valueOf(resourceInfoObject.getResourceType()));
- List<UploadArtifactInfo> artifactList = resourceInfoObject.getArtifactList();
- if (artifactList != null) {
- Map<String, ArtifactDefinition> artifactsHM = new HashMap<String, ArtifactDefinition>();
- for (UploadArtifactInfo artifact : artifactList) {
- ArtifactDefinition artifactDef = new ArtifactDefinition();
- artifactDef.setArtifactName(artifact.getArtifactName());
- artifactDef.setArtifactType(artifact.getArtifactType().getType());
- artifactDef.setDescription(artifact.getArtifactDescription());
- artifactDef.setPayloadData(artifact.getArtifactData());
- artifactDef.setArtifactRef(artifact.getArtifactPath());
- artifactsHM.put(artifactDef.getArtifactName(), artifactDef);
- }
- resource.setArtifacts(artifactsHM);
- }
- }
-
- }
-
- private Either<Map<String, byte[]>, ResponseFormat> getScarFromPayload(UploadResourceInfo innerElement) {
- String csarUUID = innerElement.getPayloadName();
- String payloadData = innerElement.getPayloadData();
- if (payloadData == null) {
- log.info("Failed to decode received csar", csarUUID);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
- }
-
- byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8));
- if (decodedPayload == null) {
- log.info("Failed to decode received csar", csarUUID);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
- }
-
- Map<String, byte[]> csar = ZipUtil.readZip(decodedPayload);
- if (csar == null) {
- log.info("Failed to unzip received csar", csarUUID);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
- }
- return Either.left(csar);
- }
-
- protected void validateInputStream(final HttpServletRequest request, Wrapper<String> dataWrapper, Wrapper<ResponseFormat> errorWrapper) throws IOException {
- InputStream inputStream = request.getInputStream();
- byte[] bytes = IOUtils.toByteArray(inputStream);
- if (bytes == null || bytes.length == 0) {
- log.info("Empty body was sent.");
- errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- } else {
- dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8));
- }
-
- }
-
- protected <T> void validateClassParse(String data, Wrapper<T> parsedClassWrapper, Supplier<Class<T>> classGen, Wrapper<ResponseFormat> errorWrapper) {
- try {
- T parsedClass = gson.fromJson(data, classGen.get());
- if (parsedClass == null) {
- errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- } else {
- parsedClassWrapper.setInnerElement(parsedClass);
- }
- } catch (JsonSyntaxException e) {
- log.debug("Failed to decode received {} {} to object.", classGen.get().getName(), data, e);
- errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- }
-
- protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) {
- ServletContext context = request.getSession().getServletContext();
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- } else {
- blWrapper.setInnerElement(componentInstanceLogic);
- }
- }
-
- protected <T> Response buildResponseFromElement(Wrapper<ResponseFormat> errorWrapper, Wrapper<T> attributeWrapper) throws IOException {
- Response response;
- if (errorWrapper.isEmpty()) {
- ObjectMapper mapper = new ObjectMapper();
- String result = mapper.writeValueAsString(attributeWrapper.getInnerElement());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
- } else {
- response = buildErrorResponse(errorWrapper.getInnerElement());
- }
- return response;
- }
-
- protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper<ResponseFormat> responseWrapper) {
- ResponseFormat responseFormat;
- if(StringUtils.isEmpty(instanceIdHeader) ){
- log.debug("Missing X-ECOMP-InstanceID header");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
- responseWrapper.setInnerElement(responseFormat);
- }
- }
-
- protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
- ResponseFormat responseFormat;
- if( StringUtils.isEmpty(header)){
- log.debug("MissingUSER_ID");
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
- responseWrapper.setInnerElement(responseFormat);
- }
- }
-
- /**
- * Convert json to Object object
- * @param <T>
- * @param classSupplier
- * @param json
- * @return
- */
- public <T> Either<T, ResponseFormat> parseToObject(String json, Supplier<Class<T>> classSupplier) {
-
- try {
- T object = RepresentationUtils.fromRepresentation(json, classSupplier.get());
- return Either.left(object);
- } catch (Exception e) {
- log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
- }
- }
-
- /**
- * Convert json to Object object
- * @param <T>
- * @param json
- * @param type
- * @return
- */
- public <T> Either<List<T>, ResponseFormat> parseListOfObjects(String json, Type type) {
- try {
- List<T> listOfObjects = gson.fromJson(json, type);
- return Either.left(listOfObjects);
- } catch (Exception e) {
- log.debug("Failed to parse json to {} object", type.getClass().getName(), e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- return Either.right(responseFormat);
- }
- }
+ private static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_";
+ private static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1");
+ private static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar");
+
+ protected ServletUtils servletUtils;
+
+ protected ResourceImportManager resourceImportManager;
+
+ protected ComponentsUtils componentsUtils;
+
+ private Logger log = null;
+
+ protected void init(Logger log) {
+ initLog(log);
+ initSpringFromContext();
+
+ }
+
+ protected synchronized void initLog(Logger log) {
+ if (this.log == null) {
+ this.log = log;
+ }
+ }
+
+ private synchronized void initSpringFromContext() {
+ if (servletUtils == null) {
+ ServletContext context = servletRequest.getSession().getServletContext();
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+ .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ servletUtils = webApplicationContext.getBean(ServletUtils.class);
+ resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
+ }
+ }
+
+ protected void validateResourceDoesNotExist(Wrapper<Response> responseWrapper, User user, String resourceName) {
+ if (resourceImportManager.isResourceExist(resourceName)) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, resourceName, AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ }
+
+ protected void validateUserExist(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, String userUserId) {
+ log.debug("get user {} from DB", userUserId);
+ // get user details
+ if (userUserId == null) {
+ log.info("user userId is null");
+ Response response = returnMissingInformation(new User());
+ responseWrapper.setInnerElement(response);
+ }
+
+ else {
+ IUserBusinessLogic userAdmin = getServletUtils().getUserAdmin();
+ Either<User, ActionStatus> eitherCreator = userAdmin.getUser(userUserId, false);
+ if (eitherCreator.isRight()) {
+ log.info("user is not listed. userId={}", userUserId);
+ User user = new User();
+ user.setUserId(userUserId);
+ Response response = returnMissingInformation(user);
+ responseWrapper.setInnerElement(response);
+ } else {
+ userWrapper.setInnerElement(eitherCreator.left().value());
+ }
+ }
+ }
+
+ protected Response returnMissingInformation(User user) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE);
+ return buildErrorResponse(responseFormat);
+ }
+
+ protected void validateDataNotNull(Wrapper<Response> responseWrapper, Object... dataParams) {
+ for (Object dataElement : dataParams) {
+ if (dataElement == null) {
+ log.info("Invalid body was received.");
+ Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ responseWrapper.setInnerElement(response);
+ break;
+ }
+ }
+
+ }
+
+ protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user) {
+ log.debug("validate user role");
+ if (!user.getRole().equals(Role.ADMIN.name()) && !user.getRole().equals(Role.DESIGNER.name())) {
+ log.info("user is not in appropriate role to perform action");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ log.debug("audit before sending response");
+ getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE);
+
+ Response response = buildErrorResponse(responseFormat);
+ errorResponseWrapper.setInnerElement(response);
+ }
+
+ }
+
+ protected void validateZip(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException {
+ InputStream fileInputStream = new FileInputStream(file);
+ Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
+ if (payloadName == null || payloadName.isEmpty() || !unzippedFolder.containsKey(payloadName)) {
+ log.info("Invalid json was received. payloadName should be yml file name");
+ Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
+ protected void validateCsar(Wrapper<Response> responseWrapper, File file, String payloadName) throws FileNotFoundException {
+ InputStream fileInputStream = new FileInputStream(file);
+ Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
+ if (payloadName == null || payloadName.isEmpty() || unzippedFolder.isEmpty()) {
+ log.info("Invalid json was received. payloadName should be yml file name");
+ Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
+
+ protected void fillZipContents(Wrapper<String> yamlStringWrapper, File file) throws FileNotFoundException {
+ InputStream fileInputStream = new FileInputStream(file);
+ Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
+ String ymlName = unzippedFolder.keySet().iterator().next();
+ fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file);
+ }
+
+ protected void fillToscaTemplateFromZip(Wrapper<String> yamlStringWrapper, String payloadName, File file) throws FileNotFoundException {
+ InputStream fileInputStream = new FileInputStream(file);
+ Map<String, byte[]> unzippedFolder = ZipUtil.readZip(new ZipInputStream(fileInputStream));
+ byte[] yamlFileInBytes = unzippedFolder.get(payloadName);
+ String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8);
+ log.debug("received yaml: {}", yamlAsString);
+ yamlStringWrapper.setInnerElement(yamlAsString);
+ }
+
+ protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) {
+ try(InputStream fileInputStream = new FileInputStream(file)){
+
+ byte [] data = new byte[(int)file.length()];
+ if( fileInputStream.read(data) == -1){
+ log.info("Invalid json was received.");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+
+ Response errorResp = buildErrorResponse(responseFormat);
+ responseWrapper.setInnerElement(errorResp);
+ }
+ String payloadData = Base64.encodeBase64String(data);
+ uploadResourceInfoWrapper.setPayloadData(payloadData);
+
+
+
+ } catch (IOException e) {
+ log.info("Invalid json was received or Error while closing input Stream.");
+ log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+
+ Response errorResp = buildErrorResponse(responseFormat);
+ responseWrapper.setInnerElement(errorResp);
+
+ }
+ }
+
+ protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user, ResourceAuthorityTypeEnum resourceAuthority) {
+ log.debug("validate user role");
+ if (resourceAuthority == ResourceAuthorityTypeEnum.NORMATIVE_TYPE_BE) {
+ if (!user.getRole().equals(Role.ADMIN.name())) {
+ log.info("user is not in appropriate role to perform action");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ log.debug("audit before sending response");
+ getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE);
+
+ Response response = buildErrorResponse(responseFormat);
+ errorResponseWrapper.setInnerElement(response);
+ }
+ } else {
+ validateUserRole(errorResponseWrapper, user);
+ }
+
+ }
+
+ protected void validateAndFillResourceJson(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) {
+ boolean isValid;
+ try {
+ log.debug("The received json is {}", resourceInfo);
+ UploadResourceInfo resourceInfoObject = gson.fromJson(resourceInfo, UploadResourceInfo.class);
+ if (resourceInfoObject == null) {
+ isValid = false;
+ } else {
+ if (!resourceAuthorityEnum.isBackEndImport()) {
+ isValid = resourceInfoObject.getPayloadName() != null && !resourceInfoObject.getPayloadName().isEmpty();
+ //only resource name is checked
+ } else {
+ isValid = true;
+ }
+ uploadResourceInfoWrapper.setInnerElement(resourceInfoObject);
+ }
+
+ } catch (JsonSyntaxException e) {
+ log.debug("Invalid json was received. {}", e.getMessage(), e);
+ isValid = false;
+
+ }
+ if (!isValid) {
+ log.info("Invalid json was received.");
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE);
+ Response errorResp = buildErrorResponse(responseFormat);
+ responseWrapper.setInnerElement(errorResp);
+ }
+ }
+
+ protected void validateAuthorityType(Wrapper<Response> responseWrapper, String authorityType) {
+ log.debug("The received authority type is {}", authorityType);
+ ResourceAuthorityTypeEnum authorityTypeEnum = ResourceAuthorityTypeEnum.findByUrlPath(authorityType);
+ if (authorityTypeEnum == null) {
+ log.info("Invalid authority type was received.");
+ Response errorResp = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ responseWrapper.setInnerElement(errorResp);
+ }
+ }
+
+ public ServletUtils getServletUtils() {
+ initSpringFromContext();
+ return servletUtils;
+ }
+
+ public Gson getGson() {
+ return getServletUtils().getGson();
+ }
+
+ public ComponentsUtils getComponentsUtils() {
+ return getServletUtils().getComponentsUtils();
+ }
+
+ protected void validatePayloadIsTosca(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
+ log.debug("checking payload is valid tosca");
+ boolean isValid;
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
+ Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
+
+ if (findFirstToscaStringElement.isRight()) {
+ isValid = false;
+ } else {
+ String defenitionVersionFound = findFirstToscaStringElement.left().value();
+ if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) {
+ isValid = false;
+ } else {
+ isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
+ }
+ }
+
+ if (!isValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
+
+ protected void validatePayloadIsYml(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) {
+ log.debug("checking tosca template is valid yml");
+ YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
+ boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes());
+ if (!isYamlValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ }
+
+ protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, String toscaPayload) {
+ boolean isValid;
+ String nameSpace = "";
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
+ Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
+ if (toscaElement.isRight() || toscaElement.left().value().size() != 1) {
+ isValid = false;
+ } else {
+ nameSpace = toscaElement.left().value().keySet().iterator().next();
+ isValid = nameSpace.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+ }
+ if (!isValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_NAMESPACE);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ } else {
+ String str1 = nameSpace.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = str1.split("\\.");
+ if (ResourceTypeEnum.containsName(findTypes[0].toUpperCase())) {
+ String type = findTypes[0].toUpperCase();
+ resourceInfo.setResourceType(type);
+ } else {
+ resourceInfo.setResourceType(ResourceTypeEnum.VFC.name());
+ }
+ }
+
+ }
+
+ protected void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
+ log.debug("checking payload contains single resource");
+ boolean isValid;
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
+ Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
+ if (toscaElement.isRight()) {
+ isValid = false;
+ } else {
+ isValid = toscaElement.left().value().size() == 1;
+ }
+
+ if (!isValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
+
+ protected void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
+ log.debug("checking payload is not a tosca service");
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
+ Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
+
+ if (toscaElement.isLeft()) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
+
+ protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
+ String toscaTemplatePayloadName = uploadResourceInfo.getPayloadName();
+ boolean isValidSuffix = false;
+ if (toscaTemplatePayloadName != null && !toscaTemplatePayloadName.isEmpty()) {
+ for (String validSuffix : TOSCA_YML_CSAR_VALID_SUFFIX) {
+ isValidSuffix = isValidSuffix || toscaTemplatePayloadName.toLowerCase().endsWith(validSuffix);
+ }
+ }
+ if (!isValidSuffix) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+
+ }
+
+ protected void validateMD5(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) {
+ boolean isValid;
+ String recievedMD5 = request.getHeader(Constants.MD5_HEADER);
+ if (recievedMD5 == null) {
+ isValid = false;
+ } else {
+ String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(resourceInfoJsonString);
+ isValid = calculateMD5.equals(recievedMD5);
+ }
+ if (!isValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ }
+
+ protected void validateComponentType(Wrapper<Response> responseWrapper, Wrapper<ComponentTypeEnum> componentTypeWrapper, String componentType) {
+ boolean isValid;
+ if (componentType == null) {
+ isValid = false;
+ } else {
+ if (ComponentTypeEnum.RESOURCE_PARAM_NAME.equalsIgnoreCase(componentType)) {
+ isValid = true;
+ componentTypeWrapper.setInnerElement(ComponentTypeEnum.RESOURCE);
+ } else if (ComponentTypeEnum.SERVICE_PARAM_NAME.equalsIgnoreCase(componentType)) {
+ isValid = true;
+ componentTypeWrapper.setInnerElement(ComponentTypeEnum.SERVICE);
+ } else {
+ isValid = false;
+ }
+ }
+ if (!isValid) {
+ log.debug("Invalid componentType:{}", componentType);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType)));
+ }
+ }
+
+ protected Either<ComponentTypeEnum, ResponseFormat> convertToComponentType(String componentType) {
+ Wrapper<Response> errorWrapper = new Wrapper<>();
+ Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<>();
+ validateComponentType(errorWrapper, componentWrapper, componentType);
+ return errorWrapper.isEmpty() ? Either.left(componentWrapper.getInnerElement()) : Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ protected void fillToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo resourceInfo) {
+ if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, resourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ } else {
+ String toscaPayload = resourceInfo.getPayloadData();
+ String decodedPayload = new String(Base64.decodeBase64(toscaPayload));
+ yamlStringWrapper.setInnerElement(decodedPayload);
+ }
+
+ }
+
+ protected void fillPayload(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum,
+ File file) throws FileNotFoundException {
+
+ if (responseWrapper.isEmpty()) {
+ if (resourceAuthorityEnum.isBackEndImport()) {
+ // PrePayload Validations
+ if (responseWrapper.isEmpty()) {
+ validateDataNotNull(responseWrapper, file, resourceInfoJsonString);
+ }
+ if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
+ if (responseWrapper.isEmpty()) {
+ validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
+ }
+
+ // Fill PayLoad From File
+ if (responseWrapper.isEmpty()) {
+ fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file);
+ }
+ }else{
+
+ if (responseWrapper.isEmpty()) {
+ validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
+ }
+
+ // Fill PayLoad From File
+ if (responseWrapper.isEmpty()) {
+ fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file);
+ }
+
+ }
+
+ } else {
+ // Fill PayLoad From JSON
+ if (responseWrapper.isEmpty()) {
+ fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement());
+ }
+ }
+
+ }
+
+ }
+
+ protected void specificResourceAuthorityValidations(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, HttpServletRequest request, String resourceInfoJsonString,
+ ResourceAuthorityTypeEnum resourceAuthorityEnum) throws FileNotFoundException {
+
+ if (responseWrapper.isEmpty()) {
+ // UI Only Validation
+ if (!resourceAuthorityEnum.isBackEndImport()) {
+ importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString);
+ }
+
+ // User Defined Type Resources
+ if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
+ if (responseWrapper.isEmpty()) {
+ validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement());
+ }
+
+ }
+ }
+ }
+
+ protected void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userUserId,
+ String resourceInfoJsonString) {
+
+ if (responseWrapper.isEmpty()) {
+ validateUserExist(responseWrapper, userWrapper, userUserId);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement());
+ }
+ if (responseWrapper.isEmpty()) {
+ validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement());
+ }
+
+ }
+
+ private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
+ String resourceType = uploadResourceInfo.getResourceType();
+ if (resourceType == null || !ResourceTypeEnum.containsName(resourceType)) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ Response errorResponse = buildErrorResponse(responseFormat);
+ getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ }
+
+ protected void importUIValidations(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) {
+ if (responseWrapper.isEmpty()) {
+ validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString);
+ }
+ if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) {
+ validateResourceDoesNotExist(responseWrapper, user, resourceInfo.getName());
+ }
+ }
+
+ protected void commonPayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
+
+ if (responseWrapper.isEmpty()) {
+ validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
+ }
+ if (responseWrapper.isEmpty()) {
+ validatePayloadIsTosca(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement());
+ }
+ if (responseWrapper.isEmpty()) {
+ validatePayloadIsNotService(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
+ }
+ if (responseWrapper.isEmpty()) {
+ validatePayloadIsSingleResource(responseWrapper, uploadResourceInfo, user, yamlStringWrapper.getInnerElement());
+ }
+ }
+
+
+ protected void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) {
+ Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> createOrUpdateResponse;
+ Response response;
+ Object representation = null;
+
+ if (CsarValidationUtils.isCsarPayloadName(resourceInfoObject.getPayloadName())) {
+ log.debug("import resource from csar");
+
+ createOrUpdateResponse = importResourceFromUICsar(resourceInfoObject, user, resourceUniqueId);
+ } else if (!authority.isUserTypeResource()) {
+ log.debug("import normative type resource");
+ createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true);
+ } else {
+ log.debug("import user resource (not normative type)");
+ createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false);
+ }
+ if (createOrUpdateResponse.isRight()) {
+ response = buildErrorResponse(createOrUpdateResponse.right().value());
+ } else {
+ try {
+ representation = RepresentationUtils.toRepresentation(createOrUpdateResponse.left().value().getLeft());
+ } catch (IOException e) {
+ log.debug("Error while building resource representation : {}", e.getMessage(), e);
+ }
+ ActionStatus successStatus = createOrUpdateResponse.left().value().right;
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(successStatus), representation);
+ }
+ responseWrapper.setInnerElement(response);
+ }
+
+ private Either<ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>, ResponseFormat> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) {
+
+ Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> createOrUpdateResourceRes;
+ ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus> result = null;
+ ActionStatus actionStatus;
+ org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource();
+ String payloadName = resourceInfoObject.getPayloadName();
+ fillResourceFromResourceInfoObject(resource, resourceInfoObject);
+
+ Either<Map<String, byte[]>, ResponseFormat> csarUIPayloadRes = getScarFromPayload(resourceInfoObject);
+ if (csarUIPayloadRes.isRight()) {
+ return Either.right(csarUIPayloadRes.right().value());
+ }
+ Map<String, byte[]> csarUIPayload = csarUIPayloadRes.left().value();
+
+ createOrUpdateResourceRes = getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName);
+ if (createOrUpdateResourceRes.isRight()) {
+ return Either.right(createOrUpdateResourceRes.right().value());
+ }
+ if (resourceUniqueId == null || resourceUniqueId.isEmpty()) {
+ createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName);
+ if (createOrUpdateResourceRes.isRight()) {
+ return Either.right(createOrUpdateResourceRes.right().value());
+ }
+ actionStatus = ActionStatus.CREATED;
+ } else {
+ createOrUpdateResourceRes = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId);
+ if (createOrUpdateResourceRes.isRight()) {
+ return Either.right(createOrUpdateResourceRes.right().value());
+ }
+ actionStatus = ActionStatus.OK;
+ }
+ result = new ImmutablePair<org.openecomp.sdc.be.model.Resource, ActionStatus>(createOrUpdateResourceRes.left().value(), actionStatus);
+ return Either.left(result);
+ }
+
+ private Either<org.openecomp.sdc.be.model.Resource, ResponseFormat> getAndValidateCsarYaml(Map<String, byte[]> csarUIPayload, org.openecomp.sdc.be.model.Resource resource, User user, String csarUUID) {
+
+ Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils());
+
+ if (getToscaYamlRes.isRight()) {
+ ResponseFormat responseFormat = getToscaYamlRes.right().value();
+ log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
+ BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
+ getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+ return Either.right(responseFormat);
+ }
+ String toscaYaml = getToscaYamlRes.left().value().getValue();
+
+ log.debug("checking tosca template is valid yml");
+ YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
+ boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes());
+ if (!isValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE);
+ getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+ return Either.right(responseFormat);
+ }
+
+ log.debug("checking payload is valid tosca");
+ String heatDecodedPayload = toscaYaml;
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
+ Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
+
+ if (findFirstToscaStringElement.isRight()) {
+ isValid = false;
+ } else {
+ String defenitionVersionFound = findFirstToscaStringElement.left().value();
+ if (defenitionVersionFound == null || defenitionVersionFound.isEmpty()) {
+ isValid = false;
+ } else {
+ isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
+ }
+ }
+
+ if (!isValid) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
+ getComponentsUtils().auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(resource);
+ }
+
+ private void fillResourceFromResourceInfoObject(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) {
+ resourceImportManager.populateResourceMetadata(resourceInfoObject, resource);
+ fillArtifacts(resource, resourceInfoObject);
+
+ }
+
+ private void fillArtifacts(org.openecomp.sdc.be.model.Resource resource, UploadResourceInfo resourceInfoObject) {
+ if (resource != null && resourceInfoObject != null) {
+ List<UploadArtifactInfo> artifactList = resourceInfoObject.getArtifactList();
+ if (artifactList != null) {
+ Map<String, ArtifactDefinition> artifactsHM = new HashMap<String, ArtifactDefinition>();
+ for (UploadArtifactInfo artifact : artifactList) {
+ ArtifactDefinition artifactDef = new ArtifactDefinition();
+ artifactDef.setArtifactName(artifact.getArtifactName());
+ artifactDef.setArtifactType(artifact.getArtifactType().getType());
+ artifactDef.setDescription(artifact.getArtifactDescription());
+ artifactDef.setPayloadData(artifact.getArtifactData());
+ artifactDef.setArtifactRef(artifact.getArtifactPath());
+ artifactsHM.put(artifactDef.getArtifactName(), artifactDef);
+ }
+ resource.setArtifacts(artifactsHM);
+ }
+ }
+ }
+
+ private Either<Map<String, byte[]>, ResponseFormat> getScarFromPayload(UploadResourceInfo innerElement) {
+ String csarUUID = innerElement.getPayloadName();
+ String payloadData = innerElement.getPayloadData();
+ if (payloadData == null) {
+ log.info("Failed to decode received csar", csarUUID);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
+ }
+
+ byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8));
+ if (decodedPayload == null) {
+ log.info("Failed to decode received csar", csarUUID);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_NOT_FOUND, csarUUID));
+ }
+
+ Map<String, byte[]> csar = ZipUtil.readZip(decodedPayload);
+ if (csar == null) {
+ log.info("Failed to unzip received csar", csarUUID);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
+ }
+ return Either.left(csar);
+ }
+
+ protected void validateInputStream(final HttpServletRequest request, Wrapper<String> dataWrapper, Wrapper<ResponseFormat> errorWrapper) throws IOException {
+ InputStream inputStream = request.getInputStream();
+ byte[] bytes = IOUtils.toByteArray(inputStream);
+ if (bytes == null || bytes.length == 0) {
+ log.info("Empty body was sent.");
+ errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ } else {
+ dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8));
+ }
+
+ }
+
+ protected <T> void validateClassParse(String data, Wrapper<T> parsedClassWrapper, Supplier<Class<T>> classGen, Wrapper<ResponseFormat> errorWrapper) {
+ try {
+ T parsedClass = gson.fromJson(data, classGen.get());
+ if (parsedClass == null) {
+ errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ } else {
+ parsedClassWrapper.setInnerElement(parsedClass);
+ }
+ } catch (JsonSyntaxException e) {
+ log.debug("Failed to decode received {} {} to object.", classGen.get().getName(), data, e);
+ errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ }
+
+ protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) {
+ ServletContext context = request.getSession().getServletContext();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ errorWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ } else {
+ blWrapper.setInnerElement(componentInstanceLogic);
+ }
+ }
+
+ protected <T> Response buildResponseFromElement(Wrapper<ResponseFormat> errorWrapper, Wrapper<T> attributeWrapper) throws IOException {
+ Response response;
+ if (errorWrapper.isEmpty()) {
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(attributeWrapper.getInnerElement());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+ } else {
+ response = buildErrorResponse(errorWrapper.getInnerElement());
+ }
+ return response;
+ }
+
+ protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper<ResponseFormat> responseWrapper) {
+ ResponseFormat responseFormat;
+ if(StringUtils.isEmpty(instanceIdHeader) ){
+ log.debug("Missing X-ECOMP-InstanceID header");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
+ responseWrapper.setInnerElement(responseFormat);
+ }
+ }
+
+ protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
+ ResponseFormat responseFormat;
+ if( StringUtils.isEmpty(header)){
+ log.debug("MissingUSER_ID");
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
+ responseWrapper.setInnerElement(responseFormat);
+ }
+ }
+
+ /**
+ * Convert json to Object object
+ * @param <T>
+ * @param classSupplier
+ * @param json
+ * @return
+ */
+ public <T> Either<T, ResponseFormat> parseToObject(String json, Supplier<Class<T>> classSupplier) {
+
+ try {
+ T object = RepresentationUtils.fromRepresentation(json, classSupplier.get());
+ return Either.left(object);
+ } catch (Exception e) {
+ log.debug("Failed to parse json to {} object", classSupplier.get().getName(), e);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(responseFormat);
+ }
+ }
+
+ /**
+ * Convert json to Object object
+ * @param <T>
+ * @param json
+ * @param type
+ * @return
+ */
+ public <T> Either<List<T>, ResponseFormat> parseListOfObjects(String json, Type type) {
+ try {
+ List<T> listOfObjects = gson.fromJson(json, type);
+ return Either.left(listOfObjects);
+ } catch (Exception e) {
+ log.debug("Failed to parse json to {} object", type.getClass().getName(), e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return Either.right(responseFormat);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
index ae103dbaca..f6d89e9065 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
@@ -20,22 +20,9 @@
package org.openecomp.sdc.be.servlets;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -50,503 +37,496 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Additional Information Servlet", description = "Additional Information Servlet")
@Singleton
public class AdditionalInformationServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(AdditionalInformationServlet.class.getName());
-
- /**
- *
- * @param resourceId
- * @param data
- * @param request
- * @param userUserId
- * @return
- */
- @POST
- @Path("/resources/{resourceId}/additionalinfo")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
-
- return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data);
-
- }
-
- /**
- *
- * @param serviceId
- * @param data
- * @param request
- * @param userUserId
- * @return
- */
- @POST
- @Path("/services/{serviceId}/additionalinfo")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
- @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
-
- return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);
-
- }
-
- /**
- *
- * @param resourceId
- * @param labelId
- * @param data
- * @param request
- * @param userId
- * @return
- */
- @PUT
- @Path("/resources/{resourceId}/additionalinfo/{labelId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data);
-
- }
-
- /**
- *
- * @param serviceId
- * @param labelId
- * @param data
- * @param request
- * @param userId
- * @return
- */
- @PUT
- @Path("/services/{serviceId}/additionalinfo/{labelId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
- @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data);
-
- }
-
- /**
- *
- * @param resourceId
- * @param labelId
- * @param request
- * @param userId
- * @return
- */
- @DELETE
- @Path("/resources/{resourceId}/additionalinfo/{labelId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
-
- }
-
- /**
- *
- * @param serviceId
- * @param labelId
- * @param request
- * @param userId
- * @return
- */
- @DELETE
- @Path("/services/{serviceId}/additionalinfo/{labelId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
- @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
-
- }
-
- /**
- *
- * @param resourceId
- * @param labelId
- * @param request
- * @param userId
- * @return
- */
- @GET
- @Path("/resources/{resourceId}/additionalinfo/{labelId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
-
- }
-
- /**
- *
- * @param serviceId
- * @param labelId
- * @param request
- * @param userId
- * @return
- */
- @GET
- @Path("/services/{serviceId}/additionalinfo/{labelId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
- @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
-
- }
-
- /**
- *
- * @param resourceId
- * @param request
- * @param userId
- * @return
- */
- @GET
- @Path("/resources/{resourceId}/additionalinfo")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId);
-
- }
-
- /**
- *
- * @param serviceId
- * @param request
- * @param userId
- * @return
- */
- @GET
- @Path("/services/{serviceId}/additionalinfo")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Additional information key already exist") })
- public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId);
-
- }
-
- /**
- *
- * Create additional information property under given resource/service
- *
- * @param nodeType
- * @param uniqueId
- * @param request
- * @param userId
- * @param data
- * @return
- */
- protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
- log.debug("data is {}", data);
-
- try {
- // convert json to AdditionalInfoParameterInfo
- AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
-
- // create the new property
- AdditionalInformationBusinessLogic businessLogic = getBL(context);
-
- Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
-
- if (either.isRight()) {
- ResponseFormat responseFormat = either.right().value();
- log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);
- return buildErrorResponse(responseFormat);
- }
-
- AdditionalInfoParameterInfo createdAI = either.left().value();
-
- log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
- return buildOkResponse(responseFormat, createdAI);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Additional Information");
- log.debug("Create additional information failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
-
- }
-
- /**
- * Update additional information property by id under given resource/service
- *
- * @param nodeType
- * @param uniqueId
- * @param labelId
- * @param request
- * @param userId
- * @param data
- * @return
- */
- protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
- log.debug("data is {}", data);
-
- try {
- // convert json to AdditionalInfoParameterInfo
- AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
-
- // create the new property
- AdditionalInformationBusinessLogic businessLogic = getBL(context);
-
- additionalInfoParameterInfo.setUniqueId(labelId);
-
- Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
-
- if (either.isRight()) {
- ResponseFormat responseFormat = either.right().value();
- log.info("Failed to update additional information property. Reason - {}", responseFormat);
- return buildErrorResponse(responseFormat);
- }
-
- AdditionalInfoParameterInfo createdAI = either.left().value();
-
- log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
+ private static final Logger log = LoggerFactory.getLogger(AdditionalInformationServlet.class);
+
+ /**
+ *
+ * @param resourceId
+ * @param data
+ * @param request
+ * @param userUserId
+ * @return
+ */
+ @POST
+ @Path("/resources/{resourceId}/additionalinfo")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response createResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
+
+ return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data);
+
+ }
+
+ /**
+ *
+ * @param serviceId
+ * @param data
+ * @param request
+ * @param userUserId
+ * @return
+ */
+ @POST
+ @Path("/services/{serviceId}/additionalinfo")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "POST", notes = "Returns created Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Additional information created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response createServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+ @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
+
+ return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);
+
+ }
+
+ /**
+ *
+ * @param resourceId
+ * @param labelId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @PUT
+ @Path("/resources/{resourceId}/additionalinfo/{labelId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data);
+
+ }
+
+ /**
+ *
+ * @param serviceId
+ * @param labelId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @PUT
+ @Path("/services/{serviceId}/additionalinfo/{labelId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Additional Information Label and Value", httpMethod = "PUT", notes = "Returns updated Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response updateServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+ @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @ApiParam(value = "Additional information key value to be created", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data);
+
+ }
+
+ /**
+ *
+ * @param resourceId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @DELETE
+ @Path("/resources/{resourceId}/additionalinfo/{labelId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response updateResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
+
+ }
+
+ /**
+ *
+ * @param serviceId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @DELETE
+ @Path("/services/{serviceId}/additionalinfo/{labelId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Additional Information Label and Value", httpMethod = "DELETE", notes = "Returns deleted Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Additional information deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response deleteServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+ @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
+
+ }
+
+ /**
+ *
+ * @param resourceId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @GET
+ @Path("/resources/{resourceId}/additionalinfo/{labelId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response getResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
+
+ }
+
+ /**
+ *
+ * @param serviceId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @GET
+ @Path("/services/{serviceId}/additionalinfo/{labelId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Additional Information by id", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "fetched additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response getServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+ @ApiParam(value = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
+
+ }
+
+ /**
+ *
+ * @param resourceId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @GET
+ @Path("/resources/{resourceId}/additionalinfo")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get all Additional Information under resource", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response getAllResourceAdditionalInformationLabel(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId);
+
+ }
+
+ /**
+ *
+ * @param serviceId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @GET
+ @Path("/services/{serviceId}/additionalinfo")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get all Additional Information under service", httpMethod = "GET", notes = "Returns Additional Inforamtion property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "list of additional information"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Additional information key already exist") })
+ public Response getAllServiceAdditionalInformationLabel(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId);
+
+ }
+
+ /**
+ *
+ * Create additional information property under given resource/service
+ *
+ * @param nodeType
+ * @param uniqueId
+ * @param request
+ * @param userId
+ * @param data
+ * @return
+ */
+ protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ log.debug("modifier id is {}", userId);
+ log.debug("data is {}", data);
+
+ try {
+ // convert json to AdditionalInfoParameterInfo
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
+
+ // create the new property
+ AdditionalInformationBusinessLogic businessLogic = getBL(context);
+
+ Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
+
+ if (either.isRight()) {
+ ResponseFormat responseFormat = either.right().value();
+ log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+
+ AdditionalInfoParameterInfo createdAI = either.left().value();
+
+ log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
+
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
+ return buildOkResponse(responseFormat, createdAI);
+
+ } catch (Exception e) {
+ log.debug("Create additional information failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
+
+ }
+
+ /**
+ * Update additional information property by id under given resource/service
+ *
+ * @param nodeType
+ * @param uniqueId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @param data
+ * @return
+ */
+ protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ log.debug("modifier id is {}", userId);
+ log.debug("data is {}", data);
+
+ try {
+ // convert json to AdditionalInfoParameterInfo
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
+
+ // create the new property
+ AdditionalInformationBusinessLogic businessLogic = getBL(context);
+
+ additionalInfoParameterInfo.setUniqueId(labelId);
+
+ Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
+
+ if (either.isRight()) {
+ ResponseFormat responseFormat = either.right().value();
+ log.info("Failed to update additional information property. Reason - {}", responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
+
+ AdditionalInfoParameterInfo createdAI = either.left().value();
+
+ log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- return buildOkResponse(responseFormat, createdAI);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ return buildOkResponse(responseFormat, createdAI);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Additional Information");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information");
- log.debug("Update additional information failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information");
+ log.debug("Update additional information failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
- }
+ }
- /**
- *
- * Delete an additional information property by id under given resource/service
- *
- * @param nodeType
- * @param uniqueId
- * @param labelId
- * @param request
- * @param userId
- * @return
- */
- protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
+ /**
+ *
+ * Delete an additional information property by id under given resource/service
+ *
+ * @param nodeType
+ * @param uniqueId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @return
+ */
+ protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
- ServletContext context = request.getSession().getServletContext();
+ ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ log.debug("modifier id is {}", userId);
- try {
+ try {
- AdditionalInformationBusinessLogic businessLogic = getBL(context);
+ AdditionalInformationBusinessLogic businessLogic = getBL(context);
- AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
- additionalInfoParameterInfo.setUniqueId(labelId);
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
+ additionalInfoParameterInfo.setUniqueId(labelId);
- Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
+ Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
- if (either.isRight()) {
- ResponseFormat responseFormat = either.right().value();
- log.info("Failed to update additional information property. Reason - {}", responseFormat);
- return buildErrorResponse(responseFormat);
- }
+ if (either.isRight()) {
+ ResponseFormat responseFormat = either.right().value();
+ log.info("Failed to update additional information property. Reason - {}", responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
- AdditionalInfoParameterInfo createdAI = either.left().value();
+ AdditionalInfoParameterInfo createdAI = either.left().value();
- log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
+ log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- return buildOkResponse(responseFormat, createdAI);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ return buildOkResponse(responseFormat, createdAI);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Additional Information");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information");
- log.debug("Delete additional information failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information");
+ log.debug("Delete additional information failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
- }
+ }
- /**
- * Get a specific additional information property by a given id under given resource/service
- *
- * @param nodeType
- * @param uniqueId
- * @param labelId
- * @param request
- * @param userId
- * @return
- */
- protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
+ /**
+ * Get a specific additional information property by a given id under given resource/service
+ *
+ * @param nodeType
+ * @param uniqueId
+ * @param labelId
+ * @param request
+ * @param userId
+ * @return
+ */
+ protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
- ServletContext context = request.getSession().getServletContext();
+ ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ log.debug("modifier id is {}", userId);
- try {
+ try {
- // create the new property
- AdditionalInformationBusinessLogic businessLogic = getBL(context);
+ // create the new property
+ AdditionalInformationBusinessLogic businessLogic = getBL(context);
- AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
- additionalInfoParameterInfo.setUniqueId(labelId);
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
+ additionalInfoParameterInfo.setUniqueId(labelId);
- Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
+ Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, null, userId);
- if (either.isRight()) {
- ResponseFormat responseFormat = either.right().value();
- log.info("Failed to update additional information property. Reason - {}", responseFormat);
- return buildErrorResponse(responseFormat);
- }
+ if (either.isRight()) {
+ ResponseFormat responseFormat = either.right().value();
+ log.info("Failed to update additional information property. Reason - {}", responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
- AdditionalInfoParameterInfo createdAI = either.left().value();
+ AdditionalInfoParameterInfo createdAI = either.left().value();
- log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
+ log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- return buildOkResponse(responseFormat, createdAI);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ return buildOkResponse(responseFormat, createdAI);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Additional Information");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information");
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information");
- log.debug("get additional information failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
+ log.debug("get additional information failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
- }
+ }
- /**
- * Get all additional information properties under given resource/service
- *
- * @param nodeType
- * @param uniqueId
- * @param request
- * @param userId
- * @return
- */
- protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) {
+ /**
+ * Get all additional information properties under given resource/service
+ *
+ * @param nodeType
+ * @param uniqueId
+ * @param request
+ * @param userId
+ * @return
+ */
+ protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) {
- ServletContext context = request.getSession().getServletContext();
+ ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ log.debug("modifier id is {}", userId);
- try {
+ try {
- AdditionalInformationBusinessLogic businessLogic = getBL(context);
+ AdditionalInformationBusinessLogic businessLogic = getBL(context);
- Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, null, userId);
- if (either.isRight()) {
- ResponseFormat responseFormat = either.right().value();
- log.info("Failed to update additional information property. Reason - {}", responseFormat);
- return buildErrorResponse(responseFormat);
- }
+ Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, null, userId);
+ if (either.isRight()) {
+ ResponseFormat responseFormat = either.right().value();
+ log.info("Failed to update additional information property. Reason - {}", responseFormat);
+ return buildErrorResponse(responseFormat);
+ }
- AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
+ AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
- log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition);
+ log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- return buildOkResponse(responseFormat, additionalInformationDefinition);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ return buildOkResponse(responseFormat, additionalInformationDefinition);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Additional Information");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information");
- log.debug("Get all addiotanl information properties failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information");
+ log.debug("Get all addiotanl information properties failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
- }
+ }
- private AdditionalInformationBusinessLogic getBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- AdditionalInformationBusinessLogic bl = webApplicationContext.getBean(AdditionalInformationBusinessLogic.class);
- return bl;
- }
+ private AdditionalInformationBusinessLogic getBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ AdditionalInformationBusinessLogic bl = webApplicationContext.getBean(AdditionalInformationBusinessLogic.class);
+ return bl;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
index 5a26b7c4e6..fa7ed4b547 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
@@ -20,23 +20,13 @@
package org.openecomp.sdc.be.servlets;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
@@ -52,15 +42,21 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Map;
/**
* Root resource (exposed at "/" path)
*/
@@ -70,535 +66,535 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class ArtifactServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(ArtifactServlet.class.getName());
-
- // *************** Resources
- @POST
- @Path("/resources/{resourceId}/artifacts")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Artifact already exist") })
- public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");
- log.debug("loadArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/resources/{resourceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");
- log.debug("updateArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @DELETE
- @Path("/resources/{resourceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);
- } catch (Exception e) {
- log.debug("deleteArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- // *************** Services
- @POST
- @Path("/services/{serviceId}/artifacts")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Artifact already exist") })
- public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");
- log.debug("loadInformationArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/services/{serviceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");
- log.debug("updateInformationArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- // *************** Services api artifacts
- @POST
- @Path("/services/{serviceId}/artifacts/api/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");
- log.debug("updateApiArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @DELETE
- @Path("/services/{serviceId}/artifacts/api/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") })
- public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");
- log.debug("deleteApiArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @DELETE
- @Path("/services/{serviceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");
- log.debug("deleteInformationalArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /*
- * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href)
- */
-
- @GET
- @Path("/services/{serviceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") })
- public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
- log.debug("downloadServiceArtifactBase64 unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/resources/{resourceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
- public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
- log.debug("downloadResourceArtifactBase64 unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") })
- public Response downloadResourceInstanceArtifactBase64(
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
- log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- // *************** Resource lifecycle ( interfces )
-
- @POST
- @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Artifact already exist") })
- public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Create, null, null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");
- log.debug("loadArtifactToInterface unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @DELETE
- @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Artifact already exist") })
- public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");
- log.debug("deleteArtifactToInterface unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "update Artifact Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Artifact already exist") })
- public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,
- @ApiParam(value = "json describe the artifact", required = true) String data) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.Update, null, null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");
- log.debug("updateArtifactToInterface unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateRIArtifact(
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
- @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");
- log.debug("updateRIArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
- @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Update, componentId, containerComponentType);
- } catch (Exception e) {
- log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.Create, componentId, containerComponentType);
- } catch (Exception e) {
- log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @DELETE
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
- @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
- } catch (Exception e) {
- log.debug("deleteArtifact unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
-
- @GET
- @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
- public Response getComponentArtifacts(
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
- log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
- public Response getComponentInstanceArtifacts(
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
- try {
- return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
- log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
-
- // ////////// API END ///////////////////////////
-
- // ************ private *********************
-
- private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {
- return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.Create);
- }
-
- private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {
- return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.Update);
- }
-
- private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);
-
- Response response;
- if (actionResult.isRight()) {
- response = buildErrorResponse(actionResult.right().value());
- } else {
- byte[] file = actionResult.left().value().getRight();
- String base64Contents = new String(Base64.encodeBase64(file));
- String artifactName = actionResult.left().value().getLeft();
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData();
- artifactUiDownloadData.setArtifactName(artifactName);
- artifactUiDownloadData.setBase64Contents(base64Contents);
- response = buildOkResponse(responseFormat, artifactUiDownloadData);
- }
- return response;
- }
-
- private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE;
- Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
-
- Response response;
- if (actionResult.isRight()) {
- response = buildErrorResponse(actionResult.right().value());
- } else {
-
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value());
- }
-
- return response;
- }
-
-
- private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {
- return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);
- }
-
- private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) {
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.Delete), artifactId, null, null, null, interfaceType, operationName,
- parentId, null);
- Response response;
- if (actionResult.isRight()) {
- response = buildErrorResponse(actionResult.right().value());
- } else {
- Either<ArtifactDefinition, Operation> result = actionResult.left().value();
- if (result.isLeft()) {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
- }
- }
- return response;
-
- }
-
- private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
- String containerComponentType) {
- ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
- String origMd5 = request.getHeader(Constants.MD5_HEADER);
-
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- ServletContext context = request.getSession().getServletContext();
- ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType,
- artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
- containerComponentType);
- Response response;
- if (actionResult.isRight()) {
- response = buildErrorResponse(actionResult.right().value());
- } else {
- Either<ArtifactDefinition, Operation> result = actionResult.left().value();
- if (result.isLeft()) {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
- }
- }
- return response;
-
- }
-
- private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {
- return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null);
- }
+ private static final Logger log = LoggerFactory.getLogger(ArtifactServlet.class);
+
+ // *************** Resources
+ @POST
+ @Path("/resources/{resourceId}/artifacts")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Artifact already exist") })
+ public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");
+ log.debug("loadArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/resources/{resourceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");
+ log.debug("updateArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Path("/resources/{resourceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);
+ } catch (Exception e) {
+ log.debug("deleteArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ // *************** Services
+ @POST
+ @Path("/services/{serviceId}/artifacts")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Artifact already exist") })
+ public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");
+ log.debug("loadInformationArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/services/{serviceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");
+ log.debug("updateInformationArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ // *************** Services api artifacts
+ @POST
+ @Path("/services/{serviceId}/artifacts/api/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");
+ log.debug("updateApiArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Path("/services/{serviceId}/artifacts/api/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") })
+ public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");
+ log.debug("deleteApiArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Path("/services/{serviceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");
+ log.debug("deleteInformationalArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /*
+ * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href)
+ */
+
+ @GET
+ @Path("/services/{serviceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") })
+ public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
+ log.debug("downloadServiceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/resources/{resourceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
+ public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
+ log.debug("downloadResourceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") })
+ public Response downloadResourceInstanceArtifactBase64(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
+ log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ // *************** Resource lifecycle ( interfces )
+
+ @POST
+ @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Artifact already exist") })
+ public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");
+ log.debug("loadArtifactToInterface unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @DELETE
+ @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Artifact already exist") })
+ public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");
+ log.debug("deleteArtifactToInterface unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "update Artifact Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Artifact already exist") })
+ public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,
+ @ApiParam(value = "json describe the artifact", required = true) String data) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");
+ log.debug("updateArtifactToInterface unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateRIArtifact(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
+ @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");
+ log.debug("updateRIArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
+ @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType);
+ } catch (Exception e) {
+ log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId, containerComponentType);
+ } catch (Exception e) {
+ log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
+ @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
+ } catch (Exception e) {
+ log.debug("deleteArtifact unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
+ public Response getComponentArtifacts(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
+ log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
+ public Response getComponentInstanceArtifacts(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+ try {
+ return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
+ log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+
+ // ////////// API END ///////////////////////////
+
+ // ************ private *********************
+
+ private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {
+ return handleArtifactRequest(data, request, componentId, null, componentType, ArtifactOperationEnum.CREATE);
+ }
+
+ private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {
+ return handleArtifactRequest(data, request, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE);
+ }
+
+ private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);
+
+ Response response;
+ if (actionResult.isRight()) {
+ response = buildErrorResponse(actionResult.right().value());
+ } else {
+ byte[] file = actionResult.left().value().getRight();
+ String base64Contents = new String(Base64.encodeBase64(file));
+ String artifactName = actionResult.left().value().getLeft();
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData();
+ artifactUiDownloadData.setArtifactName(artifactName);
+ artifactUiDownloadData.setBase64Contents(base64Contents);
+ response = buildOkResponse(responseFormat, artifactUiDownloadData);
+ }
+ return response;
+ }
+
+ private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE;
+ Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
+
+ Response response;
+ if (actionResult.isRight()) {
+ response = buildErrorResponse(actionResult.right().value());
+ } else {
+
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value());
+ }
+
+ return response;
+ }
+
+
+ private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {
+ return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);
+ }
+
+ private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) {
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName,
+ parentId, null);
+ Response response;
+ if (actionResult.isRight()) {
+ response = buildErrorResponse(actionResult.right().value());
+ } else {
+ Either<ArtifactDefinition, Operation> result = actionResult.left().value();
+ if (result.isLeft()) {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
+ }
+ }
+ return response;
+
+ }
+
+ private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
+ String containerComponentType) {
+ ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
+ String origMd5 = request.getHeader(Constants.MD5_HEADER);
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ ServletContext context = request.getSession().getServletContext();
+ ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType,
+ artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
+ containerComponentType);
+ Response response;
+ if (actionResult.isRight()) {
+ response = buildErrorResponse(actionResult.right().value());
+ } else {
+ Either<ArtifactDefinition, Operation> result = actionResult.left().value();
+ if (result.isLeft()) {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
+ }
+ }
+ return response;
+
+ }
+
+ private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {
+ return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null);
+ }
}
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 1b02e0afa4..09ebb1cd31 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
@@ -20,21 +20,11 @@
package org.openecomp.sdc.be.servlets;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -46,17 +36,13 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
/**
* Web Servlet for actions on Attributes
*
@@ -68,209 +54,209 @@ import io.swagger.annotations.ApiResponses;
@Api(value = "Resource Attribute Servlet", description = "Resource Attribute Servlet")
@Singleton
public class AttributeServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(AttributeServlet.class.getName());
-
- /**
- * Creates new Attribute on a resource with given resource ID
- *
- * @param resourceId
- * @param data
- * @param request
- * @param userId
- * @return
- */
- @POST
- @Path("resources/{resourceId}/attributes")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Resource attribute already exist") })
- public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-
- try {
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
- // convert json to AttributeDefinition
-
- buildAttributeFromString(data, attributesWrapper, errorWrapper);
- if (errorWrapper.isEmpty()) {
- AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
- Either<PropertyDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
- if (createAttribute.isRight()) {
- errorWrapper.setInnerElement(createAttribute.right().value());
- } else {
- attributesWrapper.setInnerElement(createAttribute.left().value());
- }
- }
-
- Response response;
- if (!errorWrapper.isEmpty()) {
- log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
- response = buildErrorResponse(errorWrapper.getInnerElement());
- } else {
- 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));
- }
-
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
- log.debug("create property failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- /**
- * Updates existing Attribute with given attributeID on a resource with given resourceID
- *
- * @param resourceId
- * @param attributeId
- * @param data
- * @param request
- * @param userId
- * @return
- */
- @PUT
- @Path("resources/{resourceId}/attributes/{attributeId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- try {
- // convert json to PropertyDefinition
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
- // convert json to AttributeDefinition
-
- buildAttributeFromString(data, attributesWrapper, errorWrapper);
-
- if (errorWrapper.isEmpty()) {
- AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
- Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
- // update property
- if (eitherUpdateAttribute.isRight()) {
- errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
- } else {
- attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());
- }
- }
-
- Response response;
- if (!errorWrapper.isEmpty()) {
- log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
- response = buildErrorResponse(errorWrapper.getInnerElement());
- } else {
- PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement();
- log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute));
- }
-
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
- log.debug("update attribute failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- /**
- * Deletes existing Attribute with given attributeID on a resource with given resourceID
- *
- * @param resourceId
- * @param attributeId
- * @param request
- * @param userId
- * @return
- */
- @DELETE
- @Path("resources/{resourceId}/attributes/{attributeId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 404, message = "Resource property not found") })
- public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- log.debug("modifier id is {}", userId);
-
- try {
-
- // delete the property
- AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
- Either<PropertyDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
- if (eitherAttribute.isRight()) {
- log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
- return buildErrorResponse(eitherAttribute.right().value());
- }
- PropertyDefinition attributeDefinition = eitherAttribute.left().value();
- String name = attributeDefinition.getName();
-
- log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
- return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
- log.debug("delete attribute failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) {
-
- try {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- 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);
- errorWrapper.setInnerElement(responseFormat);
- } else {
- attributesWrapper.setInnerElement(attribute);
- }
-
- } catch (Exception e) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- errorWrapper.setInnerElement(responseFormat);
- log.debug("Attribute content is invalid - {}", data, e);
- log.info("Attribute content is invalid - {}", data);
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(AttributeServlet.class);
+
+ /**
+ * Creates new Attribute on a resource with given resource ID
+ *
+ * @param resourceId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @POST
+ @Path("resources/{resourceId}/attributes")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource Attribute", httpMethod = "POST", notes = "Returns created resource attribute", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource attribute already exist") })
+ public Response createAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource attribute to be created", required = true) String data,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
+
+ try {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
+ // convert json to AttributeDefinition
+
+ buildAttributeFromString(data, attributesWrapper, errorWrapper);
+ if (errorWrapper.isEmpty()) {
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
+ Either<PropertyDefinition, ResponseFormat> createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId);
+ if (createAttribute.isRight()) {
+ errorWrapper.setInnerElement(createAttribute.right().value());
+ } else {
+ attributesWrapper.setInnerElement(createAttribute.left().value());
+ }
+ }
+
+ Response response;
+ if (!errorWrapper.isEmpty()) {
+ log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
+ response = buildErrorResponse(errorWrapper.getInnerElement());
+ } else {
+ 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));
+ }
+
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
+ log.debug("create property failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ /**
+ * Updates existing Attribute with given attributeID on a resource with given resourceID
+ *
+ * @param resourceId
+ * @param attributeId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @PUT
+ @Path("resources/{resourceId}/attributes/{attributeId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource Attribute", httpMethod = "PUT", notes = "Returns updated attribute", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource attribute updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateAttribute(@ApiParam(value = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId, @ApiParam(value = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ try {
+ // convert json to PropertyDefinition
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Wrapper<PropertyDefinition> attributesWrapper = new Wrapper<>();
+ // convert json to AttributeDefinition
+
+ buildAttributeFromString(data, attributesWrapper, errorWrapper);
+
+ if (errorWrapper.isEmpty()) {
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
+ Either<PropertyDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId);
+ // update property
+ if (eitherUpdateAttribute.isRight()) {
+ errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
+ } else {
+ attributesWrapper.setInnerElement(eitherUpdateAttribute.left().value());
+ }
+ }
+
+ Response response;
+ if (!errorWrapper.isEmpty()) {
+ log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
+ response = buildErrorResponse(errorWrapper.getInnerElement());
+ } else {
+ PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement();
+ log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId());
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute));
+ }
+
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
+ log.debug("update attribute failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ /**
+ * Deletes existing Attribute with given attributeID on a resource with given resourceID
+ *
+ * @param resourceId
+ * @param attributeId
+ * @param request
+ * @param userId
+ * @return
+ */
+ @DELETE
+ @Path("resources/{resourceId}/attributes/{attributeId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource Attribute", httpMethod = "DELETE", notes = "Returns deleted attribute", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted attribute"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "Resource property not found") })
+ public Response deleteAttribute(@ApiParam(value = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ log.debug("modifier id is {}", userId);
+
+ try {
+
+ // delete the property
+ AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
+ Either<PropertyDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
+ if (eitherAttribute.isRight()) {
+ log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
+ return buildErrorResponse(eitherAttribute.right().value());
+ }
+ PropertyDefinition attributeDefinition = eitherAttribute.left().value();
+ String name = attributeDefinition.getName();
+
+ log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
+ return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
+ log.debug("delete attribute failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ private void buildAttributeFromString(String data, Wrapper<PropertyDefinition> attributesWrapper, Wrapper<ResponseFormat> errorWrapper) {
+
+ try {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ 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);
+ errorWrapper.setInnerElement(responseFormat);
+ } else {
+ attributesWrapper.setInnerElement(attribute);
+ }
+
+ } catch (Exception e) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ errorWrapper.setInnerElement(responseFormat);
+ log.debug("Attribute content is invalid - {}", data, e);
+ log.info("Attribute content is invalid - {}", data);
+ }
+ }
}
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 7407a4dff3..0e0d20ffcb 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,30 +20,24 @@
package org.openecomp.sdc.be.servlets;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.Supplier;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-
-import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import fj.data.Either;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;
+import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
+import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ProductComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
+import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.api.IElementDAO;
@@ -51,204 +45,244 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
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.PropertyConstraint;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
+import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.servlets.BasicServlet;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.Supplier;
public class BeGenericServlet extends BasicServlet {
- @Context
- protected HttpServletRequest servletRequest;
-
- private static Logger log = LoggerFactory.getLogger(BeGenericServlet.class.getName());
-
- /******************** New error response mechanism
- * @param additionalParams **************/
-
- protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
- return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
- }
-
- protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
- return buildOkResponse(errorResponseWrapper, entity, null);
- }
-
- protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) {
- int status = errorResponseWrapper.getStatus();
- ResponseBuilder responseBuilder = Response.status(status);
- if (entity != null) {
- if (log.isTraceEnabled())
- log.trace("returned entity is {}", entity.toString());
- responseBuilder = responseBuilder.entity(entity);
- }
- if (additionalHeaders != null) {
- for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) {
- String headerName = additionalHeader.getKey();
- String headerValue = additionalHeader.getValue();
- if (log.isTraceEnabled())
- log.trace("Adding header {} with value {} to the response", headerName, headerValue);
- responseBuilder.header(headerName, headerValue);
- }
- }
- return responseBuilder.build();
- }
-
- /*******************************************************************************************************/
- protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) {
- Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
- if (eitherCreator.isRight()) {
- log.info("createResource method - user is not listed. userId= {}", userId);
- ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
- User user = new User("", "", userId, "", null, null);
-
- getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null);
- return Either.right(errorResponse);
- }
- return Either.left(eitherCreator.left().value());
-
- }
-
- protected UserBusinessLogic getUserAdminManager(ServletContext context) {
- return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
- }
-
- protected ResourceBusinessLogic getResourceBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
- }
-
- protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
- }
-
- protected ServiceBusinessLogic getServiceBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
- }
-
- protected ProductBusinessLogic getProductBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
- }
-
- protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
- }
-
- protected ElementBusinessLogic getElementBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
- }
-
- protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
- }
-
- protected AssetMetadataConverter getAssetUtils(ServletContext context) {
- return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
- }
-
- protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
- return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
- }
-
- protected <SomeClass> SomeClass getClassFromWebAppContext(ServletContext context, Supplier<Class<SomeClass>> businessLogicClassGen) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- SomeClass monitoringBusinessLogic = webApplicationContext.getBean(businessLogicClassGen.get());
- return monitoringBusinessLogic;
- }
-
- protected GroupBusinessLogic getGroupBL(ServletContext context) {
-
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- GroupBusinessLogic groupBusinessLogic = webApplicationContext.getBean(GroupBusinessLogic.class);
- return groupBusinessLogic;
- }
-
- protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context, ComponentTypeEnum containerComponentType) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- if (containerComponentType == ComponentTypeEnum.RESOURCE) {
- return webApplicationContext.getBean(VFComponentInstanceBusinessLogic.class);
- }
- if (containerComponentType == ComponentTypeEnum.SERVICE) {
- return webApplicationContext.getBean(ServiceComponentInstanceBusinessLogic.class);
- }
- if (containerComponentType == ComponentTypeEnum.PRODUCT) {
- return webApplicationContext.getBean(ProductComponentInstanceBusinessLogic.class);
- }
- return null;
- }
-
- protected IElementDAO getElementDao(Class<? extends IElementDAO> clazz, ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-
- return webApplicationContext.getBean(clazz);
- }
-
- protected ComponentsUtils getComponentsUtils() {
- ServletContext context = this.servletRequest.getSession().getServletContext();
-
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ComponentsUtils componentsUtils = webApplicationContext.getBean(ComponentsUtils.class);
- return componentsUtils;
- }
-
- /**
- * Used to support Unit Test.<br>
- * Header Params are not supported in Unit Tests
- *
- * @return
- */
- protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) {
- String retValue;
- if (headerValue != null) {
- retValue = headerValue;
- } else {
- retValue = request.getHeader(headerName);
- }
- return retValue;
- }
-
- protected String getContentDispositionValue(String artifactFileName) {
- return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString();
- }
-
- protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) {
- ComponentBusinessLogic businessLogic;
- switch (componentTypeEnum) {
- case RESOURCE: {
- businessLogic = getResourceBL(context);
- break;
- }
- case SERVICE: {
- businessLogic = getServiceBL(context);
- break;
- }
- case PRODUCT: {
- businessLogic = getProductBL(context);
- break;
- }
- case RESOURCE_INSTANCE: {
- businessLogic = getResourceBL(context);
- break;
- }
- default: {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "getComponentBL");
- BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
- throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
- }
- }
- return businessLogic;
- }
+ @Context
+ protected HttpServletRequest servletRequest;
+
+ private static final Logger log = LoggerFactory.getLogger(BeGenericServlet.class);
+
+ /******************** New error response mechanism
+ * @param requestErrorWrapper **************/
+
+ protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
+ return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
+ }
+
+ protected Response buildGeneralErrorResponse() {
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ protected Response buildOkResponse(Object entity) {
+ return buildOkResponseStatic(entity);
+ }
+
+ static public Response buildOkResponseStatic(Object entity) {
+ return Response.status(Response.Status.OK)
+ .entity(entity)
+ .build();
+ }
+
+ protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
+ return buildOkResponse(errorResponseWrapper, entity, null);
+ }
+
+ protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity, Map<String, String> additionalHeaders) {
+ int status = errorResponseWrapper.getStatus();
+ ResponseBuilder responseBuilder = Response.status(status);
+ if (entity != null) {
+ if (log.isTraceEnabled())
+ log.trace("returned entity is {}", entity.toString());
+ responseBuilder = responseBuilder.entity(entity);
+ }
+ if (additionalHeaders != null) {
+ for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) {
+ String headerName = additionalHeader.getKey();
+ String headerValue = additionalHeader.getValue();
+ if (log.isTraceEnabled())
+ log.trace("Adding header {} with value {} to the response", headerName, headerValue);
+ responseBuilder.header(headerName, headerValue);
+ }
+ }
+ return responseBuilder.build();
+ }
+
+ /*******************************************************************************************************/
+ protected Either<User, ResponseFormat> getUser(final HttpServletRequest request, String userId) {
+ Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
+ if (eitherCreator.isRight()) {
+ log.info("createResource method - user is not listed. userId= {}", userId);
+ ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ User user = new User("", "", userId, "", null, null);
+
+ getComponentsUtils().auditResource(errorResponse, user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(eitherCreator.left().value());
+
+ }
+
+ protected PolicyTypeBusinessLogic getPolicyTypeBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> PolicyTypeBusinessLogic.class);
+ }
+
+ protected UserBusinessLogic getUserAdminManager(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> UserBusinessLogic.class);
+ }
+
+ protected ResourceBusinessLogic getResourceBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> ResourceBusinessLogic.class);
+ }
+
+ protected ComponentsCleanBusinessLogic getComponentCleanerBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> ComponentsCleanBusinessLogic.class);
+ }
+
+ protected ServiceBusinessLogic getServiceBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> ServiceBusinessLogic.class);
+ }
+
+ protected ProductBusinessLogic getProductBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> ProductBusinessLogic.class);
+ }
+
+ protected ArtifactsBusinessLogic getArtifactBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> ArtifactsBusinessLogic.class);
+ }
+
+ protected ElementBusinessLogic getElementBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> ElementBusinessLogic.class);
+ }
+
+ protected MonitoringBusinessLogic getMonitoringBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> MonitoringBusinessLogic.class);
+ }
+
+ protected AssetMetadataConverter getAssetUtils(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> AssetMetadataConverter.class);
+ }
+
+ protected LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> LifecycleBusinessLogic.class);
+ }
+
+ protected PolicyBusinessLogic getPolicyBL(ServletContext context) {
+ return getClassFromWebAppContext(context, () -> PolicyBusinessLogic.class);
+ }
+
+ protected <T> T getClassFromWebAppContext(ServletContext context, Supplier<Class<T>> businessLogicClassGen) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(businessLogicClassGen.get());
+ }
+
+ protected GroupBusinessLogic getGroupBL(ServletContext context) {
+
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(GroupBusinessLogic.class);
+ }
+
+ protected ComponentInstanceBusinessLogic getComponentInstanceBL(ServletContext context, ComponentTypeEnum containerComponentType) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(ComponentInstanceBusinessLogic.class);
+ }
+
+ protected IElementDAO getElementDao(Class<? extends IElementDAO> clazz, ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+
+ return webApplicationContext.getBean(clazz);
+ }
+
+ protected ComponentsUtils getComponentsUtils() {
+ ServletContext context = this.servletRequest.getSession().getServletContext();
+
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(ComponentsUtils.class);
+ }
+
+ /**
+ * Used to support Unit Test.<br>
+ * Header Params are not supported in Unit Tests
+ *
+ * @return
+ */
+ protected String initHeaderParam(String headerValue, HttpServletRequest request, String headerName) {
+ String retValue;
+ if (headerValue != null) {
+ retValue = headerValue;
+ } else {
+ retValue = request.getHeader(headerName);
+ }
+ return retValue;
+ }
+
+ protected String getContentDispositionValue(String artifactFileName) {
+ return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString();
+ }
+
+ protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) {
+ ComponentBusinessLogic businessLogic;
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ businessLogic = getResourceBL(context);
+ break;
+ case SERVICE:
+ businessLogic = getServiceBL(context);
+ break;
+ case PRODUCT:
+ businessLogic = getProductBL(context);
+ break;
+ case RESOURCE_INSTANCE:
+ businessLogic = getResourceBL(context);
+ break;
+ default:
+ BeEcompErrorManager.getInstance().logBeSystemError("getComponentBL");
+ throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
+ }
+ return businessLogic;
+ }
+
+ protected <T> void convertJsonToObjectOfClass(String json, Wrapper<T> policyWrapper, Class<T> clazz, Wrapper<Response> errorWrapper) {
+ T object = null;
+ ObjectMapper mapper = new ObjectMapper()
+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
+ .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
+ try {
+ log.trace("Starting to convert json to object. Json=\n{}", json);
+
+ SimpleModule module = new SimpleModule("customDeserializationModule");
+ module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
+ mapper.registerModule(module);
+
+ object = mapper.readValue(json, clazz);
+ if (object != null) {
+ policyWrapper.setInnerElement(object);
+ } else {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("The object of class {} is null after converting from json. ", clazz);
+ errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("The exception {} occured upon json to object convertation. Json=\n{}", e, json);
+ errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
index 81f1775a01..aa10ce0dd4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
@@ -20,22 +20,16 @@
package org.openecomp.sdc.be.servlets;
-import java.util.List;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.tuple.Pair;
-import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic;
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -50,139 +44,135 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.List;
@Loggable(prepend = true, value = Loggable.TRACE, trim = false)
@Path("/")
@Api(value = "BE Monitoring", description = "BE Monitoring")
@Singleton
public class BeMonitoringServlet extends BeGenericServlet {
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
- private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName());
-
- @GET
- @Path("/healthCheck")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") })
- public Response getHealthCheck(@Context final HttpServletRequest request) {
- try {
- HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext());
- Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
- Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft();
- ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR;
- String sdcVersion = getVersionFromContext(request);
- if (sdcVersion == null || sdcVersion.isEmpty()) {
- sdcVersion = "UNKNOWN";
- }
- String siteMode = healthCheckBusinessLogic.getSiteMode();
- HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);
- // The response can be either with 200 or 500 aggregate status - the
- // body of individual statuses is returned either way
-
- String healthCheckStr = prettyGson.toJson(healthCheck);
- return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, "BeHealthCheck");
- BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
- log.debug("BE health check unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/monitoring")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {
- try {
- MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);
- if (monitoringEvent == null) {
- return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
- }
- log.trace("Received monitoring metrics: {}", monitoringEvent.toString());
- ServletContext context = request.getSession().getServletContext();
- MonitoringBusinessLogic bl = getMonitoringBL(context);
- Either<Boolean, ResponseFormat> result = bl.logMonitoringEvent(monitoringEvent);
- if (result.isRight()) {
- return buildErrorResponse(result.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
-
- } catch (Exception e) {
- log.debug("BE system metrics unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/version")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") })
- public Response getSdcVersion(@Context final HttpServletRequest request) {
- try {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- String version = getVersionFromContext(request);
- log.debug("asdc version from manifest is: {}", version);
- if (version == null || version.isEmpty()) {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
- }
-
- HealthCheckInfo versionInfo = new HealthCheckInfo();
- versionInfo.setVersion(version);
-
- // The response can be either with 200 or 500 aggregate status - the
- // body of individual statuses is returned either way
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "getSDCVersion");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
- log.debug("BE get ASDC version unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- private String getVersionFromContext(HttpServletRequest request) {
- ServletContext servletContext = request.getSession().getServletContext();
- String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
- return version;
- }
-
- protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {
-
- MonitoringEvent object = null;
- try {
- object = gson.fromJson(content, clazz);
- object.setFields(null);
- } catch (Exception e) {
- log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
- }
-
- return object;
- }
-
- private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
- return healthCheckBl;
- }
+ Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
+
+ private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class);
+
+ @GET
+ @Path("/healthCheck")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Return aggregate BE health check of SDC BE components", notes = "return BE health check", response = String.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "SDC BE components are all up"), @ApiResponse(code = 500, message = "One or more SDC BE components are down") })
+ public Response getHealthCheck(@Context final HttpServletRequest request) {
+ try {
+ HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(request.getSession().getServletContext());
+ Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
+ Boolean aggregateStatus = beHealthCheckInfosStatus.getLeft();
+ ActionStatus status = aggregateStatus ? ActionStatus.OK : ActionStatus.GENERAL_ERROR;
+ String sdcVersion = getVersionFromContext(request);
+ if (sdcVersion == null || sdcVersion.isEmpty()) {
+ sdcVersion = "UNKNOWN";
+ }
+ String siteMode = healthCheckBusinessLogic.getSiteMode();
+ HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);
+ // The response can be either with 200 or 500 aggregate status - the
+ // body of individual statuses is returned either way
+
+ String healthCheckStr = prettyGson.toJson(healthCheck);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
+ log.debug("BE health check unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/monitoring")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response processMonitoringMetrics(@Context final HttpServletRequest request, String json) {
+ try {
+ MonitoringEvent monitoringEvent = convertContentToJson(json, MonitoringEvent.class);
+ if (monitoringEvent == null) {
+ return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
+ }
+ log.trace("Received monitoring metrics: {}", monitoringEvent);
+ ServletContext context = request.getSession().getServletContext();
+ MonitoringBusinessLogic bl = getMonitoringBL(context);
+ Either<Boolean, ResponseFormat> result = bl.logMonitoringEvent(monitoringEvent);
+ if (result.isRight()) {
+ return buildErrorResponse(result.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
+
+ } catch (Exception e) {
+ log.debug("BE system metrics unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormatAdditionalProperty(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/version")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "return the ASDC application version", notes = "return the ASDC application version", response = String.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "return ASDC version"), @ApiResponse(code = 500, message = "Internal Error") })
+ public Response getSdcVersion(@Context final HttpServletRequest request) {
+ try {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ String version = getVersionFromContext(request);
+ log.debug("asdc version from manifest is: {}", version);
+ if (version == null || version.isEmpty()) {
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.ASDC_VERSION_NOT_FOUND));
+ }
+
+ HealthCheckInfo versionInfo = new HealthCheckInfo();
+ versionInfo.setVersion(version);
+
+ // The response can be either with 200 or 500 aggregate status - the
+ // body of individual statuses is returned either way
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), versionInfo);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
+ log.debug("BE get ASDC version unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ private String getVersionFromContext(HttpServletRequest request) {
+ ServletContext servletContext = request.getSession().getServletContext();
+ String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
+ return version;
+ }
+
+ protected MonitoringEvent convertContentToJson(String content, Class<MonitoringEvent> clazz) {
+
+ MonitoringEvent object = null;
+ try {
+ object = gson.fromJson(content, clazz);
+ object.setFields(null);
+ } catch (Exception e) {
+ log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
+ }
+
+ return object;
+ }
+
+ private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
+ return healthCheckBl;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java
new file mode 100644
index 0000000000..8ed68fa032
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentExceptionMapper.java
@@ -0,0 +1,37 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Component;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+@Component
+@Provider
+public class ComponentExceptionMapper implements ExceptionMapper<ComponentException> {
+
+ private final ComponentsUtils componentsUtils;
+ protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ public ComponentExceptionMapper(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
+
+ @Override
+ public Response toResponse(ComponentException componentException) {
+ ResponseFormat responseFormat = componentException.getResponseFormat();
+ if (componentException.getResponseFormat()==null) {
+ responseFormat = componentsUtils.getResponseFormat(componentException.getActionStatus(), componentException.getParams());
+ }
+
+ return Response.status(responseFormat.getStatus())
+ .entity(gson.toJson(responseFormat.getRequestError()))
+ .build();
+ }
+
+}
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 b5971670cf..536fdc3c7e 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
@@ -20,36 +20,26 @@
package org.openecomp.sdc.be.servlets;
-import java.io.InputStream;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
-import org.codehaus.jackson.map.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datamodel.ForwardingPaths;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
import org.openecomp.sdc.be.info.GroupDefinitionInfo;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -60,24 +50,34 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.reflect.TypeToken;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.InputStream;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
/**
* Root resource (exposed at "/" path) .json
@@ -88,845 +88,818 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class ComponentInstanceServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class.getName());
-
- Type constraintType = new TypeToken<PropertyConstraint>() {
- }.getType();
-
- Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Component instance already exist") })
- public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- try {
-
- ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
- componentInstance.setInvariantName(null);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
- log.debug("create component instance failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
- @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- try {
-
- log.debug("Start handle request of {}", url);
-
- InputStream inputStream = request.getInputStream();
-
- byte[] bytes = IOUtils.toByteArray(inputStream);
-
- if (bytes == null || bytes.length == 0) {
- log.info("Empty body was sent.");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- String data = new String(bytes);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
-
- if (convertResponse.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
- log.debug("Failed to convert received data to BE format.");
- return buildErrorResponse(convertResponse.right().value());
- }
-
- ComponentInstance resourceInstance = convertResponse.left().value();
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
- log.debug("update resource instance with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- try {
- log.debug("Start handle request of {}", url);
-
- if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) {
- log.info("Empty JSON list was sent.");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray);
-
- if (convertResponse.isRight()) {
- // Using both ECOMP error methods, show to Sofer
- BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
- log.debug("Failed to convert received data to BE format.");
- return buildErrorResponse(convertResponse.right().value());
- }
-
- List<ComponentInstance> componentInstanceList = convertResponse.left().value();
-
- Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- /*
- * BeEcompErrorManager.getInstance().processEcompError( EcompErrorName.BeRestApiGeneralError, "Update Resource Instance" );
- */
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
- log.debug("update resource instance with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @DELETE
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId,
- @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- Response response = null;
- try {
- log.debug("Start handle request of {}", url);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);
-
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- }
- return response;
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
- log.debug("delete resource instance with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true)
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/associate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Relationship already exist") })
- public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId,
- @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- Response response = null;
-
- try {
-
- log.debug("Start handle request of {}", url);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
-
- Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;
- if (regInfoW.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");
- log.debug("Failed to convert received data to BE format.");
- resultOp = Either.right(regInfoW.right().value());
- } else {
- RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
- resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);
- }
-
- Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp;
-
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
- }
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
- log.debug("associate resource instance to another RI with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @PUT
- @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response dissociateRIFromRI(
- @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
- @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- try {
-
- log.debug("Start handle request of {}", url);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
- if (regInfoW.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");
- log.debug("Failed to convert received data to BE format.");
- return buildErrorResponse(regInfoW.right().value());
- }
-
- RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
- Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
- log.debug("dissociate resource instance from service failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Relationship already exist") })
- public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- try {
-
- log.debug("Start handle request of {}", url);
-
- InputStream inputStream = request.getInputStream();
-
- byte[] bytes = IOUtils.toByteArray(inputStream);
-
- if (bytes == null || bytes.length == 0) {
- log.info("Empty body was sent.");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- String data = new String(bytes);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
- if (convertStatus.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");
- log.debug("Failed to convert received data to BE format.");
- Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
- return buildErrorResponse(formattedResponse.right().value());
- }
-
- CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value();
- Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance");
- log.debug("create and associate RI failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- try {
- Wrapper<String> dataWrapper = new Wrapper<>();
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
-
- validateInputStream(request, dataWrapper, errorWrapper);
-
- if (errorWrapper.isEmpty()) {
- validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
- }
-
- if (!errorWrapper.isEmpty()) {
- return buildErrorResponse(errorWrapper.getInnerElement());
- }
-
- ComponentInstanceProperty property = propertyWrapper.getInnerElement();
-
- log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
-
- ServletContext context = request.getSession().getServletContext();
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdatePropertyValue(componentTypeEnum, componentId, componentInstanceId, property, userId);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
-
- ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
- ObjectMapper mapper = new ObjectMapper();
- String result = mapper.writeValueAsString(resourceInstanceProperty);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/input")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- try {
- Wrapper<String> dataWrapper = new Wrapper<>();
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-
- validateInputStream(request, dataWrapper, errorWrapper);
- ComponentInstanceInput property = null;
-
- if (errorWrapper.isEmpty()) {
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Either<ComponentInstanceInput, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataWrapper.getInnerElement(), modifier, ComponentInstanceInput.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
- ComponentTypeEnum.SERVICE);
- ;
- if (inputEither.isRight()) {
- log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value());
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- property = inputEither.left().value();
-
- }
-
- if (property == null) {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
-
- ServletContext context = request.getSession().getServletContext();
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<ComponentInstanceInput, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateInstanceInputValue(componentTypeEnum, componentId, componentInstanceId, property, userId);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
-
- ComponentInstanceInput resourceInstanceProperty = actionResponse.left().value();
- ObjectMapper mapper = new ObjectMapper();
- String result = mapper.writeValueAsString(resourceInstanceProperty);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- /**
- * Updates ResourceInstance Attribute
- *
- * @param componentId
- * @param containerComponentType
- * @param componentInstanceId
- * @param userId
- * @param request
- * @return
- */
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- try {
-
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Wrapper<String> dataWrapper = new Wrapper<>();
- Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>();
- Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>();
-
- validateInputStream(request, dataWrapper, errorWrapper);
-
- if (errorWrapper.isEmpty()) {
- validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
- }
-
- if (errorWrapper.isEmpty()) {
- validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper);
- }
-
- if (errorWrapper.isEmpty()) {
- ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement();
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement());
- Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId);
- if (eitherAttribute.isRight()) {
- errorWrapper.setInnerElement(eitherAttribute.right().value());
- } else {
- attributeWrapper.setInnerElement(eitherAttribute.left().value());
- }
- }
-
- return buildResponseFromElement(errorWrapper, attributeWrapper);
-
- } catch (Exception e) {
- log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @DELETE
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId,
- @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- try {
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- } catch (Exception e) {
- log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- try {
- InputStream inputStream = request.getInputStream();
-
- byte[] bytes = IOUtils.toByteArray(inputStream);
-
- if (bytes == null || bytes.length == 0) {
- log.info("Empty body was sent.");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- String data = new String(bytes);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
-
- if (convertResponse.isRight()) {
- BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
- log.debug("Failed to convert received data to BE format.");
- return buildErrorResponse(convertResponse.right().value());
- }
-
- ComponentInstance newResourceInstance = convertResponse.left().value();
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
- log.debug("update resource instance with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @POST
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId,
- @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- try {
- Wrapper<String> dataWrapper = new Wrapper<>();
- Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
- Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
-
- validateInputStream(request, dataWrapper, errorWrapper);
-
- if (errorWrapper.isEmpty()) {
- validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
- }
-
- if (!errorWrapper.isEmpty()) {
- return buildErrorResponse(errorWrapper.getInnerElement());
- }
-
- ComponentInstanceProperty property = propertyWrapper.getInnerElement();
-
- log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
-
- ServletContext context = request.getSession().getServletContext();
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
-
- ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
- ObjectMapper mapper = new ObjectMapper();
- String result = mapper.writeValueAsString(resourceInstanceProperty);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @GET
- @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
- public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
- @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
-
- try {
-
- GroupBusinessLogic businessLogic = this.getGroupBL(context);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get all non abstract {}", containerComponentType);
- return buildErrorResponse(actionResponse.right().value());
- }
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
- log.debug("getGroupArtifactById unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- // US831698
- @GET
- @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") })
- public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
- @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
-
- try {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum);
-
- Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);
-
- if (componentInstancePropertiesById.isRight()) {
- log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId);
- return buildErrorResponse(componentInstancePropertiesById.right().value());
- }
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
- log.debug("getGroupArtifactById unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- // US330353
- @GET
- @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") })
- public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
- @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
-
- try {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum);
-
- Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId,
- capabilityType, capabilityName, userId);
-
- if (componentInstancePropertiesById.isRight()) {
- log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId);
- return buildErrorResponse(componentInstancePropertiesById.right().value());
- }
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
- log.debug("getGroupArtifactById unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
+ private static final Logger log = LoggerFactory.getLogger(ComponentInstanceServlet.class);
- private Either<List<ComponentInstanceProperty>, ResponseFormat> convertMultipleProperties(String dataList) {
- if (StringUtils.isEmpty(dataList)) {
- return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ Type constraintType = new TypeToken<PropertyConstraint>() {
+ }.getType();
+
+ Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create ComponentInstance", httpMethod = "POST", notes = "Returns created ComponentInstance", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Component created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Component instance already exist") })
+ public Response createComponentInstance(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ try {
+
+ ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
+ componentInstance.setInvariantName(null);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
+ log.debug("create component instance failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
- if (convertStatus.isRight()) {
- return Either.right(convertStatus.right().value());
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+ @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ try {
+
+ log.debug("Start handle request of {}", url);
+
+ InputStream inputStream = request.getInputStream();
+
+ byte[] bytes = IOUtils.toByteArray(inputStream);
+
+ if (bytes == null || bytes.length == 0) {
+ log.info("Empty body was sent.");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ String data = new String(bytes);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
+
+ if (convertResponse.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
+ log.debug("Failed to convert received data to BE format.");
+ return buildErrorResponse(convertResponse.right().value());
+ }
+
+ ComponentInstance resourceInstance = convertResponse.left().value();
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
+ log.debug("update resource instance with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- return Either.left(Arrays.asList(convertStatus.left().value()));
+
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance multiple component", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request, @ApiParam(value = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+ log.debug("Start handle request of {}", url);
+
+ if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) {
+ log.info("Empty JSON list was sent.");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray);
+
+ if (convertResponse.isRight()) {
+ // Using both ECOMP error methods, show to Sofer
+ BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
+ log.debug("Failed to convert received data to BE format.");
+ return buildErrorResponse(convertResponse.right().value());
+ }
+
+ List<ComponentInstance> componentInstanceList = convertResponse.left().value();
+
+ Either<List<ComponentInstance>, ResponseFormat> actionResponse = componentInstanceLogic.updateComponentInstance(containerComponentType, componentId, userId, componentInstanceList, true, true);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
+ log.debug("update resource instance with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete ResourceInstance", httpMethod = "DELETE", notes = "Returns delete resourceInstance", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "ResourceInstance deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteResourceInstance(@PathParam("componentId") final String componentId, @PathParam("resourceInstanceId") final String resourceInstanceId,
+ @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ Response response = null;
+ try {
+ log.debug("Start handle request of {}", url);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);
+
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ }
+ return response;
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
+ log.debug("delete resource instance with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + "," + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true)
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/associate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Associate RI to RI", httpMethod = "POST", notes = "Returns created RelationshipInfo", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship created"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Relationship already exist") })
+ public Response associateRIToRI(@ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ Response response = null;
+
+ try {
+
+ log.debug("Start handle request of {}", url);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> resultOp;
+ if (regInfoW.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - associateRIToRI");
+ log.debug("Failed to convert received data to BE format.");
+ resultOp = Either.right(regInfoW.right().value());
+ } else {
+ RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
+ resultOp = componentInstanceLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);
+ }
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = resultOp;
+
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+ }
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
+ log.debug("associate resource instance to another RI with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Dissociate RI from RI", httpMethod = "PUT", notes = "Returns deleted RelationshipInfo", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Relationship deleted"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response dissociateRIFromRI(
+ @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "unique id of the container component") @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @ApiParam(value = "RelationshipInfo", required = true) String data, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+
+ log.debug("Start handle request of {}", url);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> regInfoW = convertToRequirementCapabilityRelDef(data);
+ if (regInfoW.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - dissociateRIFromRI");
+ log.debug("Failed to convert received data to BE format.");
+ return buildErrorResponse(regInfoW.right().value());
+ }
+
+ RequirementCapabilityRelDef requirementDef = regInfoW.left().value();
+ Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
+ log.debug("dissociate resource instance from service failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create RI and associate RI to RI", httpMethod = "POST", notes = "Returns created RI and RelationshipInfo", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "RI created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Relationship already exist") })
+ public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ try {
+
+ log.debug("Start handle request of {}", url);
+
+ InputStream inputStream = request.getInputStream();
+
+ byte[] bytes = IOUtils.toByteArray(inputStream);
+
+ if (bytes == null || bytes.length == 0) {
+ log.info("Empty body was sent.");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ String data = new String(bytes);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
+ if (convertStatus.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");
+ log.debug("Failed to convert received data to BE format.");
+ Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
+ return buildErrorResponse(formattedResponse.right().value());
+ }
+
+ CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value();
+ Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create and Associate Resource Instance");
+ log.debug("create and associate RI failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateResourceInstanceProperties(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstancePropertiesJsonArray) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();
+ if (errorWrapper.isEmpty()) {
+ Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray);
+ if (propertiesToUpdateEither.isRight()) {
+ errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());
+ } else {
+ propertiesToUpdate = propertiesToUpdateEither.left().value();
+ }
+ }
+
+ if (!errorWrapper.isEmpty()) {
+ return buildErrorResponse(errorWrapper.getInnerElement());
+ }
+
+ log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", propertiesToUpdate);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ List<ComponentInstanceProperty> resourceInstanceProperties = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(resourceInstanceProperties);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateResourceInstanceInput(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Context final HttpServletRequest request, @ApiParam(value = "Component Instance Properties JSON Array", required = true) final String componentInstanceInputsJsonArray) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ List<ComponentInstanceInput> inputsToUpdate = new ArrayList<>();
+ if (errorWrapper.isEmpty()) {
+ Either<List<ComponentInstanceInput>, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray);
+ if (inputsToUpdateEither.isRight()) {
+ errorWrapper.setInnerElement(inputsToUpdateEither.right().value());
+ } else {
+ inputsToUpdate = inputsToUpdateEither.left().value();
+ }
+ }
+ if (!errorWrapper.isEmpty()) {
+ return buildErrorResponse(errorWrapper.getInnerElement());
+ }
+
+ log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", inputsToUpdate);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<List<ComponentInstanceInput>, ResponseFormat> actionResponse =
+ componentInstanceLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ List<ComponentInstanceInput> resourceInstanceInput = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(resourceInstanceInput);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ /**
+ * Updates ResourceInstance Attribute
+ *
+ * @param componentId
+ * @param containerComponentType
+ * @param componentInstanceId
+ * @param userId
+ * @param request
+ * @return
+ */
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance attribute", httpMethod = "POST", notes = "Returns updated resource instance attribute", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateResourceInstanceAttribute(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Wrapper<String> dataWrapper = new Wrapper<>();
+ Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>();
+ Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>();
+
+ validateInputStream(request, dataWrapper, errorWrapper);
+
+ if (errorWrapper.isEmpty()) {
+ validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper);
+ }
+
+ if (errorWrapper.isEmpty()) {
+ ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement();
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement());
+ Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId);
+ if (eitherAttribute.isRight()) {
+ errorWrapper.setInnerElement(eitherAttribute.right().value());
+ } else {
+ attributeWrapper.setInnerElement(eitherAttribute.left().value());
+ }
+ }
+
+ return buildResponseFromElement(errorWrapper, attributeWrapper);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance", httpMethod = "DELETE", notes = "Returns deleted resource instance property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteResourceInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "property id") @PathParam("propertyId") final String propertyId,
+ @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ try {
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance", httpMethod = "POST", notes = "Returns updated resource instance", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ try ( InputStream inputStream = request.getInputStream()) {
+
+ byte[] bytes = IOUtils.toByteArray(inputStream);
+
+ if (bytes == null || bytes.length == 0) {
+ log.info("Empty body was sent.");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ String data = new String(bytes);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
+
+ if (convertResponse.isRight()) {
+ BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance");
+ log.debug("Failed to convert received data to BE format.");
+ return buildErrorResponse(convertResponse.right().value());
+ }
+
+ ComponentInstance newResourceInstance = convertResponse.left().value();
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Instance");
+ log.debug("update resource instance with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update resource instance property", httpMethod = "POST", notes = "Returns updated resource instance property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource instance created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupInstanceProperty(@ApiParam(value = "service id") @PathParam("componentId") final String componentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId,
+ @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ try {
+ Wrapper<String> dataWrapper = new Wrapper<>();
+ Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
+ Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
+
+ validateInputStream(request, dataWrapper, errorWrapper);
+
+ if (errorWrapper.isEmpty()) {
+ validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
+ }
+
+ if (!errorWrapper.isEmpty()) {
+ return buildErrorResponse(errorWrapper.getInnerElement());
+ }
+
+ ComponentInstanceProperty property = propertyWrapper.getInnerElement();
+
+ log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", property);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+
+ Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(resourceInstanceProperty);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupInstId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Group not found") })
+ public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+ @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+
+ try {
+
+ GroupBusinessLogic businessLogic = this.getGroupBL(context);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all non abstract {}", containerComponentType);
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
+ log.debug("getGroupArtifactById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ // US831698
+ @GET
+ @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component instance properties", httpMethod = "GET", notes = "Returns component instance properties", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance - not found") })
+ public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
+ @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum);
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);
+
+ if (componentInstancePropertiesById.isRight()) {
+ log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId);
+ return buildErrorResponse(componentInstancePropertiesById.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
+ log.debug("getGroupArtifactById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ // US330353
+ @GET
+ @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get component instance capability properties", httpMethod = "GET", notes = "Returns component instance capability properties", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Properties found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") })
+ public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
+ @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceBL = getComponentInstanceBL(context, componentTypeEnum);
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> componentInstancePropertiesById = componentInstanceBL.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId,
+ capabilityType, capabilityName, ownerId, userId);
+
+ if (componentInstancePropertiesById.isRight()) {
+ log.debug("Failed to get properties of component instance ID: {} in {} with ID: {}", componentInstanceUniqueId, containerComponentType, containerComponentId);
+ return buildErrorResponse(componentInstancePropertiesById.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
+ log.debug("getGroupArtifactById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
}
//US 331281
@PUT
- @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/properties")
+ @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update Instance Capabilty Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Resource instance capabilty property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
@ApiResponse(code = 404, message = "Component/Component Instance/Capability - not found") })
public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType, @PathParam("containerComponentId") final String containerComponentId,
- @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName,
- @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, @PathParam("capabilityType") final String capabilityType, @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId,
+ @ApiParam(value = "Instance capabilty property to update", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
ServletContext context = request.getSession().getServletContext();
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("(PUT) Start handle request of {}", url);
@@ -964,208 +937,282 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
}
- @POST
- @Path("/{containerComponentType}/{containerComponentId}/serviceProxy")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Service proxy already exist") })
- public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- try {
-
- ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
- componentInstance.setInvariantName(null);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
- log.debug("Unsupported container component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy");
- log.debug("Create service proxy failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @DELETE
- @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
- @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- Response response = null;
- try {
- log.debug("Start handle request of {}", url);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId);
-
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- }
- return response;
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy");
- log.debug("Delete service proxy failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @POST
- @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- try {
-
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
- Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version");
- log.debug("Update service proxy with new version failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
- /**
- * REST API GET relation by Id
- * Allows to get relation contained in specified component according to received Id
- * @param containerComponentType
- * @param componentId
- * @param relationId
- * @param request
- * @param userId
- * @return Response
- */
- @GET
- @Path("/{containerComponentType}/{componentId}/relationId/{relationId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") })
- public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId,
- @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
- try {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
- if (componentInstanceLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
- }
-
- Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum);
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById");
- log.debug("getRelationById unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
-
- Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
- if (convertStatus.isRight()) {
- return Either.right(convertStatus.right().value());
- }
- ComponentInstance resourceInstanceInfo = convertStatus.left().value();
-
- return Either.left(resourceInstanceInfo);
- }
-
- private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
-
- Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
- if (convertStatus.isRight()) {
- return Either.right(convertStatus.right().value());
- }
-
- return Either.left(Arrays.asList(convertStatus.left().value()));
- }
-
- private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) {
-
- Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class);
- if (convertStatus.isRight()) {
- return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
- }
- RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value();
- return Either.left(requirementCapabilityRelDef);
- }
-
- private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
- try {
- log.trace("convert json to object. json=\n {}", data);
- T t = null;
- t = gson.fromJson(data, clazz);
- if (t == null) {
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("object is null after converting from json");
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
- return Either.left(t);
- } catch (Exception e) {
- // INVALID JSON
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("failed to convert from json", e);
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
- }
+ @POST
+ @Path("/{containerComponentType}/{containerComponentId}/serviceProxy")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Service proxy already exist") })
+ public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ try {
+
+ ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
+ componentInstance.setInvariantName(null);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
+ log.debug("Unsupported container component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy");
+ log.debug("Create service proxy failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
+ @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ Response response = null;
+ try {
+ log.debug("Start handle request of {}", url);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId);
+
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ }
+ return response;
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy");
+ log.debug("Delete service proxy failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ try {
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version");
+ log.debug("Update service proxy with new version failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ /**
+ * REST API GET relation by Id
+ * Allows to get relation contained in specified component according to received Id
+ * @param containerComponentType
+ * @param componentId
+ * @param relationId
+ * @param request
+ * @param userId
+ * @return Response
+ */
+ @GET
+ @Path("/{containerComponentType}/{componentId}/relationId/{relationId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get relation", httpMethod = "GET", notes = "Returns relation metadata according to relationId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "relation found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Relation not found") })
+ public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType, @PathParam("componentId") final String componentId,
+ @PathParam("relationId") final String relationId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ if (componentTypeEnum == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceLogic.getRelationById(componentId, relationId, userId, componentTypeEnum);
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getRelationById");
+ log.debug("getRelationById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
+
+ // Either<ComponentInstance, ActionStatus> convertStatus =
+ // convertJsonToObject(data, ComponentInstance.class);
+ Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+ if (convertStatus.isRight()) {
+ return Either.right(convertStatus.right().value());
+ }
+ ComponentInstance resourceInstanceInfo = convertStatus.left().value();
+
+ return Either.left(resourceInstanceInfo);
+ }
+
+ private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
+
+ Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+ if (convertStatus.isRight()) {
+ return Either.right(convertStatus.right().value());
+ }
+
+ return Either.left(Arrays.asList(convertStatus.left().value()));
+ }
+
+ private Either<List<ComponentInstanceProperty>, ResponseFormat> convertMultipleProperties(String dataList) {
+ if (StringUtils.isEmpty(dataList)) {
+ return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+ if (convertStatus.isRight()) {
+ return Either.right(convertStatus.right().value());
+ }
+ return Either.left(Arrays.asList(convertStatus.left().value()));
+ }
+
+ private Either<List<ComponentInstanceInput>, ResponseFormat> convertMultipleInputs(String dataList) {
+ if (StringUtils.isEmpty(dataList)) {
+ return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ Either<ComponentInstanceInput[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+ if (convertStatus.isRight()) {
+ return Either.right(convertStatus.right().value());
+ }
+ return Either.left(Arrays.asList(convertStatus.left().value()));
+ }
+
+
+ private Either<RequirementCapabilityRelDef, ResponseFormat> convertToRequirementCapabilityRelDef(String data) {
+
+ Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class);
+ if (convertStatus.isRight()) {
+ return Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
+ }
+ RequirementCapabilityRelDef requirementCapabilityRelDef = convertStatus.left().value();
+ return Either.left(requirementCapabilityRelDef);
+ }
+
+ private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
+ try {
+ log.trace("convert json to object. json=\n {}", data);
+ T t;
+ t = gson.fromJson(data, clazz);
+ if (t == null) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("object is null after converting from json");
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+ return Either.left(t);
+ } catch (Exception e) {
+ // INVALID JSON
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json", e);
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+ }
+
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/paths-to-delete")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Check if forwarding path to delete on version change", httpMethod = "GET", notes = "Returns forwarding paths to delete",
+ response = Response.class)
+ public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId,
+ @QueryParam("componentInstanceId") final String oldComponentInstanceId,
+ @QueryParam("newComponentInstanceId") final String newComponentInstanceId,
+ @ApiParam(value = "valid values: resources / services",
+ allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME)
+ @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ if (oldComponentInstanceId == null){
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE));
+ }
+ if (newComponentInstanceId == null){
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE));
+ }
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ ComponentInstance newComponentInstance;
+ if(StringUtils.isNotEmpty(newComponentInstanceId)){
+ newComponentInstance=new ComponentInstance();
+ newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,newComponentInstanceId);
+ }else{
+ log.error("missing component id");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_DATA));
+ }
+ Either<Set<String>,ResponseFormat> actionResponse= componentInstanceLogic.forwardingPathOnVersionChange(
+ containerComponentType,componentId,oldComponentInstanceId,newComponentInstance);
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ ForwardingPaths forwardingPaths=new ForwardingPaths();
+ forwardingPaths.setForwardingPathToDelete(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths);
+
+ }
+
}
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 0c955f4e5a..16fa67e7cf 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
@@ -20,26 +20,13 @@
package org.openecomp.sdc.be.servlets;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -59,345 +46,354 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Component Servlet", description = "Component Servlet")
@Singleton
public class ComponentServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(ComponentServlet.class.getName());
-
- @GET
- @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("componentUuid") final String componentUuid, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- Response response;
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- if (componentTypeEnum != null) {
- ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
- Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId);
- if (eitherConformanceLevel.isRight()) {
- response = buildErrorResponse(eitherConformanceLevel.right().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
- }
- } else {
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- return response;
- }
-
- @GET
- @Path("/{componentType}/{componentId}/requirmentsCapabilities")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
- public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- Response response;
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- if (componentTypeEnum != null) {
- try {
- ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
- Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
- if (eitherRequirementsAndCapabilities.isRight()) {
- response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
- } else {
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value()));
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);
- log.debug("getRequirementAndCapabilities failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- } else {
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- return response;
- }
-
- @GET
- @Path("/{componentType}/latestversion/notabstract")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
- public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
- @QueryParam("componentUids") List<String> componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
-
- log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
-
- Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get all non abstract {}", componentType);
- return buildErrorResponse(actionResponse.right().value());
- }
- Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
- log.debug("getCertifiedNotAbstractComponents failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
-
- }
-
- @POST
- @Path("/{componentType}/latestversion/notabstract")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
- public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
- Response response = null;
-
- try {
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
- List<String> componentUids = data;
- if (log.isDebugEnabled())
- log.debug("Received componentUids size is {}", (componentUids == null ? 0 : componentUids.size()));
-
- Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
-
- if (actionResponse.isRight()) {
- if (log.isDebugEnabled())
- log.debug("failed to get all non abstract {}", componentType);
- return buildErrorResponse(actionResponse.right().value());
-
- }
- Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
- Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
- return responseToReturn;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
- log.debug("getCertifiedNotAbstractComponents failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
-
- }
-
- @GET
- @Path("/{componentType}/latestversion/notabstract/metadata")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
- public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
- try {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
-
- Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
- if (actionResponse.isRight()) {
- log.debug("failed to get all non abstract {}", componentType);
- return buildErrorResponse(actionResponse.right().value());
- }
- Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
- log.debug("getCertifiedNotAbstractComponents failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
-
- }
-
- @GET
- @Path("/{componentType}/{componentId}/componentInstances")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", 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 getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
- @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
- Response response = null;
- try {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
-
- Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText);
- if (actionResponse.isRight()) {
- log.debug("failed to get all component instances filtered by properties and inputs", componentType);
- return buildErrorResponse(actionResponse.right().value());
- }
- Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);
- log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
-
-
- /**
- * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.
- * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.
- *
- * @param componentType
- * @param componentId
- * @param dataParamsToReturn
- * @param request
- * @param userId
- * @return
- */
-
- @GET
- @Path("/{componentType}/{componentId}/filteredDataByParams")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
- public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}" , userId);
-
- Response response = null;
-
- try {
- String resourceIdLower = componentId.toLowerCase();
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
-
- log.trace("get component with id {} filtered by ui params", componentId);
- Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get component data filtered by ui params");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");
- log.debug("get resource failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
-
- @GET
- @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
- public Response getFilteredComponentInstanceProperties(
- @PathParam("componentType") final String componentType,
- @PathParam("componentId") final String componentId,
- @PathParam("propertyNameFragment") final String propertyNameFragment,
- @QueryParam("resourceType") List<String> resourceTypes,
- @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- User user = new User();
- user.setUserId(userId);
- log.debug("User Id is {}" , userId);
- Response response = null;
- try {
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
- Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class);
- List<String> propertyNameFragments = new ArrayList<>();
- propertyNameFragments.add(propertyNameFragment);
- filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);
- if(CollectionUtils.isNotEmpty(resourceTypes)){
- filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);
- }
- Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");
- log.debug("Getting of filtered component instance properties failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(ComponentServlet.class);
+
+ @GET
+ @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("componentUuid") final String componentUuid, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ Response response;
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ if (componentTypeEnum != null) {
+ ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
+ Either<Boolean, ResponseFormat> eitherConformanceLevel = compBL.validateConformanceLevel(componentUuid, componentTypeEnum, userId);
+ if (eitherConformanceLevel.isRight()) {
+ response = buildErrorResponse(eitherConformanceLevel.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
+ }
+ } else {
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ return response;
+ }
+
+ @GET
+ @Path("/{componentType}/{componentId}/requirmentsCapabilities")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ Response response;
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ if (componentTypeEnum != null) {
+ try {
+ ComponentBusinessLogic compBL = getComponentBL(componentTypeEnum, context);
+ Either<CapReqDef, ResponseFormat> eitherRequirementsAndCapabilities = compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId);
+ if (eitherRequirementsAndCapabilities.isRight()) {
+ response = buildErrorResponse(eitherRequirementsAndCapabilities.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(eitherRequirementsAndCapabilities.left().value()));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);
+ log.debug("getRequirementAndCapabilities failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ } else {
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ return response;
+ }
+
+ @GET
+ @Path("/{componentType}/latestversion/notabstract")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
+ @QueryParam("componentUids") List<String> componentUids, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response = null;
+
+ try {
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+
+ log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
+
+ Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all non abstract {}", componentType);
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
+ log.debug("getCertifiedNotAbstractComponents failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+
+ }
+
+ @POST
+ @Path("/{componentType}/latestversion/notabstract")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "Consumer Object to be created", required = true) List<String> data) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+ Response response = null;
+
+ try {
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+ List<String> componentUids = data;
+ if (log.isDebugEnabled())
+ log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
+
+ Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, componentUids, userId);
+
+ if (actionResponse.isRight()) {
+ if (log.isDebugEnabled())
+ log.debug("failed to get all non abstract {}", componentType);
+ return buildErrorResponse(actionResponse.right().value());
+
+ }
+ Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ Response responseToReturn = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
+
+ return responseToReturn;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
+ log.debug("getCertifiedNotAbstractComponents failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+
+ }
+
+ @GET
+ @Path("/{componentType}/latestversion/notabstract/metadata")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Component uid only", httpMethod = "GET", notes = "Returns componentId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request, @QueryParam("internalComponentType") String internalComponentType,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid list", required = true) String data) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response = null;
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+
+ Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all non abstract {}", componentType);
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract" + componentType);
+ log.debug("getCertifiedNotAbstractComponents failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+
+ }
+
+ @GET
+ @Path("/{componentType}/{componentId}/componentInstances")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get Component instances", httpMethod = "GET", notes = "Returns component instances", 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 getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+ @QueryParam("searchText") String searchText, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "uid" + " " + "list", required = true) String data) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+ Response response = null;
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+
+ Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, componentTypeEnum, userId, searchText);
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all component instances filtered by properties and inputs", componentType);
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);
+ log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+
+
+ /**
+ * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.
+ * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.
+ *
+ * @param componentType
+ * @param componentId
+ * @param dataParamsToReturn
+ * @param request
+ * @param userId
+ * @return
+ */
+
+ @GET
+ @Path("/{componentType}/{componentId}/filteredDataByParams")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
+ public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+
+ Response response;
+
+ try {
+ String resourceIdLower = componentId.toLowerCase();
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+
+ log.trace("get component with id {} filtered by ui params", componentId);
+ Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get component data filtered by ui params");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");
+ log.debug("get resource failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+
+ @GET
+ @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", httpMethod = "GET", notes = "Returns properties belonging to component instances of specific component by name and optionally resource type", response = Map.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
+ public Response getFilteredComponentInstanceProperties(
+ @PathParam("componentType") final String componentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("propertyNameFragment") final String propertyNameFragment,
+ @QueryParam("resourceType") List<String> resourceTypes,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ User user = new User();
+ user.setUserId(userId);
+ log.debug("User Id is {}" , userId);
+ Response response;
+ try {
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentBusinessLogic businessLogic = getComponentBL(componentTypeEnum, context);
+ Map<FilterKeyEnum, List<String>> filters = new EnumMap<>(FilterKeyEnum.class);
+ List<String> propertyNameFragments = new ArrayList<>();
+ propertyNameFragments.add(propertyNameFragment);
+ filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);
+ if(CollectionUtils.isNotEmpty(resourceTypes)){
+ filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);
+ }
+ Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");
+ log.debug("Getting of filtered component instance properties failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java
index 164b1d7665..f8aa39c478 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java
@@ -20,18 +20,7 @@
package org.openecomp.sdc.be.servlets;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-
+import com.jcabi.aspects.Loggable;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.Constants;
@@ -39,7 +28,11 @@ import org.openecomp.sdc.common.servlets.BasicServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "/" path)
@@ -48,78 +41,78 @@ import com.jcabi.aspects.Loggable;
@Path("/configmgr")
public class ConfigMgrServlet extends BasicServlet {
- private static Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(ConfigMgrServlet.class);
- @GET
- @Path("/get")
- @Produces(MediaType.APPLICATION_JSON)
- public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) {
+ @GET
+ @Path("/get")
+ @Produces(MediaType.APPLICATION_JSON)
+ public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) {
- String result = null;
+ String result = null;
- ServletContext context = request.getSession().getServletContext();
+ ServletContext context = request.getSession().getServletContext();
- ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR);
+ ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR);
- if (type == null || type.equals("configuration")) {
+ if (type == null || type.equals("configuration")) {
- Configuration configuration = configurationManager.getConfiguration();
- if (configuration == null) {
- log.warn("Configuration of type {} was not found", Configuration.class);
- } else {
- log.info("The value returned from getConfig is {}", configuration);
+ Configuration configuration = configurationManager.getConfiguration();
+ if (configuration == null) {
+ log.warn("Configuration of type {} was not found", Configuration.class);
+ } else {
+ log.info("The value returned from getConfig is {}", configuration);
- result = gson.toJson(configuration);
+ result = gson.toJson(configuration);
- }
- }
+ }
+ }
- return result;
+ return result;
- }
+ }
- @POST
- @Path("/set1")
- @Produces(MediaType.TEXT_PLAIN)
- @Consumes(MediaType.APPLICATION_JSON)
- public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) {
+ @POST
+ @Path("/set1")
+ @Produces(MediaType.TEXT_PLAIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) {
- log.debug("{}", configuration);
+ log.debug("{}", configuration);
- return "ok";
+ return "ok";
- }
+ }
- @POST
- @Path("/set2")
- @Produces(MediaType.TEXT_PLAIN)
- @Consumes(MediaType.APPLICATION_JSON)
- public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) {
+ @POST
+ @Path("/set2")
+ @Produces(MediaType.TEXT_PLAIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) {
- log.debug("{}", configuration);
+ log.debug("{}", configuration);
- }
+ }
- @PUT
- @Path("/setput1")
- @Produces(MediaType.TEXT_PLAIN)
- @Consumes(MediaType.APPLICATION_JSON)
- public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) {
+ @PUT
+ @Path("/setput1")
+ @Produces(MediaType.TEXT_PLAIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) {
- log.debug("{}", configuration);
+ log.debug("{}", configuration);
- return "ok";
+ return "ok";
- }
+ }
- @PUT
- @Path("/setput2")
- @Produces(MediaType.TEXT_PLAIN)
- @Consumes(MediaType.APPLICATION_JSON)
- public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) {
+ @PUT
+ @Path("/setput2")
+ @Produces(MediaType.TEXT_PLAIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) {
- log.debug("{}", configuration);
+ log.debug("{}", configuration);
- }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
index 79202ac94f..a56065fcdf 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.servlets;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-
+import com.jcabi.aspects.Loggable;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.api.Constants;
@@ -35,7 +28,13 @@ import org.openecomp.sdc.common.servlets.BasicServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "/" path)
@@ -44,36 +43,36 @@ import com.jcabi.aspects.Loggable;
@Path("/config")
public class ConfigServlet extends BasicServlet {
- private static Logger log = LoggerFactory.getLogger(ConfigServlet.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(ConfigServlet.class);
- @GET
- @Path("/get")
- @Produces(MediaType.APPLICATION_JSON)
- public String getConfig(@Context final HttpServletRequest request) {
+ @GET
+ @Path("/get")
+ @Produces(MediaType.APPLICATION_JSON)
+ public String getConfig(@Context final HttpServletRequest request) {
- String result = null;
+ String result = null;
- ServletContext context = request.getSession().getServletContext();
+ ServletContext context = request.getSession().getServletContext();
- ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR);
- if (configurationSource != null) {
- Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null);
+ ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR);
+ if (configurationSource != null) {
+ Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null);
- if (configuration == null) {
- log.warn("Configuration of type {} was not found", Configuration.class);
- }
- log.debug("{}", configuration);
- log.info("Info level ENABLED...");
- log.info("The value returned from getConfig is {}", configuration);
+ if (configuration == null) {
+ log.warn("Configuration of type {} was not found", Configuration.class);
+ }
+ log.debug("{}", configuration);
+ log.info("Info level ENABLED...");
+ log.info("The value returned from getConfig is {}", configuration);
- result = gson.toJson(configuration);
+ result = gson.toJson(configuration);
- } else {
- log.warn("Source Configuration object was not initialized in the context.");
- }
+ } else {
+ log.warn("Source Configuration object was not initialized in the context.");
+ }
- return result;
+ return result;
- }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
index 943ed59e87..fda31e5032 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
@@ -20,21 +20,10 @@
package org.openecomp.sdc.be.servlets;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -49,179 +38,173 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/consumers")
@Api(value = "Consumer Servlet", description = "Consumer Servlet")
@Singleton
public class ConsumerServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(ConsumerServlet.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(ConsumerServlet.class);
- @POST
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ONAP consumer credentials", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Consumer credentials", httpMethod = "POST", notes = "Returns created ECOMP consumer credentials", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Consumer credentials created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response createConsumer(@ApiParam(value = "Consumer Object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- ServletContext context = request.getSession().getServletContext();
+ ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
- try {
- ConsumerBusinessLogic businessLogic = getConsumerBL(context);
+ try {
+ ConsumerBusinessLogic businessLogic = getConsumerBL(context);
- Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
+ Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
- if (convertionResponse.isRight()) {
- log.debug("failed to create Consumer");
- return buildErrorResponse(convertionResponse.right().value());
- }
+ if (convertionResponse.isRight()) {
+ log.debug("failed to create Consumer");
+ return buildErrorResponse(convertionResponse.right().value());
+ }
- ConsumerDefinition consumer = convertionResponse.left().value();
+ ConsumerDefinition consumer = convertionResponse.left().value();
- Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);
+ Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);
- if (actionResult.isRight()) {
- log.debug("failed to create Consumer");
- return buildErrorResponse(actionResult.right().value());
- }
+ if (actionResult.isRight()) {
+ log.debug("failed to create Consumer");
+ return buildErrorResponse(actionResult.right().value());
+ }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create consumer");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");
- log.debug("create consumer failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- @GET
- @Path("/{consumerId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
- public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ConsumerBusinessLogic businessLogic = getConsumerBL(context);
-
- Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get consumer");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Consumer");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
- log.debug("get consumer failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @DELETE
- @Path("/{consumerId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
- public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ConsumerBusinessLogic businessLogic = getConsumerBL(context);
-
- Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to delete consumer");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Consumer");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
- log.debug("delete consumer failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- private ConsumerBusinessLogic getConsumerBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- ConsumerBusinessLogic consumerBL = webApplicationContext.getBean(ConsumerBusinessLogic.class);
-
- return consumerBL;
- }
-
- public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) {
- ConsumerDefinition consumer = null;
- Gson gson = new Gson();
- try {
- log.trace("convert json to object. json=\n {}", data);
- consumer = gson.fromJson(data, ConsumerDefinition.class);
- if (consumer == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("object is null after converting from json");
- ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, actionEnum);
- return Either.right(responseFormat);
- }
- } catch (Exception e) {
- // INVALID JSON
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("failed to convert from json {}", data, e);
- ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, actionEnum);
- return Either.right(responseFormat);
- }
- return Either.left(consumer);
- }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");
+ log.debug("create consumer failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ @GET
+ @Path("/{consumerId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Consumer", httpMethod = "GET", notes = "Returns consumer according to ConsumerID", response = ConsumerDefinition.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Consumer found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
+ public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ConsumerBusinessLogic businessLogic = getConsumerBL(context);
+
+ Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get consumer");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
+ log.debug("get consumer failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @DELETE
+ @Path("/{consumerId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Deletes Consumer", httpMethod = "DELETE", notes = "Returns deleted consumer according to ConsumerID", response = ConsumerDefinition.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "Consumer deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Consumer not found") })
+ public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ConsumerBusinessLogic businessLogic = getConsumerBL(context);
+
+ Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to delete consumer");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
+ log.debug("delete consumer failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ private ConsumerBusinessLogic getConsumerBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ ConsumerBusinessLogic consumerBL = webApplicationContext.getBean(ConsumerBusinessLogic.class);
+
+ return consumerBL;
+ }
+
+ public Either<ConsumerDefinition, ResponseFormat> convertJsonToObject(String data, User user, AuditingActionEnum actionEnum) {
+ ConsumerDefinition consumer = null;
+ Gson gson = new Gson();
+ try {
+ log.trace("convert json to object. json=\n {}", data);
+ consumer = gson.fromJson(data, ConsumerDefinition.class);
+ if (consumer == null) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("object is null after converting from json");
+ //TODO call correct audit event method!!! - consumer!!!
+ ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", actionEnum);
+ return Either.right(responseFormat);
+ }
+ } catch (Exception e) {
+ // INVALID JSON
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json {}", data, e);
+ //TODO call correct audit event method!!! - consumer!!!
+ ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", actionEnum);
+ return Either.right(responseFormat);
+ }
+ return Either.left(consumer);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java
index 4f8bffa066..faf02dc5ca 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CsarBuildServlet.java
@@ -20,12 +20,10 @@
package org.openecomp.sdc.be.servlets;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.CharacterCodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-
+import com.jcabi.aspects.Loggable;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@@ -33,122 +31,78 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
-import org.openecomp.sdc.be.resources.data.ESArtifactData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.jcabi.aspects.Loggable;
-//import org.openecomp.sdc.be.builders.tosca.api.TopologyService;
-//import org.openecomp.sdc.be.tosca.parsers.ParserMode;
-
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/services")
public class CsarBuildServlet extends ToscaDaoServlet {
- private static Logger log = LoggerFactory.getLogger(CsarBuildServlet.class.getName());
-
- @GET
- @Path("/{serviceName}/{serviceVersion}")
- public Response getDefaultTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) {
-
- return null;// buildToscaCsar(request, serviceName, serviceVersion);
-
- }
-
- @GET
- @Path("/{serviceName}/{serviceVersion}/csar")
- public Response getToscaCsarTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) {
-
- return null; // buildToscaCsar(request, serviceName, serviceVersion);
-
- }
-
- /*
- * private Response buildToscaCsar(final HttpServletRequest request, String serviceName, String serviceVersion) { log.debug("Building CSAR for service:{} , version:{}", serviceName, serviceVersion); ServletContext context =
- * request.getSession().getServletContext(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); String fileName =
- * serviceName+"_"+serviceVersion+".zip";
- *
- * IResourceUploader resourceUploader = getResourceUploader(context); TopologyService topologyService = getToscaYamlBuilder(context).getServiceYaml(serviceName, serviceVersion, ParserMode.CSAR, "Scripts"); try {
- *
- *
- * //Add Service yml to Zip addZipEntry(zipOutputStream, "Definitions/"+serviceName+".yaml", topologyService.getTopologyServiceYaml());
- *
- * //Add Resources to Zip addResourcesToZip(zipOutputStream, topologyService);
- *
- * //Add Artifacts to Zip addArtifactsToZip(serviceName, serviceVersion, zipOutputStream, resourceUploader);
- *
- * //Prepare Tosca metadata addToscaMetaToZip(zipOutputStream, topologyService, resourceUploader);
- *
- * }
- *
- * catch (IOException e) { log.error("Failed to create CSAR file", e); return null; } finally{ try { byteArrayOutputStream.close(); zipOutputStream.close(); } catch (IOException e) { log.error("Failed to close output srream", e); }
- *
- * } return buildResponse(fileName, byteArrayOutputStream);
- *
- *
- * }
- */
-
- public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
-
- protected String[] prepareToscaMetaHeader(String serviceName) {
- return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n",
- "Content-Type: application/vnd.oasis.tosca.definitions.yaml\n" };
- }
-
- protected String getAppliactionMime(String fileName) {
- String mimeType;
- if (fileName.contains(".sh")) {
- mimeType = "x-sh";
- } else if (fileName.contains(".yang")) {
- mimeType = "yang";
- }
-
- else if (fileName.contains(".rar")) {
- mimeType = "x-rar-compressed";
- }
-
- else if (fileName.contains(".zip")) {
- mimeType = "zip";
- }
-
- else if (fileName.contains(".tar")) {
- mimeType = "x-tar";
- }
-
- else if (fileName.contains(".7z")) {
- mimeType = "x-7z-compressed";
- }
-
- else {
- // Undefined
- mimeType = "undefined";
- }
- return mimeType;
- }
-
- protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) {
- // return "Scripts/"+nodeTamplateName+"/"+
- // artifactData.getArtifactName();
- return "Scripts/" + nodeTamplateName + "/" + artifactData.getId();
- }
-
- protected String getResourcePath(String resourceName) {
- return "Definitions/" + resourceName + ".yaml";
- }
-
- private byte[] encodeString(String data) throws CharacterCodingException {
- Charset charset = Charset.forName("UTF-8");
- CharsetEncoder encoder = charset.newEncoder();
- ByteBuffer bb = encoder.encode(CharBuffer.wrap(data.toCharArray()));
- byte[] ba = new byte[bb.limit()];
- bb.get(ba);
- return ba;
- }
-
- @Override
- public Logger getLogger() {
- return log;
- }
+ private static final Logger log = LoggerFactory.getLogger(CsarBuildServlet.class);
+
+ @GET
+ @Path("/{serviceName}/{serviceVersion}")
+ public Response getDefaultTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) {
+
+ return null;// buildToscaCsar(request, serviceName, serviceVersion);
+
+ }
+
+ @GET
+ @Path("/{serviceName}/{serviceVersion}/csar")
+ public Response getToscaCsarTemplate(@Context final HttpServletRequest request, @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion) {
+
+ return null; // buildToscaCsar(request, serviceName, serviceVersion);
+
+ }
+
+
+ public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
+
+ protected String[] prepareToscaMetaHeader(String serviceName) {
+ return new String[] { "TOSCA-Meta-File-Version: 1.0\n", "CSAR-Version: 1.1\n", "Created-By: INTERWISE\n", "\n", "Entry-Definitions: Definitions/" + serviceName + ".yaml\n", "\n", "Name: Definitions/" + serviceName + ".yaml\n",
+ "Content-Type: application/vnd.oasis.tosca.definitions.yaml\n" };
+ }
+
+ protected String getAppliactionMime(String fileName) {
+ String mimeType;
+ if (fileName.contains(".sh")) {
+ mimeType = "x-sh";
+ } else if (fileName.contains(".yang")) {
+ mimeType = "yang";
+ }
+
+ else if (fileName.contains(".rar")) {
+ mimeType = "x-rar-compressed";
+ }
+
+ else if (fileName.contains(".zip")) {
+ mimeType = "zip";
+ }
+
+ else if (fileName.contains(".tar")) {
+ mimeType = "x-tar";
+ }
+
+ else if (fileName.contains(".7z")) {
+ mimeType = "x-7z-compressed";
+ }
+
+ else {
+ // Undefined
+ mimeType = "undefined";
+ }
+ return mimeType;
+ }
+
+ protected String getArtifactPath(String nodeTamplateName, ESArtifactData artifactData) {
+ return "Scripts/" + nodeTamplateName + "/" + artifactData.getId();
+ }
+
+ protected String getResourcePath(String resourceName) {
+ return "Definitions/" + resourceName + ".yaml";
+ }
+
+ @Override
+ public Logger getLogger() {
+ return log;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java
new file mode 100644
index 0000000000..40de94bd6a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DefaultExceptionMapper.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.be.servlets;
+
+import org.eclipse.jetty.http.HttpStatus;
+import org.springframework.stereotype.Component;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+@Component
+@Provider
+public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
+
+ @Override
+ public Response toResponse(Exception exception) {
+ return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500)
+ .entity(exception.getMessage())
+ .build();
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java
index 4215560020..dca41210cc 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java
@@ -20,20 +20,12 @@
package org.openecomp.sdc.be.servlets;
-import javax.annotation.Resource;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -47,14 +39,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.annotation.Resource;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
/**
* Root resource (exposed at "/" path)
*/
@@ -63,107 +55,105 @@ import io.swagger.annotations.ApiResponses;
@Api(value = "Distribution Service Servlet", description = "Distribution Service Servlet")
@Singleton
public class DistributionServiceServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(DistributionServiceServlet.class.getName());
-
- @Resource
- private DistributionMonitoringBusinessLogic distributionMonitoringLogic;
-
- @GET
- @Path("/services/{serviceUUID}/distribution")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list bases on the information extracted from Auditing Records according to service uuid", response = DistributionStatusListResponse.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
- public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- init(request);
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- Response response = null;
- ResponseFormat responseFormat = null;
-
- try {
- Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId);
-
- if (actionResponse.isRight()) {
-
- responseFormat = actionResponse.right().value();
- response = buildErrorResponse(responseFormat);
- } else {
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- response = buildOkResponse(responseFormat, actionResponse.left().value());
-
- }
-
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Distribution list for Service");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service");
- log.debug("failed to get service distribution statuses", e);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-
- response = buildErrorResponse(responseFormat);
- return response;
- }
-
- }
-
- @GET
- @Path("/services/distribution/{did}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return the list of distribution status objects", response = DistributionStatusListResponse.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") })
- public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- init(request);
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- Response response = null;
- ResponseFormat responseFormat = null;
-
- try {
- Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId);
-
- if (actionResponse.isRight()) {
-
- responseFormat = actionResponse.right().value();
- log.debug("failed to fount statuses for did {} {}", did, responseFormat);
- response = buildErrorResponse(responseFormat);
- } else {
-
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value());
- response = buildOkResponse(responseFormat, actionResponse.left().value());
-
- }
-
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Distribution Status");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status");
- log.debug("failed to get distribution status ", e);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-
- response = buildErrorResponse(responseFormat);
- return response;
- }
-
- }
-
- private void init(HttpServletRequest request) {
- if (distributionMonitoringLogic == null) {
- distributionMonitoringLogic = getDistributionBL(request.getSession().getServletContext());
- }
- }
-
- private DistributionMonitoringBusinessLogic getDistributionBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- DistributionMonitoringBusinessLogic distributionBl = webApplicationContext.getBean(DistributionMonitoringBusinessLogic.class);
- return distributionBl;
- }
+ private static final Logger log = LoggerFactory.getLogger(DistributionServiceServlet.class);
+
+ @Resource
+ private DistributionMonitoringBusinessLogic distributionMonitoringLogic;
+
+ @GET
+ @Path("/services/{serviceUUID}/distribution")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Returns list bases on the information extracted from Auditing Records according to service uuid", response = DistributionStatusListResponse.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
+ public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ init(request);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ Response response = null;
+ ResponseFormat responseFormat = null;
+
+ try {
+ Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId);
+
+ if (actionResponse.isRight()) {
+
+ responseFormat = actionResponse.right().value();
+ response = buildErrorResponse(responseFormat);
+ } else {
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ response = buildOkResponse(responseFormat, actionResponse.left().value());
+
+ }
+
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service");
+ log.debug("failed to get service distribution statuses", e);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+
+ response = buildErrorResponse(responseFormat);
+ return response;
+ }
+
+ }
+
+ @GET
+ @Path("/services/distribution/{did}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Distributions", httpMethod = "GET", notes = "Return the list of distribution status objects", response = DistributionStatusListResponse.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Status not found") })
+ public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ init(request);
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ Response response = null;
+ ResponseFormat responseFormat = null;
+
+ try {
+ Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId);
+
+ if (actionResponse.isRight()) {
+
+ responseFormat = actionResponse.right().value();
+ log.debug("failed to fount statuses for did {} {}", did, responseFormat);
+ response = buildErrorResponse(responseFormat);
+ } else {
+
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ log.debug("success to fount statuses for did {} {}", did, actionResponse.left().value());
+ response = buildOkResponse(responseFormat, actionResponse.left().value());
+
+ }
+
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution Status");
+ log.debug("failed to get distribution status ", e);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+
+ response = buildErrorResponse(responseFormat);
+ return response;
+ }
+
+ }
+
+ private void init(HttpServletRequest request) {
+ if (distributionMonitoringLogic == null) {
+ distributionMonitoringLogic = getDistributionBL(request.getSession().getServletContext());
+ }
+ }
+
+ private DistributionMonitoringBusinessLogic getDistributionBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ DistributionMonitoringBusinessLogic distributionBl = webApplicationContext.getBean(DistributionMonitoringBusinessLogic.class);
+ return distributionBl;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
index 7a42360355..1a6fb20b46 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
@@ -20,29 +20,11 @@
package org.openecomp.sdc.be.servlets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
+import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -50,12 +32,9 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.info.ArtifactTypesInfo;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Category;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.PropertyScope;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.Tag;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
@@ -67,14 +46,17 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Path("/v1/")
@@ -89,554 +71,536 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class ElementServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(ElementServlet.class.getName());
-
- /*
- ******************************************************************************
- * NEW CATEGORIES category / \ subcategory subcategory / grouping
- ******************************************************************************/
-
- /*
- *
- *
- * CATEGORIES
- */
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all component categories
- @GET
- @Path("/categories/{componentType}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"),
- @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<List<CategoryDefinition>, ResponseFormat> either = elementBL.getAllCategories(componentType, userId);
- if (either.isRight()) {
- log.debug("No categories were found for type {}", componentType);
- return buildErrorResponse(either.right().value());
- } else {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Categories");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories");
- log.debug("getComponentCategories failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/categories")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"),
- @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<UiCategories, ResponseFormat> either = elementBL.getAllCategories(userId);
- if (either.isRight()) {
- log.debug("No categories were found");
- return buildErrorResponse(either.right().value());
- } else {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Categories");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories");
- log.debug("getAllCategories failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
-
- @POST
- @Path("/category/{componentType}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category")
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
- @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") })
- public Response createComponentCategory(
- @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
- @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class);
-
- Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.createCategory(category, componentType, userId);
- if (createResourceCategory.isRight()) {
- return buildErrorResponse(createResourceCategory.right().value());
- }
-
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
- return buildOkResponse(responseFormat, createResourceCategory.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create resource category");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
- log.debug("createResourceCategory failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @DELETE
- @Path("/category/{componentType}/{categoryUniqueId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
- @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
- public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId);
-
- if (createResourceCategory.isRight()) {
- return buildErrorResponse(createResourceCategory.right().value());
- }
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
- return buildOkResponse(responseFormat, null);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create resource category");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
- log.debug("createResourceCategory failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- /*
- *
- *
- * SUBCATEGORIES
- *
- */
-
- @POST
- @Path("/category/{componentType}/{categoryId}/subCategory")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category")
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
- @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") })
- public Response createComponentSubCategory(
- @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
- @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class);
-
- Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId);
- if (createSubcategory.isRight()) {
- return buildErrorResponse(createSubcategory.right().value());
- }
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
- return buildOkResponse(responseFormat, createSubcategory.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create sub-category");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category");
- log.debug("createComponentSubCategory failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @DELETE
- @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
- @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
- public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,
- @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL.deleteSubCategory(categoryUniqueId, subCategoryUniqueId, componentType, userId);
- if (deleteSubResourceCategory.isRight()) {
- return buildErrorResponse(deleteSubResourceCategory.right().value());
- }
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
- return buildOkResponse(responseFormat, null);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete component category");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category");
- log.debug("deleteComponentSubCategory failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- /*
- * GROUPINGS
- */
- @POST
- @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category")
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
- @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"),
- @ApiResponse(code = 500, message = "General Error") })
- public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
- @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,
- @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class);
-
- Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId);
- if (createGrouping.isRight()) {
- return buildErrorResponse(createGrouping.right().value());
- }
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
- return buildOkResponse(responseFormat, createGrouping.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create grouping");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping");
- log.debug("createComponentGrouping failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @DELETE
- @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
- @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
- public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,
- @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBL.deleteGrouping(grandParentCategoryUniqueId, parentSubCategoryUniqueId, groupingUniqueId, componentType, userId);
- if (deleteGrouping.isRight()) {
- return buildErrorResponse(deleteGrouping.right().value());
- }
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
- return buildOkResponse(responseFormat, null);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete component grouping");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping");
- log.debug("deleteGrouping failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all tags
- @GET
- @Path("/tags")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(getTags) Start handle request of {}", url);
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<List<Tag>, ActionStatus> either = elementBL.getAllTags(userId);
- if (either.isRight() || either.left().value() == null) {
- log.debug("No tags were found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Tags");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags");
- log.debug("getAllTags failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all property scopes
- @GET
- @Path("/propertyScopes")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(getPropertyScopes) Start handle request of {}", url);
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<List<PropertyScope>, ActionStatus> either = elementBL.getAllPropertyScopes(userId);
- if (either.isRight() || either.left().value() == null) {
- log.debug("No property scopes were found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Property Scopes Categories");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories");
- log.debug("getPropertyScopes failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all artifact types
- @GET
- @Path("/artifactTypes")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<List<ArtifactType>, ActionStatus> either = elementBL.getAllArtifactTypes(userId);
- if (either.isRight() || either.left().value() == null) {
- log.debug("No artifact types were found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else {
-
- Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
- ArtifactTypesInfo typesResponse = new ArtifactTypesInfo();
- typesResponse.setArtifactTypes(either.left().value());
- typesResponse.setHeatDefaultTimeout(defaultHeatTimeout);
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse);
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Artifact Types");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
- log.debug("getArtifactTypes failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all artifact types
- @GET
- @Path("/configuration/ui")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(getConfiguration) Start handle request of {}", url);
-
- try {
- ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
- Either<List<ArtifactType>, ActionStatus> otherEither = elementBL.getAllArtifactTypes(userId);
- Either<Integer, ActionStatus> defaultHeatTimeout = elementBL.getDefaultHeatTimeout();
- Either<Map<String, Object>, ActionStatus> deploymentEither = elementBL.getAllDeploymentArtifactTypes();
- Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap();
-
- if (otherEither.isRight() || otherEither.left().value() == null) {
- log.debug("No other artifact types were found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) {
- log.debug("No deployment artifact types were found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) {
- log.debug("heat default timeout was not found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) {
- log.debug("No resource types were found");
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
- } else {
- Map<String, Object> artifacts = new HashMap<String, Object>();
- Map<String, Object> configuration = new HashMap<String, Object>();
-
- artifacts.put("other", otherEither.left().value());
- artifacts.put("deployment", deploymentEither.left().value());
- configuration.put("artifacts", artifacts);
- configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value());
- configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames());
- configuration.put("roles", elementBL.getAllSupportedRoles());
- configuration.put("resourceTypes", resourceTypesMap.left().value());
- configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration);
- }
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Artifact Types");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
- log.debug("getArtifactTypes failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all followed resources and services
- @GET
- @Path("/followed")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"),
- @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- Response res = null;
- User userData = null;
- try {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
-
- // Getting the user
- Either<User, ActionStatus> either = userAdminManager.getUser(userId, false);
- if (either.isRight()) {
- // Couldn't find or otherwise fetch the user
- return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
- }
-
- if (either.left().value() != null) {
- userData = either.left().value();
- Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData);
- // res =
- // buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
- // followedResourcesServices.left().value());
- if (followedResourcesServices.isRight()) {
- log.debug("failed to get followed resources services ");
- return buildErrorResponse(followedResourcesServices.right().value());
- }
- Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value());
- res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
- } else {
- res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Followed Resources / Services Categories");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories");
- log.debug("Getting followed resources/services failed with exception", e);
- res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return res;
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all certified resources and services and their last version
- @GET
- @Path("/screen")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"),
- @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) {
-
- Response res = null;
- try {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- Either<Map<String, List<? extends Component>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes);
-
- if (catalogData.isRight()) {
- log.debug("failed to get catalog data");
- return buildErrorResponse(catalogData.right().value());
- }
- Object data = RepresentationUtils.toRepresentation(catalogData.left().value());
- res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Catalog Components");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components");
- log.debug("Getting catalog components failed with exception", e);
- res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return res;
- }
-
- @DELETE
- @Path("/inactiveComponents/{componentType}")
- public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
- if (nodeType == null) {
- log.info("componentType is not valid: {]", componentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
-
- List<NodeTypeEnum> componentsList = new ArrayList<NodeTypeEnum>();
- componentsList.add(nodeType);
- try {
- ComponentsCleanBusinessLogic businessLogic = getComponentCleanerBL(context);
- Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = businessLogic.cleanComponents(componentsList);
- Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType);
-
- if (cleanResult.isRight()) {
- log.debug("failed to delete marked components of type {}", nodeType);
- response = buildErrorResponse(cleanResult.right().value());
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Marked Components");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components");
- log.debug("delete marked components failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @GET
- @Path("/ecompPortalMenu")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve ONAP portal menu - MOC", httpMethod = "GET", notes = "Retrieve ONAP portal menu", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ONAP portal menu") })
- public Response getListOfCsars(@Context final HttpServletRequest request) {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
- "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");
- }
+ private static final Logger log = LoggerFactory.getLogger(ElementServlet.class);
+
+ /*
+ ******************************************************************************
+ * NEW CATEGORIES category / \ subcategory subcategory / grouping
+ ******************************************************************************/
+
+ /*
+ *
+ *
+ * CATEGORIES
+ */
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all component categories
+ @GET
+ @Path("/categories/{componentType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", httpMethod = "GET", notes = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 400, message = "Invalid component type"),
+ @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getComponentCategories(@ApiParam(value = "allowed values are resources / services/ products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<List<CategoryDefinition>, ResponseFormat> either = elementBL.getAllCategories(componentType, userId);
+ if (either.isRight()) {
+ log.debug("No categories were found for type {}", componentType);
+ return buildErrorResponse(either.right().value());
+ } else {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories");
+ log.debug("getComponentCategories failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/categories")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve the all resource, service and product categories", httpMethod = "GET", notes = "Retrieve the all resource, service and product categories", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns categories Ok"), @ApiResponse(code = 403, message = "Missing information"),
+ @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getAllCategories(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<UiCategories, ResponseFormat> either = elementBL.getAllCategories(userId);
+ if (either.isRight()) {
+ log.debug("No categories were found");
+ return buildErrorResponse(either.right().value());
+ } else {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Categories");
+ log.debug("getAllCategories failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+
+ @POST
+ @Path("/category/{componentType}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create new component category", httpMethod = "POST", notes = "Create new component category")
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Category created"), @ApiResponse(code = 400, message = "Invalid category data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
+ @ApiResponse(code = 409, message = "Category already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") })
+ public Response createComponentCategory(
+ @ApiParam(value = "allowed values are resources /services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
+ @ApiParam(value = "Category to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class);
+
+ Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.createCategory(category, componentType, userId);
+ if (createResourceCategory.isRight()) {
+ return buildErrorResponse(createResourceCategory.right().value());
+ }
+
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
+ return buildOkResponse(responseFormat, createResourceCategory.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
+ log.debug("createResourceCategory failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @DELETE
+ @Path("/category/{componentType}/{categoryUniqueId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
+ @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
+ public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId);
+
+ if (createResourceCategory.isRight()) {
+ return buildErrorResponse(createResourceCategory.right().value());
+ }
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
+ return buildOkResponse(responseFormat, null);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
+ log.debug("createResourceCategory failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ /*
+ *
+ *
+ * SUBCATEGORIES
+ *
+ */
+
+ @POST
+ @Path("/category/{componentType}/{categoryId}/subCategory")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create new component sub-category", httpMethod = "POST", notes = "Create new component sub-category for existing category")
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Subcategory created"), @ApiResponse(code = 400, message = "Invalid subcategory data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
+ @ApiResponse(code = 404, message = "Parent category wasn't found"), @ApiResponse(code = 409, message = "Subcategory already exists / User not permitted to perform the action"), @ApiResponse(code = 500, message = "General Error") })
+ public Response createComponentSubCategory(
+ @ApiParam(value = "allowed values are resources / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
+ @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId, @ApiParam(value = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class);
+
+ Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId);
+ if (createSubcategory.isRight()) {
+ return buildErrorResponse(createSubcategory.right().value());
+ }
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
+ return buildOkResponse(responseFormat, createSubcategory.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category");
+ log.debug("createComponentSubCategory failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @DELETE
+ @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
+ @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
+ public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,
+ @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL.deleteSubCategory(categoryUniqueId, subCategoryUniqueId, componentType, userId);
+ if (deleteSubResourceCategory.isRight()) {
+ return buildErrorResponse(deleteSubResourceCategory.right().value());
+ }
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
+ return buildOkResponse(responseFormat, null);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component category");
+ log.debug("deleteComponentSubCategory failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ /*
+ * GROUPINGS
+ */
+ @POST
+ @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create new component grouping", httpMethod = "POST", notes = "Create new component grouping for existing sub-category")
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Grouping created"), @ApiResponse(code = 400, message = "Invalid grouping data"), @ApiResponse(code = 403, message = "USER_ID header is missing"),
+ @ApiResponse(code = 404, message = "Parent category or subcategory were not found"), @ApiResponse(code = 409, message = "Grouping already exists / User not permitted to perform the action"),
+ @ApiResponse(code = 500, message = "General Error") })
+ public Response createComponentGrouping(@ApiParam(value = "allowed values are products", allowableValues = ComponentTypeEnum.PRODUCT_PARAM_NAME, required = true) @PathParam(value = "componentType") final String componentType,
+ @ApiParam(value = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,
+ @ApiParam(value = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId, @ApiParam(value = "Subcategory to be created", required = true) String data,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class);
+
+ Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId);
+ if (createGrouping.isRight()) {
+ return buildErrorResponse(createGrouping.right().value());
+ }
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
+ return buildOkResponse(responseFormat, createGrouping.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping");
+ log.debug("createComponentGrouping failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @DELETE
+ @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete component category", httpMethod = "DELETE", notes = "Delete component category", response = Category.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "Category deleted"), @ApiResponse(code = 403, message = "USER_ID header is missing"), @ApiResponse(code = 409, message = "User not permitted to perform the action"),
+ @ApiResponse(code = 404, message = "Category not found"), @ApiResponse(code = 500, message = "General Error") })
+ public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId, @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,
+ @PathParam(value = "groupingUniqueId") final String groupingUniqueId, @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBL.deleteGrouping(grandParentCategoryUniqueId, parentSubCategoryUniqueId, groupingUniqueId, componentType, userId);
+ if (deleteGrouping.isRight()) {
+ return buildErrorResponse(deleteGrouping.right().value());
+ }
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
+ return buildOkResponse(responseFormat, null);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping");
+ log.debug("deleteGrouping failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all tags
+ @GET
+ @Path("/tags")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve all tags", httpMethod = "GET", notes = "Retrieve all tags", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns tags Ok"), @ApiResponse(code = 404, message = "No tags were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(getTags) Start handle request of {}", url);
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<List<Tag>, ActionStatus> either = elementBL.getAllTags(userId);
+ if (either.isRight() || either.left().value() == null) {
+ log.debug("No tags were found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags");
+ log.debug("getAllTags failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all property scopes
+ @GET
+ @Path("/propertyScopes")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve all propertyScopes", httpMethod = "GET", notes = "Retrieve all propertyScopes", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns propertyScopes Ok"), @ApiResponse(code = 404, message = "No propertyScopes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(getPropertyScopes) Start handle request of {}", url);
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<List<PropertyScope>, ActionStatus> either = elementBL.getAllPropertyScopes(userId);
+ if (either.isRight() || either.left().value() == null) {
+ log.debug("No property scopes were found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories");
+ log.debug("getPropertyScopes failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all artifact types
+ @GET
+ @Path("/artifactTypes")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<List<ArtifactType>, ActionStatus> either = elementBL.getAllArtifactTypes(userId);
+ if (either.isRight() || either.left().value() == null) {
+ log.debug("No artifact types were found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else {
+
+ Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
+ ArtifactTypesInfo typesResponse = new ArtifactTypesInfo();
+ typesResponse.setArtifactTypes(either.left().value());
+ typesResponse.setHeatDefaultTimeout(defaultHeatTimeout);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse);
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
+ log.debug("getArtifactTypes failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all artifact types
+ @GET
+ @Path("/configuration/ui")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve all artifactTypes", httpMethod = "GET", notes = "Retrieve all artifactTypes", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns artifactTypes Ok"), @ApiResponse(code = 404, message = "No artifactTypes were found"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getConfiguration(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(getConfiguration) Start handle request of {}", url);
+
+ try {
+ ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
+ Either<List<ArtifactType>, ActionStatus> otherEither = elementBL.getAllArtifactTypes(userId);
+ Either<Integer, ActionStatus> defaultHeatTimeout = elementBL.getDefaultHeatTimeout();
+ Either<Map<String, Object>, ActionStatus> deploymentEither = elementBL.getAllDeploymentArtifactTypes();
+ Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap();
+
+ if (otherEither.isRight() || otherEither.left().value() == null) {
+ log.debug("No other artifact types were found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else if (deploymentEither.isRight() || deploymentEither.left().value() == null) {
+ log.debug("No deployment artifact types were found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) {
+ log.debug("heat default timeout was not found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) {
+ log.debug("No resource types were found");
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
+ } else {
+ Map<String, Object> artifacts = new HashMap<String, Object>();
+ Map<String, Object> configuration = new HashMap<String, Object>();
+
+ artifacts.put("other", otherEither.left().value());
+ artifacts.put("deployment", deploymentEither.left().value());
+ configuration.put("artifacts", artifacts);
+ configuration.put("defaultHeatTimeout", defaultHeatTimeout.left().value());
+ configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames());
+ configuration.put("roles", elementBL.getAllSupportedRoles());
+ configuration.put("resourceTypes", resourceTypesMap.left().value());
+ configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), configuration);
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
+ log.debug("getArtifactTypes failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all followed resources and services
+ @GET
+ @Path("/followed")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve all followed", httpMethod = "GET", notes = "Retrieve all followed", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns followed Ok"), @ApiResponse(code = 404, message = "No followed were found"), @ApiResponse(code = 404, message = "User not found"),
+ @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getFollowedResourcesServices(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ Response res = null;
+ User userData = null;
+ try {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
+
+ // Getting the user
+ Either<User, ActionStatus> either = userAdminManager.getUser(userId, false);
+ if (either.isRight()) {
+ // Couldn't find or otherwise fetch the user
+ return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
+ }
+
+ if (either.left().value() != null) {
+ userData = either.left().value();
+ Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData);
+ if (followedResourcesServices.isRight()) {
+ log.debug("failed to get followed resources services ");
+ return buildErrorResponse(followedResourcesServices.right().value());
+ }
+ Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value());
+ res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
+ } else {
+ res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories");
+ log.debug("Getting followed resources/services failed with exception", e);
+ res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return res;
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all certified resources and services and their last version
+ @GET
+ @Path("/screen")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"),
+ @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) {
+
+ Response res = null;
+ try {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId);
+
+ if (catalogData.isRight()) {
+ log.debug("failed to get catalog data");
+ return buildErrorResponse(catalogData.right().value());
+ }
+ Object data = RepresentationUtils.toRepresentation(catalogData.left().value());
+ res = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components");
+ log.debug("Getting catalog components failed with exception", e);
+ res = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return res;
+ }
+
+ @DELETE
+ @Path("/inactiveComponents/{componentType}")
+ public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
+ if (nodeType == null) {
+ log.info("componentType is not valid: {]", componentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+
+ List<NodeTypeEnum> componentsList = new ArrayList<NodeTypeEnum>();
+ componentsList.add(nodeType);
+ try {
+ ComponentsCleanBusinessLogic businessLogic = getComponentCleanerBL(context);
+ Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = businessLogic.cleanComponents(componentsList);
+ Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType);
+
+ if (cleanResult.isRight()) {
+ log.debug("failed to delete marked components of type {}", nodeType);
+ response = buildErrorResponse(cleanResult.right().value());
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value());
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components");
+ log.debug("delete marked components failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/ecompPortalMenu")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve ecomp portal menu - MOC", httpMethod = "GET", notes = "Retrieve ecomp portal menu", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieve ecomp portal menu") })
+ public Response getListOfCsars(@Context final HttpServletRequest request) {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
+ "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
index 22391bbdc1..100fd36e27 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
@@ -20,22 +20,14 @@
package org.openecomp.sdc.be.servlets;
-import java.util.List;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.common.reflect.TypeToken;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -50,199 +42,217 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.reflect.TypeToken;
-import com.google.gson.Gson;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.List;
/**
* Root resource (exposed at "/" path)
*/
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
@Path("/v1/catalog")
-@Api(value = "Resource Group Servlet", description = "Resource Group Servlet")
+@Api(value = "Resource Group Servlet")
@Singleton
public class GroupServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(GroupServlet.class.getName());
-
- private Gson gson = new Gson();
-
- @GET
- @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "group found"),
- @ApiResponse(code = 403, message = "Restricted operation"),
- @ApiResponse(code = 404, message = "Group not found") })
- public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
- @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
-
- try {
-
- GroupBusinessLogic businessLogic = this.getGroupBL(context);
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic
- .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get all non abstract {}", containerComponentType);
- return buildErrorResponse(actionResponse.right().value());
- }
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
- actionResponse.left().value());
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
- log.debug("getGroupArtifactById unexpected exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- @PUT
- @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Group Metadata", httpMethod = "PUT", notes = "Returns updated group definition", response = GroupDefinition.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"),
- @ApiResponse(code = 403, message = "Restricted operation"),
- @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateGroupMetadata(
- @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
- @ApiParam(value = "Service object to be Updated", required = true) String data,
- @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User user = new User();
- user.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- GroupBusinessLogic businessLogic = getGroupBL(context);
-
- Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
- if (convertResponse.isRight()) {
- log.debug("failed to parse group");
- response = buildErrorResponse(convertResponse.right().value());
- return response;
- }
- GroupDefinition updatedGroup = convertResponse.left().value();
-
- // Update GroupDefinition
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic
- .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true);
-
- if (actionResponse.isRight()) {
- log.debug("failed to update GroupDefinition");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- GroupDefinition group = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(group);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
- log.debug("update group metadata failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- /**
- * Updates List of properties on a group (only values)
- * @param containerComponentType
- * @param componentId
- * @param groupUniqueId
- * @param data
- * @param request
- * @param userId
- * @return
- */
- @PUT
- @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"),
- @ApiResponse(code = 403, message = "Restricted operation"),
- @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
- @ApiParam(value = "Service object to be Updated", required = true) String data,
- @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- init(log);
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User user = new User();
- user.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- GroupBusinessLogic businessLogic = getGroupBL(context);
- Either<List<GroupProperty>, ResponseFormat> convertResponse = parseListOfObjects(data,
- new TypeToken<List<GroupProperty>>() {
- }.getType());
-
- if (convertResponse.isRight()) {
- log.debug("failed to parse group Property");
- response = buildErrorResponse(convertResponse.right().value());
- return response;
- }
- List<GroupProperty> groupPropertyToUpdate = convertResponse.left().value();
-
- // Update GroupDefinition
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
- Either<List<GroupProperty>, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties(
- componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false);
-
- if (actionResponse.isRight()) {
- log.debug("failed to update GroupDefinition");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- List<GroupProperty> groupProperty = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(groupProperty);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties");
- log.debug("update group properties failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(GroupServlet.class);
+ public static final String START_HANDLE_REQUEST = "Start handle request of {}";
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/groups/{groupType}")
+ @ApiOperation(value = "Create group ", httpMethod = "POST", notes = "Creates new group in component and returns it", response = GroupDefinition.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 201, message = "Group created"),
+ @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 404, message = "Component not found"),
+ @ApiResponse(code = 500, message = "Internal Error")
+ })
+ public Response createGroup(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("groupType") final String type,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(post) Start handle request of {}", url);
+
+ GroupBusinessLogic businessLogic = getGroupBL(context);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ GroupDefinition groupDefinition = businessLogic
+ .createGroup(type, componentTypeEnum, componentId, userId);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
+ groupDefinition);
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
+ @ApiOperation(value = "Get group artifacts ", httpMethod = "GET", notes = "Returns artifacts metadata according to groupId", response = Resource.class)
+ @ApiResponses(value = {@ApiResponse(code = 200, message = "group found"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 404, message = "Group not found")})
+ public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+
+ try {
+
+ GroupBusinessLogic businessLogic = this.getGroupBL(context);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ Either<GroupDefinitionInfo, ResponseFormat> actionResponse = businessLogic
+ .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all non abstract {}", containerComponentType);
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
+ actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
+ log.debug("getGroupArtifactById unexpected exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}")
+ @ApiOperation(value = "Delete Group", httpMethod = "DELETE", notes = "Returns deleted group id", response = Response.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 201, message = "ResourceInstance deleted"),
+ @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 404, message = "Component not found"),
+ @ApiResponse(code = 500, message = "Internal Error")
+ })
+ public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("groupUniqueId") final String groupId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug(START_HANDLE_REQUEST, url);
+ GroupBusinessLogic businessLogic = this.getGroupBL(context);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ GroupDefinition groupDefinition = businessLogic
+ .deleteGroup(componentTypeEnum, componentId, groupId, userId);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId());
+ }
+
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
+ @ApiOperation(value = "Update Group metadata", httpMethod = "PUT", notes = "Returns updated Group", response = Response.class)
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "Group updated"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "component / group Not found")})
+ public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("groupId") final String groupId,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @ApiParam(value = "GroupDefinition", required = true) GroupDefinition groupData,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+ GroupBusinessLogic businessLogic = this.getGroupBL(context);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ GroupDefinition updatedGroup = businessLogic.updateGroup(componentTypeEnum, componentId, groupId, userId, groupData);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup);
+ }
+
+ /**
+ * Updates List of properties on a group (only values)
+ * @param containerComponentType
+ * @param componentId
+ * @param groupUniqueId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
+ @ApiOperation(value = "Updates List of properties on a group (only values)", httpMethod = "PUT", notes = "Returns updated list of properties", response = GroupDefinition.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Updated"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
+ @ApiParam(value = "Group Properties to be Updated", required = true) String data,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ init(log);
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug(START_HANDLE_REQUEST, url);
+
+ User user = new User();
+ user.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ GroupBusinessLogic businessLogic = getGroupBL(context);
+ Either<List<GroupProperty>, ResponseFormat> convertResponse = parseListOfObjects(data,
+ new TypeToken<List<GroupProperty>>() {
+ }.getType());
+
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse group Property");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+ List<GroupProperty> groupPropertyToUpdate = convertResponse.left().value();
+
+ // Update GroupDefinition
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ Either<List<GroupProperty>, ResponseFormat> actionResponse = businessLogic.validateAndUpdateGroupProperties(
+ componentId, groupUniqueId, user, componentTypeEnum, groupPropertyToUpdate, false);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update GroupDefinition");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ List<GroupProperty> groupProperty = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(groupProperty);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Properties");
+ log.debug("update group properties failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java
new file mode 100644
index 0000000000..a056b1d454
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java
@@ -0,0 +1,55 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.jcabi.aspects.Loggable;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
+import org.openecomp.sdc.be.mixin.GroupTypeMixin;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.view.ResponseView;
+import org.openecomp.sdc.common.api.Constants;
+import org.springframework.stereotype.Controller;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import java.util.List;
+
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
+@Path("/v1/catalog")
+@Api(value = "group types resource")
+@Controller
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class GroupTypesEndpoint {
+
+ private final GroupTypeBusinessLogic groupTypeBusinessLogic;
+
+ public GroupTypesEndpoint(GroupTypeBusinessLogic groupTypeBusinessLogic) {
+ this.groupTypeBusinessLogic = groupTypeBusinessLogic;
+ }
+
+ @GET
+ @Path("/groupTypes")
+ @ApiOperation(value = "Get group types ", httpMethod = "GET", notes = "Returns group types", response = GroupTypeDefinition.class, responseContainer = "List")
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "group types found"),
+ @ApiResponse(code = 400, message = "field name invalid type/length, characters; mandatory field is absent, already exists (name)"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 500, message = "Internal Error")
+ })
+ @ResponseView(mixin = {GroupTypeMixin.class})
+ public List<GroupTypeDefinition> getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed")
+ @QueryParam("internalComponentType") String internalComponentType) {
+ return groupTypeBusinessLogic.getAllGroupTypes(userId, internalComponentType);
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
index 4de5488351..1d627e6fd3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
@@ -20,25 +20,14 @@
package org.openecomp.sdc.be.servlets;
-import java.util.List;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.openecomp.sdc.be.components.impl.InputsBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -58,398 +47,309 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.List;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
-@Path("/v1/catalog")
@Api(value = "Input Catalog", description = "Input Servlet")
+@Path("/v1/catalog")
@Singleton
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
public class InputsServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName());
-
- @GET
- @Path("/services/{componentId}/inputs")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", 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 getComponentInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, @QueryParam("fromId") String fromName,
- @QueryParam("amount") int amount, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
-
- InputsBusinessLogic businessLogic = getInputBL(context);
-
- Either<List<InputDefinition>, ResponseFormat> inputsResponse = businessLogic.getInputs(userId, componentId, fromName, amount);
- if (inputsResponse.isRight()) {
- log.debug("failed to get inputs {}", componentType);
- return buildErrorResponse(inputsResponse.right().value());
- }
- Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
- log.debug("getInputs failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
-
- @POST
- @Path("/{containerComponentType}/{componentId}/update/inputs")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateComponentInputs(
- @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
- @PathParam("componentId") final String componentId,
- @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) {
-
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- String userId = request.getHeader(Constants.USER_ID_HEADER);
-
- try {
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Either<InputDefinition, ResponseFormat> inputEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);;
- if(inputEither.isRight()){
- log.debug("Failed to convert data to input definition. Status is {}", inputEither.right().value());
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- InputDefinition input = inputEither.left().value();
-
- log.debug("Start handle request of updateResourceInstanceProperty. Received property is {}", input);
-
- ServletContext context = request.getSession().getServletContext();
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
-
- InputsBusinessLogic businessLogic = getInputBL(context);
- if (businessLogic == null) {
- log.debug("Unsupported component type {}", containerComponentType);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
- }
-
- Either<InputDefinition, ResponseFormat> actionResponse = businessLogic.updateInputValue(componentType, componentId, input, userId, true, false);
-
- if (actionResponse.isRight()) {
- return buildErrorResponse(actionResponse.right().value());
- }
-
- InputDefinition resourceInstanceProperty = actionResponse.left().value();
- ObjectMapper mapper = new ObjectMapper();
- String result = mapper.writeValueAsString(resourceInstanceProperty);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
-
- @GET
- @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", 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 getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
- @PathParam("originComponentUid") final String originComonentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
-
- Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId);
- if (inputsResponse.isRight()) {
- log.debug("failed to get component instance inputs {}", componentType);
- return buildErrorResponse(inputsResponse.right().value());
- }
- Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Component Instance Inputs" + componentType);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
- log.debug("getInputs failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @GET
- @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", 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 getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
- @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(GET) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
-
- Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
- if (inputPropertiesRes.isRight()) {
- log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
- return buildErrorResponse(inputPropertiesRes.right().value());
- }
- Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get properties by input id {}, for component instance {} ", inputId, instanceId);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
- log.debug("getInputPropertiesForComponentInstance failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @GET
- @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", 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 getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
-
- Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId);
-
- if (inputsRes.isRight()) {
- log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
- return buildErrorResponse(inputsRes.right().value());
- }
- Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
- log.debug("getInputsForComponentInput failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @GET
- @Path("/{componentType}/{componentId}/inputs/{inputId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", 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 getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
-
- Either<InputDefinition, ResponseFormat> inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
-
- if (inputsRes.isRight()) {
- log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
- return buildErrorResponse(inputsRes.right().value());
- }
- Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get inputs by input id {}, for component {} ", inputId, componentId);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
- log.debug("getInputsForComponentInput failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- public Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) {
- return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
- }
-
- @POST
- @Path("/{componentType}/{componentId}/create/inputs")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", 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 createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier);
- if (componentInstInputsMapRes.isRight()) {
- log.debug("failed to parse componentInstInputsMap");
- response = buildErrorResponse(componentInstInputsMapRes.right().value());
- return response;
- }
-
- ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
- ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value();
-
- Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
- if (inputPropertiesRes.isRight()) {
- log.debug("failed to create inputs for service: {}", componentId);
- return buildErrorResponse(inputPropertiesRes.right().value());
- }
- Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create inputs for service with id: {}", componentId);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId);
- log.debug("createMultipleInputs failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
-
-
- @DELETE
- @Path("/{componentType}/{componentId}/delete/{inputId}/input")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
- public Response deleteInput (
- @PathParam("componentType") final String componentType,
- @PathParam("componentId") final String componentId,
- @PathParam("inputId") final String inputId,
+ private static final Logger log = LoggerFactory.getLogger(InputsServlet.class);
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/update/inputs")
+ @ApiOperation(value = "Update resource inputs", httpMethod = "POST", notes = "Returns updated input", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Input updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateComponentInputs(
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("componentId") final String componentId,
+ @ApiParam(value = "json describe the input", required = true) String data, @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ try {
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils()
+ .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class,
+ AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);
+ if(inputsEither.isRight()){
+ log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value());
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value());
+
+ log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate);
+
+ ServletContext context = request.getSession().getServletContext();
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
+
+ InputsBusinessLogic businessLogic = getInputBL(context);
+ if (businessLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
+ }
+
+ Either<List<InputDefinition>, ResponseFormat> actionResponse = businessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+
+ List<InputDefinition> componentInputs = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(componentInputs);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ }
+ catch (Exception e) {
+ log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+
+ @GET
+ @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
+ @ApiOperation(value = "Get Inputs only", httpMethod = "GET", notes = "Returns Inputs list", 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 getComponentInstanceInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
+ @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response;
+
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+
+ Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = businessLogic.getComponentInstanceInputs(userId, componentId, instanceId);
+ if (inputsResponse.isRight()) {
+ log.debug("failed to get component instance inputs {}", componentType);
+ return buildErrorResponse(inputsResponse.right().value());
+ }
+ Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
+ log.debug("getInputs failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")
+ @ApiOperation(value = "Get properties", httpMethod = "GET", notes = "Returns properties list", 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 getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
+ @PathParam("inputId") final String inputId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(GET) Start handle request of {}", url);
+ Response response = null;
+
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+
+ Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = businessLogic.getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
+ if (inputPropertiesRes.isRight()) {
+ log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
+ return buildErrorResponse(inputPropertiesRes.right().value());
+ }
+ Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
+ log.debug("getInputPropertiesForComponentInstance failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")
+ @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", 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 getInputsForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response;
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+
+ Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = businessLogic.getInputsForComponentInput(userId, componentId, inputId);
+
+ if (inputsRes.isRight()) {
+ log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
+ return buildErrorResponse(inputsRes.right().value());
+ }
+ Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
+ log.debug("getInputsForComponentInput failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/{componentType}/{componentId}/inputs/{inputId}")
+ @ApiOperation(value = "Get inputs", httpMethod = "GET", notes = "Returns inputs list", 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 getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response;
+
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+
+ Either<InputDefinition, ResponseFormat> inputsRes = businessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
+
+ if (inputsRes.isRight()) {
+ log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
+ return buildErrorResponse(inputsRes.right().value());
+ }
+ Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
+ log.debug("getInputsForComponentInput failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) {
+ return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+ }
+
+ @POST
+ @Path("/{componentType}/{componentId}/create/inputs")
+ @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", 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 createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response = null;
+
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier);
+ if (componentInstInputsMapRes.isRight()) {
+ log.debug("failed to parse componentInstInputsMap");
+ response = buildErrorResponse(componentInstInputsMapRes.right().value());
+ return response;
+ }
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
+ ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value();
+
+ Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
+ if (inputPropertiesRes.isRight()) {
+ log.debug("failed to create inputs for service: {}", componentId);
+ return buildErrorResponse(inputPropertiesRes.right().value());
+ }
+ Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId);
+ log.debug("createMultipleInputs failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+
+
+ @DELETE
+ @Path("/{componentType}/{componentId}/delete/{inputId}/input")
+ @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
+ public Response deleteInput (
+ @PathParam("componentType") final String componentType,
+ @PathParam("componentId") final String componentId,
+ @PathParam("inputId") final String inputId,
@Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
@ApiParam(value = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
- Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId);
- if (deleteInput.isRight()){
- ResponseFormat deleteResponseFormat = deleteInput.right().value();
- response = buildErrorResponse(deleteResponseFormat);
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
- } catch (Exception e){
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
- log.debug("Delete input failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
-
-
- /*@PUT
- @Path("/{componentType}/{componentId}/edit/{inputId}/input")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Delete input from service", httpMethod = "DELETE", notes = "Delete service input", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Input deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Input not found") })
- public Response editInputValue (
- @PathParam("componentType") final String componentType,
- @PathParam("componentId") final String componentId,
- @PathParam("inputId") final String inputId,
- @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}", url);
- Response response = null;
-
- try {
- InputsBusinessLogic businessLogic = getInputBL(context);
- Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentType, componentId, userId, inputId);
- if (deleteInput.isRight()){
- ResponseFormat deleteResponseFormat = deleteInput.right().value();
- response = buildErrorResponse(deleteResponseFormat);
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
- } catch (Exception e){
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete input for service {} with id: {}", componentId, inputId);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
- log.debug("Delete input failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }*/
-
- protected InputsBusinessLogic getInputBL(ServletContext context) {
-
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- InputsBusinessLogic inputsBusinessLogic = webApplicationContext.getBean(InputsBusinessLogic.class);
- return inputsBusinessLogic;
- }
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}", url);
+ Response response = null;
+
+ try {
+ InputsBusinessLogic businessLogic = getInputBL(context);
+ Either<InputDefinition, ResponseFormat> deleteInput = businessLogic.deleteInput(componentId, userId, inputId);
+ if (deleteInput.isRight()){
+ ResponseFormat deleteResponseFormat = deleteInput.right().value();
+ response = buildErrorResponse(deleteResponseFormat);
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput.left().value());
+ } catch (Exception e){
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
+ log.debug("Delete input failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ private InputsBusinessLogic getInputBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ return webApplicationContext.getBean(InputsBusinessLogic.class);
+ }
}
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 c2d7c2a6a1..5720c56c38 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
@@ -20,20 +20,10 @@
package org.openecomp.sdc.be.servlets;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.codehaus.jackson.map.ObjectMapper;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoBase;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
@@ -52,145 +42,115 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Lifecycle Actions Servlet", description = "Lifecycle Actions Servlet")
@Singleton
public class LifecycleServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(LifecycleServlet.class.getName());
-
- @POST
- @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") })
- public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo,
- @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
- + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection,
- @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
- @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request,
- @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- Response response = null;
-
- // get modifier from graph
- log.debug("get modifier properties");
- Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
- if (eitherGetUser.isRight()) {
- return buildErrorResponse(eitherGetUser.right().value());
- }
- User user = eitherGetUser.left().value();
-
- String resourceIdLower = componentId.toLowerCase();
- log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
- Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
- if (validateEnum.isRight()) {
- return validateEnum.right().value();
- }
-
- LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
-
- try {
- if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
- // Either<LifecycleChangeInfo, ResponseFormat > changeInfoResult
- // =
- // getComponentsUtils().convertJsonToObjectUsingObjectMapper(jsonChangeInfo,
- // user, LifecycleChangeInfo.class,
- // AuditingActionEnum.CHECKOUT_RESOURCE, null);
- ObjectMapper mapper = new ObjectMapper();
- changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
- }
- }
-
- catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "convertJsonToObject");
- BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
- log.debug("failed to convert from json {}", jsonChangeInfo, e);
- ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
- return buildErrorResponse(responseFormat);
- }
-
- try {
- LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
- if (componentType != null) {
- Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
-
- if (actionResponse.isRight()) {
- log.info("failed to change resource state");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- log.debug("change state successful !!!");
- UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
- Object value = RepresentationUtils.toRepresentation(componentMetatdata);
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
- return response;
- } else {
- log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
- ComponentTypeEnum.PRODUCT_PARAM_NAME);
- ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
- return buildErrorResponse(error);
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Change Lifecycle State");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
- log.debug("change lifecycle state failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
- LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
- try {
- transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
- } catch (IllegalArgumentException e) {
- log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
- ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, AuditingActionEnum.CHECKOUT_RESOURCE);
- return Either.right(buildErrorResponse(error));
- }
- return Either.left(transitionEnum);
- }
-
-// private LifecycleBusinessLogic getLifecycleBL(ServletContext context) {
-// WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-// WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-// LifecycleBusinessLogic resourceBl = webApplicationContext.getBean(LifecycleBusinessLogic.class);
-// return resourceBl;
-// }
-//
-// protected Either<User, Response> getUser(final HttpServletRequest request, String userId) {
-//
-// Either<User, ActionStatus> eitherCreator = getUserAdminManager(request.getSession().getServletContext()).getUser(userId, false);
-// if (eitherCreator.isRight()) {
-// log.info("createResource method - user is not listed. userId= {}", userId);
-// ResponseFormat errorResponse = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_INFORMATION);
-// User user = new User("", "", userId, "", null, null);
-//
-// getComponentsUtils().auditResource(errorResponse, user, null, "", "", AuditingActionEnum.CHECKOUT_RESOURCE, null);
-// return Either.right(buildErrorResponse(errorResponse));
-// }
-// return Either.left(eitherCreator.left().value());
-//
-// }
+ private static final Logger log = LoggerFactory.getLogger(LifecycleServlet.class);
+
+ @POST
+ @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource state changed"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 409, message = "Resource already exist") })
+ public Response changeResourceState(@ApiParam(value = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification", required = false) String jsonChangeInfo,
+ @ApiParam(value = "validValues: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam(value = "componentCollection") final String componentCollection,
+ @ApiParam(allowableValues = "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification, cancelCertification, certify", required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
+ @ApiParam(value = "id of component to be changed") @PathParam(value = "componentId") final String componentId, @Context final HttpServletRequest request,
+ @ApiParam(value = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ LifecycleBusinessLogic businessLogic = getLifecycleBL(context);
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ Response response = null;
+
+ // get modifier from graph
+ log.debug("get modifier properties");
+ Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
+ if (eitherGetUser.isRight()) {
+ return buildErrorResponse(eitherGetUser.right().value());
+ }
+ User user = eitherGetUser.left().value();
+
+ String resourceIdLower = componentId.toLowerCase();
+ log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
+ Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
+ if (validateEnum.isRight()) {
+ return validateEnum.right().value();
+ }
+
+ LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
+
+ try {
+ if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
+ ObjectMapper mapper = new ObjectMapper();
+ changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
+ }
+ }
+
+ catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
+ log.debug("failed to convert from json {}", jsonChangeInfo, e);
+ ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
+ return buildErrorResponse(responseFormat);
+ }
+
+ try {
+ LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
+ ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
+ if (componentType != null) {
+ Either<? extends Component, ResponseFormat> actionResponse = businessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
+
+ if (actionResponse.isRight()) {
+ log.info("failed to change resource state");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ log.debug("change state successful !!!");
+ UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
+ Object value = RepresentationUtils.toRepresentation(componentMetatdata);
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
+ return response;
+ } else {
+ log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+ ComponentTypeEnum.PRODUCT_PARAM_NAME);
+ ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
+ return buildErrorResponse(error);
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
+ log.debug("change lifecycle state failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ private Either<LifeCycleTransitionEnum, Response> validateTransitionEnum(final String lifecycleTransition, User user) {
+ LifeCycleTransitionEnum transitionEnum = LifeCycleTransitionEnum.CHECKOUT;
+ try {
+ transitionEnum = LifeCycleTransitionEnum.getFromDisplayName(lifecycleTransition);
+ } catch (IllegalArgumentException e) {
+ log.info("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString(), e);
+ ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, "", AuditingActionEnum.CHECKOUT_RESOURCE);
+ return Either.right(buildErrorResponse(error));
+ }
+ return Either.left(transitionEnum);
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java
new file mode 100644
index 0000000000..b6e15cef9a
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java
@@ -0,0 +1,307 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.jcabi.aspects.Loggable;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.ServletUtils;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Controller;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+
+import org.openecomp.sdc.be.model.PolicyTargetDTO;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+/**
+ * Provides REST API to create, retrieve, update, delete a policy
+ */
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
+@Path("/v1/catalog")
+@Api(value = "Policy Servlet")
+@Controller
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class PolicyServlet extends AbstractValidationsServlet {
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyServlet.class);
+ private final PolicyBusinessLogic policyBusinessLogic;
+
+ public PolicyServlet(PolicyBusinessLogic policyBusinessLogic, ServletUtils servletUtils, ResourceImportManager resourceImportManager, ComponentsUtils componentsUtils) {
+ this.policyBusinessLogic = policyBusinessLogic;
+ this.servletUtils = servletUtils;
+ this.resourceImportManager = resourceImportManager;
+ this.componentsUtils = componentsUtils;
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")
+ @ApiOperation(value = "Create Policy", httpMethod = "POST", notes = "Returns created Policy", response = Response.class)
+ @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Policy already exist"), @ApiResponse(code = 404, message = "Component not found")})
+ public Response createPolicy(@PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("policyTypeName") final String policyTypeName,
+ @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
+ @Context final HttpServletRequest request) {
+ init(log);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ try {
+ Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
+ if (responseWrapper.isEmpty()) {
+ responseWrapper.setInnerElement(policyBusinessLogic.createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName, userId, true)
+ .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l),
+ this::buildErrorResponse));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
+ log.error("Failed to create policy. The exception {} occurred. ", e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ return responseWrapper.getInnerElement();
+ }
+
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
+ @ApiOperation(value = "Update Policy metadata", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
+ @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "component / policy Not found")})
+ public Response updatePolicy(@PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
+ @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
+ init(log);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ try {
+ Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
+ Wrapper<PolicyDefinition> policyWrapper = new Wrapper<>();
+ if (responseWrapper.isEmpty()) {
+ convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper);
+ if (policyWrapper.isEmpty()) {
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
+ }
+ }
+ if (!policyWrapper.isEmpty()) {
+ policyWrapper.getInnerElement().setUniqueId(policyId);
+ responseWrapper.setInnerElement(policyBusinessLogic.updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyWrapper.getInnerElement(), userId, true)
+ .either(this::buildOkResponse,
+ this::buildErrorResponse));
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
+ log.error("Failed to update policy. The exception {} occurred. ", e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ return responseWrapper.getInnerElement();
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
+ @ApiOperation(value = "Get Policy", httpMethod = "GET", notes = "Returns Policy", response = Response.class)
+ @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy was found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "component / policy Not found")})
+ public Response getPolicy(@PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
+ @Context final HttpServletRequest request) {
+ init(log);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ try {
+ Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
+ if (responseWrapper.isEmpty()) {
+ responseWrapper.setInnerElement(policyBusinessLogic.getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId)
+ .either(this::buildOkResponse,
+ this::buildErrorResponse));
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy");
+ log.error("Failed to retrieve policy. The exception {} occurred. ", e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ return responseWrapper.getInnerElement();
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
+ @ApiOperation(value = "Delete Policy", httpMethod = "DELETE", notes = "No body", response = Response.class)
+ @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "component / policy Not found")})
+ public Response deletePolicy(@PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
+ @Context final HttpServletRequest request) {
+ init(log);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ try {
+ Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
+ if (responseWrapper.isEmpty()) {
+ responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
+ .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null),
+ this::buildErrorResponse));
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy");
+ log.error("Failed to delete policy. The exception {} occurred. ", e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ return responseWrapper.getInnerElement();
+ }
+
+ @GET
+ @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
+ @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List")
+ @ApiResponses(value = {@ApiResponse(code = 200, message = "Properties found"),@ApiResponse(code = 400, message = "invalid content - Error: containerComponentType is invalid"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Componentorpolicy not found"),
+ @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.") })public Response getPolicyProperties(@ApiParam(value = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @ApiParam(value = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
+ @ApiParam(value = "the userid", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Context final HttpServletRequest request) {
+ init(log);
+ try {
+ return convertToComponentType(containerComponentType)
+ .left()
+ .bind(cmptType -> policyBusinessLogic.getPolicyProperties(cmptType, containerComponentId, policyId, userId))
+ .either(this::buildOkResponse,
+ this::buildErrorResponse);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties");
+ log.debug("#getPolicyProperties - get Policy properties has failed.", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+
+ }
+
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
+ @ApiOperation(value = "Update Policy properties", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
+ @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy properties updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "component / policy Not found")})
+ public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
+ @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
+ init(log);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ try {
+ Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
+ Wrapper<PropertyDataDefinition[]> propertiesWrapper = new Wrapper<>();
+ if (responseWrapper.isEmpty()) {
+ convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class, responseWrapper);
+ if (propertiesWrapper.isEmpty()) {
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
+ }
+ }
+ if (!propertiesWrapper.isEmpty()) {
+ responseWrapper.setInnerElement(
+ policyBusinessLogic.updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, propertiesWrapper.getInnerElement(), userId, true)
+ .either(this::buildOkResponse, this::buildErrorResponse));
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
+ log.error("Failed to update policy. The exception {} occurred. ", e);
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
+ }
+ return responseWrapper.getInnerElement();
+ }
+
+ private Wrapper<ComponentTypeEnum> validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper<Response> responseWrapper) {
+ Wrapper<ComponentTypeEnum> componentTypeWrapper = new Wrapper<>();
+ if (StringUtils.isEmpty(userId)) {
+ log.error("Missing userId HTTP header. ");
+ responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID)));
+ }
+ if (responseWrapper.isEmpty()) {
+ validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType);
+ }
+ return componentTypeWrapper;
+ }
+
+ @PUT
+ @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "update policy targets", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
+ @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy target updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content")})
+ public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @PathParam("policyId") final String policyId,
+ @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
+ @Context final HttpServletRequest request,
+ List<PolicyTargetDTO> requestJson) {
+ try {
+
+ Map<PolicyTargetType, List<String>> policyTarget = convertTargetDTOToBLTarget(requestJson);
+ if(policyTarget == null){
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, StringUtils.join(requestJson.stream().map(PolicyTargetDTO::getType).collect(Collectors.toList())), ","));
+ }
+
+ return convertToComponentType(containerComponentType)
+ .left()
+ .bind(cmptType -> policyBusinessLogic.updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId))
+ .either(this::buildOkResponse,
+ this::buildErrorResponse);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
+ log.debug("Policy creation has been failed with the exception{}. ", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+
+ private Map<PolicyTargetType, List<String>> convertTargetDTOToBLTarget(List<PolicyTargetDTO> targetDTOList) {
+ Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();
+ for (PolicyTargetDTO currentTarget : targetDTOList) {
+ if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){
+ return null;
+ }
+ }
+ return policyTarget;
+ }
+ public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {
+ PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);
+ if(targetTypeEnum != null){
+ policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));
+ return true;
+ }
+ else{
+ return false;
+ }
+ }
+
+ private List<String> validateUniquenessOfIds(List<String> uniqueIds) {
+ return uniqueIds.stream().distinct().collect(Collectors.toList());
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java
new file mode 100644
index 0000000000..aa4bfa87c7
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java
@@ -0,0 +1,64 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.jcabi.aspects.Loggable;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
+import org.openecomp.sdc.be.mixin.PolicyTypeMixin;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.view.ResponseView;
+import org.openecomp.sdc.common.api.Constants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Controller;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
+@Path("/v1/catalog")
+@Api(value = "policy types resource")
+@Controller
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class PolicyTypesEndpoint extends BeGenericServlet{
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyTypesEndpoint.class);
+
+ private final PolicyTypeBusinessLogic policyTypeBusinessLogic;
+
+ public PolicyTypesEndpoint(PolicyTypeBusinessLogic policyTypeBusinessLogic) {
+ this.policyTypeBusinessLogic = policyTypeBusinessLogic;
+ }
+
+ @GET
+ @Path("/policyTypes")
+ @ApiOperation(value = "Get policy types ", httpMethod = "GET", notes = "Returns policy types", response = PolicyTypeDefinition.class, responseContainer="List")
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "policy types found"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.")})
+ @ResponseView(mixin = {PolicyTypeMixin.class})
+ public Response getPolicyTypes(@ApiParam(value = "An optional parameter to indicate the type of the container from where this call is executed")
+ @QueryParam("internalComponentType") String internalComponentType,
+ @ApiParam(value = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ log.debug("(get) Start handle request of GET policyTypes");
+ try {
+ return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType)
+ .either(this::buildOkResponse,
+ this::buildErrorResponse);
+ } catch (Exception e) {
+ log.error("#getPolicyTypes - Exception occurred during get policy types", e);
+ return buildGeneralErrorResponse();
+ }
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java
index c0c987b78a..05ece30535 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ProductServlet.java
@@ -20,24 +20,9 @@
package org.openecomp.sdc.be.servlets;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -49,262 +34,256 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Map;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Product Catalog", description = "Product Servlet")
@Singleton
public class ProductServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(ProductServlet.class.getName());
-
- @POST
- @Path("/products")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"),
- @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") })
- public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ProductBusinessLogic businessLogic = getProductBL(context);
- Product product = RepresentationUtils.fromRepresentation(data, Product.class);
- Either<Product, ResponseFormat> actionResponse = businessLogic.createProduct(product, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("Failed to create product");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Product");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product");
- log.debug("create product failed with error ", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @GET
- @Path("/products/{productId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"),
- @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), })
- public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- ProductBusinessLogic businessLogic = getProductBL(context);
- log.trace("get product with id {}", productId);
- Either<Product, ResponseFormat> actionResponse = businessLogic.getProduct(productId, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("Failed to get product");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Product");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product");
- log.debug("get product failed with error ", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @GET
- @Path("/products/productName/{productName}/productVersion/{productVersion}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") })
- public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ProductBusinessLogic businessLogic = getProductBL(context);
- Either<Product, ResponseFormat> actionResponse = businessLogic.getProductByNameAndVersion(productName, productVersion, userId);
-
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Product product = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(product);
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get product by name and version");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version");
- log.debug("get product failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @DELETE
- @Path("/products/{productId}")
- public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- ProductBusinessLogic businessLogic = getProductBL(context);
- log.trace("delete product with id {}", productId);
- Either<Product, ResponseFormat> actionResponse = businessLogic.deleteProduct(productId, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("Failed to delete product");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
- log.debug("delete resource failed with error ", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @PUT
- @Path("/products/{productId}/metadata")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
- Response response = null;
-
- try {
- String productIdLower = productId.toLowerCase();
- ProductBusinessLogic businessLogic = getProductBL(context);
- Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class);
- Either<Product, ResponseFormat> actionResponse = businessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to update product");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Product product = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(product);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Product Metadata");
- log.debug("update product metadata failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @GET
- @Path("/products/validate-name/{productName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
- public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
- Response response = null;
- try {
- ProductBusinessLogic businessLogic = getProductBL(context);
-
- Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateProductNameExists(productName, userId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get validate service name");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Service Name");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name");
- log.debug("validate product name failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(ProductServlet.class);
+
+ @POST
+ @Path("/products")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create product", httpMethod = "POST", notes = "Returns created product", response = Product.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Product created"), @ApiResponse(code = 403, message = "Restricted operation / Empty USER_ID header"), @ApiResponse(code = 400, message = "Invalid/missing content"),
+ @ApiResponse(code = 409, message = "Product already exists / User not found / Wrong user role") })
+ public Response createProduct(@ApiParam(value = "Product object to be created", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of product strategist user", required = true) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ProductBusinessLogic businessLogic = getProductBL(context);
+ Product product = RepresentationUtils.fromRepresentation(data, Product.class);
+ Either<Product, ResponseFormat> actionResponse = businessLogic.createProduct(product, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("Failed to create product");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Product");
+ log.debug("create product failed with error ", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @GET
+ @Path("/products/{productId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve product", httpMethod = "GET", notes = "Returns product according to productId", response = Product.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Missing information"), @ApiResponse(code = 409, message = "Restricted operation"),
+ @ApiResponse(code = 500, message = "Internal Server Error"), @ApiResponse(code = 404, message = "Product not found"), })
+ public Response getProductById(@PathParam("productId") final String productId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ ProductBusinessLogic businessLogic = getProductBL(context);
+ log.trace("get product with id {}", productId);
+ Either<Product, ResponseFormat> actionResponse = businessLogic.getProduct(productId, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("Failed to get product");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Product");
+ log.debug("get product failed with error ", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @GET
+ @Path("/products/productName/{productName}/productVersion/{productVersion}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns product according to name and version", response = Product.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Product found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Product not found") })
+ public Response getServiceByNameAndVersion(@PathParam("productName") final String productName, @PathParam("productVersion") final String productVersion, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ProductBusinessLogic businessLogic = getProductBL(context);
+ Either<Product, ResponseFormat> actionResponse = businessLogic.getProductByNameAndVersion(productName, productVersion, userId);
+
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Product product = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(product);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get product by name and version");
+ log.debug("get product failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @DELETE
+ @Path("/products/{productId}")
+ public Response deleteProduct(@PathParam("productId") final String productId, @Context final HttpServletRequest request) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ ProductBusinessLogic businessLogic = getProductBL(context);
+ log.trace("delete product with id {}", productId);
+ Either<Product, ResponseFormat> actionResponse = businessLogic.deleteProduct(productId, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("Failed to delete product");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Object product = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), product);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
+ log.debug("delete resource failed with error ", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @PUT
+ @Path("/products/{productId}/metadata")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Product Metadata", httpMethod = "PUT", notes = "Returns updated product", response = Product.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Product Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateProductMetadata(@PathParam("productId") final String productId, @ApiParam(value = "Product object to be Updated", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+ Response response = null;
+
+ try {
+ String productIdLower = productId.toLowerCase();
+ ProductBusinessLogic businessLogic = getProductBL(context);
+ Product updatedProduct = RepresentationUtils.fromRepresentation(data, Product.class);
+ Either<Product, ResponseFormat> actionResponse = businessLogic.updateProductMetadata(productIdLower, updatedProduct, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update product");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Product product = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(product);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ log.debug("update product metadata failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @GET
+ @Path("/products/validate-name/{productName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "validate product name", httpMethod = "GET", notes = "checks if the chosen product name is available ", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
+ public Response validateServiceName(@PathParam("productName") final String productName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+ Response response = null;
+ try {
+ ProductBusinessLogic businessLogic = getProductBL(context);
+
+ Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateProductNameExists(productName, userId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get validate service name");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Product Name");
+ log.debug("validate product name failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java
index bc5ad35c8f..14d2628926 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java
@@ -20,29 +20,12 @@
package org.openecomp.sdc.be.servlets;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
@@ -64,383 +47,326 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.reflect.TypeToken;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Resource Property Servlet", description = "Resource Property Servlet")
@Singleton
public class PropertyServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(PropertyServlet.class.getName());
-
- @POST
- @Path("resources/{resourceId}/properties")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Resource property already exist") })
- public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-
- try {
- // convert json to PropertyDefinition
- Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
- if (either.isRight()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
- return buildErrorResponse(responseFormat);
- }
- Map<String, PropertyDefinition> properties = either.left().value();
- if (properties == null || properties.size() != 1) {
- log.info("Property conetnt is invalid - {}", data);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- return buildErrorResponse(responseFormat);
- }
- Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
- String propertyName = entry.getKey();
- PropertyDefinition newPropertyDefinition = entry.getValue();
-
- // create the new property
- PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId);
- if (status.isRight()) {
- log.info("Failed to create Property. Reason - ", status.right().value());
- return buildErrorResponse(status.right().value());
- }
- EntryData<String, PropertyDefinition> property = status.left().value();
- String name = property.getKey();
- PropertyDefinition propertyDefinition = property.getValue();
-
- log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
- return buildOkResponse(responseFormat, propertyToJson(property));
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Property");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Property");
- log.debug("create property failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- @GET
- @Path("resources/{resourceId}/properties/{propertyId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 404, message = "Resource property not found") })
- public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}, modifier id is {}", url, userId);
-
- try {
-
- //
- PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId);
-
- if (status.isRight()) {
- log.info("Failed to get Property. Reason - ", status.right().value());
- return buildErrorResponse(status.right().value());
- }
- Entry<String, PropertyDefinition> property = status.left().value();
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- return buildOkResponse(responseFormat, propertyToJson(property));
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Property");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property");
- log.debug("get property failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- @DELETE
- @Path("resources/{resourceId}/properties/{propertyId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 404, message = "Resource property not found") })
- public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {} modifier id is {}", url, userId);
-
- try {
-
- // delete the property
- PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId);
- if (status.isRight()) {
- log.debug("Failed to delete Property. Reason - ", status.right().value());
- return buildErrorResponse(status.right().value());
- }
- Entry<String, PropertyDefinition> property = status.left().value();
- String name = property.getKey();
- PropertyDefinition propertyDefinition = property.getValue();
-
- log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
- return buildOkResponse(responseFormat, propertyToJson(property));
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
- log.debug("delete property failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- @PUT
- @Path("resources/{resourceId}/properties/{propertyId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- try {
- // convert json to PropertyDefinition
- Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
- if (either.isRight()) {
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
- return buildErrorResponse(responseFormat);
- }
- Map<String, PropertyDefinition> properties = either.left().value();
- if (properties == null || properties.size() != 1) {
- log.info("Property conetnt is invalid - {}", data);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- return buildErrorResponse(responseFormat);
- }
- Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
- PropertyDefinition newPropertyDefinition = entry.getValue();
-
- // update property
- PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId);
- if (status.isRight()) {
- log.info("Failed to update Property. Reason - ", status.right().value());
- return buildErrorResponse(status.right().value());
- }
- EntryData<String, PropertyDefinition> property = status.left().value();
- PropertyDefinition propertyDefinition = property.getValue();
-
- log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId());
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- return buildOkResponse(responseFormat, propertyToJson(property));
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Property");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property");
- log.debug("update property failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
-
- }
- }
-
- private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String resourceId, String data) {
- JSONParser parser = new JSONParser();
- JSONObject root;
- try {
- Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
- root = (JSONObject) parser.parse(data);
-
- Set entrySet = root.entrySet();
- Iterator iterator = entrySet.iterator();
- while (iterator.hasNext()) {
- Entry next = (Entry) iterator.next();
- String propertyName = (String) next.getKey();
- JSONObject value = (JSONObject) next.getValue();
- String jsonString = value.toJSONString();
- Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class);
- if (convertJsonToObject.isRight()) {
- return Either.right(convertJsonToObject.right().value());
- }
- PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
- // PropertyDefinition propertyDefinition =
- // gson.fromJson(jsonString , PropertyDefinition.class);
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName);
- propertyDefinition.setUniqueId(uniqueId);
- properties.put(propertyName, propertyDefinition);
- }
-
- // Set keySet = root.keySet();
- // for (Object propertyName : keySet){
- // JSONObject val = (JSONObject) root.get(propertyName);
- // String jsonString = val.toJSONString();
- // Either<PropertyDefinition,ActionStatus> convertJsonToObject =
- // convertJsonToObject(jsonString, PropertyDefinition.class);
- // if (convertJsonToObject.isRight()){
- // return Either.right(convertJsonToObject.right().value());
- // }
- // PropertyDefinition propertyDefinition =
- // convertJsonToObject.left().value();
- // //PropertyDefinition propertyDefinition =
- // gson.fromJson(jsonString , PropertyDefinition.class);
- // String uniqueId =
- // UniqueIdBuilder.buildPropertyUniqueId("resourceId",
- // (String)propertyName);
- // propertyDefinition.setUniqueId(uniqueId);
- // properties.put((String)propertyName,propertyDefinition);
- // }
- return Either.left(properties);
- } catch (ParseException e) {
- log.info("Property conetnt is invalid - {}", data);
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
- }
-
- private String propertyToJson(Map.Entry<String, PropertyDefinition> property) {
- JSONObject root = new JSONObject();
- String propertyName = property.getKey();
- PropertyDefinition propertyDefinition = property.getValue();
- // String jsonPropertyDefinition = gson.toJson(propertyDefinition);
- // root.put(propertyName, jsonPropertyDefinition);
- JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition);
- root.put(propertyName, propertyDefinitionO);
- propertyDefinition.getType();
- return root.toString();
- }
-
- private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) {
-
- Either<String, ActionStatus> either = convertObjectToJson(propertyDefinition);
- if (either.isRight()) {
- return new JSONObject();
- }
- String value = either.left().value();
- try {
- JSONObject root = (JSONObject) new JSONParser().parse(value);
- return root;
- } catch (ParseException e) {
- log.info("failed to convert input to json");
- log.debug("failed to convert to json", e);
- return new JSONObject();
- }
-
- }
-
- private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
- T t = null;
- Type constraintType = new TypeToken<PropertyConstraint>() {
- }.getType();
- Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
- try {
- log.trace("convert json to object. json=\n {}", data);
- t = gson.fromJson(data, clazz);
- if (t == null) {
- log.info("object is null after converting from json");
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
- } catch (Exception e) {
- // INVALID JSON
- log.info("failed to convert from json");
- log.debug("failed to convert from json", e);
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
- return Either.left(t);
- }
-
- private <T> Either<String, ActionStatus> convertObjectToJson(PropertyDefinition propertyDefinition) {
- Type constraintType = new TypeToken<PropertyConstraint>() {
- }.getType();
- Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create();
- try {
- log.trace("convert object to json. propertyDefinition= {}", propertyDefinition.toString());
- String json = gson.toJson(propertyDefinition);
- if (json == null) {
- log.info("object is null after converting to json");
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
- return Either.left(json);
- } catch (Exception e) {
- // INVALID JSON
- log.info("failed to convert to json");
- log.debug("failed to convert fto json", e);
- return Either.right(ActionStatus.INVALID_CONTENT);
- }
-
- }
-
- private PropertyBusinessLogic getPropertyBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class);
- return propertytBl;
- }
-
- // private class UiProperty{
- // String type;
- // String source;
- // String name;
- // String description;
- // public String getType() {
- // return type;
- // }
- // public void setType(String type) {
- // this.type = type;
- // }
- // public String getSource() {
- // return source;
- // }
- // public void setSource(String source) {
- // this.source = source;
- // }
- // 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;
- // }
- //
- // }
+ private static final Logger log = LoggerFactory.getLogger(PropertyServlet.class);
+
+ @POST
+ @Path("resources/{resourceId}/properties")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource property already exist") })
+ public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
+
+ try {
+ // convert json to PropertyDefinition
+ Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
+ if (either.isRight()) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
+ return buildErrorResponse(responseFormat);
+ }
+ Map<String, PropertyDefinition> properties = either.left().value();
+ if (properties == null || properties.size() != 1) {
+ log.info("Property conetnt is invalid - {}", data);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return buildErrorResponse(responseFormat);
+ }
+ Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
+ String propertyName = entry.getKey();
+ PropertyDefinition newPropertyDefinition = entry.getValue();
+
+ // create the new property
+ PropertyBusinessLogic businessLogic = getPropertyBL(context);
+ Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId);
+ if (status.isRight()) {
+ log.info("Failed to create Property. Reason - ", status.right().value());
+ return buildErrorResponse(status.right().value());
+ }
+ EntryData<String, PropertyDefinition> property = status.left().value();
+ String name = property.getKey();
+ PropertyDefinition propertyDefinition = property.getValue();
+
+ log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId());
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
+ return buildOkResponse(responseFormat, propertyToJson(property));
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Property");
+ log.debug("create property failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ @GET
+ @Path("resources/{resourceId}/properties/{propertyId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "Resource property not found") })
+ public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}, modifier id is {}", url, userId);
+
+ try {
+
+ //
+ PropertyBusinessLogic businessLogic = getPropertyBL(context);
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId);
+
+ if (status.isRight()) {
+ log.info("Failed to get Property. Reason - ", status.right().value());
+ return buildErrorResponse(status.right().value());
+ }
+ Entry<String, PropertyDefinition> property = status.left().value();
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ return buildOkResponse(responseFormat, propertyToJson(property));
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property");
+ log.debug("get property failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ @DELETE
+ @Path("resources/{resourceId}/properties/{propertyId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "Resource property not found") })
+ public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {} modifier id is {}", url, userId);
+
+ try {
+
+ // delete the property
+ PropertyBusinessLogic businessLogic = getPropertyBL(context);
+ Either<Entry<String, PropertyDefinition>, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId);
+ if (status.isRight()) {
+ log.debug("Failed to delete Property. Reason - ", status.right().value());
+ return buildErrorResponse(status.right().value());
+ }
+ Entry<String, PropertyDefinition> property = status.left().value();
+ String name = property.getKey();
+ PropertyDefinition propertyDefinition = property.getValue();
+
+ log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId());
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
+ return buildOkResponse(responseFormat, propertyToJson(property));
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
+ log.debug("delete property failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ @PUT
+ @Path("resources/{resourceId}/properties/{propertyId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ try {
+ // convert json to PropertyDefinition
+ Either<Map<String, PropertyDefinition>, ActionStatus> either = getPropertyModel(resourceId, data);
+ if (either.isRight()) {
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value());
+ return buildErrorResponse(responseFormat);
+ }
+ Map<String, PropertyDefinition> properties = either.left().value();
+ if (properties == null || properties.size() != 1) {
+ log.info("Property conetnt is invalid - {}", data);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+ return buildErrorResponse(responseFormat);
+ }
+ Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
+ PropertyDefinition newPropertyDefinition = entry.getValue();
+
+ // update property
+ PropertyBusinessLogic businessLogic = getPropertyBL(context);
+ Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId);
+ if (status.isRight()) {
+ log.info("Failed to update Property. Reason - ", status.right().value());
+ return buildErrorResponse(status.right().value());
+ }
+ EntryData<String, PropertyDefinition> property = status.left().value();
+ PropertyDefinition propertyDefinition = property.getValue();
+
+ log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId());
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+ return buildOkResponse(responseFormat, propertyToJson(property));
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property");
+ log.debug("update property failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+
+ }
+ }
+
+ private Either<Map<String, PropertyDefinition>, ActionStatus> getPropertyModel(String resourceId, String data) {
+ JSONParser parser = new JSONParser();
+ JSONObject root;
+ try {
+ Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
+ root = (JSONObject) parser.parse(data);
+
+ Set entrySet = root.entrySet();
+ Iterator iterator = entrySet.iterator();
+ while (iterator.hasNext()) {
+ Entry next = (Entry) iterator.next();
+ String propertyName = (String) next.getKey();
+ JSONObject value = (JSONObject) next.getValue();
+ String jsonString = value.toJSONString();
+ Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class);
+ if (convertJsonToObject.isRight()) {
+ return Either.right(convertJsonToObject.right().value());
+ }
+ PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName);
+ propertyDefinition.setUniqueId(uniqueId);
+ properties.put(propertyName, propertyDefinition);
+ }
+
+ return Either.left(properties);
+ } catch (ParseException e) {
+ log.info("Property conetnt is invalid - {}", data);
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+ }
+
+ private String propertyToJson(Map.Entry<String, PropertyDefinition> property) {
+ JSONObject root = new JSONObject();
+ String propertyName = property.getKey();
+ PropertyDefinition propertyDefinition = property.getValue();
+ JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition);
+ root.put(propertyName, propertyDefinitionO);
+ propertyDefinition.getType();
+ return root.toString();
+ }
+
+ private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) {
+
+ Either<String, ActionStatus> either = convertObjectToJson(propertyDefinition);
+ if (either.isRight()) {
+ return new JSONObject();
+ }
+ String value = either.left().value();
+ try {
+ JSONObject root = (JSONObject) new JSONParser().parse(value);
+ return root;
+ } catch (ParseException e) {
+ log.info("failed to convert input to json");
+ log.debug("failed to convert to json", e);
+ return new JSONObject();
+ }
+
+ }
+
+ private <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
+ T t = null;
+ Type constraintType = new TypeToken<PropertyConstraint>() {
+ }.getType();
+ Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+ try {
+ log.trace("convert json to object. json=\n {}", data);
+ t = gson.fromJson(data, clazz);
+ if (t == null) {
+ log.info("object is null after converting from json");
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+ } catch (Exception e) {
+ // INVALID JSON
+ log.info("failed to convert from json");
+ log.debug("failed to convert from json", e);
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+ return Either.left(t);
+ }
+
+ private <T> Either<String, ActionStatus> convertObjectToJson(PropertyDefinition propertyDefinition) {
+ Type constraintType = new TypeToken<PropertyConstraint>() {
+ }.getType();
+ Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create();
+ try {
+ log.trace("convert object to json. propertyDefinition= {}", propertyDefinition);
+ String json = gson.toJson(propertyDefinition);
+ if (json == null) {
+ log.info("object is null after converting to json");
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+ return Either.left(json);
+ } catch (Exception e) {
+ // INVALID JSON
+ log.info("failed to convert to json");
+ log.debug("failed to convert fto json", e);
+ return Either.right(ActionStatus.INVALID_CONTENT);
+ }
+
+ }
+
+ private PropertyBusinessLogic getPropertyBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class);
+ return propertytBl;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
index 98e966e6eb..da42fe2b6f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
@@ -20,14 +20,13 @@
package org.openecomp.sdc.be.servlets;
-import java.io.IOException;
-
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.map.DeserializationConfig;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.SerializationConfig.Feature;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
@@ -36,132 +35,126 @@ import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
+import java.io.IOException;
+import com.fasterxml.jackson.databind.SerializationFeature;
public class RepresentationUtils {
- private static Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName());
-
- public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) {
-
- JsonObject jsonElement = new JsonObject();
- ArtifactDefinition resourceInfo = null;
-
- try {
- Gson gson = new Gson();
- jsonElement = gson.fromJson(content, jsonElement.getClass());
- String payload = null;
- jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD);
- //in update the group type is ignored but this spagheti code makes it too complex to remove this field.
- jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
- 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, clazz);
- 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;
- }
-
-
- public static class ResourceRep {
-
- }
-
- /**
- * Build Representation of given Object
- *
- * @param elementToRepresent
- * @return
- * @throws IOException
- * @throws JsonGenerationException
- * @throws JsonMappingException
- */
- public static <T> Object toRepresentation(T elementToRepresent) throws IOException, JsonGenerationException, JsonMappingException {
-
- // return theResource;
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
- mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
- return mapper.writeValueAsString(elementToRepresent);
- }
-
- public static <T> T fromRepresentation(String json, Class<T> clazz) {
- ObjectMapper mapper = new ObjectMapper();
- T object = null;
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
- mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
- try {
- object = mapper.readValue(json, clazz);
- } catch (Exception e) {
- log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
- } // return null in case of exception
-
- return object;
- }
-
- public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz) {
-
- 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, clazz);
- 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;
- }
+ private static final Logger log = LoggerFactory.getLogger(RepresentationUtils.class);
+
+ public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) {
+
+ JsonObject jsonElement = new JsonObject();
+ ArtifactDefinition resourceInfo = null;
+
+ try {
+ Gson gson = new Gson();
+ jsonElement = gson.fromJson(content, jsonElement.getClass());
+ String payload = null;
+ jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE);
+ //in update the group type is ignored but this spagheti code makes it too complex to remove this field.
+ jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
+ 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(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+
+ resourceInfo = mapper.readValue(json, clazz);
+ resourceInfo.setPayloadData(payload);
+
+ } catch (Exception e) {
+ 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;
+ }
+
+
+ public static class ResourceRep {
+
+ }
+
+ /**
+ * Build Representation of given Object
+ *
+ * @param elementToRepresent
+ * @return
+ * @throws IOException
+ */
+ public static <T> Object toRepresentation(T elementToRepresent) throws IOException {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ return mapper.writeValueAsString(elementToRepresent);
+ }
+
+ public static <T> T fromRepresentation(String json, Class<T> clazz) {
+ ObjectMapper mapper = new ObjectMapper();
+ T object = null;
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ try {
+ object = mapper.readValue(json, clazz);
+ } catch (Exception e) {
+ log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
+ } // return null in case of exception
+
+ return object;
+ }
+
+ public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz) {
+
+ 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);
+ 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);
+ return null;
+ } else {
+ jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE);
+ jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, 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(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+
+ resourceInfo = mapper.readValue(json, clazz);
+ resourceInfo.setPayloadData(payload);
+
+ } catch (Exception e) {
+ 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;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java
index fb4aba6af7..e8769cca9b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementsServlet.java
@@ -20,66 +20,56 @@
package org.openecomp.sdc.be.servlets;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
+import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.JsonSyntaxException;
import com.jcabi.aspects.Loggable;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
public class RequirementsServlet extends BeGenericServlet {
- private static Logger log = LoggerFactory.getLogger(RequirementsServlet.class.getName());
-
- @PUT
- @Path("resources/{resourceId}/requirements/{requirementId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId,
- @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData,
- @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ private static final Logger log = LoggerFactory.getLogger(RequirementsServlet.class);
- // Convert RequirementDefinition from JSON
- // TODO: it's going to be another object, probably. This is placeholder
- // for sake of JSON validation
- // RequirementDefinition requirementDefinition;
- ResponseFormat responseFormat;
- try {
- // requirementDefinition = gson.fromJson(requirementData,
- // RequirementDefinition.class);
- // .....
+ @PUT
+ @Path("resources/{resourceId}/requirements/{requirementId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource Requirement", httpMethod = "PUT", notes = "Returns updated requirement", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource requirement updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateRequirement(@ApiParam(value = "resource id to update with new requirement", required = true) @PathParam("resourceId") final String resourceId,
+ @ApiParam(value = "requirement id to update", required = true) @PathParam("requirementId") final String requirementId, @ApiParam(value = "Resource property to update", required = true) String requirementData,
+ @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- // TODO pass real entity
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
- } catch (JsonSyntaxException e) {
- // INVALID JSON
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
- return buildErrorResponse(responseFormat);
- } catch (Exception e) {
- log.debug("Unexpected error: {}", e);
- responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
- }
+ // Convert RequirementDefinition from JSON
+ // TODO: it's going to be another object, probably. This is placeholder
+ // for sake of JSON validation
+ // RequirementDefinition requirementDefinition;
+ ResponseFormat responseFormat;
+ try {
+ // TODO pass real entity
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
+ } catch (Exception e) {
+ log.debug("Unexpected error: ", e);
+ responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
index 54ec6e3b15..5d4001eec5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceArtifactDownloadServlet.java
@@ -20,15 +20,10 @@
package org.openecomp.sdc.be.servlets;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
import org.apache.http.HttpStatus;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -38,116 +33,116 @@ import org.openecomp.sdc.be.info.ArtifactAccessInfo;
import org.openecomp.sdc.be.resources.api.IResourceUploader;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog/resources/available")
public class ResourceArtifactDownloadServlet extends ToscaDaoServlet {
- private static Logger log = LoggerFactory.getLogger(ResourceArtifactDownloadServlet.class.getName());
-
- private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- @GET
- @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
- // @Produces(MediaType.APPLICATION_OCTET_STREAM)
- public Response getResourceArtifactByName(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
- Response response = null;
- try {
- // get the artifact data
- String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName);
-
- IResourceUploader resouceUploader = getResourceUploader(request.getSession().getServletContext());
- if (resouceUploader == null) {
- return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "");
-
- }
- Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resouceUploader.getArtifact(artifactId);
-
- DownloadArtifactLogic logic = getLogic(request.getSession().getServletContext());
- if (logic == null) {
- return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "");
-
- }
- response = logic.downloadArtifact(resourceName, resourceVersion, artifactName, getArtifactStatus, artifactId);
-
- log.info("Finish handle request of {} | result = {}", url, response.getStatus());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource Artifact By Name");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact By Name");
- log.debug("getResourceArtifactByName failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @GET
- @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}/metadata")
- @Produces(MediaType.APPLICATION_JSON)
- public Response getResourceArtifactMetadata(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName,
- @Context final HttpServletRequest request) {
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- Response response = null;
- try {
- IResourceUploader resourceDao = getResourceUploader(request.getSession().getServletContext());
- if (resourceDao == null) {
- log.error("resource dao cannot be found");
- response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Resource dao cannot be found");
- return response;
- }
-
- String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName);
- Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resourceDao.getArtifact(artifactId);
-
- if (getArtifactStatus.isRight()) {
- ResourceUploadStatus status = getArtifactStatus.right().value();
- if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) {
- response = Response.status(HttpStatus.SC_NOT_FOUND).build();
- log.debug("Could not find artifact for with id: {}", artifactId);
- } else {
- response = Response.status(HttpStatus.SC_NO_CONTENT).build();
- log.debug("Could not find artifact for with id: {}", artifactId);
- }
- return response;
- } else {
- ESArtifactData artifactData = getArtifactStatus.left().value();
- log.debug("found artifact with id: {}", artifactId);
- ArtifactAccessInfo artifactInfo = new ArtifactAccessInfo(artifactData);
- String artifactDataJson = gson.toJson(artifactInfo);
- response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build();
-
- log.info("Finish handle request of {} | result = {}", url, response.getStatus());
- return response;
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource Artifact Metadata");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact Metadata");
- log.debug("getResourceArtifactMetadata failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
-
- }
-
- @Override
- public Logger getLogger() {
- return log;
- }
+ private static final Logger log = LoggerFactory.getLogger(ResourceArtifactDownloadServlet.class);
+
+ private Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ @GET
+ @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
+ // @Produces(MediaType.APPLICATION_OCTET_STREAM)
+ public Response getResourceArtifactByName(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ Response response = null;
+ try {
+ // get the artifact data
+ String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName);
+
+ IResourceUploader resouceUploader = getResourceUploader(request.getSession().getServletContext());
+ if (resouceUploader == null) {
+ return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "");
+
+ }
+ Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resouceUploader.getArtifact(artifactId);
+
+ DownloadArtifactLogic logic = getLogic(request.getSession().getServletContext());
+ if (logic == null) {
+ return buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "");
+
+ }
+ response = logic.downloadArtifact(artifactName, getArtifactStatus, artifactId);
+
+ log.info("Finish handle request of {} | result = {}", url, response.getStatus());
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact By Name");
+ log.debug("getResourceArtifactByName failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @GET
+ @Path("/{resourceName}/{resourceVersion}/artifacts/{artifactName}/metadata")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getResourceArtifactMetadata(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName,
+ @Context final HttpServletRequest request) {
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ Response response = null;
+ try {
+ IResourceUploader resourceDao = getResourceUploader(request.getSession().getServletContext());
+ if (resourceDao == null) {
+ log.error("resource dao cannot be found");
+ response = buildResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Resource dao cannot be found");
+ return response;
+ }
+
+ String artifactId = String.format(Constants.ARTIFACT_ID_FORMAT, resourceName, resourceVersion, artifactName);
+ Either<ESArtifactData, ResourceUploadStatus> getArtifactStatus = resourceDao.getArtifact(artifactId);
+
+ if (getArtifactStatus.isRight()) {
+ ResourceUploadStatus status = getArtifactStatus.right().value();
+ if (status == ResourceUploadStatus.COMPONENT_NOT_EXIST) {
+ response = Response.status(HttpStatus.SC_NOT_FOUND).build();
+ log.debug("Could not find artifact for with id: {}", artifactId);
+ } else {
+ response = Response.status(HttpStatus.SC_NO_CONTENT).build();
+ log.debug("Could not find artifact for with id: {}", artifactId);
+ }
+ return response;
+ } else {
+ ESArtifactData artifactData = getArtifactStatus.left().value();
+ log.debug("found artifact with id: {}", artifactId);
+ ArtifactAccessInfo artifactInfo = new ArtifactAccessInfo(artifactData);
+ String artifactDataJson = gson.toJson(artifactInfo);
+ response = Response.status(HttpStatus.SC_OK).entity(artifactDataJson).type(MediaType.APPLICATION_JSON_TYPE).build();
+
+ log.info("Finish handle request of {} | result = {}", url, response.getStatus());
+ return response;
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource Artifact Metadata");
+ log.debug("getResourceArtifactMetadata failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+
+ }
+
+ @Override
+ public Logger getLogger() {
+ return log;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
index 3cf2a69fb5..2508423d03 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
@@ -20,24 +20,8 @@
package org.openecomp.sdc.be.servlets;
-import java.io.File;
-
-import javax.annotation.Resource;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import io.swagger.annotations.*;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.openecomp.sdc.be.components.impl.ResourceImportManager;
@@ -53,13 +37,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.jcabi.aspects.Loggable;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.annotation.Resource;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.File;
/**
* Root resource (exposed at "/" path)
@@ -70,115 +56,114 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class ResourceUploadServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class.getName());
- public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
- public static final String CSAR_TYPE_RESOURCE = "csar";
- public static final String USER_TYPE_RESOURCE = "user-resource";
- public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
-
- public enum ResourceAuthorityTypeEnum {
- NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
-
- private String urlPath;
- private boolean isBackEndImport, isUserTypeResource;
-
- public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
- ResourceAuthorityTypeEnum found = null;
- for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
- if (curr.getUrlPath().equals(urlPath)) {
- found = curr;
- break;
- }
- }
- return found;
- }
-
- private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
- this.urlPath = urlPath;
- this.isBackEndImport = isBackEndImport;
- this.isUserTypeResource = isUserTypeResource;
- }
-
- public String getUrlPath() {
- return urlPath;
- }
-
- public boolean isBackEndImport() {
- return isBackEndImport;
- }
-
- public boolean isUserTypeResource() {
- return isUserTypeResource;
- }
- }
-
- @Resource
- private ResourceImportManager resourceImportManager;
-
- @POST
- @Path("/{resourceAuthority}")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Resource already exist") })
- public Response uploadMultipart(
- @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + ","
- + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority,
- @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
- @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- // updateResourse Query Parameter if false checks if already exist
- @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
-
- init(request.getSession().getServletContext());
- try {
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- Wrapper<User> userWrapper = new Wrapper<>();
- Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
- Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // When we get an errorResponse it will be filled into the
- // responseWrapper
- validateAuthorityType(responseWrapper, resourceAuthority);
-
- ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
-
- commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
-
- fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
-
- // PayLoad Validations
- if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
- commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
-
- specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
- }
-
- if (responseWrapper.isEmpty()) {
- handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
- }
-
- return responseWrapper.getInnerElement();
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Upload Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
- log.debug("upload resource failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /********************************************************************************************************************/
-
- private void init(ServletContext context) {
- init(log);
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
- resourceImportManager.init(context);
- }
+ private static final Logger log = LoggerFactory.getLogger(ResourceUploadServlet.class);
+ public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
+ public static final String CSAR_TYPE_RESOURCE = "csar";
+ public static final String USER_TYPE_RESOURCE = "user-resource";
+ public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
+
+ public enum ResourceAuthorityTypeEnum {
+ NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
+
+ private String urlPath;
+ private boolean isBackEndImport, isUserTypeResource;
+
+ public static ResourceAuthorityTypeEnum findByUrlPath(String urlPath) {
+ ResourceAuthorityTypeEnum found = null;
+ for (ResourceAuthorityTypeEnum curr : ResourceAuthorityTypeEnum.values()) {
+ if (curr.getUrlPath().equals(urlPath)) {
+ found = curr;
+ break;
+ }
+ }
+ return found;
+ }
+
+ private ResourceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeResource) {
+ this.urlPath = urlPath;
+ this.isBackEndImport = isBackEndImport;
+ this.isUserTypeResource = isUserTypeResource;
+ }
+
+ public String getUrlPath() {
+ return urlPath;
+ }
+
+ public boolean isBackEndImport() {
+ return isBackEndImport;
+ }
+
+ public boolean isUserTypeResource() {
+ return isUserTypeResource;
+ }
+ }
+
+ @Resource
+ private ResourceImportManager resourceImportManager;
+
+ @POST
+ @Path("/{resourceAuthority}")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource from yaml", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource already exist") })
+ public Response uploadMultipart(
+ @ApiParam(value = "validValues: normative-resource / user-resource", allowableValues = NORMATIVE_TYPE_RESOURCE + "," + USER_TYPE_RESOURCE + ","
+ + USER_TYPE_RESOURCE_UI_IMPORT) @PathParam(value = "resourceAuthority") final String resourceAuthority,
+ @ApiParam("FileInputStream") @FormDataParam("resourceZip") File file, @ApiParam("ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
+ @ApiParam("resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ // updateResourse Query Parameter if false checks if already exist
+ @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) {
+
+ init(request.getSession().getServletContext());
+ try {
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ Wrapper<User> userWrapper = new Wrapper<>();
+ Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
+ Wrapper<String> yamlStringWrapper = new Wrapper<>();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // When we get an errorResponse it will be filled into the
+ // responseWrapper
+ validateAuthorityType(responseWrapper, resourceAuthority);
+
+ ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
+
+ commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
+
+ fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
+
+ // PayLoad Validations
+ if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
+ commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
+
+ specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
+ }
+
+ return responseWrapper.getInnerElement();
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
+ log.debug("upload resource failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /********************************************************************************************************************/
+
+ private void init(ServletContext context) {
+ init(log);
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
+ resourceImportManager.init(context);
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
index 8aa5093404..db0d4fb537 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
@@ -20,29 +20,9 @@
package org.openecomp.sdc.be.servlets;
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
@@ -66,622 +46,586 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Resources Catalog", description = "Resources Servlet")
@Singleton
public class ResourcesServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(ResourcesServlet.class.getName());
-
- @POST
- @Path("/resources")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Resource already exist") })
- public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
- init(log);
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- // UI Import
- if (isUIImport(data)) {
- performUIImport(responseWrapper, data, request, userId, null);
- }
- // UI Create
- else {
-
- ResourceBusinessLogic businessLogic = getResourceBL(context);
-
- Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier);
- if (convertResponse.isRight()) {
- log.debug("failed to parse resource");
- response = buildErrorResponse(convertResponse.right().value());
- return response;
- }
-
- Resource resource = convertResponse.left().value();
- Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);
-
- if (actionResponse.isRight()) {
- log.debug("failed to create resource");
- response = buildErrorResponse(actionResponse.right().value());
- } else {
- Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
- }
- responseWrapper.setInnerElement(response);
- }
-
- return responseWrapper.getInnerElement();
-
- // return response;
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Create Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource");
- log.debug("create resource failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- private boolean isUIImport(String data) {
- boolean isUIImport;
- try {
- JSONObject json = new JSONObject(data);
- String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME);
- isUIImport = payloadName != null && !payloadName.isEmpty();
- } catch (Exception e) {
- log.debug("failed to parse json sent from client, json:{}", data, e);
- isUIImport = false;
- }
- return isUIImport;
- }
-
- private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException {
-
- Wrapper<User> userWrapper = new Wrapper<>();
- Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
- Wrapper<String> yamlStringWrapper = new Wrapper<>();
- String resourceInfoJsonString = data;
-
- ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI;
-
- commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
-
- if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
- fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null);
-
- // PayLoad Validations
- commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
- }
- specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
-
- if (responseWrapper.isEmpty()) {
- handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId);
- }
- }
-
- public Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) {
- return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
- }
-
- public Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) {
- Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
- if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow)
- ret.left().value().setRequirements(null);
- ret.left().value().setCapabilities(null);
- }
- return ret;
- }
-
- @DELETE
- @Path("/resources/{resourceId}")
- public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}" , userId);
-
- Response response = null;
-
- try {
- String resourceIdLower = resourceId.toLowerCase();
- ResourceBusinessLogic businessLogic = getResourceBL(context);
- ResponseFormat actionResponse = businessLogic.deleteResource(resourceIdLower, modifier);
-
- if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
- log.debug("failed to delete resource");
- response = buildErrorResponse(actionResponse);
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
- log.debug("delete resource failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @DELETE
- @Path("/resources/{resourceName}/{version}")
- public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}" , userId);
-
- Response response = null;
-
- try {
- ResourceBusinessLogic businessLogic = getResourceBL(context);
- ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier);
-
- if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
- log.debug("failed to delete resource");
- response = buildErrorResponse(actionResponse);
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Delete Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
- log.debug("delete resource failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @GET
- @Path("/resources/{resourceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
- public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}" , userId);
-
- Response response = null;
-
- try {
- String resourceIdLower = resourceId.toLowerCase();
- ResourceBusinessLogic businessLogic = getResourceBL(context);
- log.trace("get resource with id {}", resourceId);
- Either<Resource, ResponseFormat> actionResponse = businessLogic.getResource(resourceIdLower, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get resource");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource");
- log.debug("get resource failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @GET
- @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
- public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}" , userId);
- Response response = null;
- try {
- ResourceBusinessLogic businessLogic = getResourceBL(context);
- Either<Resource, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Resource by name and version");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version");
- log.debug("get resource failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @GET
- @Path("/resources/validate-name/{resourceName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") })
- public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}" , userId);
- Response response = null;
- try {
- ResourceBusinessLogic businessLogic = getResourceBL(context);
-
- if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {
- log.debug("invalid resource type received");
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- return response;
-
- }
- ResourceTypeEnum typeEnum = null;
- if (resourceType != null) {
- typeEnum = ResourceTypeEnum.valueOf(resourceType);
- }
- Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateResourceNameExists(resourceName, typeEnum, userId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to validate resource name");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Validate Resource Name");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Resource Name");
- log.debug("validate resource name failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/resources/certified/abstract")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- // TODO: any validations???
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}" , url);
- Response response = null;
- try {
-
- ResourceBusinessLogic businessLogic = getResourceBL(context);
-
- Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get all abstract resources");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Abstract Resources");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources");
- log.debug("getCertifiedAbstractResources failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @GET
- @Path("/resources/certified/notabstract")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- // TODO: any vlidations???
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("(get) Start handle request of {}" , url);
- Response response = null;
-
- try {
-
- ResourceBusinessLogic businessLogic = getResourceBL(context);
-
- Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get all non abstract resources");
- return buildErrorResponse(actionResponse.right().value());
- }
- Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get Certified Non Abstract Resources");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources");
- log.debug("getCertifiedNotAbstractResources failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
-
- }
-
- @PUT
- @Path("/resources/{resourceId}/metadata")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") })
- public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- ResourceBusinessLogic businessLogic = getResourceBL(context);
- String resourceIdLower = resourceId.toLowerCase();
- Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
- if (updateInfoResource.isRight()) {
- log.debug("failed to parse resource metadata");
- response = buildErrorResponse(updateInfoResource.right().value());
- return response;
- }
- Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
-
- if (actionResponse.isRight()) {
- log.debug("failed to update resource metadata");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource Metadata");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata");
- log.debug("Update Resource Metadata failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @PUT
- @Path("/resources/{resourceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Resource already exist") })
- public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @PathParam(value = "resourceId") String resourceId) {
-
- userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
- init(log);
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- // UI Import
- if (isUIImport(data)) {
- performUIImport(responseWrapper, data, request, userId, resourceId);
- } else {
-
- ResourceBusinessLogic businessLogic = getResourceBL(context);
-
- Either<Resource, ResponseFormat> convertResponse = parseToLightResource(data, modifier);
- if (convertResponse.isRight()) {
- log.debug("failed to parse resource");
- response = buildErrorResponse(convertResponse.right().value());
- return response;
- }
-
- Resource resource = convertResponse.left().value();
- Either<Resource, ResponseFormat> actionResponse = businessLogic.validateAndUpdateResourceFromCsar(resource, modifier, null, null, resourceId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to update resource");
- response = buildErrorResponse(actionResponse.right().value());
- } else {
- Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
- }
- responseWrapper.setInnerElement(response);
- }
-
- return responseWrapper.getInnerElement();
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update Resource");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource");
- log.debug("update resource failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- /*
- * @GET
- *
- * @Path("/resources/latestversion/notabstract")
- *
- * @Consumes(MediaType.APPLICATION_JSON)
- *
- * @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionNotAbstractResources(@Context final HttpServletRequest request) { //TODO: any vlidations??? ServletContext context = request.getSession().getServletContext();
- *
- * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("(get) Start handle request of " + url); Response response=null;
- *
- * try {
- *
- * ResourceBusinessLogic businessLogic = getResourceBL(context);
- *
- * Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getLatestVersionResources(false, HighestFilterEnum.HIGHEST_ONLY);
- *
- *
- * if (actionResponse.isRight()){ log.debug( "failed to get all non abstract resources"); return buildErrorResponse(actionResponse.right().value()); } return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
- * actionResponse.left().value());
- *
- * } catch (Exception e){ BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Get Certified Non Abstract Resources"); log.debug("getCertifiedNotAbstractResources failed with exception", e); response =
- * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response;
- *
- * } }
- */
- public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) {
- if (properties == null) {
- return null;
- }
-
- List<PropertyDefinition> definitions = new ArrayList<>();
- for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
- String name = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- propertyDefinition.setName(name);
- definitions.add(propertyDefinition);
- }
-
- return definitions;
- }
-
- @GET
- @Path("/resources/csar/{csaruuid}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) {
-
- init(log);
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}" , url);
-
- // retrieve user details
- userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
- User user = new User();
- user.setUserId(userId);
-
- log.debug("user id is {}", userId);
-
- Response response = null;
-
- try {
-
- ResourceBusinessLogic businessLogic = getResourceBL(context);
-
- Either<Resource, ResponseFormat> eitherResource = businessLogic.getLatestResourceFromCsarUuid(csarUUID, user);
-
- // validate response
- if (eitherResource.isRight()) {
- log.debug("failed to get resource from csarUuid : {}", csarUUID);
- // response =
- // buildErrorResponse(eitherResource.right().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value());
- } else {
- Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
- }
-
- return response;
-
- } catch (Exception e) {
- log.debug("get resource by csar failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(ResourcesServlet.class);
+
+ @POST
+ @Path("/resources")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns created resource", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource already exist") })
+ public Response createResource(@ApiParam(value = "Resource object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
+ init(log);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ // UI Import
+ if (isUIImport(data)) {
+ performUIImport(responseWrapper, data, request, userId, null);
+ }
+ // UI Create
+ else {
+
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+
+ Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier);
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse resource");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+
+ Resource resource = convertResponse.left().value();
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to create resource");
+ response = buildErrorResponse(actionResponse.right().value());
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
+ }
+ responseWrapper.setInnerElement(response);
+ }
+
+ return responseWrapper.getInnerElement();
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Resource");
+ log.debug("create resource failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ private boolean isUIImport(String data) {
+ boolean isUIImport;
+ try {
+ JSONObject json = new JSONObject(data);
+ String payloadName = json.getString(ImportUtils.Constants.UI_JSON_PAYLOAD_NAME);
+ isUIImport = payloadName != null && !payloadName.isEmpty();
+ } catch (Exception e) {
+ log.debug("failed to parse json sent from client, json:{}", data, e);
+ isUIImport = false;
+ }
+ return isUIImport;
+ }
+
+ private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String resourceUniqueId) throws FileNotFoundException {
+
+ Wrapper<User> userWrapper = new Wrapper<>();
+ Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
+ Wrapper<String> yamlStringWrapper = new Wrapper<>();
+ String resourceInfoJsonString = data;
+
+ ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI;
+
+ commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
+
+ if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
+ fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, null);
+
+ // PayLoad Validations
+ commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
+ }
+ specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
+
+ if (responseWrapper.isEmpty()) {
+ handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId);
+ }
+ }
+
+ public Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) {
+ return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
+ }
+
+ public Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) {
+ Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
+ if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow)
+ ret.left().value().setRequirements(null);
+ ret.left().value().setCapabilities(null);
+ }
+ return ret;
+ }
+
+ @DELETE
+ @Path("/resources/{resourceId}")
+ public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+
+ Response response = null;
+
+ try {
+ String resourceIdLower = resourceId.toLowerCase();
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+ ResponseFormat actionResponse = businessLogic.deleteResource(resourceIdLower, modifier);
+
+ if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
+ log.debug("failed to delete resource");
+ response = buildErrorResponse(actionResponse);
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
+ log.debug("delete resource failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @DELETE
+ @Path("/resources/{resourceName}/{version}")
+ public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+
+ Response response = null;
+
+ try {
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+ ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier);
+
+ if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
+ log.debug("failed to delete resource");
+ response = buildErrorResponse(actionResponse);
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
+ log.debug("delete resource failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/resources/{resourceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Resource", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
+ public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+
+ Response response = null;
+
+ try {
+ String resourceIdLower = resourceId.toLowerCase();
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+ log.trace("get resource with id {}", resourceId);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.getResource(resourceIdLower, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get resource");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource");
+ log.debug("get resource failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @GET
+ @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Resource by name and version", httpMethod = "GET", notes = "Returns resource according to resourceId", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Resource not found") })
+ public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+ Response response = null;
+ try {
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version");
+ log.debug("get resource failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @GET
+ @Path("/resources/validate-name/{resourceName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "validate resource name", httpMethod = "GET", notes = "checks if the chosen resource name is available ", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource found"), @ApiResponse(code = 403, message = "Restricted operation") })
+ public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}" , userId);
+ Response response = null;
+ try {
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+
+ if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {
+ log.debug("invalid resource type received");
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ return response;
+
+ }
+ ResourceTypeEnum typeEnum = null;
+ if (resourceType != null) {
+ typeEnum = ResourceTypeEnum.valueOf(resourceType);
+ }
+ Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateResourceNameExists(resourceName, typeEnum, userId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to validate resource name");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Resource Name");
+ log.debug("validate resource name failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/resources/certified/abstract")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ // TODO: any validations???
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}" , url);
+ Response response = null;
+ try {
+
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+
+ Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all abstract resources");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources");
+ log.debug("getCertifiedAbstractResources failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Path("/resources/certified/notabstract")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ // TODO: any vlidations???
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("(get) Start handle request of {}" , url);
+ Response response = null;
+
+ try {
+
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+
+ Either<List<Resource>, ResponseFormat> actionResponse = businessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get all non abstract resources");
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ Object resources = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resources);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources");
+ log.debug("getCertifiedNotAbstractResources failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+
+ }
+
+ @PUT
+ @Path("/resources/{resourceId}/metadata")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource Metadata", httpMethod = "PUT", notes = "Returns updated resource metadata", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource metadata updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content") })
+ public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource metadata to be updated", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+ String resourceIdLower = resourceId.toLowerCase();
+ Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
+ if (updateInfoResource.isRight()) {
+ log.debug("failed to parse resource metadata");
+ response = buildErrorResponse(updateInfoResource.right().value());
+ return response;
+ }
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update resource metadata");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource Metadata");
+ log.debug("Update Resource Metadata failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @PUT
+ @Path("/resources/{resourceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Resource", httpMethod = "PUT", notes = "Returns updated resource", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Resource already exist") })
+ public Response updateResource(@ApiParam(value = "Resource object to be updated", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @PathParam(value = "resourceId") String resourceId) {
+
+ userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
+ init(log);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ // UI Import
+ if (isUIImport(data)) {
+ performUIImport(responseWrapper, data, request, userId, resourceId);
+ } else {
+
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+
+ Either<Resource, ResponseFormat> convertResponse = parseToLightResource(data, modifier);
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse resource");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+
+ Resource resource = convertResponse.left().value();
+ Either<Resource, ResponseFormat> actionResponse = businessLogic.validateAndUpdateResourceFromCsar(resource, modifier, null, null, resourceId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update resource");
+ response = buildErrorResponse(actionResponse.right().value());
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
+ }
+ responseWrapper.setInnerElement(response);
+ }
+
+ return responseWrapper.getInnerElement();
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Resource");
+ log.debug("update resource failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) {
+ if (properties == null) {
+ return null;
+ }
+
+ List<PropertyDefinition> definitions = new ArrayList<>();
+ for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
+ String name = entry.getKey();
+ PropertyDefinition propertyDefinition = entry.getValue();
+ propertyDefinition.setName(name);
+ definitions.add(propertyDefinition);
+ }
+
+ return definitions;
+ }
+
+ @GET
+ @Path("/resources/csar/{csaruuid}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Resource", httpMethod = "POST", notes = "Returns resource created from csar uuid", response = Resource.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource retrieced"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @PathParam(value = "csaruuid") String csarUUID) {
+
+ init(log);
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}" , url);
+
+ // retrieve user details
+ userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
+ User user = new User();
+ user.setUserId(userId);
+
+ log.debug("user id is {}", userId);
+
+ Response response = null;
+
+ try {
+
+ ResourceBusinessLogic businessLogic = getResourceBL(context);
+
+ Either<Resource, ResponseFormat> eitherResource = businessLogic.getLatestResourceFromCsarUuid(csarUUID, user);
+
+ // validate response
+ if (eitherResource.isRight()) {
+ log.debug("failed to get resource from csarUuid : {}", csarUUID);
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), eitherResource.right().value());
+ } else {
+ Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
+ }
+
+ return response;
+
+ } catch (Exception e) {
+ log.debug("get resource by csar failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java
new file mode 100644
index 0000000000..f794e8c90b
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java
@@ -0,0 +1,243 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.google.common.collect.Sets;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import java.util.Collections;
+import java.util.Set;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
+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.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
+import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
+@Path("/v1/catalog/services/{serviceId}/paths")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+@Api(value = "Service Forwarding Path", description = "Service Forwarding Path Servlet")
+@Singleton
+public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
+
+ private static final Logger log = LoggerFactory.getLogger(ServiceForwardingPathServlet.class);
+
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/")
+ @ApiOperation(value = "Create Forwarding Path", httpMethod = "POST", notes = "Create Forwarding Path", response = Service.class)
+ @ApiResponses(value =
+ {@ApiResponse(code = 201, message = "Create Forwarding Path"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Forwarding Path already exist")})
+ public Response createForwardingPath(
+ @ApiParam(value = "Forwarding Path to create", required = true) String data,
+ @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ return createOrUpdate(data, serviceId, request, userId, false);
+ }
+
+
+
+ @PUT
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/")
+ @ApiOperation(value = "Update Forwarding Path", httpMethod = "PUT", notes = "Update Forwarding Path", response = Service.class)
+ @ApiResponses(value =
+ {@ApiResponse(code = 201, message = "Update Forwarding Path"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Forwarding Path already exist")})
+ public Response updateForwardingPath(
+ @ApiParam(value = "Update Path to create", required = true) String data,
+ @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ return createOrUpdate(data, serviceId, request, userId, true);
+ }
+
+ private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response;
+
+ try {
+ String serviceIdLower = serviceId.toLowerCase();
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+
+ Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse service");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+ Service updatedService = convertResponse.left().value();
+ Either<Service, ResponseFormat> actionResponse ;
+ if (isUpdate) {
+ actionResponse = businessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true);
+ } else {
+ actionResponse = businessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true);
+ }
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update or create paths");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Service service = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update");
+ log.debug("create or update forwarding path with an error", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @GET
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/{forwardingPathId}")
+ @ApiOperation(value = "Get Forwarding Path", httpMethod = "GET", notes = "GET Forwarding Path", response = ForwardingPathDataDefinition.class)
+ @ApiResponses(value =
+ {@ApiResponse(code = 201, message = "Get Forwarding Path"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Forwarding Path already exist")})
+ public Response getForwardingPath(
+ @ApiParam(value = "Forwarding Path to create", required = true) String datax,
+ @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
+ @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = businessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
+ if (serviceResponse.isRight()) {
+ return buildErrorResponse(serviceResponse.right().value());
+ }
+
+ UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value();
+
+ ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition();
+ if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) {
+ forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId);
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition));
+
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
+ log.debug("update service metadata failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/{forwardingPathId}")
+ @ApiOperation(value = "Delete Forwarding Path", httpMethod = "DELETE", notes = "Delete Forwarding Path", response = Service.class)
+ @ApiResponses(value =
+ {@ApiResponse(code = 201, message = "Delete Forwarding Path"),
+ @ApiResponse(code = 403, message = "Restricted operation"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Forwarding Path already exist")})
+ public Response deleteForwardingPath(
+ @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
+ @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response;
+
+ try {
+ String serviceIdLower = serviceId.toLowerCase();
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+
+ Either<Set<String>, ResponseFormat> actionResponse = businessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to delete paths");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Set<String> deletedPaths = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(deletedPaths);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths");
+ log.debug("Delete service paths with an error", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+
+ private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
+ return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
index cb90d89ed9..49a1a82e59 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
@@ -20,47 +20,19 @@
package org.openecomp.sdc.be.servlets;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.reflect.Type;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.reflect.TypeToken;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.*;
import org.apache.http.HttpStatus;
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datamodel.ServiceRelations;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
@@ -68,15 +40,17 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.reflect.TypeToken;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@@ -84,692 +58,629 @@ import io.swagger.annotations.ApiResponses;
@Singleton
public class ServiceServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(ServiceServlet.class.getName());
-
- @POST
- @Path("/services")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Service already exist") })
- public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
- if (convertResponse.isRight()) {
- log.debug("failed to parse service");
- response = buildErrorResponse(convertResponse.right().value());
- return response;
- }
-
- Service service = convertResponse.left().value();
- Either<Service, ResponseFormat> actionResponse = businessLogic.createService(service, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("Failed to create service");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service");
- log.debug("create service failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
- return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
- }
-
- @GET
- @Path("/services/validate-name/{serviceName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
- public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
-
- Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateServiceNameExists(serviceName, userId);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get validate service name");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
- log.debug("validate service name failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/audit-records/{componentType}/{componentUniqueId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
- public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
- init(log);
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
- Wrapper<Response> responseWrapper = new Wrapper<Response>();
- Wrapper<String> uuidWrapper = new Wrapper<>();
- Wrapper<String> versionWrapper = new Wrapper<>();
- Wrapper<User> userWrapper = new Wrapper<>();
- Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<ComponentTypeEnum>();
- try {
- validateUserExist(responseWrapper, userWrapper, userId);
-
- if (responseWrapper.isEmpty()) {
- validateComponentType(responseWrapper, componentWrapper, componentType);
- }
-
- if (responseWrapper.isEmpty()) {
- fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context);
- }
-
- if (responseWrapper.isEmpty()) {
- Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = getServiceBL(context).getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
-
- if (eitherServiceAudit.isRight()) {
- Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
- responseWrapper.setInnerElement(errorResponse);
- } else {
- List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();
- Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);
- responseWrapper.setInnerElement(okResponse);
-
- }
- }
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
- log.debug("get Service Audit Records failed with exception", e);
- Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- responseWrapper.setInnerElement(errorResponse);
- }
- return responseWrapper.getInnerElement();
- }
-
- private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
-
- if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
- Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user);
- if (eitherResource.isLeft()) {
- uuidWrapper.setInnerElement(eitherResource.left().value().getUUID());
- versionWrapper.setInnerElement(eitherResource.left().value().getVersion());
- } else {
- responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));
- }
-
- } else {
- Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user);
- if (eitherService.isLeft()) {
- uuidWrapper.setInnerElement(eitherService.left().value().getUUID());
- versionWrapper.setInnerElement(eitherService.left().value().getVersion());
- } else {
- responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));
-
- }
- }
- }
-
- @DELETE
- @Path("/services/{serviceId}")
- public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- String serviceIdLower = serviceId.toLowerCase();
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier);
-
- if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
- log.debug("failed to delete service");
- response = buildErrorResponse(actionResponse);
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
- log.debug("delete service failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @DELETE
- @Path("/services/{serviceName}/{version}")
- public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- ResponseFormat actionResponse = businessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
-
- if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
- log.debug("failed to delete service");
- response = buildErrorResponse(actionResponse);
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
- log.debug("delete service failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- @PUT
- @Path("/services/{serviceId}/metadata")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
-
- try {
- String serviceIdLower = serviceId.toLowerCase();
- ServiceBusinessLogic businessLogic = getServiceBL(context);
-
- Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
- if (convertResponse.isRight()) {
- log.debug("failed to parse service");
- response = buildErrorResponse(convertResponse.right().value());
- return response;
- }
- Service updatedService = convertResponse.left().value();
- Either<Service, ResponseFormat> actionResponse = businessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to update service");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Service service = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(service);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
- log.debug("update service metadata failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
- /**
- * updates group instance property values
- * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
- * @param serviceId
- * @param componentInstanceId
- * @param groupInstanceId
- * @param data
- * @param request
- * @param userId
- * @return
- */
- @PUT
- @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
- public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- Response response = null;
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}",userId);
-
- ServiceBusinessLogic businessLogic;
- Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
- try {
- List<GroupInstanceProperty> updatedProperties;
- Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
- ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
- if (newProperties == null) {
- actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
- }
- if(actionResponse == null){
- log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
- businessLogic = getServiceBL(context);
- actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
- if(actionResponse.isRight()){
- actionResponse = Either.right(actionResponse.right().value());
- }
- }
- if(actionResponse.isLeft()){
- updatedProperties = actionResponse.left().value();
- ObjectMapper mapper = new ObjectMapper();
- String result = mapper.writeValueAsString(updatedProperties);
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
- }
- else{
- response = buildErrorResponse(actionResponse.right().value());
- }
- } catch (Exception e) {
- log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return response;
- }
-
- @GET
- @Path("/services/{serviceId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
- public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- String serviceIdLower = serviceId.toLowerCase();
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- log.debug("get service with id {}", serviceId);
- Either<Service, ResponseFormat> actionResponse = businessLogic.getService(serviceIdLower, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to get service");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Service service = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(service);
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
- log.debug("get service failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @GET
- @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
- public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
- @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- // get modifier id
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- Either<Service, ResponseFormat> actionResponse = businessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
-
- if (actionResponse.isRight()) {
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
-
- Service service = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(service);
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
- log.debug("get service failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
- }
- }
-
- @POST
- @Path("/services/{serviceId}/distribution-state/{state}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status")
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"),
- @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
- public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId,
- @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- Either<Service, ResponseFormat> actionResponse = businessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier);
-
- if (actionResponse.isRight()) {
- log.debug("failed to Update Service Distribution State");
- response = buildErrorResponse(actionResponse.right().value());
- return response;
- }
- Service service = actionResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(service);
-
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State");
- log.debug("updateServiceDistributionState failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @POST
- @Path("/services/{serviceId}/distribution/{env}/activate")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution")
- @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"),
- @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
- public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- Either<Service, ResponseFormat> distResponse = businessLogic.activateDistribution(serviceId, env, modifier, request);
-
- if (distResponse.isRight()) {
- log.debug("failed to activate service distribution");
- response = buildErrorResponse(distResponse.right().value());
- return response;
- }
- Service service = distResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(service);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
- log.debug("activate distribution failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @POST
- @Path("/services/{serviceId}/distribution/{did}/markDeployed")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created")
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"),
- @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
- public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- Either<Service, ResponseFormat> distResponse = businessLogic.markDistributionAsDeployed(serviceId, did, modifier);
-
- if (distResponse.isRight()) {
- log.debug("failed to mark distribution as deployed");
- response = buildErrorResponse(distResponse.right().value());
- return response;
- }
- Service service = distResponse.left().value();
- Object result = RepresentationUtils.toRepresentation(service);
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
- log.debug("mark distribution as deployed failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @POST
- @Path("/services/{serviceId}/tempUrlToBeDeleted")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
- public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User modifier = new User();
- modifier.setUserId(userId);
- log.debug("modifier id is {}", userId);
-
- Response response = null;
- try {
- ServiceBusinessLogic businessLogic = getServiceBL(context);
- Service service = (businessLogic.getService(serviceId, modifier)).left().value();
- Either<Service, ResponseFormat> res = (businessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED));
-
- if (res.isRight()) {
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
- log.debug("failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
- }
- }
-
- @GET
- @Path("/services/toscatoheat/{artifactName}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
- @ApiResponse(code = 404, message = "Artifact not found") })
- public Response downloadServiceArtifact(@PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) {
- Response response = null;
-
- try {
- log.debug("artifact name = {}", artifactName);
-
- Either<byte[], ResponseFormat> executeCommand = executeCommand(artifactName);
-
- if (executeCommand.isRight()) {
- log.debug("Failed to convert tosca {} to heat", artifactName);
- ResponseFormat responseFormat = executeCommand.right().value();
- response = buildErrorResponse(responseFormat);
- } else {
- log.debug("Succeed to convert tosca {} to heat", artifactName);
- byte[] value = executeCommand.left().value();
- InputStream is = new ByteArrayInputStream(value);
-
- Map<String, String> headers = new HashMap<>();
- String heatFileName;
- if (artifactName.indexOf(".") > -1) {
- heatFileName = artifactName.substring(0, artifactName.indexOf(".")) + ".heat";
- } else {
- heatFileName = artifactName + ".heat";
- }
- headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(heatFileName));
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
- response = buildOkResponse(responseFormat, is, headers);
- }
- return response;
-
- } catch (Exception e) {
- log.error("download artifact failed with exception", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- private Either<byte[], ResponseFormat> executeCommand(String artifactName) {
-
- Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
- String toscaFilesDir = configuration.getToscaFilesDir();
- if (toscaFilesDir == null) {
- toscaFilesDir = "/apps/jetty/base/be/config/tosca";
- }
- String heatTranslator = configuration.getHeatTranslatorPath();
- if (heatTranslator == null) {
- heatTranslator = "/home/m98835/heat-translator-0.3.0/heat_translator.py";
- }
-
- log.debug("toscaFilesDir= {} | heatTranslator= {}", toscaFilesDir, heatTranslator);
-
- StringBuffer output = new StringBuffer();
-
- String heatHeader = configuration.getHeatEnvArtifactHeader();
- String heatFooter = configuration.getHeatEnvArtifactFooter();
-
- output.append(heatHeader + "\n");
-
- MessageFormat mf = new MessageFormat("python {0} --template-file={1}/{2} --template-type=tosca");
-
- log.debug("After creating message format");
-
- Object[] objArray = { heatTranslator, toscaFilesDir, artifactName };
- String command = null;
- try {
- command = mf.format(objArray);
- } catch (Exception e) {
- log.debug("Failed to convert message format", e);
- }
-
- log.debug("Going to run command {}", command);
-
- Process p;
- try {
- p = Runtime.getRuntime().exec(command);
- int waitFor = p.waitFor();
- log.debug("waitFor = {}", waitFor);
-
- if (waitFor != 0) {
- log.error("Failed runnign the command {}", command);
- return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
- }
-
- BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
-
- String line;
- while ((line = reader.readLine()) != null) {
- output.append(line + "\n");
- }
-
- } catch (Exception e) {
- log.error("Failed runnign the command {}", command, e);
- return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- output.append(heatFooter);
-
- return Either.left(output.toString().getBytes());
-
- }
+ private static final Logger log = LoggerFactory.getLogger(ServiceServlet.class);
+
+ @POST
+ @Path("/services")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Service", httpMethod = "POST", notes = "Returns created service", response = Service.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Service already exist") })
+ public Response createService(@ApiParam(value = "Service object to be created", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse service");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+
+ Service service = convertResponse.left().value();
+ Either<Service, ResponseFormat> actionResponse = businessLogic.createService(service, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("Failed to create service");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Service");
+ log.debug("create service failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
+ return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+ }
+
+ @GET
+ @Path("/services/validate-name/{serviceName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "validate service name", httpMethod = "GET", notes = "checks if the chosen service name is available ", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
+ public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+ Response response = null;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+
+ Either<Map<String, Boolean>, ResponseFormat> actionResponse = businessLogic.validateServiceNameExists(serviceName, userId);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get validate service name");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
+ log.debug("validate service name failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/audit-records/{componentType}/{componentUniqueId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "get component audit records", httpMethod = "GET", notes = "get audit records for a service or a resource", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation") })
+ public Response getComponentAuditRecords(@PathParam("componentType") final String componentType, @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ init(log);
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+ Wrapper<Response> responseWrapper = new Wrapper<Response>();
+ Wrapper<String> uuidWrapper = new Wrapper<>();
+ Wrapper<String> versionWrapper = new Wrapper<>();
+ Wrapper<User> userWrapper = new Wrapper<>();
+ Wrapper<ComponentTypeEnum> componentWrapper = new Wrapper<ComponentTypeEnum>();
+ try {
+ validateUserExist(responseWrapper, userWrapper, userId);
+
+ if (responseWrapper.isEmpty()) {
+ validateComponentType(responseWrapper, componentWrapper, componentType);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), componentWrapper.getInnerElement(), componentUniqueId, context);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = getServiceBL(context).getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
+
+ if (eitherServiceAudit.isRight()) {
+ Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
+ responseWrapper.setInnerElement(errorResponse);
+ } else {
+ List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();
+ Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);
+ responseWrapper.setInnerElement(okResponse);
+
+ }
+ }
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
+ log.debug("get Service Audit Records failed with exception", e);
+ Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(errorResponse);
+ }
+ return responseWrapper.getInnerElement();
+ }
+
+ private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
+
+ if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
+ Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user);
+ if (eitherResource.isLeft()) {
+ uuidWrapper.setInnerElement(eitherResource.left().value().getUUID());
+ versionWrapper.setInnerElement(eitherResource.left().value().getVersion());
+ } else {
+ responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));
+ }
+
+ } else {
+ Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user);
+ if (eitherService.isLeft()) {
+ uuidWrapper.setInnerElement(eitherService.left().value().getUUID());
+ versionWrapper.setInnerElement(eitherService.left().value().getVersion());
+ } else {
+ responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));
+
+ }
+ }
+ }
+
+ @DELETE
+ @Path("/services/{serviceId}")
+ public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ String serviceIdLower = serviceId.toLowerCase();
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier);
+
+ if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
+ log.debug("failed to delete service");
+ response = buildErrorResponse(actionResponse);
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
+ log.debug("delete service failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @DELETE
+ @Path("/services/{serviceName}/{version}")
+ public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ ResponseFormat actionResponse = businessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
+
+ if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
+ log.debug("failed to delete service");
+ response = buildErrorResponse(actionResponse);
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
+ log.debug("delete service failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ @PUT
+ @Path("/services/{serviceId}/metadata")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Service Metadata", httpMethod = "PUT", notes = "Returns updated service", response = Service.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId, @ApiParam(value = "Service object to be Updated", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+
+ try {
+ String serviceIdLower = serviceId.toLowerCase();
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+
+ Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
+ if (convertResponse.isRight()) {
+ log.debug("failed to parse service");
+ response = buildErrorResponse(convertResponse.right().value());
+ return response;
+ }
+ Service updatedService = convertResponse.left().value();
+ Either<Service, ResponseFormat> actionResponse = businessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to update service");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Service service = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
+ log.debug("update service metadata failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+ /**
+ * updates group instance property values
+ * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
+ * @param serviceId
+ * @param componentInstanceId
+ * @param groupInstanceId
+ * @param data
+ * @param request
+ * @param userId
+ * @return
+ */
+ @PUT
+ @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Group Instance Property Values", httpMethod = "PUT", notes = "Returns updated group instance", response = Service.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Group Instance Property Values Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,@PathParam("componentInstanceId") final String componentInstanceId, @PathParam("groupInstanceId") final String groupInstanceId, @ApiParam(value = "Group instance object to be Updated", required = true) String data, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ Response response = null;
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}",userId);
+
+ ServiceBusinessLogic businessLogic;
+ Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
+ try {
+ List<GroupInstanceProperty> updatedProperties;
+ Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
+ ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
+ if (newProperties == null) {
+ actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+ }
+ if(actionResponse == null){
+ log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
+ businessLogic = getServiceBL(context);
+ actionResponse = businessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
+ if(actionResponse.isRight()){
+ actionResponse = Either.right(actionResponse.right().value());
+ }
+ }
+ if(actionResponse.isLeft()){
+ updatedProperties = actionResponse.left().value();
+ ObjectMapper mapper = new ObjectMapper();
+ String result = mapper.writeValueAsString(updatedProperties);
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+ }
+ else{
+ response = buildErrorResponse(actionResponse.right().value());
+ }
+ } catch (Exception e) {
+ log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return response;
+ }
+
+ @GET
+ @Path("/services/{serviceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to serviceId", response = Service.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
+ public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ String serviceIdLower = serviceId.toLowerCase();
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ log.debug("get service with id {}", serviceId);
+ Either<Service, ResponseFormat> actionResponse = businessLogic.getService(serviceIdLower, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get service");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Service service = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
+ log.debug("get service failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @GET
+ @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Service", httpMethod = "GET", notes = "Returns service according to name and version", response = Service.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
+ public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Either<Service, ResponseFormat> actionResponse = businessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
+
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ Service service = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
+ log.debug("get service failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
+
+ @POST
+ @Path("/services/{serviceId}/distribution-state/{state}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update Service Distribution State", httpMethod = "POST", notes = "service with the changed distribution status")
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service distribution state changed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available for distribution"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
+ public Response updateServiceDistributionState(@ApiParam(value = "DistributionChangeInfo - get comment out of body", required = true) LifecycleChangeInfoWithAction jsonChangeInfo, @PathParam("serviceId") final String serviceId,
+ @ApiParam(allowableValues = "approve, reject", required = true) @PathParam("state") final String state, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Either<Service, ResponseFormat> actionResponse = businessLogic.changeServiceDistributionState(serviceId, state, jsonChangeInfo, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to Update Service Distribution State");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+ Service service = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Distribution State");
+ log.debug("updateServiceDistributionState failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @POST
+ @Path("/services/{serviceId}/distribution/{env}/activate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Activate distribution", httpMethod = "POST", notes = "activate distribution")
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Service cannot be distributed due to missing deployment artifacts"), @ApiResponse(code = 404, message = "Requested service was not found"),
+ @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
+ public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Either<Service, ResponseFormat> distResponse = businessLogic.activateDistribution(serviceId, env, modifier, request);
+
+ if (distResponse.isRight()) {
+ log.debug("failed to activate service distribution");
+ response = buildErrorResponse(distResponse.right().value());
+ return response;
+ }
+ Service service = distResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
+ log.debug("activate distribution failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @POST
+ @Path("/services/{serviceId}/distribution/{did}/markDeployed")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Mark distribution as deployed", httpMethod = "POST", notes = "relevant audit record will be created")
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service was marked as deployed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 403, message = "Service is not available"),
+ @ApiResponse(code = 400, message = "Invalid content / Missing content"), @ApiResponse(code = 404, message = "Requested service was not found"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
+ public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Either<Service, ResponseFormat> distResponse = businessLogic.markDistributionAsDeployed(serviceId, did, modifier);
+
+ if (distResponse.isRight()) {
+ log.debug("failed to mark distribution as deployed");
+ response = buildErrorResponse(distResponse.right().value());
+ return response;
+ }
+ Service service = distResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(service);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
+ log.debug("mark distribution as deployed failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+ @POST
+ @Path("/services/{serviceId}/tempUrlToBeDeleted")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Internal Server Error. Please try again later.") })
+ public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response;
+ try {
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ Service service = (businessLogic.getService(serviceId, modifier)).left().value();
+ Either<Service, ResponseFormat> res = businessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
+
+ if (res.isRight()) {
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
+ log.debug("failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+ }
+ }
+
+
+ @GET
+ @Path("/services/{serviceId}/linksMap")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve Service component relations map", httpMethod = "GET", notes = "Returns service components relations", response = ServiceRelations.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Service found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Service not found") })
+ public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(userId);
+ log.debug("modifier id is {}", userId);
+
+ Response response = null;
+ try {
+ String serviceIdLower = serviceId.toLowerCase();
+ ServiceBusinessLogic businessLogic = getServiceBL(context);
+ log.debug("get service components relations with id {}", serviceId);
+ Either<ServiceRelations, ResponseFormat> actionResponse = businessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
+
+ if (actionResponse.isRight()) {
+ log.debug("failed to get service relations data");
+ response = buildErrorResponse(actionResponse.right().value());
+ return response;
+ }
+
+ ServiceRelations serviceRelations = actionResponse.left().value();
+ Object result = RepresentationUtils.toRepresentation(serviceRelations);
+
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
+ log.debug("get service relations data failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java
new file mode 100644
index 0000000000..fce8dd009e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/StorageExceptionMapper.java
@@ -0,0 +1,36 @@
+package org.openecomp.sdc.be.servlets;
+
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Component;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+@Component
+@Provider
+public class StorageExceptionMapper implements ExceptionMapper<StorageException> {
+
+ private final ComponentsUtils componentsUtils;
+ protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ public StorageExceptionMapper(ComponentsUtils componentsUtils) {
+ this.componentsUtils = componentsUtils;
+ }
+
+ @Override
+ public Response toResponse(StorageException exception) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(exception.getStorageOperationStatus());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus);
+ return Response.status(responseFormat.getStatus())
+ .entity(gson.toJson(responseFormat.getRequestError()))
+ .build();
+ }
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java
index eea2bfdc42..a30cd3c7b2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ToscaDaoServlet.java
@@ -20,9 +20,6 @@
package org.openecomp.sdc.be.servlets;
-import javax.servlet.ServletContext;
-import javax.ws.rs.core.Response;
-
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.impl.DownloadArtifactLogic;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
@@ -33,60 +30,45 @@ import org.openecomp.sdc.common.config.EcompErrorName;
import org.slf4j.Logger;
import org.springframework.web.context.WebApplicationContext;
+import javax.servlet.ServletContext;
+import javax.ws.rs.core.Response;
+
public abstract class ToscaDaoServlet extends BeGenericServlet {
- public abstract Logger getLogger();
-
- protected IResourceUploader getResourceUploader(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- if (webApplicationContextWrapper == null) {
- getLogger().error("Failed to get web application context from context.");
- return null;
- }
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-
- return webApplicationContext.getBean(IResourceUploader.class);
-
- }
-
- // protected IToscaYamlBuilder getToscaYamlBuilder(ServletContext context){
- // WebAppContextWrapper webApplicationContextWrapper =
- // (WebAppContextWrapper) context
- // .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- //
- // if (webApplicationContextWrapper == null) {
- // getLogger().error("Failed to get web application context from context.");
- // return null;
- // }
- //
- // WebApplicationContext webApplicationContext =
- // webApplicationContextWrapper
- // .getWebAppContext(context);
- //
- // return webApplicationContext.getBean(IToscaYamlBuilder.class);
- //
- // }
-
- protected DownloadArtifactLogic getLogic(ServletContext context) {
- DownloadArtifactLogic downloadLogic = (DownloadArtifactLogic) context.getAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR);
-
- if (downloadLogic == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInitializationError, "DownloadArtifactLogic from context");
- BeEcompErrorManager.getInstance().logBeInitializationError("DownloadArtifactLogic from context");
- return null;
- }
- return downloadLogic;
- }
-
- protected Response buildResponse(int status, String errorMessage) {
-
- ServletJsonResponse jsonResponse = new ServletJsonResponse();
- jsonResponse.setDescription(errorMessage);
- jsonResponse.setSource(Constants.CATALOG_BE);
-
- Response response = Response.status(status).entity(jsonResponse).build();
-
- return response;
- }
+ public abstract Logger getLogger();
+
+ protected IResourceUploader getResourceUploader(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+
+ if (webApplicationContextWrapper == null) {
+ getLogger().error("Failed to get web application context from context.");
+ return null;
+ }
+
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+
+ return webApplicationContext.getBean(IResourceUploader.class);
+
+ }
+
+
+ protected DownloadArtifactLogic getLogic(ServletContext context) {
+ DownloadArtifactLogic downloadLogic = (DownloadArtifactLogic) context.getAttribute(Constants.DOWNLOAD_ARTIFACT_LOGIC_ATTR);
+
+ if (downloadLogic == null) {
+ BeEcompErrorManager.getInstance().logBeInitializationError("DownloadArtifactLogic from context");
+ return null;
+ }
+ return downloadLogic;
+ }
+
+ protected Response buildResponse(int status, String errorMessage) {
+
+ ServletJsonResponse jsonResponse = new ServletJsonResponse();
+ jsonResponse.setDescription(errorMessage);
+ jsonResponse.setSource(Constants.CATALOG_BE);
+
+ Response response = Response.status(status).entity(jsonResponse).build();
+
+ return response;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
index 3ad15961e7..9829566a12 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
@@ -20,20 +20,12 @@
package org.openecomp.sdc.be.servlets;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -48,77 +40,75 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import javax.inject.Singleton;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Map;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
@Api(value = "Types Fetch Servlet", description = "Types Fetch Servlet")
@Singleton
public class TypesFetchServlet extends AbstractValidationsServlet {
- private static Logger log = LoggerFactory.getLogger(TypesFetchServlet.class.getName());
-
- @GET
- @Path("dataTypes")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 404, message = "Data types not found") })
- public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
- Wrapper<Response> responseWrapper = new Wrapper<Response>();
- Wrapper<User> userWrapper = new Wrapper<User>();
- ServletContext context = request.getSession().getServletContext();
-
- try {
- init(log);
- validateUserExist(responseWrapper, userWrapper, userId);
-
- if (responseWrapper.isEmpty()) {
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
- PropertyBusinessLogic businessLogic = getPropertyBL(context);
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes();
-
- if (allDataTypes.isRight()) {
- log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value());
- Response errorResponse = buildErrorResponse(allDataTypes.right().value());
- responseWrapper.setInnerElement(errorResponse);
-
- // return buildErrorResponse(allDataTypes.right().value());
- } else {
-
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
- String dataTypeJson = gson.toJson(dataTypes);
- Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
- responseWrapper.setInnerElement(okResponse);
-
- }
- }
-
- return responseWrapper.getInnerElement();
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get all data types");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property");
- log.debug("get all data types failed with exception", e);
- ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(responseFormat);
- }
- }
-
- private PropertyBusinessLogic getPropertyBL(ServletContext context) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class);
- return propertytBl;
- }
+ private static final Logger log = LoggerFactory.getLogger(TypesFetchServlet.class);
+
+ @GET
+ @Path("dataTypes")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Get data types", httpMethod = "GET", notes = "Returns data types", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "datatypes"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 404, message = "Data types not found") })
+ public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+
+ Wrapper<Response> responseWrapper = new Wrapper<Response>();
+ Wrapper<User> userWrapper = new Wrapper<User>();
+ ServletContext context = request.getSession().getServletContext();
+
+ try {
+ init(log);
+ validateUserExist(responseWrapper, userWrapper, userId);
+
+ if (responseWrapper.isEmpty()) {
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {} | modifier id is {}", url, userId);
+
+ PropertyBusinessLogic businessLogic = getPropertyBL(context);
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = businessLogic.getAllDataTypes();
+
+ if (allDataTypes.isRight()) {
+ log.info("Failed to get all dara types. Reason - {}", allDataTypes.right().value());
+ Response errorResponse = buildErrorResponse(allDataTypes.right().value());
+ responseWrapper.setInnerElement(errorResponse);
+
+ } else {
+
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+ String dataTypeJson = gson.toJson(dataTypes);
+ Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
+ responseWrapper.setInnerElement(okResponse);
+
+ }
+ }
+
+ return responseWrapper.getInnerElement();
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property");
+ log.debug("get all data types failed with exception", e);
+ ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return buildErrorResponse(responseFormat);
+ }
+ }
+
+ private PropertyBusinessLogic getPropertyBL(ServletContext context) {
+ WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+ WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+ PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class);
+ return propertytBl;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
index bb0be372bf..92f15c4a1d 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
@@ -20,27 +20,13 @@
package org.openecomp.sdc.be.servlets;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;
@@ -52,7 +38,6 @@ import org.openecomp.sdc.be.components.impl.PolicyTypeImportManager;
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.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
@@ -63,244 +48,256 @@ import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.web.context.WebApplicationContext;
-
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
+import org.springframework.stereotype.Controller;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog/uploadType")
-@Api(value = "Catalog Types Upload", description = "Upload Type from yaml")
-@Singleton
+@Api(value = "Catalog Types Upload")
+@Controller
public class TypesUploadServlet extends AbstractValidationsServlet {
- @Resource
- private CapabilityTypeImportManager capabilityTypeImportManager;
-
- @Resource
- private InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager;
-
- @Resource
- private CategoriesImportManager categoriesImportManager;
-
- @Resource
- private DataTypeImportManager dataTypeImportManager;
-
- @Resource
- private GroupTypeImportManager groupTypeImportManager;
-
- @Resource
- private PolicyTypeImportManager policyTypeImportManager;
-
- private static Logger log = LoggerFactory.getLogger(TypesUploadServlet.class.getName());
-
- @POST
- @Path("/capability")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Capability Type already exist") })
- public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
- capabilityTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CapabilityTypeImportManager.class);
- ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));
- return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name());
- }
-
- @POST
- @Path("/interfaceLifecycle")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") })
- public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
- interfaceLifecycleTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> InterfaceLifecycleTypeImportManager.class);
- ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));
- return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types");
- }
-
- @POST
- @Path("/categories")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Category already exist") })
- public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
- categoriesImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> CategoriesImportManager.class);
- ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload));
- return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories");
- }
-
- @POST
- @Path("/datatypes")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "Data types already exist") })
- public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
- dataTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> DataTypeImportManager.class);
- ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload);
- return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName());
- }
-
- @POST
- @Path("/grouptypes")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "group types already exist") })
- public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
- groupTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> GroupTypeImportManager.class);
- ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload);
- return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName());
- }
-
- @POST
- @Path("/policytypes")
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
- @ApiResponse(code = 409, message = "policy types already exist") })
- public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
- policyTypeImportManager = initElementTypeImportManager(request.getSession().getServletContext(), () -> PolicyTypeImportManager.class);
- ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createPolicyTypes(responseWrapper, ymlPayload);
- return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.PolicyType.getName());
- }
-
- private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) {
- init(log);
- String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);
- try {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- Wrapper<User> userWrapper = new Wrapper<>();
- Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- validateUserExist(responseWrapper, userWrapper, userId);
-
- if (responseWrapper.isEmpty()) {
- validateUserRole(responseWrapper, userWrapper.getInnerElement());
- }
-
- if (responseWrapper.isEmpty()) {
- validateDataNotNull(responseWrapper, file);
- }
-
- if (responseWrapper.isEmpty()) {
- fillZipContents(yamlStringWrapper, file);
- }
-
- if (responseWrapper.isEmpty()) {
- createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement());
- }
-
- return responseWrapper.getInnerElement();
-
- } catch (Exception e) {
- log.debug("create {} failed with exception:", elementTypeName, e);
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- private <T> void createElementsType(Wrapper<Response> responseWrapper, Supplier<Either<T, ResponseFormat>> elementsCreater) {
- Either<T, ResponseFormat> eitherResult = elementsCreater.get();
- if (eitherResult.isRight()) {
- Response response = buildErrorResponse(eitherResult.right().value());
- responseWrapper.setInnerElement(response);
- } else {
- try {
- Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value()));
- responseWrapper.setInnerElement(response);
- } catch (Exception e) {
- Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- responseWrapper.setInnerElement(response);
- }
- }
- }
-
- // data types
- private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) {
- final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml);
- buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name());
- }
-
- // group types
- private void createGroupTypes(Wrapper<Response> responseWrapper, String groupTypesYml) {
- final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml);
- buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name());
- }
-
- // policy types
- private void createPolicyTypes(Wrapper<Response> responseWrapper, String policyTypesYml) {
- final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml);
- buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name());
- }
-
- // data types
- private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) {
- Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get();
-
- if (eitherResult.isRight()) {
- Response response = buildErrorResponse(eitherResult.right().value());
- responseWrapper.setInnerElement(response);
- } else {
- Object representation;
- try {
- List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value();
- ActionStatus status = ActionStatus.OK;
- if (list != null) {
-
- // Group result by the right value - true or false.
- // I.e., get the number of data types which are new and
- // which are old.
- Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight));
- if (collect != null) {
- Set<Boolean> keySet = collect.keySet();
- if (keySet.size() == 1) {
- Boolean isNew = keySet.iterator().next();
- if (isNew.booleanValue() == true) {
- // all data types created at the first time
- status = ActionStatus.CREATED;
- } else {
- // All data types already exists
-
- status = alreadyExistStatus;
- }
- }
- }
- }
- representation = RepresentationUtils.toRepresentation(eitherResult.left().value());
-
- Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation);
- responseWrapper.setInnerElement(response);
-
- } catch (IOException e) {
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName);
- log.debug("failed to convert {} to json", elementTypeName, e);
- Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- responseWrapper.setInnerElement(response);
- }
- }
- }
-
- private <T> T initElementTypeImportManager(ServletContext context, Supplier<Class<T>> classGetter) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
- T elementTypeImortManager = webApplicationContext.getBean(classGetter.get());
- return elementTypeImortManager;
- }
+ private static final Logger log = LoggerFactory.getLogger(TypesUploadServlet.class);
+ private CapabilityTypeImportManager capabilityTypeImportManager;
+
+ private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager;
+
+ private final CategoriesImportManager categoriesImportManager;
+
+ private final DataTypeImportManager dataTypeImportManager;
+
+ private final GroupTypeImportManager groupTypeImportManager;
+
+ private final PolicyTypeImportManager policyTypeImportManager;
+
+ public TypesUploadServlet(CapabilityTypeImportManager capabilityTypeImportManager, InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager, CategoriesImportManager categoriesImportManager, DataTypeImportManager dataTypeImportManager, GroupTypeImportManager groupTypeImportManager, PolicyTypeImportManager policyTypeImportManager) {
+ this.capabilityTypeImportManager = capabilityTypeImportManager;
+ this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager;
+ this.categoriesImportManager = categoriesImportManager;
+ this.dataTypeImportManager = dataTypeImportManager;
+ this.groupTypeImportManager = groupTypeImportManager;
+ this.policyTypeImportManager = policyTypeImportManager;
+ }
+
+ @POST
+ @Path("/capability")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Capability Type from yaml", httpMethod = "POST", notes = "Returns created Capability Type", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Capability Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Capability Type already exist") })
+ public Response uploadCapabilityType(@ApiParam("FileInputStream") @FormDataParam("capabilityTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+ ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));
+ return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name());
+ }
+
+ @POST
+ @Path("/interfaceLifecycle")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Interface Lyfecycle Type from yaml", httpMethod = "POST", notes = "Returns created Interface Lifecycle Type", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Interface Lifecycle Type created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Interface Lifecycle Type already exist") })
+ public Response uploadInterfaceLifecycleType(@ApiParam("FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+ ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));
+ return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types");
+ }
+
+ @POST
+ @Path("/categories")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created categories", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Categories created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Category already exist") })
+ public Response uploadCategories(@ApiParam("FileInputStream") @FormDataParam("categoriesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+ ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper, () -> categoriesImportManager.createCategories(ymlPayload));
+ return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories");
+ }
+
+ @POST
+ @Path("/datatypes")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create Categories from yaml", httpMethod = "POST", notes = "Returns created data types", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Data types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Data types already exist") })
+ public Response uploadDataTypes(@ApiParam("FileInputStream") @FormDataParam("dataTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+ ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createDataTypes(responseWrapper, ymlPayload);
+ return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName());
+ }
+
+ @POST
+ @Path("/grouptypes")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create GroupTypes from yaml", httpMethod = "POST", notes = "Returns created group types", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "group types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "group types already exist") })
+ public Response uploadGroupTypes(@ApiParam("FileInputStream") @FormDataParam("groupTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+ ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createGroupTypes(responseWrapper, ymlPayload);
+ return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.GroupType.getName());
+ }
+
+ @POST
+ @Path("/policytypes")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create PolicyTypes from yaml", httpMethod = "POST", notes = "Returns created policy types", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "policy types created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "policy types already exist") })
+ public Response uploadPolicyTypes(@ApiParam("FileInputStream") @FormDataParam("policyTypesZip") File file, @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+ return uploadElementTypeServletLogic(this::createPolicyTypes, file, request, creator, NodeTypeEnum.PolicyType.getName());
+ }
+
+ private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) {
+ init(log);
+ String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);
+ try {
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ Wrapper<User> userWrapper = new Wrapper<>();
+ Wrapper<String> yamlStringWrapper = new Wrapper<>();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ validateUserExist(responseWrapper, userWrapper, userId);
+
+ if (responseWrapper.isEmpty()) {
+ validateUserRole(responseWrapper, userWrapper.getInnerElement());
+ }
+
+ if (responseWrapper.isEmpty()) {
+ validateDataNotNull(responseWrapper, file);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ fillZipContents(yamlStringWrapper, file);
+ }
+
+ if (responseWrapper.isEmpty()) {
+ createElementsMethod.accept(responseWrapper, yamlStringWrapper.getInnerElement());
+ }
+
+ return responseWrapper.getInnerElement();
+
+ } catch (Exception e) {
+ log.debug("create {} failed with exception:", elementTypeName, e);
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ private <T> void createElementsType(Wrapper<Response> responseWrapper, Supplier<Either<T, ResponseFormat>> elementsCreater) {
+ Either<T, ResponseFormat> eitherResult = elementsCreater.get();
+ if (eitherResult.isRight()) {
+ Response response = buildErrorResponse(eitherResult.right().value());
+ responseWrapper.setInnerElement(response);
+ } else {
+ try {
+ Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value()));
+ responseWrapper.setInnerElement(response);
+ } catch (Exception e) {
+ Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(response);
+ log.error("#createElementsType - json serialization failed with error: ", e);
+ }
+ }
+ }
+
+ // data types
+ private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) {
+ final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager.createDataTypes(dataTypesYml);
+ buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name());
+ }
+
+ // group types
+ private void createGroupTypes(Wrapper<Response> responseWrapper, String groupTypesYml) {
+ final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager.createGroupTypes(groupTypesYml);
+ buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name());
+ }
+
+ // policy types
+ private void createPolicyTypes(Wrapper<Response> responseWrapper, String policyTypesYml) {
+ final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager.createPolicyTypes(policyTypesYml);
+ buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name());
+ }
+
+ // data types
+ private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) {
+ Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get();
+
+ if (eitherResult.isRight()) {
+ Response response = buildErrorResponse(eitherResult.right().value());
+ responseWrapper.setInnerElement(response);
+ } else {
+ Object representation;
+ try {
+ List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value();
+ ActionStatus status = ActionStatus.OK;
+ if (list != null) {
+
+ // Group result by the right value - true or false.
+ // I.e., get the number of data types which are new and
+ // which are old.
+ Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight));
+ if (collect != null) {
+ Set<Boolean> keySet = collect.keySet();
+ if (keySet.size() == 1) {
+ Boolean isNew = keySet.iterator().next();
+ if (isNew.booleanValue()) {
+ // all data types created at the first time
+ status = ActionStatus.CREATED;
+ } else {
+ // All data types already exists
+
+ status = alreadyExistStatus;
+ }
+ }
+ }
+ }
+ representation = RepresentationUtils.toRepresentation(eitherResult.left().value());
+
+ Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation);
+ responseWrapper.setInnerElement(response);
+
+ } catch (IOException e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create " + elementTypeName);
+ log.debug("failed to convert {} to json", elementTypeName, e);
+ Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ responseWrapper.setInnerElement(response);
+ }
+ }
+ }
}
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 a6f6359ac1..c9ea5dd951 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
@@ -20,10 +20,22 @@
package org.openecomp.sdc.be.servlets;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.List;
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+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;
import javax.inject.Singleton;
import javax.servlet.ServletContext;
@@ -40,437 +52,352 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
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.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.jcabi.aspects.Loggable;
-
-import fj.data.Either;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-import io.swagger.annotations.ApiResponse;
-import io.swagger.annotations.ApiResponses;
-
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.List;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/user")
@Api(value = "User Administration", description = "User admininstarator operations")
@Singleton
public class UserAdminServlet extends BeGenericServlet {
- private static final String ROLE_DELIMITER = ",";
- private static Logger log = LoggerFactory.getLogger(UserAdminServlet.class.getName());
-
- /***************************************
- * API start
- *************************************************************/
-
- /* User by userId CRUD start */
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve all user details
- @GET
- @Path("/{userId}")
- @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 get(@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<User, ActionStatus> either = userAdminManager.getUser(userId, false);
-
- if (either.isRight()) {
- return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
- } else {
- if (either.left().value() != null) {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- } else {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");
- log.debug("get user failed with unexpected error: {}", e.getMessage(), e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // update user - internal API
- /*
- * @POST
- *
- * @Path("/{userId}")
- *
- * @Consumes(MediaType.APPLICATION_JSON)
- *
- * @Produces(MediaType.APPLICATION_JSON)
- *
- * @ApiOperation(value = "update user - internal API", notes = "Update user", response = User.class)
- *
- * @ApiResponses(value = {
- *
- * @ApiResponse(code = 200, message = "Update user OK"),
- *
- * @ApiResponse(code = 400, message = "Invalid Content."),
- *
- * @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
- *
- * @ApiResponse(code = 404, message = "User not found"),
- *
- * @ApiResponse(code = 405, message = "Method Not Allowed"),
- *
- * @ApiResponse(code = 409, message = "User already exists"),
- *
- * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String userIdUpdateUser,
- *
- * @Context final HttpServletRequest request,
- *
- * @ApiParam(value="json describe the update user", required=true) String data,
- *
- * @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
- *
- * ServletContext context = request.getSession().getServletContext();
- *
- * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url);
- *
- * // get modifier id User modifier = new User(); modifier.setUserId(modifierAttId); log.debug("modifier id is {}", modifierAttId);
- *
- * Response response = null;
- *
- * try { UserAdminBuisinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); Either<User, ResponseFormat>
- * updateUserResponse = null;// businessLogic.updateUser(modifier, userIdUpdateUser, updateInfoUser);
- *
- * if (updateUserResponse.isRight()) { log.debug("failed to update user metadata"); response = buildErrorResponse(updateUserResponse.right().value()); return response; } response =
- * buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); return response;
- *
- * } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Update User Metadata"); log.debug("Update User Metadata failed with exception", e); response =
- * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response;
- *
- * } }
- *
- */
- /* User userId CRUD end */
-
- /* User role CRUD start */
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // retrieve user role
- @GET
- @Path("/{userId}/role")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"),
- @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getRole(@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("(getRole) Start handle request of {}", url);
-
- UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
-
- try {
- Either<User, ActionStatus> either = userAdminManager.getUser(userId, false);
- if (either.isRight()) {
- return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
- } else {
- if (either.left().value() != null) {
- String roleJson = ("{ \"role\" : \"" + either.left().value().getRole().toString() + "\" }");
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson);
- } else {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User Role");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role");
- log.debug("Get user role failed with unexpected error: {}", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // update user role
- @POST
- @Path("/{userId}/role")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "update user role", notes = "Update user role", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
- @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request,
- @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(modifierUserId);
- log.debug("modifier id is {}", modifierUserId);
-
- Response response = null;
-
- try {
- UserBusinessLogic businessLogic = getUserAdminManager(context);
- User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value();
- Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());
-
- if (updateUserResponse.isRight()) {
- log.debug("failed to update user role");
- response = buildErrorResponse(updateUserResponse.right().value());
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
- log.debug("Update User Role failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- /* User role CRUD end */
-
- /* New user CRUD start */
- @POST
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
- @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
-
- ServletContext context = request.getSession().getServletContext();
-
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- // get modifier id
- User modifier = new User();
- modifier.setUserId(modifierAttId);
- log.debug("modifier id is {}", modifierAttId);
-
- Response response = null;
-
- try {
- UserBusinessLogic businessLogic = getUserAdminManager(context);
- User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value();
- Either<User, ResponseFormat> createUserResponse = businessLogic.createUser(modifier, newUserInfo);
-
- if (createUserResponse.isRight()) {
- log.debug("failed to create user");
- response = buildErrorResponse(createUserResponse.right().value());
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
- log.debug("Create User failed with exception", e);
- response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- return response;
-
- }
- }
-
- /* New user CRUD end */
-
- /* User authorization start */
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // User Authorization
- @GET
- @Path("/authorize")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
-
- @ApiOperation(value = "authorize", notes = "authorize user", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName,
- @HeaderParam("HTTP_CSP_EMAIL") String email) {
-
- try {
- userId = (userId != null ? URLDecoder.decode(userId, "UTF-8") : null);
- firstName = (firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null);
- lastName = (lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null);
- email = (email != null ? URLDecoder.decode(email, "UTF-8") : null);
- } catch (UnsupportedEncodingException e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Authorize User - decode headers");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers");
- ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
- return buildErrorResponse(errorResponseWrapper);
- }
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {}", url);
-
- User authUser = new User();
- authUser.setUserId(userId);
- authUser.setFirstName(firstName);
- authUser.setLastName(lastName);
- authUser.setEmail(email);
- log.debug("auth user id is {}", userId);
-
- Response response = null;
- try {
- UserBusinessLogic userAdminManager = getUserAdminManager(context);
- Either<User, ResponseFormat> authorize = userAdminManager.authorize(authUser);
-
- if (authorize.isRight()) {
- log.debug("authorize user failed");
- response = buildErrorResponse(authorize.right().value());
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users");
- log.debug("authorize user failed with unexpected error: {}", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- /* User authorization end */
-
- @GET
- @Path("/admins")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getAdminsUser(@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<List<User>, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext());
-
- if (either.isRight()) {
- log.debug("Failed to get all admin users");
- return buildErrorResponse(either.right().value());
- } else {
- if (either.left().value() != null) {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- } else {
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Administrators");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators");
- log.debug("get all admins failed with unexpected error: {}", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
-
- @GET
- @Path("/users")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"),
- @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
- @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {} modifier id is {}", url, userId);
-
- List<String> rolesList = new ArrayList<>();
- if (roles != null && !roles.trim().isEmpty()) {
- String[] rolesArr = roles.split(ROLE_DELIMITER);
- for (String role : rolesArr) {
- rolesList.add(role.trim());
- }
- }
-
- try {
- UserBusinessLogic userAdminManager = getUserAdminManager(context);
- Either<List<User>, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles);
-
- if (either.isRight()) {
- log.debug("Failed to get ASDC users");
- return buildErrorResponse(either.right().value());
- } else {
- return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
- log.debug("get users failed with unexpected error: {}", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- }
-
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // delete user
- @DELETE
- @Path("/{userId}")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "delete user", notes = "Delete user", response = User.class)
- @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
- @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
- public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) {
-
- ServletContext context = request.getSession().getServletContext();
- String url = request.getMethod() + " " + request.getRequestURI();
- log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);
-
- User modifier = new User();
- modifier.setUserId(userIdHeader);
-
- Response response = null;
- try {
- UserBusinessLogic userAdminManager = getUserAdminManager(context);
- Either<User, ResponseFormat> deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId);
-
- if (deactiveUserResponse.isRight()) {
- log.debug("Failed to deactivate user");
- response = buildErrorResponse(deactiveUserResponse.right().value());
- return response;
- }
- response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value());
- return response;
-
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users");
- BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
- log.debug("deactivate user failed with unexpected error: {}", e);
- return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- }
+ private static final String ROLE_DELIMITER = ",";
+ private static final Logger log = LoggerFactory.getLogger(UserAdminServlet.class);
+
+ /***************************************
+ * API start
+ *************************************************************/
+
+ /* User by userId CRUD start */
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // retrieve all user details
+ @GET
+ @Path("/{userId}")
+ @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 get(@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<User, ActionStatus> either = userAdminManager.getUser(userId, false);
+
+ if (either.isRight()) {
+ return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
+ } else {
+ if (either.left().value() != null) {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ } else {
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");
+ log.debug("get user failed with unexpected error: {}", e.getMessage(), e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/{userId}/role")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"),
+ @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getRole(@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("(getRole) Start handle request of {}", url);
+
+ UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
+
+ try {
+ Either<User, ActionStatus> either = userAdminManager.getUser(userId, false);
+ if (either.isRight()) {
+ return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
+ } else {
+ if (either.left().value() != null) {
+ String roleJson = "{ \"role\" : \"" + either.left().value().getRole() + "\" }";
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson);
+ } else {
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role");
+ log.debug("Get user role failed with unexpected error: {}", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // update user role
+ @POST
+ @Path("/{userId}/role")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "update user role", notes = "Update user role", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
+ @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request,
+ @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(modifierUserId);
+ log.debug("modifier id is {}", modifierUserId);
+
+ Response response = null;
+
+ try {
+ UserBusinessLogic businessLogic = getUserAdminManager(context);
+ User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value();
+ Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());
+
+ if (updateUserResponse.isRight()) {
+ log.debug("failed to update user role");
+ response = buildErrorResponse(updateUserResponse.right().value());
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value());
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
+ log.debug("Update User Role failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ /* User role CRUD end */
+
+ /* New user CRUD start */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
+ @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
+
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ // get modifier id
+ User modifier = new User();
+ modifier.setUserId(modifierAttId);
+ log.debug("modifier id is {}", modifierAttId);
+
+ Response response = null;
+
+ try {
+ UserBusinessLogic businessLogic = getUserAdminManager(context);
+ User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value();
+ Either<User, ResponseFormat> createUserResponse = businessLogic.createUser(modifier, newUserInfo);
+
+ if (createUserResponse.isRight()) {
+ log.debug("failed to create user");
+ response = buildErrorResponse(createUserResponse.right().value());
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value());
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
+ log.debug("Create User failed with exception", e);
+ response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ return response;
+
+ }
+ }
+
+ /* New user CRUD end */
+
+ /* User authorization start */
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // User Authorization
+ @GET
+ @Path("/authorize")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+
+ @ApiOperation(value = "authorize", notes = "authorize user", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName,
+ @HeaderParam("HTTP_CSP_EMAIL") String email) {
+
+ try {
+ userId = userId != null ? URLDecoder.decode(userId, "UTF-8") : null;
+ firstName = firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null;
+ lastName = lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null;
+ email = email != null ? URLDecoder.decode(email, "UTF-8") : null;
+ } catch (UnsupportedEncodingException e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers");
+ ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+ log.error("#authorize - authorization decoding failed with error: ", e);
+ return buildErrorResponse(errorResponseWrapper);
+ }
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+
+ User authUser = new User();
+ authUser.setUserId(userId);
+ authUser.setFirstName(firstName);
+ authUser.setLastName(lastName);
+ authUser.setEmail(email);
+ log.debug("auth user id is {}", userId);
+
+ Response response = null;
+ try {
+ UserBusinessLogic userAdminManager = getUserAdminManager(context);
+ Either<User, ResponseFormat> authorize = userAdminManager.authorize(authUser);
+
+ if (authorize.isRight()) {
+ log.debug("authorize user failed");
+ response = buildErrorResponse(authorize.right().value());
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value());
+ return response;
+
+ } catch (Exception e) {
+ log.debug("authorize user failed with unexpected error: {}", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ /* User authorization end */
+
+ @GET
+ @Path("/admins")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getAdminsUser(@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<List<User>, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext());
+
+ if (either.isRight()) {
+ log.debug("Failed to get all admin users");
+ return buildErrorResponse(either.right().value());
+ } else {
+ if (either.left().value() != null) {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ } else {
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators");
+ log.debug("get all admins failed with unexpected error: {}", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @GET
+ @Path("/users")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"),
+ @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
+ @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {} modifier id is {}", url, userId);
+
+ List<String> rolesList = new ArrayList<>();
+ if (roles != null && !roles.trim().isEmpty()) {
+ String[] rolesArr = roles.split(ROLE_DELIMITER);
+ for (String role : rolesArr) {
+ rolesList.add(role.trim());
+ }
+ }
+
+ try {
+ UserBusinessLogic userAdminManager = getUserAdminManager(context);
+ Either<List<User>, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles);
+
+ if (either.isRight()) {
+ log.debug("Failed to get ASDC users");
+ return buildErrorResponse(either.right().value());
+ } else {
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
+ log.debug("get users failed with unexpected error: {}", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////////////
+ // delete user
+ @DELETE
+ @Path("/{userId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "delete user", notes = "Delete user", response = User.class)
+ @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
+ @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
+ public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) {
+
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);
+
+ User modifier = new User();
+ modifier.setUserId(userIdHeader);
+
+ Response response = null;
+ try {
+ UserBusinessLogic userAdminManager = getUserAdminManager(context);
+ Either<User, ResponseFormat> deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId);
+
+ if (deactiveUserResponse.isRight()) {
+ log.debug("Failed to deactivate user");
+ response = buildErrorResponse(deactiveUserResponse.right().value());
+ return response;
+ }
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value());
+ return response;
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
+ log.debug("deactivate 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/switchover/detector/SwitchoverDetector.java b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
index faebb7614b..fb5710cc20 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,19 @@
package org.openecomp.sdc.be.switchover.detector;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
import java.net.InetAddress;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
@@ -29,293 +42,272 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import org.apache.commons.codec.binary.Base64;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.rest.HttpRestClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
@Component("switchover-detector")
public class SwitchoverDetector {
- protected static String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector";
+ protected static String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector";
- private static Logger switchoverLogger = LoggerFactory.getLogger(SWITCHOVER_DETECTOR_LOG_CONTEXT);
+ private static final Logger switchoverLogger = LoggerFactory.getLogger(SWITCHOVER_DETECTOR_LOG_CONTEXT);
- private SwitchoverDetectorConfig switchoverDetectorConfig;
+ private SwitchoverDetectorConfig switchoverDetectorConfig;
- private Properties authHeader = null;
+ private Properties authHeader = null;
- private long detectorInterval = 60;
+ private long detectorInterval = 60;
- private int maxBeQueryAttempts = 3;
+ private int maxBeQueryAttempts = 3;
- private int maxFeQueryAttempts = 3;
+ private int maxFeQueryAttempts = 3;
- private Boolean beMatch = null;
+ private Boolean beMatch = null;
- private Boolean feMatch = null;
+ private Boolean feMatch = null;
- private static Logger logger = LoggerFactory.getLogger(SwitchoverDetector.class.getName());
+ private static final Logger logger = LoggerFactory.getLogger(SwitchoverDetector.class);
- private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState();
+ private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState();
- private ScheduledFuture<?> scheduledFuture = null;
+ private ScheduledFuture<?> scheduledFuture = null;
- ScheduledExecutorService switchoverDetectorScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "Switchover-Detector-Task");
- }
- });
+ ScheduledExecutorService switchoverDetectorScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "Switchover-Detector-Task");
+ }
+ });
- SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null;
+ SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null;
- public enum SwitchoverDetectorState {
+ public enum SwitchoverDetectorState {
- UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby");
+ UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby");
- private String state;
+ private String state;
- SwitchoverDetectorState(String state) {
- this.state = state;
- }
+ SwitchoverDetectorState(String state) {
+ this.state = state;
+ }
- public String getState() {
- return state;
- }
- }
+ public String getState() {
+ return state;
+ }
+ }
- public enum SwitchoverDetectorGroup {
+ public enum SwitchoverDetectorGroup {
- BE_SET("beSet"), FE_SET("feSet");
+ BE_SET("beSet"), FE_SET("feSet");
- private String group;
+ private String group;
- SwitchoverDetectorGroup(String group) {
- this.group = group;
- }
+ SwitchoverDetectorGroup(String group) {
+ this.group = group;
+ }
- public String getGroup() {
- return group;
- }
- }
+ public String getGroup() {
+ return group;
+ }
+ }
- public String getSiteMode() {
- return siteMode;
- }
+ public String getSiteMode() {
+ return siteMode;
+ }
- public void setSiteMode(String mode) {
- this.siteMode = mode;
- }
+ public void setSiteMode(String mode) {
+ this.siteMode = mode;
+ }
- private Boolean queryBe() {
- return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts);
- }
+ private Boolean queryBe() {
+ return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts);
+ }
- private Boolean queryFe() {
- return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts);
- }
+ private Boolean queryFe() {
+ return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts);
+ }
- private void setAuthorizationProperties() {
- String userInfo = switchoverDetectorConfig.getChangePriorityUser() + ":" + switchoverDetectorConfig.getChangePriorityPassword();
- String auth = "Basic " + new String(new Base64().encode(userInfo.getBytes()));
- authHeader = new Properties();
- authHeader.put("Authorization", auth);
- }
+ private void setAuthorizationProperties() {
+ String userInfo = switchoverDetectorConfig.getChangePriorityUser() + ":" + switchoverDetectorConfig.getChangePriorityPassword();
+ String auth = "Basic " + new String(new Base64().encode(userInfo.getBytes()));
+ authHeader = new Properties();
+ authHeader.put("Authorization", auth);
+ }
- private void initializeSiteMode() {
- while (siteMode == SwitchoverDetectorState.UNKNOWN.getState()) {
+ private void initializeSiteMode() {
+ while (siteMode.equals(SwitchoverDetectorState.UNKNOWN.getState())) {
- beMatch = queryBe();
- feMatch = queryFe();
+ beMatch = queryBe();
+ feMatch = queryFe();
- if (beMatch == feMatch && beMatch != null) {
- if (beMatch) {
- setSiteMode(SwitchoverDetectorState.ACTIVE.getState());
- } else {
- setSiteMode(SwitchoverDetectorState.STANDBY.getState());
- }
- }
- }
- }
+ if (beMatch == feMatch && beMatch != null) {
+ if (beMatch) {
+ setSiteMode(SwitchoverDetectorState.ACTIVE.getState());
+ } else {
+ setSiteMode(SwitchoverDetectorState.STANDBY.getState());
+ }
+ }
+ }
+ }
- private Boolean queryGss(String fqdn, String vip, int maxAttempts) {
+ private Boolean queryGss(String fqdn, String vip, int maxAttempts) {
- Boolean result = null;
- int attempts = 0;
+ Boolean result = null;
+ int attempts = 0;
- while (result == null && (++attempts < maxAttempts)) {
- try {
- InetAddress inetAddress = InetAddress.getByName(fqdn);
- result = inetAddress.getHostAddress().equals(vip);
+ while (result == null && (++attempts < maxAttempts)) {
+ try {
+ InetAddress inetAddress = InetAddress.getByName(fqdn);
+ result = inetAddress.getHostAddress().equals(vip);
- } catch (Exception e) {
- String message = e.getMessage();
- if (message == null) {
- message = e.getClass().getName();
- }
- logger.debug("Error occured during switchover detector query, Result is {}", message, e);
- }
- }
- if (null == result) {
- BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts");
- }
- return result;
- }
-
- public class SwitchoverDetectorScheduledTask implements Runnable {
-
- public SwitchoverDetectorScheduledTask() {
-
- }
-
- @Override
- public void run() {
- logger.trace("Executing Switchover Detector Task - Start");
-
- initializeSiteMode();
-
- Boolean beRes = queryBe();
- Boolean feRes = queryFe();
-
- if (null == beRes || null == feRes) {
- return;
- }
-
- Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) & (beMatch != beRes || feMatch != feRes);
-
- updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired);
-
- beMatch = beRes;
- feMatch = feRes;
- }
-
- ExecutorService switchoverDetectorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "Switchover-Detector-Thread");
- }
- });
-
- private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) {
- if (bothMatch && previousModeStandby) {
- logger.trace("Site switch over was done. Site is now in active mode");
- setSiteMode(SwitchoverDetectorState.ACTIVE.getState());
- BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode);
- } else if (!bothMatch && !previousModeStandby) {
- logger.trace("Site switch over was done. Site is now in stand-by mode");
- setSiteMode(SwitchoverDetectorState.STANDBY.getState());
- BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode);
- }
- if (updateRequired) {
- changeSitePriority(SwitchoverDetectorGroup.BE_SET.getGroup());
- changeSitePriority(SwitchoverDetectorGroup.FE_SET.getGroup());
- publishNetwork();
- }
- }
-
- private void changeSitePriority(String groupToSet) {
-
- String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl();
- String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody();
-
- HttpRestClient httpRestClient = new HttpRestClient();
-
- try {
- httpRestClient.doPUT(url, authHeader, body);
-
- } catch (Exception e) {
- String message = e.getMessage();
- if (message == null) {
- message = e.getClass().getName();
- }
-
- logger.debug("Error occured during change site priority request, Result is {}", message, e);
- }
-
- }
-
- private void publishNetwork() {
-
- String url = switchoverDetectorConfig.getPublishNetworkUrl();
- String body = switchoverDetectorConfig.getPublishNetworkBody();
-
- HttpRestClient httpRestClient = new HttpRestClient();
-
- try {
- httpRestClient.doPOST(url, authHeader, body);
-
- } catch (Exception e) {
- String message = e.getMessage();
- if (message == null) {
- message = e.getClass().getName();
- }
-
- logger.debug("Error occured during publish network request, Result is {}", message, e);
- }
- }
-
- }
-
- @PostConstruct
- private void init() {
- logger.info("Enter init method of SwitchoverDetector");
-
- switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector();
-
- if (!switchoverDetectorConfig.getEnabled()) {
- logger.info("switchover detector service is disabled");
- return;
- }
-
- Long detectorIntervalConfig = switchoverDetectorConfig.getInterval();
- if (detectorIntervalConfig != null) {
- detectorInterval = detectorIntervalConfig.longValue();
- }
-
- Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts();
- if (maxAttempts != null) {
- maxBeQueryAttempts = maxAttempts.intValue();
- }
- maxAttempts = switchoverDetectorConfig.getFeResolveAttempts();
- if (maxAttempts != null) {
- maxFeQueryAttempts = maxAttempts.intValue();
- }
-
- setAuthorizationProperties();
- logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval);
-
- this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask();
- startSwitchoverDetectorTask();
- logger.trace("Exit init method of SwitchoverDetector");
-
- }
-
- @PreDestroy
- private void destroy() {
-
- if (scheduledFuture != null) {
- scheduledFuture.cancel(true);
- scheduledFuture = null;
- }
-
- if (switchoverDetectorScheduler != null) {
- switchoverDetectorScheduler.shutdown();
- }
-
- }
-
- public void startSwitchoverDetectorTask() {
- if (this.scheduledFuture == null) {
- this.scheduledFuture = this.switchoverDetectorScheduler.scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS);
- }
- }
+ } catch (Exception e) {
+ String message = e.getMessage();
+ if (message == null) {
+ message = e.getClass().getName();
+ }
+ logger.debug("Error occured during switchover detector query, Result is {}", message, e);
+ }
+ }
+ if (null == result) {
+ BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts");
+ }
+ return result;
+ }
+
+ public class SwitchoverDetectorScheduledTask implements Runnable {
+
+ public SwitchoverDetectorScheduledTask() {
+
+ }
+
+ @Override
+ public void run() {
+ logger.trace("Executing Switchover Detector Task - Start");
+
+ initializeSiteMode();
+
+ Boolean beRes = queryBe();
+ Boolean feRes = queryFe();
+
+ if (null == beRes || null == feRes) {
+ return;
+ }
+
+ Boolean updateRequired = siteMode == SwitchoverDetectorState.STANDBY.getState() && (beRes || feRes) && (beMatch != beRes || feMatch != feRes);
+
+ updateSiteModeAndPriority(beRes && feRes, siteMode == SwitchoverDetectorState.STANDBY.getState(), updateRequired);
+
+ beMatch = beRes;
+ feMatch = feRes;
+ }
+
+ ExecutorService switchoverDetectorExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "Switchover-Detector-Thread");
+ }
+ });
+
+ private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) {
+ if (bothMatch && previousModeStandby) {
+ logger.trace("Site switch over was done. Site is now in active mode");
+ setSiteMode(SwitchoverDetectorState.ACTIVE.getState());
+ BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode);
+ } else if (!bothMatch && !previousModeStandby) {
+ logger.trace("Site switch over was done. Site is now in stand-by mode");
+ setSiteMode(SwitchoverDetectorState.STANDBY.getState());
+ BeEcompErrorManager.getInstance().logSiteSwitchoverInfo(SWITCHOVER_DETECTOR_LOG_CONTEXT, siteMode);
+ }
+ if (updateRequired) {
+ changeSitePriority(SwitchoverDetectorGroup.BE_SET.getGroup());
+ changeSitePriority(SwitchoverDetectorGroup.FE_SET.getGroup());
+ publishNetwork();
+ }
+ }
+
+ private void changeSitePriority(String groupToSet) {
+
+ String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl();
+ String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody();
+
+ try {
+ HttpRequest.put(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON));
+ } catch (Exception e) {
+ String message = e.getMessage();
+ if (message == null) {
+ message = e.getClass().getName();
+ }
+ logger.debug("Error occured during change site priority request, Result is {}", message, e);
+ }
+
+ }
+
+ private void publishNetwork() {
+
+ String url = switchoverDetectorConfig.getPublishNetworkUrl();
+ String body = switchoverDetectorConfig.getPublishNetworkBody();
+ try {
+ HttpRequest.post(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON));
+ } catch (Exception e) {
+ String message = e.getMessage();
+ if (message == null) {
+ message = e.getClass().getName();
+ }
+ logger.debug("Error occured during publish network request, Result is {}", message, e);
+ }
+ }
+
+ }
+
+ @PostConstruct
+ private void init() {
+ logger.info("Enter init method of SwitchoverDetector");
+
+ switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector();
+
+ if (!switchoverDetectorConfig.getEnabled()) {
+ logger.info("switchover detector service is disabled");
+ return;
+ }
+
+ Long detectorIntervalConfig = switchoverDetectorConfig.getInterval();
+ if (detectorIntervalConfig != null) {
+ detectorInterval = detectorIntervalConfig.longValue();
+ }
+
+ Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts();
+ if (maxAttempts != null) {
+ maxBeQueryAttempts = maxAttempts.intValue();
+ }
+ maxAttempts = switchoverDetectorConfig.getFeResolveAttempts();
+ if (maxAttempts != null) {
+ maxFeQueryAttempts = maxAttempts.intValue();
+ }
+
+ setAuthorizationProperties();
+ logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval);
+
+ this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask();
+ startSwitchoverDetectorTask();
+ logger.trace("Exit init method of SwitchoverDetector");
+
+ }
+
+ @PreDestroy
+ private void destroy() {
+
+ if (scheduledFuture != null) {
+ scheduledFuture.cancel(true);
+ scheduledFuture = null;
+ }
+
+ if (switchoverDetectorScheduler != null) {
+ switchoverDetectorScheduler.shutdown();
+ }
+
+ }
+
+ public void startSwitchoverDetectorTask() {
+ if (this.scheduledFuture == null) {
+ this.scheduledFuture = this.switchoverDetectorScheduler.scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java
index 13356e5de4..f13331ed0b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java
@@ -20,19 +20,19 @@
package org.openecomp.sdc.be.tosca;
-import java.util.List;
-
import org.openecomp.sdc.generator.data.ArtifactType;
+import java.util.List;
+
public class ArtifactTypes {
- private List<ArtifactType> artifactTypes;
+ private List<ArtifactType> artifactTypes;
- public List<ArtifactType> getArtifactTypes() {
- return artifactTypes;
- }
+ public List<ArtifactType> getArtifactTypes() {
+ return artifactTypes;
+ }
- public void setArtifactTypes(List<ArtifactType> artifactTypes) {
- this.artifactTypes = artifactTypes;
- }
+ public void setArtifactTypes(List<ArtifactType> artifactTypes) {
+ this.artifactTypes = artifactTypes;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java
deleted file mode 100644
index 7fecced358..0000000000
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.tosca;
-
-import org.openecomp.sdc.be.model.Component;
-
-public class CSARTool {
- public static byte[] createCsar(Component component) {
-
- final String TOSCA_META_VERSION = "1.0";
- final String CSAR_VERSION = component.getCsarVersion();
- final String CREATED_BY = component.getCreatorFullName();
- final String ENTRY_DEFINITIONS = component.getNormalizedName();
-
- /*
- * StringBuilder builder = new StringBuilder(); try( FileOutputStream f = new FileOutputStream("test.zip"); ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f)); ){ }
- */
-
- return null;
- }
-
- public static String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
- final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s";
-
- return null;
- }
-}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
index 886b654b81..4dbbf925d3 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
@@ -20,50 +20,34 @@
package org.openecomp.sdc.be.tosca;
-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.Optional;
-import java.util.stream.Collectors;
-
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
-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.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.tosca.ToscaUtils.SubstituitionEntry;
-import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
-import org.openecomp.sdc.be.tosca.model.ToscaCapability;
-import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
-import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
-import org.openecomp.sdc.be.tosca.model.ToscaProperty;
-import org.openecomp.sdc.be.tosca.model.ToscaRequirement;
-import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability;
+import org.openecomp.sdc.be.tosca.model.*;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
+import java.util.*;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.apache.commons.lang3.StringUtils.*;
-import fj.data.Either;
/**
* Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template
*
@@ -71,502 +55,545 @@ import fj.data.Either;
@org.springframework.stereotype.Component("capabilty-requirement-convertor")
@Scope(value = "singleton")
public class CapabiltyRequirementConvertor {
-
- private static final String NO_CAPABILITIES = "No Capabilities for node type";
- private static CapabiltyRequirementConvertor instance;
- private static Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class.getName());
- public static final String PATH_DELIMITER = ".";
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
-
- protected CapabiltyRequirementConvertor() {}
-
- public static synchronized CapabiltyRequirementConvertor getInstance() {
- if (instance == null) {
- instance = new CapabiltyRequirementConvertor();
- }
- return instance;
- }
- /**
- * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template
- * @param componentInstance
- * @param dataTypes
- * @param nodeTemplate
- * @return
- */
- public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) {
-
- Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities();
- if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) {
- Map<String, ToscaTemplateCapability> capabilties = new HashMap<>();
- capabilitiesInst.entrySet().forEach(e -> {
- List<CapabilityDefinition> capList = e.getValue();
- if (capList != null && !capList.isEmpty()) {
- capList.forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilties, c));
- }
- });
- if (MapUtils.isNotEmpty(capabilties)) {
- nodeTemplate.setCapabilities(capabilties);
- }
- }
- return Either.left(nodeTemplate);
- }
-
- private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c) {
- if (CollectionUtils.isNotEmpty(c.getProperties())) {
- c.getProperties()
- .stream()
- .filter(p -> p.getValue() != null || p.getDefaultValue() != null)
- .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties, c, p));
- }
- }
-
- private void convertOverridenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c, ComponentInstanceProperty p) {
- if (logger.isDebugEnabled()) {
- logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), c.getName(), p.getValue());
- }
- ToscaTemplateCapability toscaTemplateCapability = capabilties.get(c.getName());
- if (toscaTemplateCapability == null) {
- toscaTemplateCapability = new ToscaTemplateCapability();
- capabilties.put(c.getName(), toscaTemplateCapability);
- }
- Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties();
- if (toscaCapProp == null) {
- toscaCapProp = new HashMap<>();
- }
- Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p);
- toscaCapProp.put(p.getName(), convertedValue);
- toscaTemplateCapability.setProperties(toscaCapProp);
- }
-
- private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) {
- logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
- String propertyType = prop.getType();
- String innerType = null;
- if (prop.getSchema() != null && prop.getSchema().getProperty() != null) {
- innerType = prop.getSchema().getProperty().getType();
- }
- String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
- return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes);
- }
- /**
- * Allows to convert requirements of a node type to tosca template requirements representation
- * @param component
- * @param nodeType
- * @return
- */
- public Either<ToscaNodeType, ToscaError> convertRequirements(Component component, ToscaNodeType nodeType) {
- List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(component);
- if (!toscaRequirements.isEmpty()) {
- nodeType.setRequirements(toscaRequirements);
- }
- logger.debug("Finish convert Requirements for node type");
-
- return Either.left(nodeType);
- }
-
- /**
- * Allows to convert component requirements to the tosca template substitution mappings requirements
- * @param componentsCache
- * @param component
- * @param substitutionMappings
- * @return
- */
- public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) {
- Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
- Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component);
- if(toscaRequirementsRes.isRight()){
- result = Either.right(toscaRequirementsRes.right().value());
- logger.error("Failed convert requirements for the component {}. ", component.getName());
- } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) {
- substitutionMappings.setRequirements(toscaRequirementsRes.left().value());
- result = Either.left(substitutionMappings);
- logger.debug("Finish convert requirements for the component {}. ", component.getName());
- }
- return result;
- }
-
- private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Component component) {
- Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
- List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
- if (requirements != null) {
- for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> {
- ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r);
- Map<String, ToscaRequirement> requirement = new HashMap<>();
-
- requirement.put(pair.left, pair.right);
- toscaRequirements.add(requirement);
- });
- logger.debug("Finish convert Requirements for node type");
- }
- } else {
- logger.debug("No Requirements for node type");
- }
- return toscaRequirements;
- }
-
- private boolean filter(Component component, String ownerId) {
- return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null);
- }
-
- private boolean isNodeTypeOwner(Component component, String ownerId) {
- return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId);
- }
-
- private String getSubPathByLastDelimiterAppearance(String path) {
- return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1);
- }
-
- private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) {
- Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
- Either<Map<String, String[]>, ToscaError> result;
- if (requirements != null) {
- result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements);
- } else {
- result = Either.left(Maps.newHashMap());
- logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName());
- }
- return result;
- }
-
- private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) {
-
- Map<String, String[]> toscaRequirements = new HashMap<>();
- Either<Map<String, String[]>, ToscaError> result = null;
- for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- Optional<RequirementDefinition> failedToAddRequirement = entry.getValue()
- .stream()
- .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getPath()))
- .findAny();
- if(failedToAddRequirement.isPresent()){
- logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ",
- failedToAddRequirement.get().getName(), component.getName());
- result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
- }
- logger.debug("Finish convert requirements for the component {}. ", component.getName());
- }
- if(result == null){
- result = Either.left(toscaRequirements);
- }
- return result;
- }
-
- private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) {
-
- Map<String, String[]> toscaRequirements = new HashMap<>();
- Either<Map<String, String[]>, ToscaError> result = null;
- for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue()
- .stream()
- .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getPath()))
- .findAny();
- if(failedToAddRequirement.isPresent()){
- logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ",
- failedToAddRequirement.get().getName(), component.getName());
- result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR);
- }
- logger.debug("Finish convert capalilities for the component {}. ", component.getName());
- }
- if(result == null){
- result = Either.left(toscaRequirements);
- }
- return result;
- }
-
- private boolean addEntry(Map<String,Component> componentsCache, Map<String, String[]> capReqMap, Component component, String name, String parentName, List<String> path){
-
- SubstituitionEntry entry = new SubstituitionEntry(name, parentName, "");
-
- if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, entry)){
- return false;
- }
- logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId());
- if (entry.getSourceName() != null) {
- addEntry(capReqMap, component, path, entry);
- }
- logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName());
- return true;
-
- }
-
- private boolean shouldBuildSubstitutionName(Component component, List<String> path) {
- return !ToscaUtils.isComplexVfc(component) && CollectionUtils.isNotEmpty(path) && path.iterator().hasNext();
- }
-
- private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, List<String> path, SubstituitionEntry entry) {
- Optional<ComponentInstance> ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
- if(ci.isPresent()){
- Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ci.get());
- if(buildSubstitutedName.isRight()){
- return false;
- }
- entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value());
- entry.setSourceName(buildSubstitutedName.left().value());
- } else {
- return false;
- }
- return true;
- }
-
- private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstituitionEntry entry) {
- Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst();
- if (findFirst.isPresent()) {
- entry.setOwner(findFirst.get().getNormalizedName());
- }
- toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() });
- }
-
- private Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, List<String> path, ComponentInstance instance) {
-
- Either<String, Boolean> result = null;
- Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance);
- if(getOriginRes.isRight()){
- logger.debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid());
- result = Either.right(false);
- }
- if(result == null){
- List<String> reducedPath = getReducedPath(path);
- reducedPath.remove(reducedPath.size()-1);
- result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name);
- }
- return result;
- }
-
- private String getRequirementPath(Component component, RequirementDefinition r) {
-
- // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..)
- // dirty quick fix. must be changed as capability redesign
- List<String> capPath = r.getPath();
- String lastInPath = capPath.get(capPath.size() - 1);
- Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst();
- if (findFirst.isPresent()) {
- String lastInPathName = findFirst.get().getNormalizedName();
-
- if (capPath.size() > 1) {
- List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList()));
-
- return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString();
- }else{
- return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString();
- }
- }
- return "";
- }
-
- private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) {
- String name = r.getName();
- if (!isNodeType) {
- name = getRequirementPath(component, r);
- }
- logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId());
- ToscaRequirement toscaRequirement = new ToscaRequirement();
-
- List<Object> occurences = new ArrayList<>();
- occurences.add(Integer.valueOf(r.getMinOccurrences()));
- if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- occurences.add(r.getMaxOccurrences());
- } else {
- occurences.add(Integer.valueOf(r.getMaxOccurrences()));
- }
- toscaRequirement.setOccurrences(occurences);
- toscaRequirement.setNode(r.getNode());
- toscaRequirement.setCapability(r.getCapability());
- toscaRequirement.setRelationship(r.getRelationship());
-
- return new ImmutablePair<>(name, toscaRequirement);
- }
-
- /**
- * Allows to convert capabilities of a node type to tosca template capabilities
- * @param component
- * @param dataTypes
- * @return
- */
- public Map<String, ToscaCapability> convertCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) {
- Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
- Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
- if (capabilities != null) {
- boolean isNodeType = ModelConverter.isAtomicComponent(component);
- for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes));
- }
- } else {
- logger.debug(NO_CAPABILITIES);
- }
-
- return toscaCapabilities;
- }
-
- /**
- * Allows to convert capabilities of a server proxy node type to tosca template capabilities
- * @param component
- * @param proxyComponent
- * @param instanceProxy
- * @param dataTypes
- * @return
- */
- public Map<String, ToscaCapability> convertProxyCapabilities(Component component, Component proxyComponent, ComponentInstance instanceProxy, Map<String, DataTypeDefinition> dataTypes) {
- Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities();
- Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
- if (capabilities != null) {
- boolean isNodeType = ModelConverter.isAtomicComponent(component);
- for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes));
- }
- } else {
- logger.debug(NO_CAPABILITIES);
- }
-
- return toscaCapabilities;
- }
-
- /**
- * Allows to convert component capabilities to the tosca template substitution mappings capabilities
- * @param componentsCache
- * @param component
- * @return
- */
- public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) {
- Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
- Either<Map<String, String[]>, ToscaError> res;
- if (capabilities != null) {
- res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities);
- } else {
- res = Either.left(Maps.newHashMap());
- logger.debug(NO_CAPABILITIES);
- }
- return res;
- }
-
- private String getCapabilityPath(CapabilityDefinition c, Component component) {
- // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..)
- // dirty quick fix. must be changed as capability redesign
- List<String> capPath = c.getPath();
- String lastInPath = capPath.get(capPath.size() - 1);
- Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst();
- if (findFirst.isPresent()) {
- String lastInPathName = findFirst.get().getNormalizedName();
-
- if (capPath.size() > 1) {
- List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList()));
-
- return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString();
- }else{
- return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString();
- }
- }
- return "";
- }
-
- private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes) {
- String name = c.getName();
- if (!isNodeType) {
- name = getCapabilityPath(c, component);
- }
- logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId());
- ToscaCapability toscaCapability = new ToscaCapability();
- toscaCapability.setDescription(c.getDescription());
- toscaCapability.setType(c.getType());
-
- List<Object> occurences = new ArrayList<>();
- occurences.add(Integer.valueOf(c.getMinOccurrences()));
- if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- occurences.add(c.getMaxOccurrences());
- } else {
- occurences.add(Integer.valueOf(c.getMaxOccurrences()));
- }
- toscaCapability.setOccurrences(occurences);
-
- toscaCapability.setValid_source_types(c.getValidSourceTypes());
- List<ComponentInstanceProperty> properties = c.getProperties();
- if (CollectionUtils.isNotEmpty(properties)) {
- Map<String, ToscaProperty> toscaProperties = new HashMap<>();
- for (PropertyDefinition property : properties) {
- ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true);
- toscaProperties.put(property.getName(), toscaProperty);
- }
- toscaCapability.setProperties(toscaProperties);
- }
- toscaCapabilities.put(name, toscaCapability);
- }
- /**
- * Allows to build substituted name of capability\requirement of the origin component instance according to the path
- * @param componentsCache
- * @param originComponent
- * @param path
- * @param name
- * @return
- */
- public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name) {
- StringBuilder substitutedName = new StringBuilder();
- boolean nameBuiltSuccessfully = true;
- Either<String, Boolean> result;
- if(CollectionUtils.isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){
- List<String> reducedPath = getReducedPath(path);
- Collections.reverse(reducedPath);
- nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName);
- }
- if(nameBuiltSuccessfully){
- result = Either.left(substitutedName.append(name).toString());
- } else {
- result = Either.right(nameBuiltSuccessfully);
- }
- return result;
- }
-
- private List<String> getReducedPath(List<String> path) {
- List<String> pathCopy = Lists.newArrayList();
- path.stream().forEach(id -> {if(!pathCopy.contains(id))pathCopy.add(id);});
- return pathCopy;
- }
-
- private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) {
- if(CollectionUtils.isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){
- String instanceId = instanceIdIter.next();
- Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
- if(!instanceOpt.isPresent()){
- logger.debug("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId());
- return false;
- }
- substitutedName.append(instanceOpt.get().getNormalizedName()).append('.');
- Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get());
- if(getOriginRes.isRight()){
- return false;
- }
- appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName);
- }
- return true;
- }
-
- Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) {
- Either<Component, Boolean> result;
- Either<Component, StorageOperationStatus> getOriginRes;
- if(componentsCache.containsKey(instance.getActualComponentUid())){
- result = Either.left(componentsCache.get(instance.getActualComponentUid()));
- } else {
- ComponentParametersView filter = getFilter(instance);
- getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter);
- if(getOriginRes.isRight()){
- logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid());
- result = Either.right(false);
- } else {
- result = Either.left(getOriginRes.left().value());
- componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value());
- }
- }
- return result;
- }
-
- private ComponentParametersView getFilter(ComponentInstance instance) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- if(instance.getIsProxy()){
- filter.setIgnoreCapabilities(false);
- filter.setIgnoreRequirements(false);
- }
- return filter;
- }
-
-}
+
+ private static final String NO_CAPABILITIES = "No Capabilities for node type";
+ private static CapabiltyRequirementConvertor instance;
+ private static final Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class);
+ public static final String PATH_DELIMITER = ".";
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+
+ protected CapabiltyRequirementConvertor() {}
+
+ public static synchronized CapabiltyRequirementConvertor getInstance() {
+ if (instance == null) {
+ instance = new CapabiltyRequirementConvertor();
+ }
+ return instance;
+ }
+
+ public String buildCapabilityNameForComponentInstance( Map<String,Component> componentCache , ComponentInstance componentInstance, CapabilityDefinition c) {
+
+ Either eitherName = buildSubstitutedName(componentCache, c.getName(), c.getPath(), c.getOwnerId(), componentInstance);
+
+ return eitherName.isLeft() ? (String) eitherName.left().value() : c.getName() ;
+ }
+
+
+ /**
+ * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template
+ * @param componentInstance
+ * @param dataTypes
+ * @param nodeTemplate
+ * @return
+ */
+ public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) {
+
+ Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities();
+ Map<String,Component> componentCache = new HashMap<>();
+ if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) {
+ Map<String, ToscaTemplateCapability> capabilities = new HashMap<>();
+ capabilitiesInst.entrySet().forEach( e -> {
+ List<CapabilityDefinition> capList = e.getValue();
+ if ( capList != null && !capList.isEmpty() ) {
+ capList.forEach( c -> {
+ String capName = buildCapabilityNameForComponentInstance( componentCache , componentInstance , c ) ;
+ convertOverridenProperties( componentInstance, dataTypes, capabilities, c , capName );
+ } );
+ }
+ });
+ if (MapUtils.isNotEmpty(capabilities)) {
+ nodeTemplate.setCapabilities(capabilities);
+ }
+ }
+ return Either.left(nodeTemplate);
+ }
+
+ private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c , String capabilityName) {
+ if (isNotEmpty(c.getProperties())) {
+ c.getProperties()
+ .stream()
+ .filter(p -> p.getValue() != null || p.getDefaultValue() != null)
+ .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName));
+ }
+ }
+
+ private void convertOverridenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p ,String capabilityName) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), capabilityName, p.getValue());
+ }
+ ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() );
+
+ Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties();
+ if (toscaCapProp == null) {
+ toscaCapProp = new HashMap<>();
+ }
+ Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p);
+ toscaCapProp.put(p.getName(), convertedValue);
+ toscaTemplateCapability.setProperties(toscaCapProp);
+ }
+
+ private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) {
+ logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
+ String propertyType = prop.getType();
+ String innerType = null;
+ if (prop.getSchema() != null && prop.getSchema().getProperty() != null) {
+ innerType = prop.getSchema().getProperty().getType();
+ }
+ String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
+ return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes);
+ }
+ /**
+ * Allows to convert requirements of a node type to tosca template requirements representation
+ * @param component
+ * @param nodeType
+ * @return
+ */
+ public Either<ToscaNodeType, ToscaError> convertRequirements(Component component, ToscaNodeType nodeType) {
+ List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(component);
+ if (!toscaRequirements.isEmpty()) {
+ nodeType.setRequirements(toscaRequirements);
+ }
+ logger.debug("Finish convert Requirements for node type");
+
+ return Either.left(nodeType);
+ }
+
+ /**
+ * Allows to convert component requirements to the tosca template substitution mappings requirements
+ * @param componentsCache
+ * @param component
+ * @param substitutionMappings
+ * @return
+ */
+ public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) {
+ Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
+ Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component);
+ if(toscaRequirementsRes.isRight()){
+ result = Either.right(toscaRequirementsRes.right().value());
+ logger.error("Failed convert requirements for the component {}. ", component.getName());
+ } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) {
+ substitutionMappings.setRequirements(toscaRequirementsRes.left().value());
+ result = Either.left(substitutionMappings);
+ logger.debug("Finish convert requirements for the component {}. ", component.getName());
+ }
+ return result;
+ }
+
+ private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Component component) {
+ Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
+ List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
+ if (requirements != null) {
+ for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
+ entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> {
+ ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r);
+ Map<String, ToscaRequirement> requirement = new HashMap<>();
+
+ requirement.put(pair.left, pair.right);
+ toscaRequirements.add(requirement);
+ });
+ logger.debug("Finish convert Requirements for node type");
+ }
+ } else {
+ logger.debug("No Requirements for node type");
+ }
+ return toscaRequirements;
+ }
+
+ private boolean filter(Component component, String ownerId) {
+ return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null);
+ }
+
+ private boolean isNodeTypeOwner(Component component, String ownerId) {
+ return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId);
+ }
+
+ private String getSubPathByLastDelimiterAppearance(String path) {
+ return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1);
+ }
+
+ private String dropLast( String path, String delimiter ) {
+ if (isBlank(path) || isBlank(delimiter)){
+ return path;
+ }
+ return path.substring(0, path.lastIndexOf(delimiter));
+ }
+
+ private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) {
+ Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
+ Either<Map<String, String[]>, ToscaError> result;
+ if (requirements != null) {
+ result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements);
+ } else {
+ result = Either.left(Maps.newHashMap());
+ logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName());
+ }
+ return result;
+ }
+
+ private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) {
+
+ Map<String, String[]> toscaRequirements = new HashMap<>();
+ Either<Map<String, String[]>, ToscaError> result = null;
+ for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
+ Optional<RequirementDefinition> failedToAddRequirement = entry.getValue()
+ .stream()
+ .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getOwnerId(), r.getPath()))
+ .findAny();
+ if(failedToAddRequirement.isPresent()){
+ logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ",
+ failedToAddRequirement.get().getName(), component.getName());
+ result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
+ }
+ logger.debug("Finish convert requirements for the component {}. ", component.getName());
+ }
+ if(result == null){
+ result = Either.left(toscaRequirements);
+ }
+ return result;
+ }
+
+ private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) {
+
+ Map<String, String[]> toscaRequirements = new HashMap<>();
+ Either<Map<String, String[]>, ToscaError> result = null;
+ for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
+ Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue()
+ .stream()
+ .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getOwnerId(), c.getPath()))
+ .findAny();
+ if(failedToAddRequirement.isPresent()){
+ logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ",
+ failedToAddRequirement.get().getName(), component.getName());
+ result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR);
+ }
+ logger.debug("Finish convert capalilities for the component {}. ", component.getName());
+ }
+ if(result == null){
+ result = Either.left(toscaRequirements);
+ }
+ return result;
+ }
+
+ private boolean addEntry(Map<String,Component> componentsCache, Map<String, String[]> capReqMap, Component component, String name, String parentName, String ownerId, List<String> path){
+
+ SubstituitionEntry entry = new SubstituitionEntry(name, parentName, "");
+
+ if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, ownerId, entry)){
+ return false;
+ }
+ logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId());
+ if (entry.getSourceName() != null) {
+ addEntry(capReqMap, component, path, entry);
+ }
+ logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName());
+ return true;
+
+ }
+
+ private boolean shouldBuildSubstitutionName(Component component, List<String> path) {
+ return !ToscaUtils.isComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext();
+ }
+
+ private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, List<String> path, String ownerId, SubstituitionEntry entry) {
+ Optional<ComponentInstance> ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
+ if(!ci.isPresent()){
+ logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId());
+
+ Collections.reverse(path);
+
+ logger.error("try to reverse path {} component {}", path, component.getUniqueId());
+ ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
+ }
+ if(ci.isPresent()){
+ Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ownerId, ci.get());
+ if(buildSubstitutedName.isRight()){
+ logger.error("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId());
+ return false;
+ }
+ entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value());
+ entry.setSourceName(buildSubstitutedName.left().value());
+ } else {
+ logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId());
+ return false;
+ }
+ return true;
+ }
+
+ private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstituitionEntry entry) {
+ Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst();
+ if (findFirst.isPresent()) {
+ entry.setOwner(findFirst.get().getNormalizedName());
+ }
+ toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() });
+ }
+
+ public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, List<String> path, String ownerId, ComponentInstance instance) {
+
+ Either<String, Boolean> result = null;
+ Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance);
+ if(getOriginRes.isRight()){
+ logger.error("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid());
+ result = Either.right(false);
+ }
+ if(result == null){
+ List<String> reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ;
+ logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath);
+ reducedPath.remove(reducedPath.size()-1);
+ result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name);
+ }
+ return result;
+ }
+
+ private String getRequirementPath(Component component, RequirementDefinition r) {
+
+ // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..)
+ // dirty quick fix. must be changed as capability redesign
+ List<String> capPath = r.getPath();
+ String lastInPath = capPath.get(capPath.size() - 1);
+ Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst();
+ if (findFirst.isPresent()) {
+ String lastInPathName = findFirst.get().getNormalizedName();
+
+ if (capPath.size() > 1) {
+ List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList()));
+
+ return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString();
+ }else{
+ return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString();
+ }
+ }
+ return "";
+ }
+
+ private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) {
+ String name = r.getName();
+ if (!isNodeType) {
+ name = getRequirementPath(component, r);
+ }
+ logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId());
+ ToscaRequirement toscaRequirement = new ToscaRequirement();
+
+ List<Object> occurences = new ArrayList<>();
+ occurences.add(Integer.valueOf(r.getMinOccurrences()));
+ if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ occurences.add(r.getMaxOccurrences());
+ } else {
+ occurences.add(Integer.valueOf(r.getMaxOccurrences()));
+ }
+ toscaRequirement.setOccurrences(occurences);
+ toscaRequirement.setNode(r.getNode());
+ toscaRequirement.setCapability(r.getCapability());
+ toscaRequirement.setRelationship(r.getRelationship());
+
+ return new ImmutablePair<>(name, toscaRequirement);
+ }
+
+ /**
+ * Allows to convert capabilities of a node type to tosca template capabilities
+ * @param component
+ * @param dataTypes
+ * @return
+ */
+ public Map<String, ToscaCapability> convertCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
+ Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
+ if (capabilities != null) {
+ boolean isNodeType = ModelConverter.isAtomicComponent(component);
+ for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
+ entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes , c.getName()));
+ }
+ } else {
+ logger.debug(NO_CAPABILITIES);
+ }
+
+ return toscaCapabilities;
+ }
+
+ /**
+ * Allows to convert capabilities of a server proxy node type to tosca template capabilities
+ * @param component
+ * @param proxyComponent
+ * @param instanceProxy
+ * @param dataTypes
+ * @return
+ */
+ public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache, Component component, Component proxyComponent, ComponentInstance instanceProxy, Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities();
+ Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
+ if (capabilities != null) {
+ boolean isNodeType = ModelConverter.isAtomicComponent(component);
+ for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
+ entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes , buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c )));
+ }
+ } else {
+ logger.debug(NO_CAPABILITIES);
+ }
+
+ return toscaCapabilities;
+ }
+
+ /**
+ * Allows to convert component capabilities to the tosca template substitution mappings capabilities
+ * @param componentsCache
+ * @param component
+ * @return
+ */
+ public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) {
+ Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
+ Either<Map<String, String[]>, ToscaError> res;
+ if (capabilities != null) {
+ res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities);
+ } else {
+ res = Either.left(Maps.newHashMap());
+ logger.debug(NO_CAPABILITIES);
+ }
+ return res;
+ }
+
+ private String getCapabilityPath(CapabilityDefinition c, Component component) {
+ // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..)
+ // dirty quick fix. must be changed as capability redesign
+ List<String> capPath = c.getPath();
+ String lastInPath = capPath.get(capPath.size() - 1);
+ Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst();
+ if (findFirst.isPresent()) {
+ String lastInPathName = findFirst.get().getNormalizedName();
+
+ if (capPath.size() > 1) {
+ List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList()));
+
+ return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString();
+ }else{
+ return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString();
+ }
+ }
+ return "";
+ }
+
+ private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes , String capabilityName) {
+ String name = isNoneBlank(capabilityName) ? capabilityName : c.getName();
+ if (!isNodeType) {
+ name = getCapabilityPath(c, component);
+ }
+ logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId());
+ ToscaCapability toscaCapability = new ToscaCapability();
+ toscaCapability.setDescription(c.getDescription());
+ toscaCapability.setType(c.getType());
+
+ List<Object> occurences = new ArrayList<>();
+ occurences.add(Integer.valueOf(c.getMinOccurrences()));
+ if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ occurences.add(c.getMaxOccurrences());
+ } else {
+ occurences.add(Integer.valueOf(c.getMaxOccurrences()));
+ }
+ toscaCapability.setOccurrences(occurences);
+
+ toscaCapability.setValid_source_types(c.getValidSourceTypes());
+ List<ComponentInstanceProperty> properties = c.getProperties();
+ if (isNotEmpty(properties)) {
+ Map<String, ToscaProperty> toscaProperties = new HashMap<>();
+ for (PropertyDefinition property : properties) {
+ ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true);
+ toscaProperties.put(property.getName(), toscaProperty);
+ }
+ toscaCapability.setProperties(toscaProperties);
+ }
+ toscaCapabilities.put(name, toscaCapability);
+ }
+ /**
+ * Allows to build substituted name of capability\requirement of the origin component instance according to the path
+ * @param componentsCache
+ * @param originComponent
+ * @param path
+ * @param name
+ * @return
+ */
+ public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name) {
+ StringBuilder substitutedName = new StringBuilder();
+ boolean nameBuiltSuccessfully = true;
+ Either<String, Boolean> result;
+ if(isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){
+ List<String> reducedPath = getReducedPath(path);
+ Collections.reverse(reducedPath);
+ nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName);
+ }
+ if(nameBuiltSuccessfully){
+ result = Either.left(substitutedName.append(name).toString());
+ } else {
+ result = Either.right(nameBuiltSuccessfully);
+ }
+ return result;
+ }
+
+ protected List<String> getReducedPathByOwner(List<String> path , String ownerId) {
+ logger.debug("ownerId {}, path {} ", ownerId, path);
+ if ( CollectionUtils.isEmpty(path) ){
+ logger.debug("cannot perform reduce by owner, path to component is empty");
+ return path;
+ }
+ if ( isBlank(ownerId) ){
+ logger.debug("cannot perform reduce by owner, component owner is empty");
+ return path;
+ }
+ //reduce by owner
+ Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it,PATH_DELIMITER) , Function.identity() , ( a , b ) -> a.endsWith(ownerId) ? a : b ));
+ //reduce list&duplicates and preserve order
+ return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList());
+ }
+
+ private List<String> getReducedPath(List<String> path) {
+ return path.stream().distinct().collect(Collectors.toList());
+ }
+
+ private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) {
+ if(isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){
+ String instanceId = instanceIdIter.next();
+ Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+ if(!instanceOpt.isPresent()){
+ logger.error("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId());
+ return false;
+ }
+ substitutedName.append(instanceOpt.get().getNormalizedName()).append('.');
+ Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get());
+ if(getOriginRes.isRight()){
+ return false;
+ }
+ appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName);
+ }
+ return true;
+ }
+
+ Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) {
+ Either<Component, Boolean> result;
+ Either<Component, StorageOperationStatus> getOriginRes;
+ if(componentsCache.containsKey(instance.getActualComponentUid())){
+ result = Either.left(componentsCache.get(instance.getActualComponentUid()));
+ } else {
+ ComponentParametersView filter = getFilter(instance);
+ getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter);
+ if(getOriginRes.isRight()){
+ logger.error("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid());
+ result = Either.right(false);
+ } else {
+ result = Either.left(getOriginRes.left().value());
+ componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value());
+ }
+ }
+ return result;
+ }
+
+ private ComponentParametersView getFilter(ComponentInstance instance) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ if(instance.getIsProxy()){
+ filter.setIgnoreCapabilities(false);
+ filter.setIgnoreRequirements(false);
+ filter.setIgnoreCategories(false);
+ }
+ return filter;
+ }
+
+} \ No newline at end of file
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 f6ae79b26a..ed3a2462bd 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
@@ -103,1458 +103,1466 @@ import fj.data.Either;
*/
@org.springframework.stereotype.Component("csar-utils")
public class CsarUtils {
- private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName());
-
- @Autowired
- private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
- @Autowired
- private ArtifactCassandraDao artifactCassandraDao;
- @Autowired
- private ComponentsUtils componentsUtils;
- @Autowired
- private ToscaExportHandler toscaExportUtils;
- @Autowired
- private ArtifactsBusinessLogic artifactsBusinessLogic;
- @Autowired
- protected ToscaOperationFacade toscaOperationFacade;
-
-
- @javax.annotation.Resource
- private ServiceBusinessLogic serviceBusinessLogic;
-
- private Gson gson = new Gson();
-
- public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
- public static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
-
- public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
- public static final String ARTIFACTS_PATH = "Artifacts/";
- public static final String RESOURCES_PATH = "Resources/";
- public static final String INFORMATIONAL_ARTIFACTS = "Informational/";
- public static final String DEPLOYMENT_ARTIFACTS = "Deployment/";
-
- public static final String DEFINITIONS_PATH = "Definitions/";
- private static final String CSAR_META_VERSION = "1.0";
- private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
- 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 ARTIFACTS = "Artifacts";
- public static final String DEFINITION = "Definitions";
- public static final String DEL_PATTERN = "([/\\\\]+)";
- private static String versionFirstThreeOctates;
-
- public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
- ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
- "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
- "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
- "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
- "([\\d\\w\\_\\-\\.\\s]+)";
-
- public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
- // Artifact Group (i.e Deployment/Informational)
- "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
- // Artifact Type
- "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
- // Artifact Any File Name
- ".+";
- public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
+ private static final Logger log = LoggerFactory.getLogger(CsarUtils.class);
+
+ @Autowired
+ private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
+ @Autowired
+ private ArtifactCassandraDao artifactCassandraDao;
+ @Autowired
+ private ComponentsUtils componentsUtils;
+ @Autowired
+ private ToscaExportHandler toscaExportUtils;
+ @Autowired
+ private ArtifactsBusinessLogic artifactsBusinessLogic;
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+
+ @javax.annotation.Resource
+ private ServiceBusinessLogic serviceBusinessLogic;
+
+ private Gson gson = new Gson();
+
+ public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
+ public static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
+
+ public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0");
+ public static final String ARTIFACTS_PATH = "Artifacts/";
+ public static final String RESOURCES_PATH = "Resources/";
+ public static final String INFORMATIONAL_ARTIFACTS = "Informational/";
+ public static final String DEPLOYMENT_ARTIFACTS = "Deployment/";
+
+ public static final String DEFINITIONS_PATH = "Definitions/";
+ private static final String CSAR_META_VERSION = "1.0";
+ private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
+ 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 ARTIFACTS = "Artifacts";
+ public static final String DEFINITION = "Definitions";
+ public static final String DEL_PATTERN = "([/\\\\]+)";
+ private static String versionFirstThreeOctates;
+
+ public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
+ ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
+ "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
+ "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
+ "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
+ "([\\d\\w\\_\\-\\.\\s]+)";
+
+ public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
+ // Artifact Group (i.e Deployment/Informational)
+ "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
+ // Artifact Type
+ "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN +
+ // Artifact Any File Name
+ ".+";
+ public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
// Service Template File Name
"([\\w\\_\\-\\.\\s]+)";
public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
- public CsarUtils() {
- if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
- Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
- matcher.find();
- versionFirstThreeOctates = matcher.group(0);
- } else {
- versionFirstThreeOctates = "";
- }
- }
-
- /**
- *
- * @param component
- * @param getFromCS
- * @param isInCertificationRequest
- * @return
- */
- public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
- return createCsar(component, getFromCS, isInCertificationRequest, false);
- }
-
- private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
- final String createdBy = component.getCreatorFullName();
-
- String fileName;
- Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- fileName = artifactDefinition.getArtifactName();
-
- String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
- String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
- byte[] csarBlock0Byte = csarBlock0.getBytes();
-
- final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
- byte[] toscaBlock0Byte = toscaBlock0.getBytes();
-
- Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator);
-
- if (generateCsarZipResponse.isRight()) {
- return Either.right(generateCsarZipResponse.right().value());
- }
-
- return Either.left(generateCsarZipResponse.left().value());
- }
-
- private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
- try (
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ZipOutputStream zip = new ZipOutputStream(out);
- ){
- zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
- zip.write(csarBlock0Byte);
- zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
- zip.write(toscaBlock0Byte);
- Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator);
- if (populateZip.isRight()) {
- log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
- return Either.right(populateZip.right().value());
- }
-
- zip.finish();
- byte[] byteArray = out.toByteArray();
-
- return Either.left(byteArray);
- } catch (IOException e) {
- log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e);
-
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- return Either.right(responseFormat);
- }
- }
-
- private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException {
-
- LifecycleStateEnum lifecycleState = component.getLifecycleState();
- String componentYaml;
- Either<ToscaRepresentation, ToscaError> exportComponent;
- byte[] mainYaml;
- // <file name, cassandraId, component>
- List<Triple<String, String, Component>> dependencies = null;
- List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>();
-
- Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- String fileName = artifactDefinition.getArtifactName();
-
- if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- String cassandraId = artifactDefinition.getEsId();
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
- if (fromCassandra.isRight()) {
+ 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
+ * @param getFromCS
+ * @param isInCertificationRequest
+ * @return
+ */
+ public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
+ return createCsar(component, getFromCS, isInCertificationRequest, false);
+ }
+
+ private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
+ final String createdBy = component.getCreatorFullName();
+
+ String fileName;
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ fileName = artifactDefinition.getArtifactName();
+
+ String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
+ String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
+ byte[] csarBlock0Byte = csarBlock0.getBytes();
+
+ final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
+ byte[] toscaBlock0Byte = toscaBlock0.getBytes();
+
+ Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator);
+
+ if (generateCsarZipResponse.isRight()) {
+ return Either.right(generateCsarZipResponse.right().value());
+ }
+
+ return Either.left(generateCsarZipResponse.left().value());
+ }
+
+ private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) {
+ try (
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ZipOutputStream zip = new ZipOutputStream(out);
+ ){
+ zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
+ zip.write(csarBlock0Byte);
+ zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
+ zip.write(toscaBlock0Byte);
+ Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator);
+ if (populateZip.isRight()) {
+ log.debug("Failed to populate CSAR zip file {}", populateZip.right().value());
+ return Either.right(populateZip.right().value());
+ }
+
+ zip.finish();
+ byte[] byteArray = out.toByteArray();
+
+ return Either.left(byteArray);
+ } catch (IOException e) {
+ log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e);
+
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(responseFormat);
+ }
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException {
+
+ LifecycleStateEnum lifecycleState = component.getLifecycleState();
+ String componentYaml;
+ Either<ToscaRepresentation, ToscaError> exportComponent;
+ byte[] mainYaml;
+ // <file name, cassandraId, component>
+ List<Triple<String, String, Component>> dependencies = null;
+ List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>();
+
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ String fileName = artifactDefinition.getArtifactName();
+
+ if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
+ String cassandraId = artifactDefinition.getEsId();
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
+ if (fromCassandra.isRight()) {
log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
- return Either.right(responseFormat);
- }
- mainYaml = fromCassandra.left().value();
-
- } else {
- exportComponent = toscaExportUtils.exportComponent(component);
- if (exportComponent.isRight()) {
- log.debug("exportComponent failed", exportComponent.right().value());
- ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
- return Either.right(responseFormat);
- }
- ToscaRepresentation exportResult = exportComponent.left().value();
- componentYaml = exportResult.getMainYaml();
- mainYaml = componentYaml.getBytes();
- dependencies = exportResult.getDependencies();
- }
-
- zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
- zip.write(mainYaml);
- //US798487 - Abstraction of complex types
- if (!ModelConverter.isAtomicComponent(component)){
- log.debug("Component {} is complex - generating abstract type for it..", component.getName());
- writeComponentInterface(component, zip, fileName);
- }
-
- generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));
-
- if (dependencies == null) {
- Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
- if (dependenciesRes.isRight()) {
- log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
- dependenciesRes.right().value());
- ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
- return Either.right(responseFormat);
- }
- dependencies = dependenciesRes.left().value().getDependencies();
- }
-
- //UID <cassandraId,filename,component>
- Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
-
- if (dependencies != null && !dependencies.isEmpty()) {
- for (Triple<String, String, Component> d : dependencies) {
- String cassandraId = d.getMiddle();
- Component childComponent = d.getRight();
- Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
-
- if (entryData.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
- return Either.right(responseFormat);
- }
-
- //fill innerComponentsCache
- fileName = d.getLeft();
- addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
- addInnerComponentsToCache(innerComponentsCache, childComponent);
-
- byte[] content = entryData.left().value();
- generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
- }
-
- //add inner components to CSAR
- for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
-
- ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
-
- Component innerComponent = innerComponentTriple.getRight();
- String icFileName = innerComponentTriple.getMiddle();
-
- // add component to zip
- Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
- if (entryData.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
- log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
- entryData.right().value());
- return Either.right(responseFormat);
- }
- byte[] content = entryData.left().value();
- zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
- zip.write(content);
-
- // add component interface to zip
- if (!ModelConverter.isAtomicComponent(innerComponent)) {
- writeComponentInterface(innerComponent, zip, icFileName);
- }
- }
- }
-
- //retrieve SDC.zip from Cassandra
- Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
-
- if(latestSchemaFilesFromCassandra.isRight()){
- log.error("Error retrieving SDC Schema files from cassandra" );
- return Either.right(latestSchemaFilesFromCassandra.right().value());
- }
-
- //add files from retireved SDC.zip to Definitions folder in CSAR
- Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value());
-
- if(addSchemaFilesFromCassandra.isRight()){
- return addSchemaFilesFromCassandra;
- }
-
- // Artifact Generation
- if (component.getComponentType() == ComponentTypeEnum.SERVICE
- && isInCertificationRequest) {
-
- List<ArtifactDefinition> aiiArtifactList;
-
- Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs);
-
- if (handleAAIArtifacts.isLeft()) {
- aiiArtifactList = handleAAIArtifacts.left().value();
- } else {
- log.debug("AAI Artifacts handling failed");
- return Either.right(handleAAIArtifacts.right().value());
- }
-
- if (isInCertificationRequest) {
- Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
- component, aiiArtifactList, false, true);
-
- if (handleAllAAIArtifactsInDataModel.isRight()) {
- log.debug("AAI Artifacts handling (create, update, delete) failed");
- return Either.right(handleAllAAIArtifactsInDataModel.right().value());
- }
- }
-
- }
-
- Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
-
- if (collectedComponentCsarDefinition.isRight()) {
- return Either.right(collectedComponentCsarDefinition.right().value());
- }
-
- return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
- }
-
- private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){
-
- final int initSize = 2048;
-
- log.debug("Starting copy 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);) {
-
- 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();
- }
- } 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 addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
- Component childComponent) {
-
- List<ComponentInstance> instances = childComponent.getComponentInstances();
-
- if(instances != null) {
- instances.forEach(ci -> {
- ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
- if (componentRecord == null) {
- // all resource must be only once!
- Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
- if (resource.isRight()) {
- log.debug("Failed to fetch resource with id {} for instance {}");
- }
- Component componentRI = resource.left().value();
-
- Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
- ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- if (childArtifactDefinition != null) {
- //add to cache
- addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
- }
-
- //if not atomic - insert inner components as well
- if(!ModelConverter.isAtomicComponent(componentRI)) {
- addInnerComponentsToCache(componentCache, componentRI);
- }
- }
- });
- }
- }
-
- private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
- String id, String fileName, Component component) {
-
- ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
- if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
- componentCache.put(component.getInvariantUUID(),
- new ImmutableTriple<String, String, Component>(id, fileName, component));
-
- if(cachedComponent != null) {
- //overwriting component with newer version
- log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
- }
- }
- }
-
- private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
- try {
- Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component);
- ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
- String mainYaml = componentInterfaceYaml.getMainYaml();
- String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
-
- zip.putNextEntry(new ZipEntry(interfaceFileName));
- zip.write(mainYaml.getBytes());
-
- } catch (Exception e) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
-
- return Either.left(zip);
- }
-
- private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
-
- ComponentTypeEnum componentType = component.getComponentType();
- List<Artifact> generatedArtifacts;
- List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
-
- if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
- List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
-
- Either<List<Artifact>, String> generatorResponse;
-
- if (mockGenerator) {
- generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
- } else {
- generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component);
- }
-
- if (generatorResponse.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
- return Either.right(responseFormat);
- }
-
- generatedArtifacts = generatorResponse.left().value();
-
- aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts);
-
- }
-
- return Either.left(aaiArtifacts);
- }
-
- private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
-
- Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
- User lastComponentUpdater;
-
- List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
- List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
- List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component);
-
- String lastUpdaterUserId = component.getLastUpdaterUserId();
- Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true);
-
- if (validateUserExists.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found");
- return Either.right(responseFormat);
- }
-
- lastComponentUpdater = validateUserExists.left().value();
-
- handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock,
- inTransaction);
-
- if (handleAAIArtifactsResponse.isRight()) {
- return handleAAIArtifactsResponse;
- }
-
- handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock,
- inTransaction);
-
- if (handleAAIArtifactsResponse.isRight()) {
- return handleAAIArtifactsResponse;
- }
-
- return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction);
- }
-
- private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
-
- Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
- Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
-
- return artifactsFromAAI.stream()
- .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))
- .filter(e -> checkAaiForUpdate(component, e))
- .collect(Collectors.toList());
- }
-
- private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) {
- ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel());
-
- if (artifactDefinitionComp == null) {
- log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel());
- return false;
- }
-
- // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated
- if (artifactDefinitionComp.getGenerated() == null) {
- if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) {
- return true;
- } else {
- log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel());
- }
- } else {
- if (artifactDefinition.getGenerated()) {
- return true;
- } else {
- log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel());
- }
- }
- return false;
- }
-
- private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
-
- Set<String> aaiLabels = artifactsFromAAI.stream()
- .map(ArtifactDefinition::getArtifactLabel)
- .collect(Collectors.toSet());
-
- List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream()
- // Filter Out Artifacts that are not contained in artifacts returned
- // from AAI API
- .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
- .collect(Collectors.toList());
-
- List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream()
- // Filter Out Artifacts that are not contained in artifacts returned
- // from AAI API
- .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
- .collect(Collectors.toList());
-
- artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational);
-
- return artifactsForDeleteDeployment.stream()
- .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai")))
- .collect(Collectors.toList());
- }
-
- private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
-
- Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet();
- Set<String> componentInfoLabels = component.getArtifacts().keySet();
-
- // If the artifact label does not exist in the service -
- // store the artifact (generate uuid and version, "generated" flag is TRUE)
- return artifactsFromAAI.stream()
- .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel()))
- .collect(Collectors.toList());
- }
-
- private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
- boolean inTransaction) {
-
- String componentUniqueId = component.getUniqueId();
- ComponentTypeEnum componentType = component.getComponentType();
-
- for (ArtifactDefinition artDef : generatedArtifactsDefinitions) {
- String data = gson.toJson(artDef);
- String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data);
- String artifactUniqueId = null;
-
- if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) {
- String artifactLabel = artDef.getArtifactLabel();
- ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
- if (artifactDefinition != null) {
- artifactUniqueId = artifactDefinition.getUniqueId();
- }
- }
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null,
- null, null, user, component, shouldLock, inTransaction, false);
-
- if (validateAndHandleArtifact.isRight()) {
- if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString());
-
- Either.right(responseFormat);
- } else {
- log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel());
- }
- }
- }
-
- return Either.left(ActionStatus.OK);
- }
-
- private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) {
- List<ArtifactDefinition> artifactDefList = new LinkedList<>();
-
- for (Artifact artifact : generatorOutput) {
- ArtifactDefinition newEntry = new ArtifactDefinition();
- newEntry.setArtifactName(artifact.getName());
- newEntry.setArtifactType(artifact.getType());
- newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType()));
- newEntry.setDescription(artifact.getDescription());
-
- // Normalizing the artifact label to match those stored in DB
- String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
- newEntry.setArtifactLabel(normalizeArtifactLabel);
- newEntry.setPayload(Base64.decodeBase64(artifact.getPayload()));
- newEntry.setArtifactChecksum(artifact.getChecksum());
- // Flag that set to true in case that the artifact is generated by AI&I generator
- newEntry.setGenerated(Boolean.TRUE);
-
- artifactDefList.add(newEntry);
- }
-
- return artifactDefList;
- }
-
- // List<ImmutablePair<Component, byte[] artifactBytes>>
- // artifact stored by label
- private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) {
- List<Artifact> listOfArtifactsInput = new LinkedList<>();
- for (ImmutablePair<Component, byte[]> triple : inputs) {
- Component component = triple.getLeft();
-
- Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
-
- String artifactName = artifactDefinition.getArtifactName();
- String artifactType = artifactDefinition.getArtifactType();
- String artifactGroupType = artifactDefinition.getArtifactGroupType().getType();
- String artifactDescription = artifactDefinition.getDescription();
- String artifactLabel = artifactDefinition.getArtifactLabel();
- byte[] right = triple.getRight();
- // The md5 calculated on the uncoded data
- String md5Hex = DigestUtils.md5Hex(right);
- byte[] payload = Base64.encodeBase64(right);
- String artifactVersion = artifactDefinition.getArtifactVersion();
-
- Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload);
- convertedArtifact.setName(artifactName);
- convertedArtifact.setDescription(artifactDescription);
- convertedArtifact.setLabel(artifactLabel);
- convertedArtifact.setVersion(artifactVersion);
-
- listOfArtifactsInput.add(convertedArtifact);
- }
-
- return listOfArtifactsInput;
- }
-
- private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
- byte[] content;
- if (cassandraId == null || cassandraId.isEmpty()) {
- Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
- if (exportRes.isRight()) {
- log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value());
- return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
- }
- content = exportRes.left().value().getMainYaml().getBytes();
- } else {
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
- if (fromCassandra.isRight()) {
- return Either.right(fromCassandra.right().value());
- } else {
- content = fromCassandra.left().value();
- }
- }
- return Either.left(content);
- }
-
- private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
- Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL);
-
- 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<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
-
- if(listOfSchemas.isEmpty()){
- 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));
- }
-
- SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
-
- return Either.left(schemaFile.getPayloadAsArray());
- }
-
- private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
- Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
-
- if (artifactResponse.isRight()) {
- log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
-
- StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
- ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
- return Either.right(convertedFromStorageResponse);
- }
- ESArtifactData artifactData = artifactResponse.left().value();
- return Either.left(artifactData.getDataAsArray());
- }
-
- private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
- final String BLOCK_0_TEMPLATE =
- "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
- String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
- return readyBlock;
- }
-
- private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
- final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n";
- return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
- }
-
- private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
-
- ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
- ArtifactTypes artifactTypes = new ArtifactTypes();
- List<ArtifactType> artifactTypesList = new LinkedList<>();
- ArtifactType otherType;
-
- if (type == null) {
- otherType = ArtifactType.OTHER;
- } else {
- otherType = type;
- }
-
- artifactTypesList.add(otherType);
- artifactTypes.setArtifactTypes(artifactTypesList);
-
- String configJson = gson.toJson(artifactTypes);
- Map<String, String> additionalParams = new HashMap<>();
- String version;
-
- if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
- version = component.getVersion();
- } else {
- String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
- Integer majorVersion = Integer.parseInt(versionParts[0]);
-
- version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0";
- }
-
- additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
- GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams);
-
- Map<String, List<String>> errorData = generatedArtifacts.getErrorData();
-
- if (!errorData.isEmpty()) {
- Set<String> keySet = errorData.keySet();
- StringBuilder error = new StringBuilder();
-
- for (String key : keySet) {
- List<String> errorList = errorData.get(key);
- log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList);
- error.append(key + errorList);
- }
-
- return Either.right(error.toString());
- }
-
- return Either.left(generatedArtifacts.getResultData());
- }
-
- /**
- * Extracts artifacts of VFCs from CSAR
- *
- * @param csar
- * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
- */
- public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
-
- Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
- if (csar != null) {
- log.debug("************* Going to extract VFCs artifacts from Csar. ");
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
- csar.entrySet().stream()
- // filter CSAR entry by node type artifact path
- .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
- // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
- .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
- // add counter suffix to artifact labels
- handleWarningMessages(collectedWarningMessages);
-
- }
- return artifacts;
- }
-
- /**
- * Print warnings to log
- *
- * @param collectedWarningMessages
- */
- public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
- collectedWarningMessages.entrySet().stream()
- // for each vfc
- .forEach(e -> e.getValue().stream()
- // add each warning message to log
- .forEach(args -> log.warn(e.getKey(), args.toArray())));
-
- }
-
- private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
- if (extractedVfcArtifact != null) {
- List<ArtifactDefinition> currArtifactsList;
- String vfcToscaNamespace = extractedVfcArtifact.getKey();
- if (artifacts.containsKey(vfcToscaNamespace)) {
- currArtifactsList = artifacts.get(vfcToscaNamespace);
- } else {
- currArtifactsList = new ArrayList<>();
- artifacts.put(vfcToscaNamespace, currArtifactsList);
- }
- currArtifactsList.add(extractedVfcArtifact.getValue());
- }
- }
-
- private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
- ArtifactDefinition artifact;
- String[] parsedCsarArtifactPath = entry.getKey().split("/");
- Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
- if (eitherArtifactGroupType.isLeft()) {
- artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
- } else {
- return null;
- }
- return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
- }
-
- private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
- Either<ArtifactGroupTypeEnum, Boolean> result;
- try {
- ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
- if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
- String warningMessage = "Warning - unrecognized artifact group type {} was received.";
- List<String> messageArguments = new ArrayList<>();
- messageArguments.add(groupType);
- if (!collectedWarningMessages.containsKey(warningMessage)) {
- Set<List<String>> messageArgumentLists = new HashSet<>();
- messageArgumentLists.add(messageArguments);
- collectedWarningMessages.put(warningMessage, messageArgumentLists);
- } else {
- collectedWarningMessages.get(warningMessage).add(messageArguments);
- }
-
- result = Either.right(false);
- } else {
-
- result = Either.left(artifactGroupType);
- }
- } catch (Exception e) {
- log.debug("detectArtifactGroupType failed with exception", e);
- result = Either.right(false);
- }
- return result;
- }
-
- private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
- ArtifactDefinition artifact;
- artifact = new ArtifactDefinition();
- artifact.setArtifactGroupType(artifactGroupType);
- artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
- artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
- artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
- artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
- artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
- artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
- artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
- return artifact;
- }
-
- public static final class NonMetaArtifactInfo {
- private final String path;
- private final String artifactName;
- private final String displayName;
- private final String artifactLabel;
- private final ArtifactTypeEnum artifactType;
- private final ArtifactGroupTypeEnum artifactGroupType;
- private String payloadData;
- private String artifactChecksum;
- private String artifactUniqueId;
-
- public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) {
- super();
- this.path = path;
- this.artifactName = ValidationUtils.normalizeFileName(artifactName);
- this.artifactType = artifactType;
- this.artifactGroupType = artifactGroupType;
- final int pointIndex = artifactName.lastIndexOf('.');
- if (pointIndex > 0) {
- displayName = artifactName.substring(0, pointIndex);
- } else {
- displayName = artifactName;
- }
- this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
- if (payloadData != null) {
- this.payloadData = Base64.encodeBase64String(payloadData);
- this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
- }
- this.artifactUniqueId = artifactUniqueId;
- }
-
- public String getPath() {
- return path;
- }
-
- public String getArtifactName() {
- return artifactName;
- }
-
- public ArtifactTypeEnum getArtifactType() {
- return artifactType;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public ArtifactGroupTypeEnum getArtifactGroupType() {
- return artifactGroupType;
- }
-
- public String getArtifactLabel() {
- return artifactLabel;
- }
-
- public String getPayloadData() {
- return payloadData;
- }
-
- public String getArtifactChecksum() {
- return artifactChecksum;
- }
-
- public String getArtifactUniqueId() {
- return artifactUniqueId;
- }
-
- public void setArtifactUniqueId(String artifactUniqueId) {
- this.artifactUniqueId = artifactUniqueId;
- }
-
- }
-
- /**
- * This method checks the artifact GroupType & Artifact Type. <br>
- * if there is any problem warning messages are added to collectedWarningMessages
- *
- * @param artifactPath
- * @param collectedWarningMessages
- * @return
- */
- public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
- Either<NonMetaArtifactInfo, Boolean> ret;
- try {
- String[] parsedArtifactPath = artifactPath.split("/");
- // Validate Artifact Group Type
- Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
- if (eitherGroupType.isLeft()) {
- final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
-
- // Validate Artifact Type
- String artifactType = parsedArtifactPath[2];
- artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
-
- String artifactFileNameType = parsedArtifactPath[3];
- ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null));
-
- } else {
- ret = Either.right(eitherGroupType.right().value());
- }
- } catch (Exception e) {
- log.debug("detectArtifactGroupType failed with exception", e);
- ret = Either.right(false);
- }
- return ret;
-
- }
-
- private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
- String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
- return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
- }
-
- private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
- String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
- return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
- }
-
- private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
-
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
- Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
-
- if(artifactGroupType != null){
- switch (artifactGroupType) {
- case INFORMATIONAL:
- resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getResourceInformationalArtifacts();
- break;
- case DEPLOYMENT:
- resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getResourceDeploymentArtifacts();
- break;
- default:
- break;
- }
- }
-
- Set<String> validArtifactTypes = null;
- if(resourceValidTypeArtifacts != null){
- validArtifactTypes = resourceValidTypeArtifacts.keySet();
- }
-
- if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
- List<String> messageArguments = new ArrayList<>();
- messageArguments.add(receivedTypeName);
- messageArguments.addAll(Arrays.asList(arguments));
- if (!collectedWarningMessages.containsKey(warningMessage)) {
- Set<List<String>> messageArgumentLists = new HashSet<>();
- messageArgumentLists.add(messageArguments);
- collectedWarningMessages.put(warningMessage, messageArgumentLists);
- } else {
- collectedWarningMessages.get(warningMessage).add(messageArguments);
- }
- }
-
- return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
- }
-
- private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
- ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
-
- Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
-
- if(writeComponentArtifactsToSpecifiedtPath.isRight()){
- return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
- }
-
- ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
- writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
-
- if(writeComponentArtifactsToSpecifiedtPath.isRight()){
- return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
- }
-
- Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
- Set<String> keySet = componentInstancesArtifacts.keySet();
-
- String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
- for (String keyAssetName : keySet) {
- ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
- String pathWithAssetName = currentPath + keyAssetName + "/";
- writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
-
- if(writeComponentArtifactsToSpecifiedtPath.isRight()){
- return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
- }
- }
-
- return Either.left(zipstream);
- }
-
- private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
- String currentPath, boolean isInCertificationRequest) throws IOException {
- Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
- //Keys are defined:
- //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
- //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
- Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
- for (String keyAssetName : componentTypeArtifactsKeys) {
- ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
- ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
- String pathWithAssetName = currentPath + keyAssetName + "/";
- Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
-
- if(writeArtifactsInfoToSpecifiedtPath.isRight()){
- return writeArtifactsInfoToSpecifiedtPath;
- }
- }
-
- return Either.left(zipstream);
- }
-
- private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
- Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
- .getArtifactsInfo();
- Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
-
- for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
- String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/";
-
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
- Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
-
- for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
- List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
- String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/";
-
- Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
-
- if(writeArtifactDefinition.isRight()){
- return writeArtifactDefinition;
- }
- }
- }
-
- return Either.left(zip);
- }
-
- private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
- String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
-
- ComponentTypeEnum componentType = mainComponent.getComponentType();
- String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
-
- for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
- if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
- && artifactDefinition.getArtifactType().equals(heatEnvType) ||
+ return Either.right(responseFormat);
+ }
+ mainYaml = fromCassandra.left().value();
+
+ } else {
+ exportComponent = toscaExportUtils.exportComponent(component);
+ if (exportComponent.isRight()) {
+ log.debug("exportComponent failed", exportComponent.right().value());
+ ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
+ return Either.right(responseFormat);
+ }
+ ToscaRepresentation exportResult = exportComponent.left().value();
+ componentYaml = exportResult.getMainYaml();
+ mainYaml = componentYaml.getBytes();
+ dependencies = exportResult.getDependencies();
+ }
+
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
+ zip.write(mainYaml);
+ //US798487 - Abstraction of complex types
+ if (!ModelConverter.isAtomicComponent(component)){
+ log.debug("Component {} is complex - generating abstract type for it..", component.getName());
+ writeComponentInterface(component, zip, fileName);
+ }
+
+ generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml));
+
+ if (dependencies == null) {
+ Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
+ if (dependenciesRes.isRight()) {
+ log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
+ dependenciesRes.right().value());
+ ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
+ return Either.right(responseFormat);
+ }
+ dependencies = dependenciesRes.left().value().getDependencies();
+ }
+
+ //UID <cassandraId,filename,component>
+ Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
+
+ if (dependencies != null && !dependencies.isEmpty()) {
+ for (Triple<String, String, Component> d : dependencies) {
+ String cassandraId = d.getMiddle();
+ Component childComponent = d.getRight();
+ Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
+
+ if (entryData.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
+ return Either.right(responseFormat);
+ }
+
+ //fill innerComponentsCache
+ fileName = d.getLeft();
+ addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
+ addInnerComponentsToCache(innerComponentsCache, childComponent);
+
+ byte[] content = entryData.left().value();
+ generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
+ }
+
+ //add inner components to CSAR
+ for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
+
+ ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
+
+ Component innerComponent = innerComponentTriple.getRight();
+ String icFileName = innerComponentTriple.getMiddle();
+
+ // add component to zip
+ Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
+ if (entryData.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
+ log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
+ entryData.right().value());
+ return Either.right(responseFormat);
+ }
+ byte[] content = entryData.left().value();
+ zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
+ zip.write(content);
+
+ // add component interface to zip
+ if (!ModelConverter.isAtomicComponent(innerComponent)) {
+ writeComponentInterface(innerComponent, zip, icFileName);
+ }
+ }
+ }
+
+ //retrieve SDC.zip from Cassandra
+ Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
+
+ if(latestSchemaFilesFromCassandra.isRight()){
+ log.error("Error retrieving SDC Schema files from cassandra" );
+ return Either.right(latestSchemaFilesFromCassandra.right().value());
+ }
+
+ //add files from retireved SDC.zip to Definitions folder in CSAR
+ Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value());
+
+ if(addSchemaFilesFromCassandra.isRight()){
+ return addSchemaFilesFromCassandra;
+ }
+
+ // Artifact Generation
+ if (component.getComponentType() == ComponentTypeEnum.SERVICE
+ && isInCertificationRequest) {
+
+ List<ArtifactDefinition> aiiArtifactList;
+
+ Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs);
+
+ if (handleAAIArtifacts.isLeft()) {
+ aiiArtifactList = handleAAIArtifacts.left().value();
+ } else {
+ log.debug("AAI Artifacts handling failed");
+ return Either.right(handleAAIArtifacts.right().value());
+ }
+
+ if (isInCertificationRequest) {
+ Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel(
+ component, aiiArtifactList, false, true);
+
+ if (handleAllAAIArtifactsInDataModel.isRight()) {
+ log.debug("AAI Artifacts handling (create, update, delete) failed");
+ return Either.right(handleAllAAIArtifactsInDataModel.right().value());
+ }
+ }
+
+ }
+
+ Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
+
+ if (collectedComponentCsarDefinition.isRight()) {
+ return Either.right(collectedComponentCsarDefinition.right().value());
+ }
+
+ return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){
+
+ final int initSize = 2048;
+
+ log.debug("Starting copy 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);) {
+
+ 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();
+ }
+ } 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 addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ Component childComponent) {
+
+ List<ComponentInstance> instances = childComponent.getComponentInstances();
+
+ if(instances != null) {
+ instances.forEach(ci -> {
+ ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
+ if (componentRecord == null) {
+ // all resource must be only once!
+ Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
+ if (resource.isRight()) {
+ log.debug("Failed to fetch resource with id {} for instance {}");
+ }
+ Component componentRI = resource.left().value();
+
+ Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
+ ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ if (childArtifactDefinition != null) {
+ //add to cache
+ addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
+ }
+
+ //if not atomic - insert inner components as well
+ if(!ModelConverter.isAtomicComponent(componentRI)) {
+ addInnerComponentsToCache(componentCache, componentRI);
+ }
+ }
+ });
+ }
+ }
+
+ private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ String id, String fileName, Component component) {
+
+ ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
+ if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
+ componentCache.put(component.getInvariantUUID(),
+ new ImmutableTriple<String, String, Component>(id, fileName, component));
+
+ if(cachedComponent != null) {
+ //overwriting component with newer version
+ log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
+ }
+ }
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
+ try {
+ Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component);
+ ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
+ String mainYaml = componentInterfaceYaml.getMainYaml();
+ String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
+
+ zip.putNextEntry(new ZipEntry(interfaceFileName));
+ zip.write(mainYaml.getBytes());
+
+ } catch (Exception e) {
+ log.error("#writeComponentInterface - zip writing failed with error: ", e);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
+ return Either.left(zip);
+ }
+
+ private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) {
+
+ ComponentTypeEnum componentType = component.getComponentType();
+ List<Artifact> generatedArtifacts;
+ List<ArtifactDefinition> aaiArtifacts = new LinkedList<>();
+
+ if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) {
+ List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs);
+
+ Either<List<Artifact>, String> generatorResponse;
+
+ if (mockGenerator) {
+ generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component);
+ } else {
+ generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component);
+ }
+
+ if (generatorResponse.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value());
+ return Either.right(responseFormat);
+ }
+
+ generatedArtifacts = generatorResponse.left().value();
+
+ aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts);
+
+ }
+
+ return Either.left(aaiArtifacts);
+ }
+
+ private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) {
+
+ Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse;
+ User lastComponentUpdater;
+
+ List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component);
+ List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component);
+ List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component);
+
+ String lastUpdaterUserId = component.getLastUpdaterUserId();
+ Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true);
+
+ if (validateUserExists.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found");
+ return Either.right(responseFormat);
+ }
+
+ lastComponentUpdater = validateUserExists.left().value();
+
+ handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock,
+ inTransaction);
+
+ if (handleAAIArtifactsResponse.isRight()) {
+ return handleAAIArtifactsResponse;
+ }
+
+ handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock,
+ inTransaction);
+
+ if (handleAAIArtifactsResponse.isRight()) {
+ return handleAAIArtifactsResponse;
+ }
+
+ return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction);
+ }
+
+ private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
+
+ Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet();
+ Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet();
+
+ return artifactsFromAAI.stream()
+ .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel()))
+ .filter(e -> checkAaiForUpdate(component, e))
+ .collect(Collectors.toList());
+ }
+
+ private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) {
+ ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel());
+
+ if (artifactDefinitionComp == null) {
+ log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel());
+ return false;
+ }
+
+ // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated
+ if (artifactDefinitionComp.getGenerated() == null) {
+ if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) {
+ return true;
+ } else {
+ log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel());
+ }
+ } else {
+ if (artifactDefinition.getGenerated()) {
+ return true;
+ } else {
+ log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel());
+ }
+ }
+ return false;
+ }
+
+ private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) {
+
+ Set<String> aaiLabels = artifactsFromAAI.stream()
+ .map(ArtifactDefinition::getArtifactLabel)
+ .collect(Collectors.toSet());
+
+ List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream()
+ // Filter Out Artifacts that are not contained in artifacts returned
+ // from AAI API
+ .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
+
+ List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream()
+ // Filter Out Artifacts that are not contained in artifacts returned
+ // from AAI API
+ .filter(e -> !aaiLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
+
+ artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational);
+
+ return artifactsForDeleteDeployment.stream()
+ .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai")))
+ .collect(Collectors.toList());
+ }
+
+ private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) {
+
+ Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet();
+ Set<String> componentInfoLabels = component.getArtifacts().keySet();
+
+ // If the artifact label does not exist in the service -
+ // store the artifact (generate uuid and version, "generated" flag is TRUE)
+ return artifactsFromAAI.stream()
+ .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel()))
+ .collect(Collectors.toList());
+ }
+
+ private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock,
+ boolean inTransaction) {
+
+ String componentUniqueId = component.getUniqueId();
+ ComponentTypeEnum componentType = component.getComponentType();
+
+ for (ArtifactDefinition artDef : generatedArtifactsDefinitions) {
+ String data = gson.toJson(artDef);
+ String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data);
+ String artifactUniqueId = null;
+
+ if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) {
+ String artifactLabel = artDef.getArtifactLabel();
+ ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel);
+ if (artifactDefinition != null) {
+ artifactUniqueId = artifactDefinition.getUniqueId();
+ }
+ }
+
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null,
+ null, user, component, shouldLock, inTransaction, false);
+
+ if (validateAndHandleArtifact.isRight()) {
+ if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString());
+
+ Either.right(responseFormat);
+ } else {
+ log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel());
+ }
+ }
+ }
+
+ return Either.left(ActionStatus.OK);
+ }
+
+ private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) {
+ List<ArtifactDefinition> artifactDefList = new LinkedList<>();
+
+ for (Artifact artifact : generatorOutput) {
+ ArtifactDefinition newEntry = new ArtifactDefinition();
+ newEntry.setArtifactName(artifact.getName());
+ newEntry.setArtifactType(artifact.getType());
+ newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType()));
+ newEntry.setDescription(artifact.getDescription());
+
+ // Normalizing the artifact label to match those stored in DB
+ String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel());
+ newEntry.setArtifactLabel(normalizeArtifactLabel);
+ newEntry.setPayload(Base64.decodeBase64(artifact.getPayload()));
+ newEntry.setArtifactChecksum(artifact.getChecksum());
+ // Flag that set to true in case that the artifact is generated by AI&I generator
+ newEntry.setGenerated(Boolean.TRUE);
+
+ artifactDefList.add(newEntry);
+ }
+
+ return artifactDefList;
+ }
+
+ // List<ImmutablePair<Component, byte[] artifactBytes>>
+ // artifact stored by label
+ private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) {
+ List<Artifact> listOfArtifactsInput = new LinkedList<>();
+ for (ImmutablePair<Component, byte[]> triple : inputs) {
+ Component component = triple.getLeft();
+
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+
+ String artifactName = artifactDefinition.getArtifactName();
+ String artifactType = artifactDefinition.getArtifactType();
+ String artifactGroupType = artifactDefinition.getArtifactGroupType().getType();
+ String artifactDescription = artifactDefinition.getDescription();
+ String artifactLabel = artifactDefinition.getArtifactLabel();
+ byte[] right = triple.getRight();
+ // The md5 calculated on the uncoded data
+ String md5Hex = DigestUtils.md5Hex(right);
+ byte[] payload = Base64.encodeBase64(right);
+ String artifactVersion = artifactDefinition.getArtifactVersion();
+
+ Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload);
+ convertedArtifact.setName(artifactName);
+ convertedArtifact.setDescription(artifactDescription);
+ convertedArtifact.setLabel(artifactLabel);
+ convertedArtifact.setVersion(artifactVersion);
+
+ listOfArtifactsInput.add(convertedArtifact);
+ }
+
+ return listOfArtifactsInput;
+ }
+
+ private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
+ byte[] content;
+ if (cassandraId == null || cassandraId.isEmpty()) {
+ Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
+ if (exportRes.isRight()) {
+ log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value());
+ return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
+ }
+ content = exportRes.left().value().getMainYaml().getBytes();
+ } else {
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
+ if (fromCassandra.isRight()) {
+ return Either.right(fromCassandra.right().value());
+ } else {
+ content = fromCassandra.left().value();
+ }
+ }
+ return Either.left(content);
+ }
+
+ private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
+ Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL);
+
+ 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<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
+
+ if(listOfSchemas.isEmpty()){
+ 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));
+ }
+
+ SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
+
+ return Either.left(schemaFile.getPayloadAsArray());
+ }
+
+ private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
+ Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
+
+ if (artifactResponse.isRight()) {
+ log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
+
+ StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
+ ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
+ return Either.right(convertedFromStorageResponse);
+ }
+ ESArtifactData artifactData = artifactResponse.left().value();
+ return Either.left(artifactData.getDataAsArray());
+ }
+
+ private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
+ final String BLOCK_0_TEMPLATE =
+ "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
+ String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
+ return readyBlock;
+ }
+
+ private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
+ final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n";
+ return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
+ }
+
+ private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) {
+
+ ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl();
+ ArtifactTypes artifactTypes = new ArtifactTypes();
+ List<ArtifactType> artifactTypesList = new LinkedList<>();
+ ArtifactType otherType;
+
+ if (type == null) {
+ otherType = ArtifactType.OTHER;
+ } else {
+ otherType = type;
+ }
+
+ artifactTypesList.add(otherType);
+ artifactTypes.setArtifactTypes(artifactTypesList);
+
+ String configJson = gson.toJson(artifactTypes);
+ Map<String, String> additionalParams = new HashMap<>();
+ String version;
+
+ if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
+ version = component.getVersion();
+ } else {
+ String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
+ Integer majorVersion = Integer.parseInt(versionParts[0]);
+
+ version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0";
+ }
+
+ additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
+ GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams);
+
+ Map<String, List<String>> errorData = generatedArtifacts.getErrorData();
+
+ if (!errorData.isEmpty()) {
+ Set<String> keySet = errorData.keySet();
+ StringBuilder error = new StringBuilder();
+
+ for (String key : keySet) {
+ List<String> errorList = errorData.get(key);
+ log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList);
+ error.append(key + errorList);
+ }
+
+ return Either.right(error.toString());
+ }
+
+ return Either.left(generatedArtifacts.getResultData());
+ }
+
+ /**
+ * Extracts artifacts of VFCs from CSAR
+ *
+ * @param csar
+ * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
+ */
+ public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
+
+ Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
+ if (csar != null) {
+ log.debug("************* Going to extract VFCs artifacts from Csar. ");
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+ csar.entrySet().stream()
+ // filter CSAR entry by node type artifact path
+ .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+ // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
+ .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
+ // add counter suffix to artifact labels
+ handleWarningMessages(collectedWarningMessages);
+
+ }
+ return artifacts;
+ }
+
+ /**
+ * Print warnings to log
+ *
+ * @param collectedWarningMessages
+ */
+ public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
+ collectedWarningMessages.entrySet().stream()
+ // for each vfc
+ .forEach(e -> e.getValue().stream()
+ // add each warning message to log
+ .forEach(args -> log.warn(e.getKey(), args.toArray())));
+
+ }
+
+ private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
+ if (extractedVfcArtifact != null) {
+ List<ArtifactDefinition> currArtifactsList;
+ String vfcToscaNamespace = extractedVfcArtifact.getKey();
+ if (artifacts.containsKey(vfcToscaNamespace)) {
+ currArtifactsList = artifacts.get(vfcToscaNamespace);
+ } else {
+ currArtifactsList = new ArrayList<>();
+ artifacts.put(vfcToscaNamespace, currArtifactsList);
+ }
+ currArtifactsList.add(extractedVfcArtifact.getValue());
+ }
+ }
+
+ private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
+ ArtifactDefinition artifact;
+ String[] parsedCsarArtifactPath = entry.getKey().split("/");
+ Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
+ if (eitherArtifactGroupType.isLeft()) {
+ artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
+ } else {
+ return null;
+ }
+ return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
+ }
+
+ private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
+ Either<ArtifactGroupTypeEnum, Boolean> result;
+ try {
+ ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
+ if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
+ String warningMessage = "Warning - unrecognized artifact group type {} was received.";
+ List<String> messageArguments = new ArrayList<>();
+ messageArguments.add(groupType);
+ if (!collectedWarningMessages.containsKey(warningMessage)) {
+ Set<List<String>> messageArgumentLists = new HashSet<>();
+ messageArgumentLists.add(messageArguments);
+ collectedWarningMessages.put(warningMessage, messageArgumentLists);
+ } else {
+ collectedWarningMessages.get(warningMessage).add(messageArguments);
+ }
+
+ result = Either.right(false);
+ } else {
+
+ result = Either.left(artifactGroupType);
+ }
+ } catch (Exception e) {
+ log.debug("detectArtifactGroupType failed with exception", e);
+ result = Either.right(false);
+ }
+ return result;
+ }
+
+ private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
+ ArtifactDefinition artifact;
+ artifact = new ArtifactDefinition();
+ artifact.setArtifactGroupType(artifactGroupType);
+ artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
+ artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
+ artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
+ artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
+ artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
+ artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
+ artifact.setIsFromCsar(true);
+ artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
+ return artifact;
+ }
+
+ public static final class NonMetaArtifactInfo {
+ private final String path;
+ private final String artifactName;
+ private final String displayName;
+ private final String artifactLabel;
+ private final ArtifactTypeEnum artifactType;
+ private final ArtifactGroupTypeEnum artifactGroupType;
+ private String payloadData;
+ private String artifactChecksum;
+ private String artifactUniqueId;
+ private final boolean isFromCsar;
+
+ public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) {
+ super();
+ this.path = path;
+ this.isFromCsar = isFromCsar;
+ this.artifactName = ValidationUtils.normalizeFileName(artifactName);
+ this.artifactType = artifactType;
+ this.artifactGroupType = artifactGroupType;
+ final int pointIndex = artifactName.lastIndexOf('.');
+ if (pointIndex > 0) {
+ displayName = artifactName.substring(0, pointIndex);
+ } else {
+ displayName = artifactName;
+ }
+ this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
+ if (payloadData != null) {
+ this.payloadData = Base64.encodeBase64String(payloadData);
+ this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
+ }
+ this.artifactUniqueId = artifactUniqueId;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public ArtifactTypeEnum getArtifactType() {
+ return artifactType;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ public ArtifactGroupTypeEnum getArtifactGroupType() {
+ return artifactGroupType;
+ }
+
+ public String getArtifactLabel() {
+ return artifactLabel;
+ }
+
+ public boolean isFromCsar(){
+ return isFromCsar;
+ }
+
+ public String getPayloadData() {
+ return payloadData;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public String getArtifactUniqueId() {
+ return artifactUniqueId;
+ }
+
+ public void setArtifactUniqueId(String artifactUniqueId) {
+ this.artifactUniqueId = artifactUniqueId;
+ }
+
+ }
+
+ /**
+ * This method checks the artifact GroupType & Artifact Type. <br>
+ * if there is any problem warning messages are added to collectedWarningMessages
+ *
+ * @param artifactPath
+ * @param collectedWarningMessages
+ * @return
+ */
+ public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
+ Either<NonMetaArtifactInfo, Boolean> ret;
+ try {
+ String[] parsedArtifactPath = artifactPath.split("/");
+ // Validate Artifact Group Type
+ Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
+ if (eitherGroupType.isLeft()) {
+ final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
+
+ // Validate Artifact Type
+ String artifactType = parsedArtifactPath[2];
+ artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
+
+ String artifactFileNameType = parsedArtifactPath[3];
+ ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true));
+
+ } else {
+ ret = Either.right(eitherGroupType.right().value());
+ }
+ } catch (Exception e) {
+ log.debug("detectArtifactGroupType failed with exception", e);
+ ret = Either.right(false);
+ }
+ return ret;
+
+ }
+
+ private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
+ String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
+ return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
+ }
+
+ private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
+ String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
+ return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
+ }
+
+ private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
+
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
+ Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
+
+ if(artifactGroupType != null){
+ switch (artifactGroupType) {
+ case INFORMATIONAL:
+ resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getResourceInformationalArtifacts();
+ break;
+ case DEPLOYMENT:
+ resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getResourceDeploymentArtifacts();
+ break;
+ default:
+ break;
+ }
+ }
+
+ Set<String> validArtifactTypes = null;
+ if(resourceValidTypeArtifacts != null){
+ validArtifactTypes = resourceValidTypeArtifacts.keySet();
+ }
+
+ if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
+ List<String> messageArguments = new ArrayList<>();
+ messageArguments.add(receivedTypeName);
+ messageArguments.addAll(Arrays.asList(arguments));
+ if (!collectedWarningMessages.containsKey(warningMessage)) {
+ Set<List<String>> messageArgumentLists = new HashSet<>();
+ messageArgumentLists.add(messageArguments);
+ collectedWarningMessages.put(warningMessage, messageArgumentLists);
+ } else {
+ collectedWarningMessages.get(warningMessage).add(messageArguments);
+ }
+ }
+
+ return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
+ ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
+
+ Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
+
+ if(writeComponentArtifactsToSpecifiedtPath.isRight()){
+ return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
+ }
+
+ ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
+ writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
+
+ if(writeComponentArtifactsToSpecifiedtPath.isRight()){
+ return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
+ }
+
+ Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
+ Set<String> keySet = componentInstancesArtifacts.keySet();
+
+ String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
+ for (String keyAssetName : keySet) {
+ ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
+ String pathWithAssetName = currentPath + keyAssetName + "/";
+ writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
+
+ if(writeComponentArtifactsToSpecifiedtPath.isRight()){
+ return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value());
+ }
+ }
+
+ return Either.left(zipstream);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
+ String currentPath, boolean isInCertificationRequest) throws IOException {
+ Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
+ //Keys are defined:
+ //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
+ //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
+ Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
+ for (String keyAssetName : componentTypeArtifactsKeys) {
+ ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
+ ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
+ String pathWithAssetName = currentPath + keyAssetName + "/";
+ Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
+
+ if(writeArtifactsInfoToSpecifiedtPath.isRight()){
+ return writeArtifactsInfoToSpecifiedtPath;
+ }
+ }
+
+ return Either.left(zipstream);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
+ Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
+ .getArtifactsInfo();
+ Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
+
+ for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
+ String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/";
+
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
+ Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
+
+ for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
+ List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
+ String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/";
+
+ Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
+
+ if(writeArtifactDefinition.isRight()){
+ return writeArtifactDefinition;
+ }
+ }
+ }
+
+ return Either.left(zip);
+ }
+
+ private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
+ String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
+
+ ComponentTypeEnum componentType = mainComponent.getComponentType();
+ String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
+
+ for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
+ if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
+ && artifactDefinition.getArtifactType().equals(heatEnvType) ||
//this is placeholder
(artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
- continue;
- }
-
- byte[] payloadData = artifactDefinition.getPayloadData();
- String artifactFileName = artifactDefinition.getArtifactName();
-
- if (payloadData == null) {
- Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
-
- if (fromCassandra.isRight()) {
+ continue;
+ }
+
+ byte[] payloadData = artifactDefinition.getPayloadData();
+ String artifactFileName = artifactDefinition.getArtifactName();
+
+ if (payloadData == null) {
+ Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
+
+ if (fromCassandra.isRight()) {
log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
- log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
- continue;
- }
- payloadData = fromCassandra.left().value();
- }
- zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
- zip.write(payloadData);
- }
-
- return Either.left(zip);
- }
-
- /************************************ Artifacts Structure ******************************************************************/
- /**
- * The artifacts Definition saved by their structure
- */
- private class ArtifactsInfo {
- //Key is the type of artifacts(Informational/Deployment)
- //Value is a map between an artifact type and a list of all artifacts of this type
- private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
-
- public ArtifactsInfo() {
- this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
- }
-
- public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
- return artifactsInfoField;
- }
-
- public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
- List<ArtifactDefinition> artifacts = new ArrayList<>();
- for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
- artifacts.addAll(artifactsByType);
- }
- return artifacts;
- }
-
- public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
- artifactsInfoField.put(artifactGroup, artifactsDefinition);
- }
-
- public boolean isEmpty() {
- return artifactsInfoField.isEmpty();
- }
-
- }
-
- /**
- * The artifacts of the component and of all its composed instances
- *
- */
- private class ComponentTypeArtifacts {
- private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
- private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
-
- public ComponentTypeArtifacts() {
- componentArtifacts = new ArtifactsInfo();
- componentInstancesArtifacts = new HashMap<>();
- }
-
- public ArtifactsInfo getComponentArtifacts() {
- return componentArtifacts;
- }
- public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
- this.componentArtifacts = artifactsInfo;
- }
- public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
- return componentInstancesArtifacts;
- }
- public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
- this.componentInstancesArtifacts = componentInstancesArtifacts;
- }
-
- public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
- componentInstancesArtifacts.put(normalizedName, artifactsInfo);
- }
-
- }
-
- private class ComponentArtifacts {
- //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
- private ComponentTypeArtifacts mainTypeAndCIArtifacts;
- //artifacts of all component types mapped by their tosca name
- private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
-
- public ComponentArtifacts(){
- mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
- componentTypeArtifacts = new HashMap<>();
- }
-
- public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
- return mainTypeAndCIArtifacts;
- }
-
- public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
- this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
- }
-
- public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
- return componentTypeArtifacts;
- }
-
- public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
- this.componentTypeArtifacts = componentTypeArtifacts;
- }
- }
-
- private class CsarDefinition {
- private ComponentArtifacts componentArtifacts;
-
- // add list of tosca artifacts and meta describes CSAR zip root
-
- public CsarDefinition(ComponentArtifacts componentArtifacts) {
- this.componentArtifacts = componentArtifacts;
- }
-
- public ComponentArtifacts getComponentArtifacts() {
- return componentArtifacts;
- }
- }
-
- /************************************ Artifacts Structure END******************************************************************/
-
- private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
- ComponentArtifacts componentArtifacts = new ComponentArtifacts();
- Component updatedComponent = component;
-
- //get service to receive the AII artifacts uploaded to the service
- if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
- Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
-
- if(getServiceResponse.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
- return Either.right(componentsUtils.getResponseFormat(actionStatus));
- }
-
- updatedComponent = getServiceResponse.left().value();
- }
-
- //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
- ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
- ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
- componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
- componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
-
- Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
- //get the component instances
- List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
- if (componentInstances!=null){
- for (ComponentInstance componentInstance:componentInstances){
- //call recursive to find artifacts for all the path
- Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
- updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
- if (collectComponentInstanceArtifacts.isRight()){
- return Either.right(collectComponentInstanceArtifacts.right().value());
- }
- }
- }
-
- if(log.isDebugEnabled()){
- printResult(componentArtifacts,updatedComponent.getName());
- }
-
- return Either.left(new CsarDefinition(componentArtifacts));
- }
-
- private void printResult(ComponentArtifacts componentArtifacts, String name) {
- StringBuilder result = new StringBuilder();
- result.append("Artifacts of main component " + name + "\n");
- ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
- printArtifacts(componentInstanceArtifacts);
- result.append("Type Artifacts\n");
- for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
- result.append("Folder " + typeArtifacts.getKey() + "\n");
- result.append(printArtifacts(typeArtifacts.getValue()));
- }
-
- if(log.isDebugEnabled()){
- log.debug(result.toString());
- }
- }
-
- private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
- StringBuilder result = new StringBuilder();
- ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
- Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
- printArtifacts(componetArtifacts);
- result = result.append("Resources\n");
- for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
- result.append("Folder" + resourceInstance.getKey() + "\n");
- result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
- }
-
- return result.toString();
- }
-
- private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
- StringBuilder result = new StringBuilder();
- for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
- result.append(" " + artifactGroup.getKey().getType());
- for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
- result.append(" " + groupArtifacts.getKey().getType());
- for (ArtifactDefinition artifact:groupArtifacts.getValue()){
- result.append(" " + artifact.getArtifactDisplayName());
- }
- }
- }
-
- return result.toString();
- }
-
- private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
- Resource fetchedComponent) {
- String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
-
- ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
- //if there are no artifacts for this component type we need to fetch and build them
- if (componentArtifactsInfo==null){
- ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
- componentArtifactsInfo = new ComponentTypeArtifacts();
- if (!componentArtifacts.isEmpty()){
- componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
- resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
- }
- }
- return componentArtifactsInfo;
- }
-
- private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
- Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
- //1. get the component instance component
- String componentUid = componentInstance.getComponentUid();
- Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid);
- if (resource.isRight()) {
- log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
- parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
- componentInstance.getOriginType().getComponentType().getValue(), componentUid));
- }
- Resource fetchedComponent = resource.left().value();
-
- //2. fill the artifacts for the current component parent type
- ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
-
- //3. find the artifacts specific to the instance
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
- getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
- componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
- getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
- componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
-
- //4. add the instances artifacts to the component type
- ArtifactsInfo artifactsInfo = new ArtifactsInfo();
- if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
- artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
- }
- if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
- artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
- }
- if (!artifactsInfo.isEmpty()){
- instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
- }
-
- //5. do the same for all the component instances
- List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
- if (componentInstances!=null){
- for (ComponentInstance childComponentInstance:componentInstances){
- Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
- fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
- if (collectComponentInstanceArtifacts.isRight()){
- return collectComponentInstanceArtifacts;
- }
- }
- }
-
- return Either.left(true);
- }
-
- private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
- Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
-
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
- if (componentArtifacts!=null){
- for (ArtifactDefinition artifact:componentArtifacts.values()){
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
- List<ArtifactDefinition> parentArtifactsByType = null;
- if (parentArtifacts!=null){
- parentArtifactsByType = parentArtifacts.get(artifactType);
- }
- //the artifact is of instance
- if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
- List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
- if (typeArtifacts == null){
- typeArtifacts = new ArrayList<>();
- artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
- }
- typeArtifacts.add(artifact);
- }
- }
- }
-
- return artifactsByTypeOfComponentInstance;
- }
-
- private ArtifactsInfo collectComponentArtifacts(Component component) {
- Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
- Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
- ArtifactsInfo artifactsInfo = new ArtifactsInfo();
- if (!informationalArtifactsByType.isEmpty()){
- artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
- }
- if (!deploymentArtifactsByType.isEmpty() ){
- artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
- }
-
- return artifactsInfo;
- }
-
- private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
- Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
- for (ArtifactDefinition artifact:componentArtifacts.values()){
- if (artifact.getArtifactUUID()!=null){
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
- List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
- if (typeArtifacts==null){
- typeArtifacts = new ArrayList<>();
- artifactsByType.put(artifactType, typeArtifacts);
- }
- typeArtifacts.add(artifact);
- }
- }
- return artifactsByType;
- }
+ log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
+ continue;
+ }
+ payloadData = fromCassandra.left().value();
+ }
+ zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
+ zip.write(payloadData);
+ }
+
+ return Either.left(zip);
+ }
+
+ /************************************ Artifacts Structure ******************************************************************/
+ /**
+ * The artifacts Definition saved by their structure
+ */
+ private class ArtifactsInfo {
+ //Key is the type of artifacts(Informational/Deployment)
+ //Value is a map between an artifact type and a list of all artifacts of this type
+ private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
+
+ public ArtifactsInfo() {
+ this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
+ }
+
+ public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
+ return artifactsInfoField;
+ }
+
+ public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+ for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
+ artifacts.addAll(artifactsByType);
+ }
+ return artifacts;
+ }
+
+ public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
+ artifactsInfoField.put(artifactGroup, artifactsDefinition);
+ }
+
+ public boolean isEmpty() {
+ return artifactsInfoField.isEmpty();
+ }
+
+ }
+
+ /**
+ * The artifacts of the component and of all its composed instances
+ *
+ */
+ private class ComponentTypeArtifacts {
+ private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
+ private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
+
+ public ComponentTypeArtifacts() {
+ componentArtifacts = new ArtifactsInfo();
+ componentInstancesArtifacts = new HashMap<>();
+ }
+
+ public ArtifactsInfo getComponentArtifacts() {
+ return componentArtifacts;
+ }
+ public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
+ this.componentArtifacts = artifactsInfo;
+ }
+ public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
+ return componentInstancesArtifacts;
+ }
+ public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
+ this.componentInstancesArtifacts = componentInstancesArtifacts;
+ }
+
+ public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
+ componentInstancesArtifacts.put(normalizedName, artifactsInfo);
+ }
+
+ }
+
+ private class ComponentArtifacts {
+ //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
+ private ComponentTypeArtifacts mainTypeAndCIArtifacts;
+ //artifacts of all component types mapped by their tosca name
+ private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
+
+ public ComponentArtifacts(){
+ mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
+ componentTypeArtifacts = new HashMap<>();
+ }
+
+ public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
+ return mainTypeAndCIArtifacts;
+ }
+
+ public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
+ this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
+ }
+
+ public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
+ return componentTypeArtifacts;
+ }
+
+ public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
+ this.componentTypeArtifacts = componentTypeArtifacts;
+ }
+ }
+
+ private class CsarDefinition {
+ private ComponentArtifacts componentArtifacts;
+
+ // add list of tosca artifacts and meta describes CSAR zip root
+
+ public CsarDefinition(ComponentArtifacts componentArtifacts) {
+ this.componentArtifacts = componentArtifacts;
+ }
+
+ public ComponentArtifacts getComponentArtifacts() {
+ return componentArtifacts;
+ }
+ }
+
+ /************************************ Artifacts Structure END******************************************************************/
+
+ private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
+ ComponentArtifacts componentArtifacts = new ComponentArtifacts();
+ Component updatedComponent = component;
+
+ //get service to receive the AII artifacts uploaded to the service
+ if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
+ Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
+
+ if(getServiceResponse.isRight()){
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
+ return Either.right(componentsUtils.getResponseFormat(actionStatus));
+ }
+
+ updatedComponent = getServiceResponse.left().value();
+ }
+
+ //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
+ ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
+ ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
+ componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
+ componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
+
+ Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
+ //get the component instances
+ List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
+ if (componentInstances!=null){
+ for (ComponentInstance componentInstance:componentInstances){
+ //call recursive to find artifacts for all the path
+ Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
+ updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
+ if (collectComponentInstanceArtifacts.isRight()){
+ return Either.right(collectComponentInstanceArtifacts.right().value());
+ }
+ }
+ }
+
+ if(log.isDebugEnabled()){
+ printResult(componentArtifacts,updatedComponent.getName());
+ }
+
+ return Either.left(new CsarDefinition(componentArtifacts));
+ }
+
+ private void printResult(ComponentArtifacts componentArtifacts, String name) {
+ StringBuilder result = new StringBuilder();
+ result.append("Artifacts of main component " + name + "\n");
+ ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
+ printArtifacts(componentInstanceArtifacts);
+ result.append("Type Artifacts\n");
+ for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
+ result.append("Folder " + typeArtifacts.getKey() + "\n");
+ result.append(printArtifacts(typeArtifacts.getValue()));
+ }
+
+ if(log.isDebugEnabled()){
+ log.debug(result.toString());
+ }
+ }
+
+ private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
+ StringBuilder result = new StringBuilder();
+ ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
+ Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
+ printArtifacts(componetArtifacts);
+ result = result.append("Resources\n");
+ for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
+ result.append("Folder" + resourceInstance.getKey() + "\n");
+ result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
+ }
+
+ return result.toString();
+ }
+
+ private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
+ StringBuilder result = new StringBuilder();
+ for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
+ result.append(" " + artifactGroup.getKey().getType());
+ for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
+ result.append(" " + groupArtifacts.getKey().getType());
+ for (ArtifactDefinition artifact:groupArtifacts.getValue()){
+ result.append(" " + artifact.getArtifactDisplayName());
+ }
+ }
+ }
+
+ return result.toString();
+ }
+
+ private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
+ Resource fetchedComponent) {
+ String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
+
+ ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
+ //if there are no artifacts for this component type we need to fetch and build them
+ if (componentArtifactsInfo==null){
+ ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
+ componentArtifactsInfo = new ComponentTypeArtifacts();
+ if (!componentArtifacts.isEmpty()){
+ componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
+ resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
+ }
+ }
+ return componentArtifactsInfo;
+ }
+
+ private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
+ Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
+ //1. get the component instance component
+ String componentUid = componentInstance.getComponentUid();
+ Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid);
+ if (resource.isRight()) {
+ log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
+ parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
+ componentInstance.getOriginType().getComponentType().getValue(), componentUid));
+ }
+ Resource fetchedComponent = resource.left().value();
+
+ //2. fill the artifacts for the current component parent type
+ ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
+
+ //3. find the artifacts specific to the instance
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
+ getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
+ componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
+ getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
+ componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ //4. add the instances artifacts to the component type
+ ArtifactsInfo artifactsInfo = new ArtifactsInfo();
+ if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
+ }
+ if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
+ }
+ if (!artifactsInfo.isEmpty()){
+ instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
+ }
+
+ //5. do the same for all the component instances
+ List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
+ if (componentInstances!=null){
+ for (ComponentInstance childComponentInstance:componentInstances){
+ Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
+ fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
+ if (collectComponentInstanceArtifacts.isRight()){
+ return collectComponentInstanceArtifacts;
+ }
+ }
+ }
+
+ return Either.left(true);
+ }
+
+ private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
+ Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
+
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
+ if (componentArtifacts!=null){
+ for (ArtifactDefinition artifact:componentArtifacts.values()){
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ List<ArtifactDefinition> parentArtifactsByType = null;
+ if (parentArtifacts!=null){
+ parentArtifactsByType = parentArtifacts.get(artifactType);
+ }
+ //the artifact is of instance
+ if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
+ List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
+ if (typeArtifacts == null){
+ typeArtifacts = new ArrayList<>();
+ artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
+ }
+ typeArtifacts.add(artifact);
+ }
+ }
+ }
+
+ return artifactsByTypeOfComponentInstance;
+ }
+
+ private ArtifactsInfo collectComponentArtifacts(Component component) {
+ Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
+ Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
+ ArtifactsInfo artifactsInfo = new ArtifactsInfo();
+ if (!informationalArtifactsByType.isEmpty()){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
+ }
+ if (!deploymentArtifactsByType.isEmpty() ){
+ artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
+ }
+
+ return artifactsInfo;
+ }
+
+ private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
+ Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
+ for (ArtifactDefinition artifact:componentArtifacts.values()){
+ if (artifact.getArtifactUUID()!=null){
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
+ if (typeArtifacts==null){
+ typeArtifacts = new ArrayList<>();
+ artifactsByType.put(artifactType, typeArtifacts);
+ }
+ typeArtifacts.add(artifact);
+ }
+ }
+ return artifactsByType;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
index 083ea67769..f40ebf0e64 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
@@ -49,59 +49,59 @@ import com.google.gson.stream.JsonReader;
import fj.data.Either;
public class PropertyConvertor {
- private static PropertyConvertor instance;
- private JsonParser jsonParser = new JsonParser();
- private static Logger log = LoggerFactory.getLogger(PropertyConvertor.class.getName());
- Gson gson = new Gson();
- protected PropertyConvertor() {
-
- }
-
- public static synchronized PropertyConvertor getInstance() {
- if (instance == null) {
- instance = new PropertyConvertor();
- }
- return instance;
- }
-
- public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) {
-
- if (component instanceof Resource) {
- Resource resource = (Resource) component;
- List<PropertyDefinition> props = resource.getProperties();
- if (props != null) {
- Map<String, ToscaProperty> properties = new HashMap<>();
-
- // take only the properties of this resource
- props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> {
+ private static PropertyConvertor instance;
+ private JsonParser jsonParser = new JsonParser();
+ private static final Logger log = LoggerFactory.getLogger(PropertyConvertor.class);
+ Gson gson = new Gson();
+ protected PropertyConvertor() {
+
+ }
+
+ public static synchronized PropertyConvertor getInstance() {
+ if (instance == null) {
+ instance = new PropertyConvertor();
+ }
+ return instance;
+ }
+
+ public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) {
+
+ if (component instanceof Resource) {
+ Resource resource = (Resource) component;
+ List<PropertyDefinition> props = resource.getProperties();
+ if (props != null) {
+ Map<String, ToscaProperty> properties = new HashMap<>();
+
+ // take only the properties of this resource
+ props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> {
properties.put(property.getName(), convertProperty(dataTypes, property, false));
- });
- if (!properties.isEmpty()) {
- toscaNodeType.setProperties(properties);
- }
- }
- }
- return Either.left(toscaNodeType);
- }
-
- public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) {
- ToscaProperty prop = new ToscaProperty();
-
- String innerType = null;
- SchemaDefinition schema = property.getSchema();
- if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
- innerType = schema.getProperty().getType();
- EntrySchema eschema = new EntrySchema();
- eschema.setType(innerType);
- eschema.setDescription(schema.getProperty().getDescription());
- prop.setEntry_schema(eschema);
- }
- log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue());
+ });
+ if (!properties.isEmpty()) {
+ toscaNodeType.setProperties(properties);
+ }
+ }
+ }
+ return Either.left(toscaNodeType);
+ }
+
+ public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) {
+ ToscaProperty prop = new ToscaProperty();
+
+ String innerType = null;
+ SchemaDefinition schema = property.getSchema();
+ if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
+ innerType = schema.getProperty().getType();
+ EntrySchema eschema = new EntrySchema();
+ eschema.setType(innerType);
+ eschema.setDescription(schema.getProperty().getDescription());
+ prop.setEntry_schema(eschema);
+ }
+ log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue());
Object convertedObj = convertToToscaObject(property.getType(), property.getDefaultValue(), innerType, dataTypes);
if (convertedObj != null) {
prop.setDefaultp(convertedObj);
}
- prop.setType(property.getType());
+ prop.setType(property.getType());
prop.setDescription(property.getDescription());
if (isCapabiltyProperty) {
prop.setStatus(property.getStatus());
@@ -109,91 +109,91 @@ public class PropertyConvertor {
}
return prop;
- }
-
- public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
- if (StringUtils.isEmpty(value)) {
- value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
- if(StringUtils.isEmpty(value)){
- return null;
- }
- }
- try {
- ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
- ToscaValueConverter innerConverter = null;
- Boolean isScalar = true;
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- if (type == null) {
- log.trace("isn't prederfined type, get from all data types");
- DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- if (innerType == null) {
- innerType = propertyType;
- }
-
- if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
- log.trace("This is scalar type. get suitable converter for type {}", type);
- innerConverter = type.getValueConverter();
- } else {
- isScalar = false;
- }
- } else {
- ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
- if (typeIfScalar == null) {
- isScalar = false;
- }
-
- innerConverter = type.getValueConverter();
- if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) {
- return innerConverter.convertToToscaValue(value, innerType, dataTypes);
- }
- }
- JsonElement jsonElement = null;
-
- StringReader reader = new StringReader(value);
- JsonReader jsonReader = new JsonReader(reader);
- jsonReader.setLenient(true);
-
- jsonElement = jsonParser.parse(jsonReader);
-
- if (value.equals("")) {
- return value;
- }
-
- if (jsonElement.isJsonPrimitive() && isScalar) {
- log.trace("It's well defined type. convert it");
- ToscaValueConverter converter = type.getValueConverter();
- return converter.convertToToscaValue(value, innerType, dataTypes);
- } else {
- log.trace("It's data type or inputs in primitive type. convert as map");
- Object convertedValue;
- if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) {
- convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
- } else {
- if (isScalar) {
- // complex json for scalar type
- convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
- } else {
- if (innerConverter != null) {
- convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
- } else {
- convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement);
- }
- }
- }
- return convertedValue;
- }
-
- } catch (Exception e) {
- log.debug("convertToToscaValue failed to parse json value :", e);
- return null;
- }
-
- }
-
- private boolean valueStartsWithNonJsonChar(String value) {
- return value.startsWith("/") || value.startsWith(":");
- }
+ }
+
+ public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
+ if (StringUtils.isEmpty(value)) {
+ value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
+ if(StringUtils.isEmpty(value)){
+ return null;
+ }
+ }
+ try {
+ ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
+ ToscaValueConverter innerConverter = null;
+ Boolean isScalar = true;
+
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ if (type == null) {
+ log.trace("isn't prederfined type, get from all data types");
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ if (innerType == null) {
+ innerType = propertyType;
+ }
+
+ if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
+ log.trace("This is scalar type. get suitable converter for type {}", type);
+ innerConverter = type.getValueConverter();
+ } else {
+ isScalar = false;
+ }
+ } else {
+ ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
+ if (typeIfScalar == null) {
+ isScalar = false;
+ }
+
+ innerConverter = type.getValueConverter();
+ if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) {
+ return innerConverter.convertToToscaValue(value, innerType, dataTypes);
+ }
+ }
+ JsonElement jsonElement = null;
+
+ StringReader reader = new StringReader(value);
+ JsonReader jsonReader = new JsonReader(reader);
+ jsonReader.setLenient(true);
+
+ jsonElement = jsonParser.parse(jsonReader);
+
+ if (value.equals("")) {
+ return value;
+ }
+
+ if (jsonElement.isJsonPrimitive() && isScalar) {
+ log.trace("It's well defined type. convert it");
+ ToscaValueConverter converter = type.getValueConverter();
+ return converter.convertToToscaValue(value, innerType, dataTypes);
+ } else {
+ log.trace("It's data type or inputs in primitive type. convert as map");
+ Object convertedValue;
+ if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) {
+ convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
+ } else {
+ if (isScalar) {
+ // complex json for scalar type
+ convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement);
+ } else {
+ if (innerConverter != null) {
+ convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
+ } else {
+ convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement);
+ }
+ }
+ }
+ return convertedValue;
+ }
+
+ } catch (Exception e) {
+ log.debug("convertToToscaValue failed to parse json value :", e);
+ return null;
+ }
+
+ }
+
+ private boolean valueStartsWithNonJsonChar(String value) {
+ return value.startsWith("/") || value.startsWith(":");
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java
index 94dd559d2d..c3acb43186 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java
@@ -22,5 +22,5 @@ package org.openecomp.sdc.be.tosca;
public enum ToscaError {
- NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR
+ NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR
}
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 c37c15f694..05be7f9cda 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
@@ -20,19 +20,7 @@
package org.openecomp.sdc.be.tosca;
-import java.beans.IntrospectionException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
@@ -44,42 +32,16 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
-import org.openecomp.sdc.be.tosca.model.IToscaMetadata;
-import org.openecomp.sdc.be.tosca.model.SubstitutionMapping;
-import org.openecomp.sdc.be.tosca.model.ToscaCapability;
-import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
-import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
-import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
-import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
-import org.openecomp.sdc.be.tosca.model.ToscaProperty;
-import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
-import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
-import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate;
-import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
+import org.openecomp.sdc.be.tosca.model.*;
+import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
import org.openecomp.sdc.common.api.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -97,1119 +59,1158 @@ import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;
-import fj.data.Either;
+import java.beans.IntrospectionException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("tosca-export-handler")
public class ToscaExportHandler {
- @Autowired
- private ApplicationDataTypeCache dataTypeCache;
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
- @Autowired
- private CapabiltyRequirementConvertor capabiltyRequirementConvertor;
- private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
- Map<String, Component> originComponents = new HashMap<>();
-
- private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName());
-
- public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
- public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
- public static final String IMPORTS_FILE_KEY = "file";
- public static final String TOSCA_TEMPLATE_NAME = "-template.yml";
- public static final String TOSCA_INTERFACE_NAME = "-interface.yml";
- public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
- public static final String VF_MODULE_TYPE_KEY = "vf_module_type";
- public static final String VF_MODULE_DESC_KEY = "vf_module_description";
- public static final String VOLUME_GROUP_KEY = "volume_group";
- public static final String VF_MODULE_TYPE_BASE = "Base";
- public static final String VF_MODULE_TYPE_EXPANSION = "Expansion";
- private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
- private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
- protected static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
- .getConfigurationManager().getConfiguration().getDefaultImports();
-
- public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
-
- Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
- if (toscaTemplateRes.isRight()) {
- return Either.right(toscaTemplateRes.right().value());
- }
-
- ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
- ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
- return Either.left(toscaRepresentation);
- }
-
- public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) {
- if (null == DEFAULT_IMPORTS) {
- log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
- return Either.right(ToscaError.GENERAL_ERROR);
- }
-
- ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
- toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
- Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
- Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate,
- nodeTypes);
- if (toscaTemplateRes.isRight()) {
- return Either.right(toscaTemplateRes.right().value());
- }
-
- toscaTemplate = toscaTemplateRes.left().value();
- ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
- return Either.left(toscaRepresentation);
- }
-
- public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
- CustomRepresenter representer = new CustomRepresenter();
- DumperOptions options = new DumperOptions();
- options.setAllowReadOnlyProperties(false);
- options.setPrettyFlow(true);
-
- options.setDefaultFlowStyle(FlowStyle.FLOW);
- options.setCanonical(false);
-
- representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
-
- representer.setPropertyUtils(new UnsortedPropertyUtils());
- Yaml yaml = new Yaml(representer, options);
-
- String yamlAsString = yaml.dumpAsMap(toscaTemplate);
-
- StringBuilder sb = new StringBuilder();
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
- sb.append(yamlAsString);
- sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
-
- ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
- toscaRepresentation.setMainYaml(sb.toString());
- toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
-
- return toscaRepresentation;
- }
-
- public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
- ToscaTemplate toscaTemplate = new ToscaTemplate(null);
- Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
- toscaTemplate);
- if (fillImports.isRight()) {
- return Either.right(fillImports.right().value());
- }
- return Either.left(fillImports.left().value().left);
- }
-
- private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
- if (null == DEFAULT_IMPORTS) {
- log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
- return Either.right(ToscaError.GENERAL_ERROR);
- }
-
- log.trace("start tosca export for {}", component.getUniqueId());
- ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
-
- toscaTemplate.setMetadata(convertMetadata(component));
- toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
- Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
- if (ModelConverter.isAtomicComponent(component)) {
- log.trace("convert component as node type");
- return convertNodeType(component, toscaTemplate, nodeTypes);
- } else {
- log.trace("convert component as topology template");
- return convertToscaTemplate(component, toscaTemplate);
- }
-
- }
-
- private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
-
- Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
- toscaNode);
- if (importsRes.isRight()) {
- return Either.right(importsRes.right().value());
- }
- toscaNode = importsRes.left().value().left;
- Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(component);
- if (nodeTypesMapEither.isRight()) {
- log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
- nodeTypesMapEither.right().value());
- return Either.right(nodeTypesMapEither.right().value());
- }
- Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
- if (nodeTypesMap != null && !nodeTypesMap.isEmpty())
- toscaNode.setNode_types(nodeTypesMap);
-
- Map<String, Component> componentCache = importsRes.left().value().right;
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
- if (dataTypesEither.isRight()) {
- log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
- return Either.right(ToscaError.GENERAL_ERROR);
- }
- Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
-
- ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
-
- Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
- if (inputs.isRight()) {
- return Either.right(inputs.right().value());
- }
- topologyTemplate = inputs.left().value();
-
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
- .getComponentInstancesProperties();
- List<GroupDefinition> groups = component.getGroups();
- if (componentInstances != null && !componentInstances.isEmpty()) {
-
- Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
- componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
- if (nodeTemplates.isRight()) {
- return Either.right(nodeTemplates.right().value());
- }
- log.debug("node templates converted");
-
- topologyTemplate.setNode_templates(nodeTemplates.left().value());
- }
- Map<String, ToscaGroupTemplate> groupsMap;
- if (groups != null && !groups.isEmpty()) {
- groupsMap = new HashMap<>();
- for (GroupDefinition group : groups) {
- boolean addToTosca = true;
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- List<String> artifacts = group.getArtifacts();
- if (artifacts == null || artifacts.isEmpty()) {
- addToTosca = false;
- }
- }
- if (addToTosca) {
- ToscaGroupTemplate toscaGroup = convertGroup(group);
- groupsMap.put(group.getName(), toscaGroup);
- }
-
- }
- log.debug("groups converted");
- topologyTemplate.addGroups(groupsMap);
- }
- SubstitutionMapping substitutionMapping = new SubstitutionMapping();
- String toscaResourceName;
- switch (component.getComponentType()) {
- case RESOURCE:
- toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
- .getMetadataDataDefinition()).getToscaResourceName();
- break;
- case SERVICE:
- toscaResourceName = SERVICE_NODE_TYPE_PREFIX
- + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
- break;
- default:
- log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
- return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
- }
- substitutionMapping.setNode_type(toscaResourceName);
-
- Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping);
- if (capabilities.isRight()) {
- return Either.right(capabilities.right().value());
- }
- substitutionMapping = capabilities.left().value();
-
- Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor
- .convertSubstitutionMappingRequirements(originComponents, component, substitutionMapping);
- if (requirements.isRight()) {
- return Either.right(requirements.right().value());
- }
- substitutionMapping = requirements.left().value();
-
- topologyTemplate.setSubstitution_mappings(substitutionMapping);
-
- toscaNode.setTopology_template(topologyTemplate);
- return Either.left(toscaNode);
- }
-
- private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
- ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
- if (log.isDebugEnabled())
- log.debug("fillInputs for component {}", component.getUniqueId());
- List<InputDefinition> inputDef = component.getInputs();
- Map<String, ToscaProperty> inputs = new HashMap<>();
-
- if (inputDef != null) {
- inputDef.forEach(i -> {
- ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
- inputs.put(i.getName(), property);
- });
- if (!inputs.isEmpty()) {
- topologyTemplate.setInputs(inputs);
- }
- }
- return Either.left(topologyTemplate);
- }
-
- private ToscaMetadata convertMetadata(Component component) {
- return convertMetadata(component, false, null);
- }
-
- private ToscaMetadata convertMetadata(Component component, boolean isInstance,
- ComponentInstance componentInstance) {
- ToscaMetadata toscaMetadata = new ToscaMetadata();
- toscaMetadata.setInvariantUUID(component.getInvariantUUID());
- toscaMetadata.setUUID(component.getUUID());
- toscaMetadata.setDescription(component.getDescription());
- toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
- List<CategoryDefinition> categories = component.getCategories();
- CategoryDefinition categoryDefinition = categories.get(0);
- toscaMetadata.setCategory(categoryDefinition.getName());
-
- if (isInstance) {
- toscaMetadata.setVersion(component.getVersion());
- toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
- if (componentInstance.getSourceModelInvariant() != null
- && !componentInstance.getSourceModelInvariant().isEmpty()) {
- toscaMetadata.setVersion(componentInstance.getComponentVersion());
- toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
- toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
- toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
- toscaMetadata.setName(
- componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
- toscaMetadata.setDescription(componentInstance.getDescription());
- }
-
- }
- switch (component.getComponentType()) {
- case RESOURCE:
- Resource resource = (Resource) component;
-
- if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
- toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
- } else
- toscaMetadata.setType(resource.getResourceType().name());
- toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
- toscaMetadata.setResourceVendor(resource.getVendorName());
- toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
- toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
- break;
- case SERVICE:
- Service service = (Service) component;
- toscaMetadata.setType(component.getComponentType().getValue());
- toscaMetadata.setServiceType(service.getServiceType());
- toscaMetadata.setServiceRole(service.getServiceRole());
- toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
- if (!isInstance) {
- // DE268546
- toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
- toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
- toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
- }
- break;
- default:
- log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
- }
- return toscaMetadata;
- }
-
- private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
- ToscaTemplate toscaTemplate) {
-
- if (null == DEFAULT_IMPORTS) {
- log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
- return Either.right(ToscaError.GENERAL_ERROR);
- }
-
- Map<String, Component> componentCache = new HashMap<>();
-
- if (!ModelConverter.isAtomicComponent(component)) {
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null && !componentInstances.isEmpty()) {
-
- List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
- ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
-
- List<Triple<String, String, Component>> dependecies = new ArrayList<>();
-
- Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
-
- Map<String, Map<String, String>> importsListMember = new HashMap<>();
- Map<String, String> interfaceFiles = new HashMap<>();
- interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
- StringBuilder keyNameBuilder = new StringBuilder();
- keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
- keyNameBuilder.append("-");
- keyNameBuilder.append(component.getName());
- keyNameBuilder.append("-interface");
- importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
- additionalImports.add(importsListMember);
-
- componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
- originComponents.putAll(componentCache);
- toscaTemplate.setDependencies(dependecies);
- toscaTemplate.setImports(additionalImports);
- }
- } else {
- log.debug("currently imports supported for VF and service only");
- }
- return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
- }
-
- private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
- List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
- Map<String, String> files = new HashMap<>();
- Map<String, Map<String, String>> importsListMember = new HashMap<>();
- StringBuilder keyNameBuilder;
-
- Component componentRI = componentCache.get(ci.getComponentUid());
- if (componentRI == null) {
- // all resource must be only once!
- Either<Component, StorageOperationStatus> resource = toscaOperationFacade
- .getToscaFullElement(ci.getComponentUid());
- if (resource.isRight()) {
- log.debug("Failed to fetch resource with id {} for instance {}");
- }
- Component fetchedComponent = resource.left().value();
- componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
- componentRI = fetchedComponent;
-
- Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
- ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
- if (artifactDefinition != null) {
- String artifactName = artifactDefinition.getArtifactName();
- files.put(IMPORTS_FILE_KEY, artifactName);
- keyNameBuilder = new StringBuilder();
- keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
- keyNameBuilder.append("-");
- keyNameBuilder.append(ci.getComponentName());
- importsListMember.put(keyNameBuilder.toString(), files);
- imports.add(importsListMember);
- dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
- artifactDefinition.getEsId(), fetchedComponent));
-
- if (!ModelConverter.isAtomicComponent(componentRI)) {
- importsListMember = new HashMap<>();
- Map<String, String> interfaceFiles = new HashMap<>();
- interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
- keyNameBuilder.append("-interface");
- importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
- imports.add(importsListMember);
- }
- }
- }
- }
-
- public static String getInterfaceFilename(String artifactName) {
- return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
- }
-
- private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
- Map<String, ToscaNodeType> nodeTypes) {
- log.debug("start convert node type for {}", component.getUniqueId());
- ToscaNodeType toscaNodeType = createNodeType(component);
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
- if (dataTypesEither.isRight()) {
- log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
- return Either.right(ToscaError.GENERAL_ERROR);
- }
-
- Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
- Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
- dataTypes);
- if (properties.isRight()) {
- return Either.right(properties.right().value());
- }
- toscaNodeType = properties.left().value();
- log.debug("Properties converted for {}", component.getUniqueId());
-
- // Extracted to method for code reuse
- return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
- }
-
- private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
- Map<String, ToscaNodeType> nodeTypes) {
- log.debug("start convert node type for {}", component.getUniqueId());
- ToscaNodeType toscaNodeType = createNodeType(component);
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
- if (dataTypesEither.isRight()) {
- log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
- return Either.right(ToscaError.GENERAL_ERROR);
- }
-
- Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
-
- List<InputDefinition> inputDef = component.getInputs();
- Map<String, ToscaProperty> inputs = new HashMap<>();
-
- if (inputDef != null) {
- inputDef.forEach(i -> {
- ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
- inputs.put(i.getName(), property);
- });
- if (!inputs.isEmpty()) {
- toscaNodeType.setProperties(inputs);
- }
- }
-
- // Extracted to method for code reuse
- return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
- }
-
- private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
- Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
- Map<String, DataTypeDefinition> dataTypes) {
- Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
- if (capabilities.isRight()) {
- return Either.right(capabilities.right().value());
- }
- toscaNodeType = capabilities.left().value();
- log.debug("Capabilities converted for {}", component.getUniqueId());
-
- Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
- toscaNodeType);
- if (requirements.isRight()) {
- return Either.right(requirements.right().value());
- }
- toscaNodeType = requirements.left().value();
- log.debug("Requirements converted for {}", component.getUniqueId());
-
- String toscaResourceName;
- switch (component.getComponentType()) {
- case RESOURCE:
- toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
- .getMetadataDataDefinition()).getToscaResourceName();
- break;
- case SERVICE:
- toscaResourceName = SERVICE_NODE_TYPE_PREFIX
- + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
- break;
- default:
- log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
- return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
- }
-
- nodeTypes.put(toscaResourceName, toscaNodeType);
- toscaNode.setNode_types(nodeTypes);
- log.debug("finish convert node type for {}", component.getUniqueId());
- return Either.left(toscaNode);
- }
-
- private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
- List<ComponentInstance> componentInstances,
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
- Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
- ToscaTopolgyTemplate topologyTemplate) {
-
- Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
- log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
- component.getComponentType());
- Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
-
- Map<String, ToscaGroupTemplate> groupsMap = null;
- for (ComponentInstance componentInstance : componentInstances) {
- ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
- nodeTemplate.setType(componentInstance.getToscaComponentName());
-
- Either<Component, Boolean> originComponentRes = capabiltyRequirementConvertor
- .getOriginComponent(componentCache, componentInstance);
- if (originComponentRes.isRight()) {
- convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
- break;
- }
- Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
- componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
- originComponentRes.left().value());
- if (requirements.isRight()) {
- convertNodeTemplatesRes = Either.right(requirements.right().value());
- break;
- }
- String instanceUniqueId = componentInstance.getUniqueId();
- log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
-
- nodeTemplate = requirements.left().value();
-
- Component componentOfInstance = componentCache.get(componentInstance.getActualComponentUid());
- nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance));
-
- Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor
- .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
- if (capabilities.isRight()) {
- convertNodeTemplatesRes = Either.right(requirements.right().value());
- break;
- }
- log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
-
- nodeTemplate = capabilities.left().value();
- Map<String, Object> props = new HashMap<>();
-
- if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) {
- // Adds the properties of parent component to map
- addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props);
- }
-
- if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
- addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
- instanceUniqueId, props);
- }
-
- if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
- addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
- props);
- }
- if (props != null && !props.isEmpty()) {
- nodeTemplate.setProperties(props);
- }
-
- List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
- if (groupInstances != null) {
- if (groupsMap == null) {
- groupsMap = new HashMap<>();
- }
- for (GroupInstance groupInst : groupInstances) {
- boolean addToTosca = true;
-
- List<String> artifacts = groupInst.getArtifacts();
- if (artifacts == null || artifacts.isEmpty()) {
- addToTosca = false;
- }
-
- if (addToTosca) {
- ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
- groupsMap.put(groupInst.getName(), toscaGroup);
- }
- }
- }
-
- nodeTemplates.put(componentInstance.getName(), nodeTemplate);
- }
- if (groupsMap != null) {
- log.debug("instance groups added");
- topologyTemplate.addGroups(groupsMap);
- }
-
- if (convertNodeTemplatesRes == null) {
- convertNodeTemplatesRes = Either.left(nodeTemplates);
- }
- log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
- component.getComponentType());
- return convertNodeTemplatesRes;
- }
-
- private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
- String instanceUniqueId, Map<String, Object> props) {
-
- List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
- if (instanceInputsList != null) {
- instanceInputsList.forEach(input -> {
-
- Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
- ? input.getValue() : input.getDefaultValue();
- convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
- });
- }
- }
-
- private void addPropertiesOfComponentInstance(
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
- Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
- Map<String, Object> props) {
-
- if (!MapUtils.isEmpty(componentInstancesProperties)) {
- componentInstancesProperties.get(instanceUniqueId).stream()
- // Collects filtered properties to List
- .collect(Collectors.toList()).stream()
- // Converts and adds each value to property map
- .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
- () -> prop.getValue()));
- }
- }
-
- private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
- ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
-
- List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
- if (!CollectionUtils.isEmpty(componentProperties)) {
- componentProperties.stream()
- // Filters out properties with empty default values
- .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
- // Collects filtered properties to List
- .collect(Collectors.toList()).stream()
- // Converts and adds each value to property map
- .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
- () -> prop.getDefaultValue()));
- }
- }
-
- /**
- * @param dataTypes
- * @param componentInstance
- * @param props
- * @param prop
- * @param supplier
- */
- private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
- Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
- Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
- if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
- props.put(prop.getName(), convertedValue);
- }
- }
-
- private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
- ComponentInstance componentInstance, T input, Supplier<String> supplier) {
- log.debug("Convert property or input value {} for instance {}", input.getName(),
- componentInstance.getUniqueId());
- String propertyType = input.getType();
- String innerType = null;
- if (input.getSchema() != null && input.getSchema().getProperty() != null) {
- innerType = input.getSchema().getProperty().getType();
- }
- return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
- }
-
- private ToscaGroupTemplate convertGroup(GroupDefinition group) {
-
- ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
- Map<String, String> members = group.getMembers();
- if (members != null)
- toscaGroup.setMembers(new ArrayList<String>(members.keySet()));
-
- Supplier<String> supplGroupType = () -> group.getType();
- Supplier<String> supplDescription = () -> group.getDescription();
- Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
- Supplier<String> supplgroupName = () -> group.getName();
- Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
- Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
- Supplier<String> supplVersion = () -> group.getVersion();
-
- IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
- supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
- toscaGroup.setMetadata(toscaMetadata);
- return toscaGroup;
- }
-
- private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
- ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
-
- Supplier<String> supplGroupType = () -> groupInstance.getType();
- Supplier<String> supplDescription = () -> groupInstance.getDescription();
- Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance
- .convertToGroupInstancesProperties();
- Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
- Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
- Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
- Supplier<String> supplVersion = () -> groupInstance.getVersion();
-
- IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
- supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
-
- toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
- toscaGroup.setMetadata(toscaMetadata);
- return toscaGroup;
- }
-
- private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
- Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
- Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
- boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
- toscaGroup.setType(groupType.get());
-
- IToscaMetadata toscaMetadata;
- if (!isVfModule) {
- toscaMetadata = new ToscaMetadata();
- } else {
- toscaMetadata = new VfModuleToscaMetadata();
-
- Map<String, Object> properties = fillGroupProperties(props.get());
- if (!properties.containsKey(VF_MODULE_DESC_KEY)
- || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) {
- properties.put(VF_MODULE_DESC_KEY, description.get());
- }
- toscaGroup.setProperties(properties);
- }
- toscaMetadata.setName(groupName.get());
- toscaMetadata.setInvariantUUID(invariantUUID.get());
- toscaMetadata.setUUID(groupUUID.get());
- toscaMetadata.setVersion(version.get());
- return toscaMetadata;
- }
-
- private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
- Map<String, Object> properties = new HashMap<>();
- if (groupProps != null) {
- for (GroupProperty gp : groupProps) {
- if (gp.getName().equals(Constants.IS_BASE)) {
- Boolean isBase = Boolean.parseBoolean(gp.getValue());
- String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
- properties.put(VF_MODULE_TYPE_KEY, type);
- } else {
- Object value = null;
- String type = gp.getType();
-
- switch (type) {
- case "integer":
- if (gp.getValue() != null) {
- value = Integer.valueOf(gp.getValue());
- }
- break;
- case "boolean":
- if (gp.getValue() != null) {
- value = Boolean.valueOf(gp.getValue());
- }
- break;
-
- default:
- value = gp.getValue();
- break;
- }
- properties.put(gp.getName(), value);
- }
- }
- }
- return properties;
- }
-
- private ToscaNodeType createNodeType(Component component) {
- ToscaNodeType toscaNodeType = new ToscaNodeType();
- if (ModelConverter.isAtomicComponent(component)) {
- if (((Resource) component).getDerivedFrom() != null) {
- toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
- }
- toscaNodeType.setDescription(component.getDescription()); // or
- // name??
- } else {
- String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
- : "tosca.nodes.Root";
- toscaNodeType.setDerived_from(derivedFrom);
- }
- return toscaNodeType;
- }
-
- private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Component container) {
-
- Map<String, ToscaNodeType> nodeTypesMap = null;
- Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
-
- List<ComponentInstance> componetInstances = container.getComponentInstances();
-
- if (componetInstances == null || componetInstances.isEmpty())
- return res;
- Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
- List<ComponentInstance> proxyInst = componetInstances.stream()
- .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
- .collect(Collectors.toList());
- if (proxyInst != null && !proxyInst.isEmpty()) {
- for (ComponentInstance inst : proxyInst) {
- serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
- }
- }
-
- if (serviceProxyInstanceList.isEmpty())
- return res;
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreCapabilities(false);
- filter.setIgnoreComponentInstances(false);
- Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
- .getLatestByName("serviceProxy");
- if (serviceProxyOrigin.isRight()) {
- log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
- serviceProxyOrigin.right().value());
- return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
- }
- Component origComponent = serviceProxyOrigin.left().value();
-
- nodeTypesMap = new HashMap<>();
- for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
- Component serviceComponent = null;
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreCategories(false);
- Either<Component, StorageOperationStatus> service = toscaOperationFacade
- .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
- if (service.isRight()) {
- log.debug("Failed to fetch resource with id {} for instance {}");
- } else
- serviceComponent = service.left().value();
-
- ToscaNodeType toscaNodeType = createProxyNodeType(origComponent, serviceComponent, entryProxy.getValue());
- nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
- }
-
- return Either.left(nodeTypesMap);
- }
-
- private ToscaNodeType createProxyNodeType(Component origComponent, Component proxyComponent,
- ComponentInstance instance) {
- ToscaNodeType toscaNodeType = new ToscaNodeType();
- String derivedFrom = ((Resource) origComponent).getToscaResourceName();
-
- toscaNodeType.setDerived_from(derivedFrom);
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
- if (dataTypesEither.isRight()) {
- log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
- }
- Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
- Map<String, ToscaCapability> capabilities = this.capabiltyRequirementConvertor
- .convertProxyCapabilities(origComponent, proxyComponent, instance, dataTypes);
-
- toscaNodeType.setCapabilities(capabilities);
-
- return toscaNodeType;
- }
-
- private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
- ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
- ToscaNodeTemplate nodeTypeTemplate, Component originComponent) {
-
- List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
- if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements)) {
- log.debug("Failed to convert component instance requirements for the component instance {}. ",
- componentInstance.getName());
- return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
- }
- if (!toscaRequirements.isEmpty()) {
- nodeTypeTemplate.setRequirements(toscaRequirements);
- }
- log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
- return Either.left(nodeTypeTemplate);
- }
-
- private boolean addRequirements(Component component, ComponentInstance componentInstance,
- List<RequirementCapabilityRelDef> relations, Component originComponent,
- List<Map<String, ToscaTemplateRequirement>> toscaRequirements) {
- boolean result;
- List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
- .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
- if (CollectionUtils.isEmpty(filteredRelations)) {
- result = true;
- } else {
- result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent,
- component.getComponentInstances(), rel, toscaRequirements)).findFirst().isPresent();
- }
- return result;
- }
-
- private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
- List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
- List<Map<String, ToscaTemplateRequirement>> toscaRequirements) {
-
- boolean result = true;
- Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
- RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
- Either<Component, StorageOperationStatus> getOriginRes = null;
- Optional<RequirementDefinition> reqOpt = null;
- Component toOriginComponent = null;
- Optional<CapabilityDefinition> cap = null;
-
- ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
- .findFirst().orElse(null);
- if (toInstance == null) {
- log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
- rel.getToNode());
- result = false;
- }
- if (result) {
- reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, toInstance.getUniqueId());
- if (!reqOpt.isPresent()) {
- log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
- reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
- result = false;
- }
- }
- if (result) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreCapabilities(false);
- getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
- if (getOriginRes.isRight()) {
- log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
- reqOpt.get().getName(), toInstance.getActualComponentUid());
- result = false;
- }
- }
- if (result) {
- toOriginComponent = getOriginRes.left().value();
- cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
- .filter(c -> c.getName().equals(reqAndRelationshipPair.getCapability())).findFirst();
- if (!cap.isPresent()) {
- cap = findCapability(reqMap, reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance);
- if(!cap.isPresent()){
- result = false;
- log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
- reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
- }
- }
- }
- if (result) {
- result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(),
- reqOpt.get(), reqAndRelationshipPair, toInstance);
- }
- return result;
- }
-
- private Optional<CapabilityDefinition> findCapability(Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) {
- Optional<CapabilityDefinition> cap = Optional.empty();
- Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny();
- if (findAny.isPresent()) {
- RequirementDefinition reqDefinition = findAny.get();
- cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(reqDefinition.getCapability())).findFirst();
- if (!cap.isPresent()) {
- log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
- }
- }
- return cap;
- }
-
- private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance) {
- boolean result = true;
- Either<String, Boolean> buildReqNameRes = null;
- Either<String, Boolean> buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents,
- toOriginComponent, capability.getPath(), reqAndRelationshipPair.getCapability());
- if (buildCapNameRes.isRight()) {
- log.debug(
- "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
- reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
- result = false;
- }
- if (result) {
- buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, fromOriginComponent,
- requirement.getPath(), reqAndRelationshipPair.getRequirement());
- if (buildReqNameRes.isRight()) {
- log.debug(
- "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
- reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
- result = false;
- }
- }
- if (result) {
- ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
- Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
- toscaRequirement.setNode(toInstance.getName());
- toscaRequirement.setCapability(buildCapNameRes.left().value());
- toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
- toscaRequirements.add(toscaReqMap);
- }
- return result;
- }
-
- private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String toInstanceId) {
- for(List<RequirementDefinition> reqList: reqMap.values()){
- Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, toInstanceId)).findFirst();
- if(reqOpt.isPresent()){
- return reqOpt;
- }
- }
- return Optional.empty();
- }
-
- /**
- * Allows detecting the requirement belonging to the received relationship
- * The detection logic is: A requirement belongs to a relationship IF 1.The
- * name of the requirement equals to the "requirement" field of the
- * relation; AND 2. In case of a non-atomic resource, OwnerId of the
- * requirement equals to requirementOwnerId of the relation OR uniqueId of
- * toInstance equals to capabilityOwnerId of the relation
- *
- * @param fromOriginComponent
- * @param reqAndRelationshipPair
- * @param requirement
- * @param toInstanceId
- * @return
- */
- private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) {
- if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement()))
- return false;
- if (!ModelConverter.isAtomicComponent(originComponent))
- return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, toInstanceId);
- return true;
- }
-
- private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) {
- return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils.equals(toInstanceId, reqAndRelationshipPair.getCapabilityOwnerId());
- }
-
- private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
- SubstitutionMapping substitutionMappings) {
-
- Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
- Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor
- .convertSubstitutionMappingCapabilities(originComponents, component);
- if (toscaCapabilitiesRes.isRight()) {
- result = Either.right(toscaCapabilitiesRes.right().value());
- log.error("Failed convert capabilities for the component {}. ", component.getName());
- } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) {
- substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
- log.debug("Finish convert capabilities for the component {}. ", component.getName());
- }
- log.debug("Finished to convert capabilities for the component {}. ", component.getName());
- return result;
- }
-
- private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
- Map<String, DataTypeDefinition> dataTypes) {
- Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
- dataTypes);
- if (!toscaCapabilities.isEmpty()) {
- nodeType.setCapabilities(toscaCapabilities);
- }
- log.debug("Finish convert Capabilities for node type");
-
- return Either.left(nodeType);
- }
-
- private static class CustomRepresenter extends Representer {
- public CustomRepresenter() {
- super();
- // null representer is exceptional and it is stored as an instance
- // variable.
- this.nullRepresenter = new RepresentNull();
-
- }
-
- @Override
- protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
- Tag customTag) {
- if (propertyValue == null) {
- return null;
- } else {
- // skip not relevant for Tosca property
- if ("dependencies".equals(property.getName())) {
- return null;
- }
- NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
-
- return "_defaultp_".equals(property.getName())
- ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
- }
- }
-
- @Override
- protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
- // remove the bean type from the output yaml (!! ...)
- if (!classTags.containsKey(javaBean.getClass()))
- addClassTag(javaBean.getClass(), Tag.MAP);
-
- return super.representJavaBean(properties, javaBean);
- }
-
- private class RepresentNull implements Represent {
- @Override
- public Node representData(Object data) {
- // possible values are here http://yaml.org/type/null.html
- return representScalar(Tag.NULL, "");
- }
- }
- }
-
- private static class UnsortedPropertyUtils extends PropertyUtils {
- @Override
- protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
- throws IntrospectionException {
- Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
- return new LinkedHashSet<>(fields);
- }
- }
+ @Autowired
+ private ApplicationDataTypeCache dataTypeCache;
+
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+ @Autowired
+ private CapabiltyRequirementConvertor capabiltyRequirementConvertor;
+ private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance();
+
+ private static final Logger log = LoggerFactory.getLogger(ToscaExportHandler.class);
+
+ public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1";
+ public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
+ public static final String IMPORTS_FILE_KEY = "file";
+ public static final String TOSCA_TEMPLATE_NAME = "-template.yml";
+ public static final String TOSCA_INTERFACE_NAME = "-interface.yml";
+ public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
+ public static final String VF_MODULE_TYPE_KEY = "vf_module_type";
+ public static final String VF_MODULE_DESC_KEY = "vf_module_description";
+ public static final String VOLUME_GROUP_KEY = "volume_group";
+ public static final String VF_MODULE_TYPE_BASE = "Base";
+ public static final String VF_MODULE_TYPE_EXPANSION = "Expansion";
+ private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
+ private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
+ protected static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager
+ .getConfigurationManager().getConfiguration().getDefaultImports();
+
+ public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
+
+ Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component);
+ if (toscaTemplateRes.isRight()) {
+ return Either.right(toscaTemplateRes.right().value());
+ }
+
+ ToscaTemplate toscaTemplate = toscaTemplateRes.left().value();
+ ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
+ return Either.left(toscaRepresentation);
+ }
+
+ public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) {
+ if (null == DEFAULT_IMPORTS) {
+ log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+
+ ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
+ toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
+ Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
+ Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate,
+ nodeTypes);
+ if (toscaTemplateRes.isRight()) {
+ return Either.right(toscaTemplateRes.right().value());
+ }
+
+ toscaTemplate = toscaTemplateRes.left().value();
+ ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
+ return Either.left(toscaRepresentation);
+ }
+
+ public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) {
+ CustomRepresenter representer = new CustomRepresenter();
+ DumperOptions options = new DumperOptions();
+ options.setAllowReadOnlyProperties(false);
+ options.setPrettyFlow(true);
+
+ options.setDefaultFlowStyle(FlowStyle.FLOW);
+ options.setCanonical(false);
+
+ representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
+
+ representer.setPropertyUtils(new UnsortedPropertyUtils());
+ Yaml yaml = new Yaml(representer, options);
+
+ String yamlAsString = yaml.dumpAsMap(toscaTemplate);
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
+ sb.append(yamlAsString);
+ sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
+
+ ToscaRepresentation toscaRepresentation = new ToscaRepresentation();
+ toscaRepresentation.setMainYaml(sb.toString());
+ toscaRepresentation.setDependencies(toscaTemplate.getDependencies());
+
+ return toscaRepresentation;
+ }
+
+ public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
+ ToscaTemplate toscaTemplate = new ToscaTemplate(null);
+ Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
+ toscaTemplate);
+ if (fillImports.isRight()) {
+ return Either.right(fillImports.right().value());
+ }
+ return Either.left(fillImports.left().value().left);
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) {
+ if (null == DEFAULT_IMPORTS) {
+ log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+
+ log.trace("start tosca export for {}", component.getUniqueId());
+ ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION);
+
+ toscaTemplate.setMetadata(convertMetadata(component));
+ toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS));
+ Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
+ if (ModelConverter.isAtomicComponent(component)) {
+ log.trace("convert component as node type");
+ return convertNodeType(component, toscaTemplate, nodeTypes);
+ } else {
+ log.trace("convert component as topology template");
+ return convertToscaTemplate(component, toscaTemplate);
+ }
+
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
+
+ Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
+ toscaNode);
+ if (importsRes.isRight()) {
+ return Either.right(importsRes.right().value());
+ }
+ toscaNode = importsRes.left().value().left;
+ Map<String, Component> componentCache = importsRes.left().value().right;
+ Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component );
+ if (nodeTypesMapEither.isRight()) {
+ log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
+ nodeTypesMapEither.right().value());
+ return Either.right(nodeTypesMapEither.right().value());
+ }
+ Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
+ if (nodeTypesMap != null && !nodeTypesMap.isEmpty())
+ toscaNode.setNode_types(nodeTypesMap);
+
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
+ if (dataTypesEither.isRight()) {
+ log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+ Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
+
+ ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
+
+ Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes);
+ if (inputs.isRight()) {
+ return Either.right(inputs.right().value());
+ }
+ topologyTemplate = inputs.left().value();
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
+ .getComponentInstancesProperties();
+ List<GroupDefinition> groups = component.getGroups();
+ if (componentInstances != null && !componentInstances.isEmpty()) {
+
+ Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component,
+ componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate);
+ if (nodeTemplates.isRight()) {
+ return Either.right(nodeTemplates.right().value());
+ }
+ log.debug("node templates converted");
+
+ topologyTemplate.setNode_templates(nodeTemplates.left().value());
+ }
+ Map<String, ToscaGroupTemplate> groupsMap;
+ if (groups != null && !groups.isEmpty()) {
+ groupsMap = new HashMap<>();
+ for (GroupDefinition group : groups) {
+ boolean addToTosca = true;
+ if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ List<String> artifacts = group.getArtifacts();
+ if (artifacts == null || artifacts.isEmpty()) {
+ addToTosca = false;
+ }
+ }
+ if (addToTosca) {
+ ToscaGroupTemplate toscaGroup = convertGroup(group);
+ groupsMap.put(group.getName(), toscaGroup);
+ }
+
+ }
+ log.debug("groups converted");
+ topologyTemplate.addGroups(groupsMap);
+ }
+ SubstitutionMapping substitutionMapping = new SubstitutionMapping();
+ String toscaResourceName;
+ switch (component.getComponentType()) {
+ case RESOURCE:
+ toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
+ .getMetadataDataDefinition()).getToscaResourceName();
+ break;
+ case SERVICE:
+ toscaResourceName = SERVICE_NODE_TYPE_PREFIX
+ + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+ break;
+ default:
+ log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
+ return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
+ }
+ substitutionMapping.setNode_type(toscaResourceName);
+
+ Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
+ if (capabilities.isRight()) {
+ return Either.right(capabilities.right().value());
+ }
+ substitutionMapping = capabilities.left().value();
+
+ Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor
+ .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
+ if (requirements.isRight()) {
+ return Either.right(requirements.right().value());
+ }
+ substitutionMapping = requirements.left().value();
+
+ topologyTemplate.setSubstitution_mappings(substitutionMapping);
+
+ toscaNode.setTopology_template(topologyTemplate);
+ return Either.left(toscaNode);
+ }
+
+ private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component,
+ ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) {
+ if (log.isDebugEnabled())
+ log.debug("fillInputs for component {}", component.getUniqueId());
+ List<InputDefinition> inputDef = component.getInputs();
+ Map<String, ToscaProperty> inputs = new HashMap<>();
+
+ if (inputDef != null) {
+ inputDef.forEach(i -> {
+ ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
+ inputs.put(i.getName(), property);
+ });
+ if (!inputs.isEmpty()) {
+ topologyTemplate.setInputs(inputs);
+ }
+ }
+ return Either.left(topologyTemplate);
+ }
+
+ private ToscaMetadata convertMetadata(Component component) {
+ return convertMetadata(component, false, null);
+ }
+
+ private ToscaMetadata convertMetadata(Component component, boolean isInstance,
+ ComponentInstance componentInstance) {
+ ToscaMetadata toscaMetadata = new ToscaMetadata();
+ toscaMetadata.setInvariantUUID(component.getInvariantUUID());
+ toscaMetadata.setUUID(component.getUUID());
+ toscaMetadata.setDescription(component.getDescription());
+ toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+
+ List<CategoryDefinition> categories = component.getCategories();
+ CategoryDefinition categoryDefinition = categories.get(0);
+ toscaMetadata.setCategory(categoryDefinition.getName());
+
+ if (isInstance) {
+ toscaMetadata.setVersion(component.getVersion());
+ toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID());
+ if (componentInstance.getSourceModelInvariant() != null
+ && !componentInstance.getSourceModelInvariant().isEmpty()) {
+ toscaMetadata.setVersion(componentInstance.getComponentVersion());
+ toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant());
+ toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid());
+ toscaMetadata.setSourceModelName(componentInstance.getSourceModelName());
+ toscaMetadata.setName(
+ componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
+ toscaMetadata.setDescription(componentInstance.getDescription());
+ }
+
+ }
+ switch (component.getComponentType()) {
+ case RESOURCE:
+ Resource resource = (Resource) component;
+
+ if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
+ toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue());
+ } else
+ toscaMetadata.setType(resource.getResourceType().name());
+ toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
+ toscaMetadata.setResourceVendor(resource.getVendorName());
+ toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
+ toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
+ break;
+ case SERVICE:
+ Service service = (Service) component;
+ toscaMetadata.setType(component.getComponentType().getValue());
+ toscaMetadata.setServiceType(service.getServiceType());
+ toscaMetadata.setServiceRole(service.getServiceRole());
+ toscaMetadata.setEnvironmentContext(service.getEnvironmentContext());
+ if (!isInstance) {
+ // DE268546
+ toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming());
+ toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming());
+ toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy());
+ }
+ break;
+ default:
+ log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
+ }
+ return toscaMetadata;
+ }
+
+ private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
+ ToscaTemplate toscaTemplate) {
+
+ if (null == DEFAULT_IMPORTS) {
+ log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+ Map<String, Component> componentCache = new HashMap<>();
+
+ if (!ModelConverter.isAtomicComponent(component)) {
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (componentInstances != null && !componentInstances.isEmpty()) {
+
+ List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null
+ ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports());
+
+ List<Triple<String, String, Component>> dependecies = new ArrayList<>();
+
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+
+ Map<String, Map<String, String>> importsListMember = new HashMap<>();
+ Map<String, String> interfaceFiles = new HashMap<>();
+ interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
+ StringBuilder keyNameBuilder = new StringBuilder();
+ keyNameBuilder.append(component.getComponentType().toString().toLowerCase());
+ keyNameBuilder.append("-");
+ keyNameBuilder.append(component.getName());
+ keyNameBuilder.append("-interface");
+ importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
+ additionalImports.add(importsListMember);
+
+ componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci));
+ toscaTemplate.setDependencies(dependecies);
+ toscaTemplate.setImports(additionalImports);
+ }
+ } else {
+ log.debug("currently imports supported for VF and service only");
+ }
+ return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache));
+ }
+
+ private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports,
+ List<Triple<String, String, Component>> dependecies, ComponentInstance ci) {
+ Map<String, String> files = new HashMap<>();
+ Map<String, Map<String, String>> importsListMember = new HashMap<>();
+ StringBuilder keyNameBuilder;
+
+ Component componentRI = componentCache.get(ci.getComponentUid());
+ if (componentRI == null) {
+ // all resource must be only once!
+ Either<Component, StorageOperationStatus> resource = toscaOperationFacade
+ .getToscaFullElement(ci.getComponentUid());
+ if ((resource.isRight()) && (log.isDebugEnabled())) {
+ log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
+ return ;
+ }
+
+ Component fetchedComponent = resource.left().value();
+ componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
+
+ if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){
+ Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
+ .getToscaFullElement(ci.getSourceModelUid());
+ if (sourceService.isRight() && (log.isDebugEnabled())) {
+ log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId());
+ }
+ Component fetchedSource = sourceService.left().value();
+ componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
+ }
+
+ componentRI = fetchedComponent;
+
+ Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts();
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
+ if (artifactDefinition != null) {
+ String artifactName = artifactDefinition.getArtifactName();
+ files.put(IMPORTS_FILE_KEY, artifactName);
+ keyNameBuilder = new StringBuilder();
+ keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase());
+ keyNameBuilder.append("-");
+ keyNameBuilder.append(ci.getComponentName());
+ importsListMember.put(keyNameBuilder.toString(), files);
+ imports.add(importsListMember);
+ dependecies.add(new ImmutableTriple<String, String, Component>(artifactName,
+ artifactDefinition.getEsId(), fetchedComponent));
+
+ if (!ModelConverter.isAtomicComponent(componentRI)) {
+ importsListMember = new HashMap<>();
+ Map<String, String> interfaceFiles = new HashMap<>();
+ interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
+ keyNameBuilder.append("-interface");
+ importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
+ imports.add(importsListMember);
+ }
+ }
+ }
+ }
+
+ public static String getInterfaceFilename(String artifactName) {
+ return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode,
+ Map<String, ToscaNodeType> nodeTypes) {
+ log.debug("start convert node type for {}", component.getUniqueId());
+ ToscaNodeType toscaNodeType = createNodeType(component);
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
+ if (dataTypesEither.isRight()) {
+ log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
+ Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType,
+ dataTypes);
+ if (properties.isRight()) {
+ return Either.right(properties.right().value());
+ }
+ toscaNodeType = properties.left().value();
+ log.debug("Properties converted for {}", component.getUniqueId());
+
+ // Extracted to method for code reuse
+ return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode,
+ Map<String, ToscaNodeType> nodeTypes) {
+ log.debug("start convert node type for {}", component.getUniqueId());
+ ToscaNodeType toscaNodeType = createNodeType(component);
+
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
+ if (dataTypesEither.isRight()) {
+ log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
+ return Either.right(ToscaError.GENERAL_ERROR);
+ }
+
+ Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
+
+ List<InputDefinition> inputDef = component.getInputs();
+ Map<String, ToscaProperty> inputs = new HashMap<>();
+
+ if (inputDef != null) {
+ inputDef.forEach(i -> {
+ ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false);
+ inputs.put(i.getName(), property);
+ });
+ if (!inputs.isEmpty()) {
+ toscaNodeType.setProperties(inputs);
+ }
+ }
+
+ // Extracted to method for code reuse
+ return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes);
+ }
+
+ private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode,
+ Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType,
+ Map<String, DataTypeDefinition> dataTypes) {
+ Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes);
+ if (capabilities.isRight()) {
+ return Either.right(capabilities.right().value());
+ }
+ toscaNodeType = capabilities.left().value();
+ log.debug("Capabilities converted for {}", component.getUniqueId());
+
+ Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component,
+ toscaNodeType);
+ if (requirements.isRight()) {
+ return Either.right(requirements.right().value());
+ }
+ toscaNodeType = requirements.left().value();
+ log.debug("Requirements converted for {}", component.getUniqueId());
+
+ String toscaResourceName;
+ switch (component.getComponentType()) {
+ case RESOURCE:
+ toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
+ .getMetadataDataDefinition()).getToscaResourceName();
+ break;
+ case SERVICE:
+ toscaResourceName = SERVICE_NODE_TYPE_PREFIX
+ + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+ break;
+ default:
+ log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
+ return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
+ }
+
+ nodeTypes.put(toscaResourceName, toscaNodeType);
+ toscaNode.setNode_types(nodeTypes);
+ log.debug("finish convert node type for {}", component.getUniqueId());
+ return Either.left(toscaNode);
+ }
+
+ private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component,
+ List<ComponentInstance> componentInstances,
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
+ Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes,
+ ToscaTopolgyTemplate topologyTemplate) {
+
+ Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null;
+ log.debug("start convert topology template for {} for type {}", component.getUniqueId(),
+ component.getComponentType());
+ Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>();
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs();
+
+ Map<String, ToscaGroupTemplate> groupsMap = null;
+ for (ComponentInstance componentInstance : componentInstances) {
+ ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate();
+ nodeTemplate.setType(componentInstance.getToscaComponentName());
+
+ Either<Component, Boolean> originComponentRes = capabiltyRequirementConvertor
+ .getOriginComponent(componentCache, componentInstance);
+ if (originComponentRes.isRight()) {
+ convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
+ break;
+ }
+ Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component,
+ componentInstance, component.getComponentInstancesRelations(), nodeTemplate,
+ originComponentRes.left().value(), componentCache);
+ if (requirements.isRight()) {
+ convertNodeTemplatesRes = Either.right(requirements.right().value());
+ break;
+ }
+ String instanceUniqueId = componentInstance.getUniqueId();
+ log.debug("Component instance Requirements converted for instance {}", instanceUniqueId);
+
+ nodeTemplate = requirements.left().value();
+
+ Component originalComponent = componentCache.get(componentInstance.getActualComponentUid());
+
+ if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){
+ Component componentOfProxy = componentCache.get(componentInstance.getComponentUid());
+ nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance));
+ } else {
+ nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance));
+ }
+
+ Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor
+ .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate);
+ if (capabilities.isRight()) {
+ convertNodeTemplatesRes = Either.right(requirements.right().value());
+ break;
+ }
+ log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId);
+
+ nodeTemplate = capabilities.left().value();
+ Map<String, Object> props = new HashMap<>();
+
+ if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ // Adds the properties of parent component to map
+ addPropertiesOfParentComponent(dataTypes, componentInstance, originalComponent, props);
+ }
+
+ if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) {
+ addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance,
+ instanceUniqueId, props);
+ }
+
+ if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) {
+ addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId,
+ props);
+ }
+ if (props != null && !props.isEmpty()) {
+ nodeTemplate.setProperties(props);
+ }
+
+ List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
+ if (groupInstances != null) {
+ if (groupsMap == null) {
+ groupsMap = new HashMap<>();
+ }
+ for (GroupInstance groupInst : groupInstances) {
+ boolean addToTosca = true;
+
+ List<String> artifacts = groupInst.getArtifacts();
+ if (artifacts == null || artifacts.isEmpty()) {
+ addToTosca = false;
+ }
+
+ if (addToTosca) {
+ ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst);
+ groupsMap.put(groupInst.getName(), toscaGroup);
+ }
+ }
+ }
+
+ nodeTemplates.put(componentInstance.getName(), nodeTemplate);
+ }
+ if (groupsMap != null) {
+ log.debug("instance groups added");
+ topologyTemplate.addGroups(groupsMap);
+ }
+ if (component.getComponentType() == ComponentTypeEnum.SERVICE && MapUtils.isNotEmpty(((Service) component).getForwardingPaths())) {
+ log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(),
+ component.getName());
+ ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabiltyRequirementConvertor, componentCache, toscaOperationFacade);
+ log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(),
+ component.getName());
+ }
+ if (convertNodeTemplatesRes == null) {
+ convertNodeTemplatesRes = Either.left(nodeTemplates);
+ }
+ log.debug("finish convert topology template for {} for type {}", component.getUniqueId(),
+ component.getComponentType());
+ return convertNodeTemplatesRes;
+ }
+
+ private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes,
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance,
+ String instanceUniqueId, Map<String, Object> props) {
+
+ List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
+ if (instanceInputsList != null) {
+ instanceInputsList.forEach(input -> {
+
+ Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()
+ ? input.getValue() : input.getDefaultValue();
+ convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
+ });
+ }
+ }
+
+ private void addPropertiesOfComponentInstance(
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
+ Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId,
+ Map<String, Object> props) {
+
+ if (!MapUtils.isEmpty(componentInstancesProperties)) {
+ componentInstancesProperties.get(instanceUniqueId).stream()
+ // Collects filtered properties to List
+ .collect(Collectors.toList()).stream()
+ // Converts and adds each value to property map
+ .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
+ () -> prop.getValue()));
+ }
+ }
+
+ private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes,
+ ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) {
+
+ List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties();
+ if (!CollectionUtils.isEmpty(componentProperties)) {
+ componentProperties.stream()
+ // Filters out properties with empty default values
+ .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue()))
+ // Collects filtered properties to List
+ .collect(Collectors.toList()).stream()
+ // Converts and adds each value to property map
+ .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop,
+ () -> prop.getDefaultValue()));
+ }
+ }
+
+ /**
+ * @param dataTypes
+ * @param componentInstance
+ * @param props
+ * @param prop
+ * @param supplier
+ */
+ private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
+ Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) {
+ Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier);
+ if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
+ props.put(prop.getName(), convertedValue);
+ }
+ }
+
+ private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
+ ComponentInstance componentInstance, T input, Supplier<String> supplier) {
+ log.debug("Convert property or input value {} for instance {}", input.getName(),
+ componentInstance.getUniqueId());
+ String propertyType = input.getType();
+ String innerType = null;
+ if (input.getSchema() != null && input.getSchema().getProperty() != null) {
+ innerType = input.getSchema().getProperty().getType();
+ }
+ return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
+ }
+
+ private ToscaGroupTemplate convertGroup(GroupDefinition group) {
+ ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
+ Map<String, String> members = group.getMembers();
+ if (members != null)
+ toscaGroup.setMembers(new ArrayList<String>(members.keySet()));
+
+ Supplier<String> supplGroupType = () -> group.getType();
+ Supplier<String> supplDescription = () -> group.getDescription();
+ Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties();
+ Supplier<String> supplgroupName = () -> group.getName();
+ Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID();
+ Supplier<String> supplGroupUUID = () -> group.getGroupUUID();
+ Supplier<String> supplVersion = () -> group.getVersion();
+
+ IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
+ supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
+ toscaGroup.setMetadata(toscaMetadata);
+ return toscaGroup;
+ }
+
+ private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) {
+ ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate();
+
+ Supplier<String> supplGroupType = () -> groupInstance.getType();
+ Supplier<String> supplDescription = () -> groupInstance.getDescription();
+ Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance
+ .convertToGroupInstancesProperties();
+ Supplier<String> supplgroupName = () -> groupInstance.getGroupName();
+ Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID();
+ Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID();
+ Supplier<String> supplVersion = () -> groupInstance.getVersion();
+
+ IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName,
+ supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType);
+
+ toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID());
+ toscaGroup.setMetadata(toscaMetadata);
+ return toscaGroup;
+ }
+
+ private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props,
+ Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID,
+ Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) {
+ boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false;
+ toscaGroup.setType(groupType.get());
+
+ IToscaMetadata toscaMetadata;
+ if (!isVfModule) {
+ toscaMetadata = new ToscaMetadata();
+ } else {
+ toscaMetadata = new VfModuleToscaMetadata();
+
+ Map<String, Object> properties = fillGroupProperties(props.get());
+ if (!properties.containsKey(VF_MODULE_DESC_KEY)
+ || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) {
+ properties.put(VF_MODULE_DESC_KEY, description.get());
+ }
+ toscaGroup.setProperties(properties);
+ }
+ toscaMetadata.setName(groupName.get());
+ toscaMetadata.setInvariantUUID(invariantUUID.get());
+ toscaMetadata.setUUID(groupUUID.get());
+ toscaMetadata.setVersion(version.get());
+ return toscaMetadata;
+ }
+
+ private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) {
+ Map<String, Object> properties = new HashMap<>();
+ if (groupProps != null) {
+ for (GroupProperty gp : groupProps) {
+ if (gp.getName().equals(Constants.IS_BASE)) {
+ Boolean isBase = Boolean.parseBoolean(gp.getValue());
+ String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION;
+ properties.put(VF_MODULE_TYPE_KEY, type);
+ } else {
+ Object value = null;
+ String type = gp.getType();
+
+ switch (type) {
+ case "integer":
+ if (gp.getValue() != null) {
+ value = Integer.valueOf(gp.getValue());
+ }
+ break;
+ case "boolean":
+ if (gp.getValue() != null) {
+ value = Boolean.valueOf(gp.getValue());
+ }
+ break;
+
+ default:
+ value = gp.getValue();
+ break;
+ }
+ properties.put(gp.getName(), value);
+ }
+ }
+ }
+ return properties;
+ }
+
+ private ToscaNodeType createNodeType(Component component) {
+ ToscaNodeType toscaNodeType = new ToscaNodeType();
+ if (ModelConverter.isAtomicComponent(component)) {
+ if (((Resource) component).getDerivedFrom() != null) {
+ toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0));
+ }
+ toscaNodeType.setDescription(component.getDescription()); // or
+ // name??
+ } else {
+ String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType()
+ : "tosca.nodes.Root";
+ toscaNodeType.setDerived_from(derivedFrom);
+ }
+ return toscaNodeType;
+ }
+
+ private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) {
+
+ Map<String, ToscaNodeType> nodeTypesMap = null;
+ Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap);
+
+ List<ComponentInstance> componetInstances = container.getComponentInstances();
+
+ if (componetInstances == null || componetInstances.isEmpty())
+ return res;
+ Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>();
+ List<ComponentInstance> proxyInst = componetInstances.stream()
+ .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name()))
+ .collect(Collectors.toList());
+ if (proxyInst != null && !proxyInst.isEmpty()) {
+ for (ComponentInstance inst : proxyInst) {
+ serviceProxyInstanceList.put(inst.getToscaComponentName(), inst);
+ }
+ }
+
+ if (serviceProxyInstanceList.isEmpty())
+ return res;
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreCapabilities(false);
+ filter.setIgnoreComponentInstances(false);
+ Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
+ .getLatestByName("serviceProxy");
+ if (serviceProxyOrigin.isRight()) {
+ log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
+ serviceProxyOrigin.right().value());
+ return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
+ }
+ Component origComponent = serviceProxyOrigin.left().value();
+
+ nodeTypesMap = new HashMap<>();
+ for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) {
+ Component serviceComponent = null;
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreCategories(false);
+ Either<Component, StorageOperationStatus> service = toscaOperationFacade
+ .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView);
+ if (service.isRight()) {
+ log.debug("Failed to fetch resource with id {} for instance {}");
+ } else
+ serviceComponent = service.left().value();
+
+ ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue());
+ nodeTypesMap.put(entryProxy.getKey(), toscaNodeType);
+ }
+
+ return Either.left(nodeTypesMap);
+ }
+
+ private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent,
+ ComponentInstance instance) {
+ ToscaNodeType toscaNodeType = new ToscaNodeType();
+ String derivedFrom = ((Resource) origComponent).getToscaResourceName();
+
+ toscaNodeType.setDerived_from(derivedFrom);
+ Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll();
+ if (dataTypesEither.isRight()) {
+ log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
+ }
+ Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
+ Map<String, ToscaCapability> capabilities = this.capabiltyRequirementConvertor
+ .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes);
+
+ toscaNodeType.setCapabilities(capabilities);
+
+ return toscaNodeType;
+ }
+
+ private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component,
+ ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations,
+ ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) {
+
+ List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
+ if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) {
+ log.debug("Failed to convert component instance requirements for the component instance {}. ",
+ componentInstance.getName());
+ return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
+ }
+ if (!toscaRequirements.isEmpty()) {
+ nodeTypeTemplate.setRequirements(toscaRequirements);
+ }
+ log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName());
+ return Either.left(nodeTypeTemplate);
+ }
+
+ private boolean addRequirements(Component component, ComponentInstance componentInstance,
+ List<RequirementCapabilityRelDef> relations, Component originComponent,
+ List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
+ boolean result;
+ List<RequirementCapabilityRelDef> filteredRelations = relations.stream()
+ .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList());
+ if (CollectionUtils.isEmpty(filteredRelations)) {
+ result = true;
+ } else {
+ result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent,
+ component.getComponentInstances(), rel, toscaRequirements, componentCache)).findFirst().isPresent();
+ }
+ return result;
+ }
+
+ private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent,
+ List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel,
+ List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) {
+
+ boolean result = true;
+ Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements();
+ RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation();
+ Either<Component, StorageOperationStatus> getOriginRes = null;
+ Optional<RequirementDefinition> reqOpt = null;
+ Component toOriginComponent = null;
+ Optional<CapabilityDefinition> cap = null;
+
+ ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId()))
+ .findFirst().orElse(null);
+ if (toInstance == null) {
+ log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(),
+ rel.getToNode());
+ result = false;
+ }
+ if (result) {
+ reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId());
+ if (!reqOpt.isPresent()) {
+ log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}",
+ reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId());
+ result = false;
+ }
+ }
+ if (result) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreComponentInstances(false);
+ filter.setIgnoreCapabilities(false);
+ getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter);
+ if (getOriginRes.isRight()) {
+ log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}",
+ reqOpt.get().getName(), toInstance.getActualComponentUid());
+ result = false;
+ }
+ }
+ if (result) {
+ toOriginComponent = getOriginRes.left().value();
+ cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream()
+ .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst();
+ if (!cap.isPresent()) {
+ cap = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance);
+ if(!cap.isPresent()){
+ result = false;
+ log.debug("Failed to find a capability with name {} on a component with uniqueId {}",
+ reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
+ }
+ }
+ }
+ if (result) {
+ result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(),
+ reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache);
+ }
+ return result;
+ }
+
+ private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) {
+ return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId()));
+ }
+
+ private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) {
+ Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst();
+ if (!cap.isPresent()) {
+ log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
+ }
+ return cap;
+ }
+
+ private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) {
+ boolean result = true;
+ Either<String, Boolean> buildReqNameRes = null;
+ List<String> reducedPath = capability.getPath();
+ if(capability.getOwnerId() !=null){
+ reducedPath = capabiltyRequirementConvertor.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() );
+ }
+ Either<String, Boolean> buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache,
+ toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability());
+ if (buildCapNameRes.isRight()) {
+ log.debug(
+ "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}",
+ reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId());
+ result = false;
+ }
+ if (result) {
+ buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, fromOriginComponent,
+ requirement.getPath(), reqAndRelationshipPair.getRequirement());
+ if (buildReqNameRes.isRight()) {
+ log.debug(
+ "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}",
+ reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId());
+ result = false;
+ }
+ }
+ if (result) {
+ ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement();
+ Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
+ toscaRequirement.setNode(toInstance.getName());
+ toscaRequirement.setCapability(buildCapNameRes.left().value());
+ toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement);
+ toscaRequirements.add(toscaReqMap);
+ }
+ return result;
+ }
+
+ private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) {
+ for(List<RequirementDefinition> reqList: reqMap.values()){
+ Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst();
+ if(reqOpt.isPresent()){
+ return reqOpt;
+ }
+ }
+ return Optional.empty();
+ }
+
+ /**
+ * Allows detecting the requirement belonging to the received relationship
+ * The detection logic is: A requirement belongs to a relationship IF 1.The
+ * name of the requirement equals to the "requirement" field of the
+ * relation; AND 2. In case of a non-atomic resource, OwnerId of the
+ * requirement equals to requirementOwnerId of the relation OR uniqueId of
+ * toInstance equals to capabilityOwnerId of the relation
+ */
+ private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) {
+ if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())){
+ log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}",
+ requirement.getName(), reqAndRelationshipPair.getRequirement());
+ return false;
+ }
+ if (!ModelConverter.isAtomicComponent(originComponent))
+ return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
+ return true;
+ }
+
+ private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) {
+ return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()));
+ }
+
+ private boolean isCvfc(Component component) {
+ if (component.getComponentType() != ComponentTypeEnum.RESOURCE)
+ return false;
+ return ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
+ }
+
+ private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
+ SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) {
+
+ Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
+ Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor
+ .convertSubstitutionMappingCapabilities(componentCache, component);
+ if (toscaCapabilitiesRes.isRight()) {
+ result = Either.right(toscaCapabilitiesRes.right().value());
+ log.error("Failed convert capabilities for the component {}. ", component.getName());
+ } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) {
+ substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value());
+ log.debug("Finish convert capabilities for the component {}. ", component.getName());
+ }
+ log.debug("Finished to convert capabilities for the component {}. ", component.getName());
+ return result;
+ }
+
+ private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType,
+ Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component,
+ dataTypes);
+ if (!toscaCapabilities.isEmpty()) {
+ nodeType.setCapabilities(toscaCapabilities);
+ }
+ log.debug("Finish convert Capabilities for node type");
+
+ return Either.left(nodeType);
+ }
+
+ private static class CustomRepresenter extends Representer {
+ public CustomRepresenter() {
+ super();
+ // null representer is exceptional and it is stored as an instance
+ // variable.
+ this.nullRepresenter = new RepresentNull();
+
+ }
+
+ @Override
+ protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
+ Tag customTag) {
+ if (propertyValue == null) {
+ return null;
+ } else {
+ // skip not relevant for Tosca property
+ if ("dependencies".equals(property.getName())) {
+ return null;
+ }
+ NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
+
+ return "_defaultp_".equals(property.getName())
+ ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
+ }
+ }
+
+ @Override
+ protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
+ // remove the bean type from the output yaml (!! ...)
+ if (!classTags.containsKey(javaBean.getClass()))
+ addClassTag(javaBean.getClass(), Tag.MAP);
+
+ return super.representJavaBean(properties, javaBean);
+ }
+
+ private class RepresentNull implements Represent {
+ @Override
+ public Node representData(Object data) {
+ // possible values are here http://yaml.org/type/null.html
+ return representScalar(Tag.NULL, "");
+ }
+ }
+ }
+
+ private static class UnsortedPropertyUtils extends PropertyUtils {
+ @Override
+ protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess)
+ throws IntrospectionException {
+ Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
+ return new LinkedHashSet<>(fields);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java
index 6b1895b6ec..49fd91cfed 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java
@@ -20,30 +20,30 @@
package org.openecomp.sdc.be.tosca;
-import java.util.List;
-
import org.apache.commons.lang3.tuple.Triple;
import org.openecomp.sdc.be.model.Component;
+import java.util.List;
+
public class ToscaRepresentation {
- private String mainYaml;
- private List<Triple<String, String, Component>> dependencies;
+ private String mainYaml;
+ private List<Triple<String, String, Component>> dependencies;
- public String getMainYaml() {
- return mainYaml;
- }
+ public String getMainYaml() {
+ return mainYaml;
+ }
- public void setMainYaml(String mainYaml) {
- this.mainYaml = mainYaml;
- }
+ public void setMainYaml(String mainYaml) {
+ this.mainYaml = mainYaml;
+ }
- public List<Triple<String, String, Component>> getDependencies() {
- return dependencies;
- }
+ public List<Triple<String, String, Component>> getDependencies() {
+ return dependencies;
+ }
- public void setDependencies(List<Triple<String, String, Component>> dependancies) {
- this.dependencies = dependancies;
- }
+ public void setDependencies(List<Triple<String, String, Component>> dependancies) {
+ this.dependencies = dependancies;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
index 0c54e7229e..8abaaf73f8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
@@ -20,92 +20,88 @@
package org.openecomp.sdc.be.tosca;
-import java.lang.reflect.Field;
-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.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Component;
+import java.lang.reflect.Field;
+import java.util.*;
+
public class ToscaUtils {
- public static boolean isComplexVfc(Component component) {
- if (ComponentTypeEnum.RESOURCE == component.getComponentType()) {
- ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
- if (ResourceTypeEnum.CVFC == resourceType) {
- return true;
- }
- }
- return false;
- }
-
- public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalArgumentException, IllegalAccessException {
- Map<String, Object> map = new HashMap<>();
- List<Field> fields = new ArrayList<>();
-
- fields = getAllFields(fields, clazz);
-
- for (Field field : fields) {
- field.setAccessible(true);
- map.put(field.getName(), field.get(objectToConvert));
- }
- return map;
- }
-
- public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
- fields.addAll(Arrays.asList(type.getDeclaredFields()));
-
- if (type.getSuperclass() != null) {
- fields = getAllFields(fields, type.getSuperclass());
- }
- return fields;
- }
-
- public static class SubstituitionEntry{
-
- private String fullName = "";
- private String sourceName = "";
- private String owner = "";
-
- public SubstituitionEntry() {}
-
- public SubstituitionEntry(String fullName, String sourceName, String owner) {
- if(fullName != null)
- this.fullName = fullName;
- if(sourceName != null)
- this.sourceName = sourceName;
- if(owner != null)
- this.owner = owner;
- }
-
- public String getFullName() {
- return fullName;
- }
-
- public void setFullName(String fullName) {
- this.fullName = fullName;
- }
-
- public String getSourceName() {
- return sourceName;
- }
-
- public void setSourceName(String sourceName) {
- this.sourceName = sourceName;
- }
-
- public String getOwner() {
- return owner;
- }
-
- public void setOwner(String owner) {
- this.owner = owner;
- }
- }
-
+ public static boolean isComplexVfc(Component component) {
+ if (ComponentTypeEnum.RESOURCE == component.getComponentType()) {
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ if (ResourceTypeEnum.CVFC == resourceType) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalArgumentException, IllegalAccessException {
+ Map<String, Object> map = new HashMap<>();
+ List<Field> fields = new ArrayList<>();
+
+ fields = getAllFields(fields, clazz);
+
+ for (Field field : fields) {
+ field.setAccessible(true);
+ map.put(field.getName(), field.get(objectToConvert));
+ }
+ return map;
+ }
+
+ public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
+ fields.addAll(Arrays.asList(type.getDeclaredFields()));
+
+ if (type.getSuperclass() != null) {
+ fields = getAllFields(fields, type.getSuperclass());
+ }
+ return fields;
+ }
+
+ public static class SubstituitionEntry{
+
+ private String fullName = "";
+ private String sourceName = "";
+ private String owner = "";
+
+ public SubstituitionEntry() {}
+
+ public SubstituitionEntry(String fullName, String sourceName, String owner) {
+ if(fullName != null)
+ this.fullName = fullName;
+ if(sourceName != null)
+ this.sourceName = sourceName;
+ if(owner != null)
+ this.owner = owner;
+ }
+
+ public String getFullName() {
+ return fullName;
+ }
+
+ public void setFullName(String fullName) {
+ this.fullName = fullName;
+ }
+
+ public String getSourceName() {
+ return sourceName;
+ }
+
+ public void setSourceName(String sourceName) {
+ this.sourceName = sourceName;
+ }
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java
index 0c586c7043..f1a7dcb9e5 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java
@@ -21,23 +21,23 @@
package org.openecomp.sdc.be.tosca.model;
public class EntrySchema {
- private String type;
- private String description;
+ private String type;
+ private String description;
- public String getType() {
- return type;
- }
+ public String getType() {
+ return type;
+ }
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
index 70b05b8158..1bb865f562 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
@@ -22,13 +22,13 @@ package org.openecomp.sdc.be.tosca.model;
public interface IToscaMetadata {
- public void setName(String name);
+ public void setName(String name);
- public void setInvariantUUID(String invariantUUID);
+ public void setInvariantUUID(String invariantUUID);
- public void setUUID(String uUID);
+ public void setUUID(String uUID);
- public void setVersion(String version);
-
- public void setCustomizationUUID(String customizationUUID);
+ public void setVersion(String version);
+
+ public void setCustomizationUUID(String customizationUUID);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
index 5dc8ddee2a..bbbb303900 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
@@ -23,36 +23,36 @@ package org.openecomp.sdc.be.tosca.model;
import java.util.Map;
public class SubstitutionMapping {
- private String node_type;
- private Map<String, String[]> capabilities;
- private Map<String, String[]> requirements;
-
- public SubstitutionMapping() {
- 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<String, String[]> getCapabilities() {
- return capabilities;
- }
-
- public void setCapabilities(Map<String, String[]> capabilities) {
- this.capabilities = capabilities;
- }
-
- public Map<String, String[]> getRequirements() {
- return requirements;
- }
-
- public void setRequirements(Map<String, String[]> requirements) {
- this.requirements = requirements;
- }
+ private String node_type;
+ private Map<String, String[]> capabilities;
+ private Map<String, String[]> requirements;
+
+ public SubstitutionMapping() {
+ 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<String, String[]> getCapabilities() {
+ return capabilities;
+ }
+
+ public void setCapabilities(Map<String, String[]> capabilities) {
+ this.capabilities = capabilities;
+ }
+
+ public Map<String, String[]> getRequirements() {
+ return requirements;
+ }
+
+ public void setRequirements(Map<String, String[]> requirements) {
+ this.requirements = requirements;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java
index 2688e5e6b3..d26fd0447c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java
@@ -25,56 +25,56 @@ import java.util.Map;
public class ToscaCapability {
- private String type;
- private String description;
+ private String type;
+ private String description;
- private List<Object> occurrences;
+ private List<Object> occurrences;
- private List<String> valid_source_types;
+ private List<String> valid_source_types;
- private Map<String, ToscaProperty> properties;
+ private Map<String, ToscaProperty> properties;
- public List<String> getValid_source_types() {
- return valid_source_types;
- }
+ public List<String> getValid_source_types() {
+ return valid_source_types;
+ }
- public void setValid_source_types(List<String> valid_source_types) {
- this.valid_source_types = valid_source_types;
- }
+ public void setValid_source_types(List<String> valid_source_types) {
+ this.valid_source_types = valid_source_types;
+ }
- public ToscaCapability() {
- }
+ public ToscaCapability() {
+ }
- public String getType() {
- return type;
- }
+ public String getType() {
+ return type;
+ }
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public List<Object> getOccurrences() {
- return occurrences;
- }
+ public List<Object> getOccurrences() {
+ return occurrences;
+ }
- public void setOccurrences(List<Object> occurrences) {
- this.occurrences = occurrences;
- }
+ public void setOccurrences(List<Object> occurrences) {
+ this.occurrences = occurrences;
+ }
- public Map<String, ToscaProperty> getProperties() {
- return properties;
- }
+ public Map<String, ToscaProperty> getProperties() {
+ return properties;
+ }
- public void setProperties(Map<String, ToscaProperty> properties) {
- this.properties = properties;
- }
+ public void setProperties(Map<String, ToscaProperty> properties) {
+ this.properties = properties;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java
index b91cffa5be..2c5e095b8f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java
@@ -24,46 +24,46 @@ import java.util.List;
import java.util.Map;
public class ToscaGroupTemplate {
- private String type;
- List<String> members;
- private IToscaMetadata metadata;
- private Map<String, Object> properties;
+ private String type;
+ List<String> members;
+ private IToscaMetadata metadata;
+ private Map<String, Object> properties;
- public ToscaGroupTemplate() {
- super();
+ public ToscaGroupTemplate() {
+ super();
- }
+ }
- public String getType() {
- return type;
- }
+ public String getType() {
+ return type;
+ }
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- public List<String> getMembers() {
- return members;
- }
+ public List<String> getMembers() {
+ return members;
+ }
- public void setMembers(List<String> members) {
- this.members = members;
- }
+ public void setMembers(List<String> members) {
+ this.members = members;
+ }
- public IToscaMetadata getMetadata() {
- return metadata;
- }
+ public IToscaMetadata getMetadata() {
+ return metadata;
+ }
- public void setMetadata(IToscaMetadata metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(IToscaMetadata metadata) {
+ this.metadata = metadata;
+ }
- public Map<String, Object> getProperties() {
- return properties;
- }
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
- public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
index 4f91e211cc..69907beaec 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
@@ -21,200 +21,200 @@
package org.openecomp.sdc.be.tosca.model;
public class ToscaMetadata implements IToscaMetadata {
- private String invariantUUID;
- private String UUID;
- private String customizationUUID;
- private String version;
- private String name;
- private String description;
- private String type;
- private String category;
- private String subcategory;
- private String resourceVendor;
- private String resourceVendorRelease;
- private String resourceVendorModelNumber;
- private String serviceType;
- private String serviceRole;
- private Boolean serviceEcompNaming;
- private Boolean ecompGeneratedNaming;
- private String namingPolicy;
- private String sourceModelInvariant;
- private String environmentContext;
- private String sourceModelName;
- private String sourceModelUuid;
-
-
- public String getName() {
- return name;
- }
-
- @Override
- public void setName(String name) {
- this.name = name;
- }
-
- public String getInvariantUUID() {
- return invariantUUID;
- }
-
- @Override
- public void setInvariantUUID(String invariantUUID) {
- this.invariantUUID = invariantUUID;
- }
-
- public String getUUID() {
- return UUID;
- }
-
- @Override
- public void setUUID(String uUID) {
- UUID = uUID;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- 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;
- }
-
- public String getResourceVendor() {
- return resourceVendor;
- }
-
- public void setResourceVendor(String resourceVendor) {
- this.resourceVendor = resourceVendor;
- }
-
- public String getResourceVendorRelease() {
- return resourceVendorRelease;
- }
-
- public void setResourceVendorRelease(String resourceVendorRelease) {
- this.resourceVendorRelease = resourceVendorRelease;
- }
-
- public String getResourceVendorModelNumber() {
- return resourceVendorModelNumber;
- }
-
- public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
- this.resourceVendorModelNumber = resourceVendorModelNumber;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public String getServiceRole() {
- return serviceRole;
- }
-
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
-
- public Boolean isEcompGeneratedNaming() {
- return ecompGeneratedNaming;
- }
-
- public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
- this.ecompGeneratedNaming = ecompGeneratedNaming;
- }
-
- public String isNamingPolicy() {
- return namingPolicy;
- }
-
- public void setNamingPolicy(String namingPolicy) {
- this.namingPolicy = namingPolicy;
- }
-
- public Boolean getServiceEcompNaming() {
- return serviceEcompNaming;
- }
-
- public void setServiceEcompNaming(Boolean serviceEcompNaming) {
- this.serviceEcompNaming = serviceEcompNaming;
- }
-
- public String getVersion() {
- return version;
- }
-
- @Override
- public void setVersion(String version) {
- this.version = version;
- }
-
- public String getCustomizationUUID() {
- return customizationUUID;
- }
-
- public void setCustomizationUUID(String customizationUUID) {
- this.customizationUUID = customizationUUID;
- }
-
- public String getSourceModelInvariant() {
- return sourceModelInvariant;
- }
-
- public void setSourceModelInvariant(String sourceModelInvariant) {
- this.sourceModelInvariant = sourceModelInvariant;
- }
-
- public String getSourceModelName() {
- return sourceModelName;
- }
-
- public void setSourceModelName(String sourceModelName) {
- this.sourceModelName = sourceModelName;
- }
-
- public String getSourceModelUuid() {
- return sourceModelUuid;
- }
-
- public void setSourceModelUuid(String sourceModelUuid) {
- this.sourceModelUuid = sourceModelUuid;
- }
-
-
-
- public String getEnvironmentContext() {
- return environmentContext;
- }
-
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
+ private String invariantUUID;
+ private String UUID;
+ private String customizationUUID;
+ private String version;
+ private String name;
+ private String description;
+ private String type;
+ private String category;
+ private String subcategory;
+ private String resourceVendor;
+ private String resourceVendorRelease;
+ private String resourceVendorModelNumber;
+ private String serviceType;
+ private String serviceRole;
+ private Boolean serviceEcompNaming;
+ private Boolean ecompGeneratedNaming;
+ private String namingPolicy;
+ private String sourceModelInvariant;
+ private String environmentContext;
+ private String sourceModelName;
+ private String sourceModelUuid;
+
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ @Override
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+ public String getUUID() {
+ return UUID;
+ }
+
+ @Override
+ public void setUUID(String uUID) {
+ UUID = uUID;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ 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;
+ }
+
+ public String getResourceVendor() {
+ return resourceVendor;
+ }
+
+ public void setResourceVendor(String resourceVendor) {
+ this.resourceVendor = resourceVendor;
+ }
+
+ public String getResourceVendorRelease() {
+ return resourceVendorRelease;
+ }
+
+ public void setResourceVendorRelease(String resourceVendorRelease) {
+ this.resourceVendorRelease = resourceVendorRelease;
+ }
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
+
+ public Boolean isEcompGeneratedNaming() {
+ return ecompGeneratedNaming;
+ }
+
+ public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
+ this.ecompGeneratedNaming = ecompGeneratedNaming;
+ }
+
+ public String isNamingPolicy() {
+ return namingPolicy;
+ }
+
+ public void setNamingPolicy(String namingPolicy) {
+ this.namingPolicy = namingPolicy;
+ }
+
+ public Boolean getServiceEcompNaming() {
+ return serviceEcompNaming;
+ }
+
+ public void setServiceEcompNaming(Boolean serviceEcompNaming) {
+ this.serviceEcompNaming = serviceEcompNaming;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ @Override
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getCustomizationUUID() {
+ return customizationUUID;
+ }
+
+ public void setCustomizationUUID(String customizationUUID) {
+ this.customizationUUID = customizationUUID;
+ }
+
+ public String getSourceModelInvariant() {
+ return sourceModelInvariant;
+ }
+
+ public void setSourceModelInvariant(String sourceModelInvariant) {
+ this.sourceModelInvariant = sourceModelInvariant;
+ }
+
+ public String getSourceModelName() {
+ return sourceModelName;
+ }
+
+ public void setSourceModelName(String sourceModelName) {
+ this.sourceModelName = sourceModelName;
+ }
+
+ public String getSourceModelUuid() {
+ return sourceModelUuid;
+ }
+
+ public void setSourceModelUuid(String sourceModelUuid) {
+ this.sourceModelUuid = sourceModelUuid;
+ }
+
+
+
+ public String getEnvironmentContext() {
+ return environmentContext;
+ }
+
+ public void setEnvironmentContext(String environmentContext) {
+ this.environmentContext = environmentContext;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java
index b2d7ef5ab6..c27944e8ee 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java
@@ -24,50 +24,58 @@ import java.util.List;
import java.util.Map;
public class ToscaNodeTemplate {
- private String type;
- private ToscaMetadata metadata;
- private Map<String, Object> properties;
- private List<Map<String, ToscaTemplateRequirement>> requirements;
- private Map<String, ToscaTemplateCapability> capabilities;
+ private String type;
+ private ToscaMetadata metadata;
+ private String description;
+ private Map<String, Object> properties;
+ private List<Map<String, ToscaTemplateRequirement>> requirements;
+ private Map<String, ToscaTemplateCapability> capabilities;
- public String getType() {
- return type;
- }
+ public String getType() {
+ return type;
+ }
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- public Map<String, Object> getProperties() {
- return properties;
- }
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
- public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
- public List<Map<String, ToscaTemplateRequirement>> getRequirements() {
- return requirements;
- }
+ public List<Map<String, ToscaTemplateRequirement>> getRequirements() {
+ return requirements;
+ }
- public void setRequirements(List<Map<String, ToscaTemplateRequirement>> requirements) {
- this.requirements = requirements;
- }
+ public void setRequirements(List<Map<String, ToscaTemplateRequirement>> requirements) {
+ this.requirements = requirements;
+ }
- public Map<String, ToscaTemplateCapability> getCapabilities() {
- return capabilities;
- }
+ public Map<String, ToscaTemplateCapability> getCapabilities() {
+ return capabilities;
+ }
- public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) {
- this.capabilities = capabilities;
- }
+ public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) {
+ this.capabilities = capabilities;
+ }
- public ToscaMetadata getMetadata() {
- return metadata;
- }
+ public ToscaMetadata getMetadata() {
+ return metadata;
+ }
- public void setMetadata(ToscaMetadata metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(ToscaMetadata metadata) {
+ this.metadata = metadata;
+ }
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java
index df9070f49c..4f56cc3bef 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java
@@ -24,64 +24,64 @@ import java.util.List;
import java.util.Map;
public class ToscaNodeType {
- public ToscaNodeType() {
- }
+ public ToscaNodeType() {
+ }
- private ToscaMetadata metadata;
- private String derived_from;
- private String description;
+ private ToscaMetadata metadata;
+ private String derived_from;
+ private String description;
- private Map<String, ToscaProperty> properties;
- private Map<String, ToscaCapability> capabilities;
+ private Map<String, ToscaProperty> properties;
+ private Map<String, ToscaCapability> capabilities;
- private List<Map<String, ToscaRequirement>> requirements;
+ private List<Map<String, ToscaRequirement>> requirements;
- public Map<String, ToscaProperty> getProperties() {
- return properties;
- }
+ public Map<String, ToscaProperty> getProperties() {
+ return properties;
+ }
- public void setProperties(Map<String, ToscaProperty> properties) {
- this.properties = properties;
- }
+ public void setProperties(Map<String, ToscaProperty> properties) {
+ this.properties = properties;
+ }
- public Map<String, ToscaCapability> getCapabilities() {
- return capabilities;
- }
+ public Map<String, ToscaCapability> getCapabilities() {
+ return capabilities;
+ }
- public void setCapabilities(Map<String, ToscaCapability> capabilities) {
- this.capabilities = capabilities;
- }
+ public void setCapabilities(Map<String, ToscaCapability> capabilities) {
+ this.capabilities = capabilities;
+ }
- public List<Map<String, ToscaRequirement>> getRequirements() {
- return requirements;
- }
+ public List<Map<String, ToscaRequirement>> getRequirements() {
+ return requirements;
+ }
- public void setRequirements(List<Map<String, ToscaRequirement>> requirements) {
- this.requirements = requirements;
- }
+ public void setRequirements(List<Map<String, ToscaRequirement>> requirements) {
+ this.requirements = requirements;
+ }
- public String getDerived_from() {
- return derived_from;
- }
+ public String getDerived_from() {
+ return derived_from;
+ }
- public void setDerived_from(String derived_from) {
- this.derived_from = derived_from;
- }
+ public void setDerived_from(String derived_from) {
+ this.derived_from = derived_from;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public ToscaMetadata getMetadata() {
- return metadata;
- }
+ public ToscaMetadata getMetadata() {
+ return metadata;
+ }
- public void setMetadata(ToscaMetadata metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(ToscaMetadata metadata) {
+ this.metadata = metadata;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java
index 8b5c60b1d4..e1ac69fbe0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java
@@ -22,62 +22,62 @@ package org.openecomp.sdc.be.tosca.model;
public class ToscaProperty {
- private String type;
- private Object _defaultp_;
- private String description;
- private Boolean required;
- private EntrySchema entry_schema;
- private String status;
-
- public EntrySchema getEntry_schema() {
- return entry_schema;
- }
-
- public void setEntry_schema(EntrySchema entry_schema) {
- this.entry_schema = entry_schema;
- }
-
- public ToscaProperty() {
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public Object getDefaultp() {
- return _defaultp_;
- }
-
- public void setDefaultp(Object defaultp) {
- this._defaultp_ = defaultp;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Boolean getRequired() {
- return required;
- }
-
- public void setRequired(Boolean required) {
- this.required = required;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
+ private String type;
+ private Object _defaultp_;
+ private String description;
+ private Boolean required;
+ private EntrySchema entry_schema;
+ private String status;
+
+ public EntrySchema getEntry_schema() {
+ return entry_schema;
+ }
+
+ public void setEntry_schema(EntrySchema entry_schema) {
+ this.entry_schema = entry_schema;
+ }
+
+ public ToscaProperty() {
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public Object getDefaultp() {
+ return _defaultp_;
+ }
+
+ public void setDefaultp(Object defaultp) {
+ this._defaultp_ = defaultp;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Boolean getRequired() {
+ return required;
+ }
+
+ public void setRequired(Boolean required) {
+ this.required = required;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java
index 21fdc9f722..35d5c4e6e1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java
@@ -25,21 +25,21 @@ import java.util.Map;
public class ToscaRequirement extends ToscaTemplateRequirement {
- private List<Object> occurrences;
+ private List<Object> occurrences;
- public ToscaRequirement() {
- }
+ public ToscaRequirement() {
+ }
- public List<Object> getOccurrences() {
- return occurrences;
- }
+ public List<Object> getOccurrences() {
+ return occurrences;
+ }
- public void setOccurrences(List<Object> occurrences) {
- this.occurrences = occurrences;
- }
+ public void setOccurrences(List<Object> occurrences) {
+ this.occurrences = occurrences;
+ }
- public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException {
- return super.toMap();
- }
+ public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException {
+ return super.toMap();
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java
index e80d52167c..387238206c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java
@@ -20,71 +20,71 @@
package org.openecomp.sdc.be.tosca.model;
-import java.util.List;
-import java.util.Map;
-
import org.apache.commons.lang3.tuple.Triple;
import org.openecomp.sdc.be.model.Component;
+import java.util.List;
+import java.util.Map;
+
public class ToscaTemplate {
- private String tosca_definitions_version;
- private ToscaMetadata metadata;
- private List<Map<String, Map<String, String>>> imports;
- private Map<String, ToscaNodeType> node_types;
- private ToscaTopolgyTemplate topology_template;
+ private String tosca_definitions_version;
+ private ToscaMetadata metadata;
+ private List<Map<String, Map<String, String>>> imports;
+ private Map<String, ToscaNodeType> node_types;
+ private ToscaTopolgyTemplate topology_template;
- private List<Triple<String, String, Component>> dependencies;
+ private List<Triple<String, String, Component>> dependencies;
- public ToscaTemplate(String tosca_definitions_version) {
- this.tosca_definitions_version = tosca_definitions_version;
- }
+ public ToscaTemplate(String tosca_definitions_version) {
+ this.tosca_definitions_version = tosca_definitions_version;
+ }
- public Map<String, ToscaNodeType> getNode_types() {
- return node_types;
- }
+ public Map<String, ToscaNodeType> getNode_types() {
+ return node_types;
+ }
- public void setNode_types(Map<String, ToscaNodeType> node_types) {
- this.node_types = node_types;
- }
+ public void setNode_types(Map<String, ToscaNodeType> node_types) {
+ this.node_types = node_types;
+ }
- public List<Map<String, Map<String, String>>> getImports() {
- return imports;
- }
+ public List<Map<String, Map<String, String>>> getImports() {
+ return imports;
+ }
- public void setImports(List<Map<String, Map<String, String>>> imports) {
- this.imports = imports;
- }
+ public void setImports(List<Map<String, Map<String, String>>> imports) {
+ this.imports = imports;
+ }
- public String getTosca_definitions_version() {
- return tosca_definitions_version;
- }
+ 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 void setTosca_definitions_version(String tosca_definitions_version) {
+ this.tosca_definitions_version = tosca_definitions_version;
+ }
- public ToscaMetadata getMetadata() {
- return metadata;
- }
+ public ToscaMetadata getMetadata() {
+ return metadata;
+ }
- public void setMetadata(ToscaMetadata metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(ToscaMetadata metadata) {
+ this.metadata = metadata;
+ }
- public ToscaTopolgyTemplate getTopology_template() {
- return topology_template;
- }
+ public ToscaTopolgyTemplate getTopology_template() {
+ return topology_template;
+ }
- public void setTopology_template(ToscaTopolgyTemplate topology_template) {
- this.topology_template = topology_template;
- }
+ public void setTopology_template(ToscaTopolgyTemplate topology_template) {
+ this.topology_template = topology_template;
+ }
- public List<Triple<String, String, Component>> getDependencies() {
- return dependencies;
- }
+ public List<Triple<String, String, Component>> getDependencies() {
+ return dependencies;
+ }
- public void setDependencies(List<Triple<String, String, Component>> dependencies) {
- this.dependencies = dependencies;
- }
+ public void setDependencies(List<Triple<String, String, Component>> dependencies) {
+ this.dependencies = dependencies;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java
index 9adb9edfe1..68341079c1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java
@@ -24,23 +24,23 @@ import java.util.List;
import java.util.Map;
public class ToscaTemplateCapability {
- private List<String> valid_source_types;
- private Map<String, Object> properties;
+ private List<String> valid_source_types;
+ private Map<String, Object> properties;
- public List<String> getValid_source_types() {
- return valid_source_types;
- }
+ public List<String> getValid_source_types() {
+ return valid_source_types;
+ }
- public void setValid_source_types(List<String> valid_source_types) {
- this.valid_source_types = valid_source_types;
- }
+ public void setValid_source_types(List<String> valid_source_types) {
+ this.valid_source_types = valid_source_types;
+ }
- public Map<String, Object> getProperties() {
- return properties;
- }
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
- public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java
index 71bae81f9c..7a77c4f47c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java
@@ -25,44 +25,44 @@ import java.util.HashMap;
import java.util.Map;
public class ToscaTemplateRequirement {
- private String capability;
- private String node;
- private String relationship;
+ private String capability;
+ private String node;
+ private String relationship;
- public ToscaTemplateRequirement() {
- }
+ public ToscaTemplateRequirement() {
+ }
- public String getCapability() {
- return capability;
- }
+ public String getCapability() {
+ return capability;
+ }
- public void setCapability(String capability) {
- this.capability = capability;
- }
+ public void setCapability(String capability) {
+ this.capability = capability;
+ }
- public String getNode() {
- return node;
- }
+ public String getNode() {
+ return node;
+ }
- public void setNode(String node) {
- this.node = node;
- }
+ public void setNode(String node) {
+ this.node = node;
+ }
- public String getRelationship() {
- return relationship;
- }
+ public String getRelationship() {
+ return relationship;
+ }
- public void setRelationship(String relationship) {
- this.relationship = relationship;
- }
+ public void setRelationship(String relationship) {
+ this.relationship = relationship;
+ }
- public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException {
- Map<String, Object> map = new HashMap<>();
- Field[] fields = this.getClass().getDeclaredFields();
- for (Field field : fields) {
- field.setAccessible(true);
- map.put(field.getName(), field.get(this));
- }
- return map;
- }
+ public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException {
+ Map<String, Object> map = new HashMap<>();
+ Field[] fields = this.getClass().getDeclaredFields();
+ for (Field field : fields) {
+ field.setAccessible(true);
+ map.put(field.getName(), field.get(this));
+ }
+ return map;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
index df285c6ad9..8ef32cb06f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
@@ -24,44 +24,44 @@ import java.util.HashMap;
import java.util.Map;
public class ToscaTopolgyTemplate {
- private Map<String, ToscaProperty> inputs;
- private Map<String, ToscaNodeTemplate> node_templates;
- private Map<String, ToscaGroupTemplate> groups;
- private SubstitutionMapping substitution_mappings;
+ private Map<String, ToscaProperty> inputs;
+ private Map<String, ToscaNodeTemplate> node_templates;
+ private Map<String, ToscaGroupTemplate> groups;
+ private SubstitutionMapping substitution_mappings;
- public Map<String, ToscaNodeTemplate> getNode_templates() {
- return node_templates;
- }
+ public Map<String, ToscaNodeTemplate> getNode_templates() {
+ return node_templates;
+ }
- public void setNode_templates(Map<String, ToscaNodeTemplate> node_templates) {
- this.node_templates = node_templates;
- }
+ public void setNode_templates(Map<String, ToscaNodeTemplate> node_templates) {
+ this.node_templates = node_templates;
+ }
- public Map<String, ToscaGroupTemplate> getGroups() {
- return groups;
- }
+ public Map<String, ToscaGroupTemplate> getGroups() {
+ return groups;
+ }
- public void addGroups(Map<String, ToscaGroupTemplate> groups) {
- if ( this.groups == null ){
- this.groups = new HashMap<>();
- }
- this.groups.putAll(groups);
- }
+ public void addGroups(Map<String, ToscaGroupTemplate> groups) {
+ if ( this.groups == null ){
+ this.groups = new HashMap<>();
+ }
+ this.groups.putAll(groups);
+ }
- public SubstitutionMapping getSubstitution_mappings() {
- return substitution_mappings;
- }
+ public SubstitutionMapping getSubstitution_mappings() {
+ return substitution_mappings;
+ }
- public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) {
- this.substitution_mappings = substitution_mapping;
- }
+ public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) {
+ this.substitution_mappings = substitution_mapping;
+ }
- public Map<String, ToscaProperty> getInputs() {
- return inputs;
- }
+ public Map<String, ToscaProperty> getInputs() {
+ return inputs;
+ }
- public void setInputs(Map<String, ToscaProperty> inputs) {
- this.inputs = inputs;
- }
+ public void setInputs(Map<String, ToscaProperty> inputs) {
+ this.inputs = inputs;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
index 26ce118a1a..198e233fde 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
@@ -22,54 +22,54 @@ package org.openecomp.sdc.be.tosca.model;
public class VfModuleToscaMetadata implements IToscaMetadata {
- private String vfModuleModelName;
- private String vfModuleModelInvariantUUID;
- private String vfModuleModelUUID;
- private String vfModuleModelVersion;
- private String vfModuleModelCustomizationUUID;
+ private String vfModuleModelName;
+ private String vfModuleModelInvariantUUID;
+ private String vfModuleModelUUID;
+ private String vfModuleModelVersion;
+ private String vfModuleModelCustomizationUUID;
- @Override
- public void setName(String name) {
- vfModuleModelName = name;
- }
+ @Override
+ public void setName(String name) {
+ vfModuleModelName = name;
+ }
- @Override
- public void setInvariantUUID(String invariantUUID) {
- vfModuleModelInvariantUUID = invariantUUID;
- }
+ @Override
+ public void setInvariantUUID(String invariantUUID) {
+ vfModuleModelInvariantUUID = invariantUUID;
+ }
- @Override
- public void setUUID(String uUID) {
- vfModuleModelUUID = uUID;
- }
+ @Override
+ public void setUUID(String uUID) {
+ vfModuleModelUUID = uUID;
+ }
- @Override
- public void setVersion(String version) {
- vfModuleModelVersion = version;
- }
+ @Override
+ public void setVersion(String version) {
+ vfModuleModelVersion = version;
+ }
- public String getVfModuleModelName() {
- return vfModuleModelName;
- }
+ public String getVfModuleModelName() {
+ return vfModuleModelName;
+ }
- public String getVfModuleModelInvariantUUID() {
- return vfModuleModelInvariantUUID;
- }
+ public String getVfModuleModelInvariantUUID() {
+ return vfModuleModelInvariantUUID;
+ }
- public String getVfModuleModelUUID() {
- return vfModuleModelUUID;
- }
+ public String getVfModuleModelUUID() {
+ return vfModuleModelUUID;
+ }
- public String getVfModuleModelVersion() {
- return vfModuleModelVersion;
- }
+ public String getVfModuleModelVersion() {
+ return vfModuleModelVersion;
+ }
- public String getVfModuleModelCustomizationUUID() {
- return vfModuleModelCustomizationUUID;
- }
+ public String getVfModuleModelCustomizationUUID() {
+ return vfModuleModelCustomizationUUID;
+ }
- public void setCustomizationUUID(String customizationUUID) {
- this.vfModuleModelCustomizationUUID = customizationUUID;
- }
+ public void setCustomizationUUID(String customizationUUID) {
+ this.vfModuleModelCustomizationUUID = customizationUUID;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java
new file mode 100644
index 0000000000..c4905d005e
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java
@@ -0,0 +1,124 @@
+package org.openecomp.sdc.be.tosca.utils;
+
+import fj.data.Either;
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor;
+import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
+import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
+
+import java.util.*;
+
+/**
+ * @author KATYR
+ * @since November 19, 2017
+ */
+
+public class ForwardingPathToscaUtil {
+ public static final String FORWARDS_TO_TOSCA_NAME =
+ "org.openecomp.relationships.ForwardsTo";
+ public static final String PROTOCOL = "protocol";
+ public static final String PORTS_RANGE = "target_range";
+ public static final String FORWARDER = "forwarder";
+
+ public static void addForwardingPaths(Service service, Map<String, ToscaNodeTemplate>
+ nodeTemplates, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
+ for (String forwardingPathName : service.getForwardingPaths().keySet()) {
+ ToscaNodeTemplate forwardingPathNodeTemplate =
+ new ToscaNodeTemplate();
+ final ForwardingPathDataDefinition path =
+ service.getForwardingPaths().get(forwardingPathName);
+ forwardingPathNodeTemplate.setType(path.getToscaResourceName());
+
+ if (Objects.nonNull(path.getDescription())) {
+ forwardingPathNodeTemplate.setDescription(path
+ .getDescription());
+ }
+ Map<String, Object> props = new HashMap<>();
+ if (Objects.nonNull(path.getDestinationPortNumber())) {
+ props.put(PORTS_RANGE, Collections.singletonList(path.getDestinationPortNumber()));
+ }
+ if (Objects.nonNull(path.getProtocol())) {
+ props.put(PROTOCOL, path.getProtocol());
+ }
+ if (MapUtils.isNotEmpty(props)) {
+ forwardingPathNodeTemplate.setProperties(props);
+ }
+
+ final List<ForwardingPathElementDataDefinition> pathElements =
+ path.getPathElements()
+ .getListToscaDataDefinition();
+ forwardingPathNodeTemplate.setRequirements(convertPathElementsToRequirements(pathElements,
+ service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade));
+
+ nodeTemplates.put(path.getName(), forwardingPathNodeTemplate);
+ }
+
+ }
+
+ private static List<Map<String, ToscaTemplateRequirement>> convertPathElementsToRequirements(
+ List<ForwardingPathElementDataDefinition> pathElements, Service service, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents,ToscaOperationFacade toscaOperationFacade) {
+ List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
+ for (int i = 0; i <= pathElements.size() -1 ; i++) {
+ final ForwardingPathElementDataDefinition element = pathElements.get(i);
+ toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getFromNode(), element.getFromCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element.getFromNode())));
+ if ( i == pathElements.size() -1) {
+ toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getToNode(), element.getToCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element
+ .getToNode())));
+ }
+ }
+ return toscaRequirements;
+
+ }
+
+ private static String fetchNodeName(Service service, String nodeId) {
+ if (service.getComponentInstanceById(nodeId).isPresent()) {
+ return service.getComponentInstanceById(nodeId).get().getName();
+ } else {
+ return "";
+ }
+ }
+
+
+ private static Map<String, ToscaTemplateRequirement> handleSingleReq(
+ String fromCP, String fromNode) {
+ Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
+ ToscaTemplateRequirement firstReq = new ToscaTemplateRequirement();
+ firstReq.setRelationship(FORWARDS_TO_TOSCA_NAME); //todo
+ firstReq.setCapability(fromCP);
+ firstReq.setNode(fromNode);
+ toscaReqMap.put(FORWARDER, firstReq);
+
+ return toscaReqMap;
+ }
+
+ /**
+ * @todo handle errors.
+ */
+ private static String fetchCPName(Service service, String nodeID, String cpName, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
+ Optional<ComponentInstance> componentInstance = service.getComponentInstanceById(nodeID);
+ ComponentInstance componentInstanceVal = componentInstance.get();
+ String name = componentInstanceVal.getNormalizedName();
+ Component component = originComponents.get(componentInstanceVal.getComponentUid());
+ if(componentInstanceVal.getIsProxy()){
+ component = originComponents.get(componentInstanceVal.getSourceModelUid());
+ if (component == null) {
+ component = toscaOperationFacade.getToscaFullElement(componentInstanceVal.getSourceModelUid()).left().value();
+ }
+
+ }
+ CapabilityDefinition capability = componentInstanceVal.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream())
+ .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(cpName)).findAny().get();
+ List<String> path = capability.getPath();
+ List<String> reducedPath = new ArrayList<>(path);
+ reducedPath.remove(reducedPath.size() - 1);
+ Either<String, Boolean> stringBooleanEither = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, component, reducedPath, capability.getName());
+ return name + "." + stringBooleanEither.left().value();
+ }
+}
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 6bec3fa938..ee454d72f3 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
@@ -20,15 +20,13 @@
package org.openecomp.sdc.be.user;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.List;
/**
*
@@ -36,17 +34,17 @@ import fj.data.Either;
*
*/
public interface IUserBusinessLogic {
- public Either<User, ActionStatus> getUser(String userId, boolean inTransaction);
+ public Either<User, ActionStatus> getUser(String userId, boolean inTransaction);
- public Either<User, ResponseFormat> createUser(User modifier, User newUser);
+ public Either<User, ResponseFormat> createUser(User modifier, User newUser);
- public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole);
+ public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole);
- public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context);
+ public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context);
- public Either<List<User>, ResponseFormat> getUsersList(String userId, List<String> roles, String rolesStr);
+ public Either<List<User>, ResponseFormat> getUsersList(String userId, List<String> roles, String rolesStr);
- public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive);
+ public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive);
- public Either<User, ResponseFormat> authorize(User authUser);
+ public Either<User, ResponseFormat> authorize(User authUser);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java
index ab58ea7bf0..9397f6d93b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java
@@ -25,5 +25,5 @@ package org.openecomp.sdc.be.user;
* which may result in ecompRole id change
*/
public enum Role {
- ADMIN, TESTER, DESIGNER, GOVERNOR, OPS, PRODUCT_MANAGER, PRODUCT_STRATEGIST
+ ADMIN, TESTER, DESIGNER, GOVERNOR, OPS, PRODUCT_MANAGER, PRODUCT_STRATEGIST
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java
index ffc5e4f947..f5b33beb7e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java
@@ -22,6 +22,6 @@ package org.openecomp.sdc.be.user;
public enum UserAdminAction {
- ADD_USER, UPDATE_USER, DELET_USER
+ ADD_USER, UPDATE_USER, DELET_USER
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
index 796b3a78c0..589fdd8de4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
@@ -25,44 +25,44 @@ import java.util.regex.Pattern;
public class UserAdminValidator {
- private Pattern emailPat;
- private Pattern userIdPat;
- private Matcher matcher;
+ private Pattern emailPat;
+ private Pattern userIdPat;
+ private Matcher matcher;
- private static UserAdminValidator userAdminValidator = null;
+ private static UserAdminValidator userAdminValidator = null;
- public static synchronized UserAdminValidator getInstance() {
- if (userAdminValidator == null) {
- userAdminValidator = new UserAdminValidator();
- }
- return userAdminValidator;
- }
+ public static synchronized UserAdminValidator getInstance() {
+ if (userAdminValidator == null) {
+ userAdminValidator = new UserAdminValidator();
+ }
+ return userAdminValidator;
+ }
- private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
+ private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
- private static final String USER_ID_PATTERN = "\\w{1,25}";
+ private static final String USER_ID_PATTERN = "\\w{1,25}";
- private UserAdminValidator() {
- emailPat = Pattern.compile(EMAIL_PATTERN);
- userIdPat = Pattern.compile(USER_ID_PATTERN);
- }
+ private UserAdminValidator() {
+ emailPat = Pattern.compile(EMAIL_PATTERN);
+ userIdPat = Pattern.compile(USER_ID_PATTERN);
+ }
- public boolean validateEmail(final String hex) {
- matcher = emailPat.matcher(hex);
- return matcher.matches();
- }
+ public boolean validateEmail(final String hex) {
+ matcher = emailPat.matcher(hex);
+ return matcher.matches();
+ }
- public boolean validateUserId(String userId) {
- matcher = userIdPat.matcher(userId);
- return matcher.matches();
- }
+ public boolean validateUserId(String userId) {
+ matcher = userIdPat.matcher(userId);
+ return matcher.matches();
+ }
- public boolean validateRole(String role) {
- for (Role r : Role.values()) {
- if (r.name().equals(role)) {
- return true;
- }
- }
- return false;
- }
+ public boolean validateRole(String role) {
+ for (Role r : Role.values()) {
+ if (r.name().equals(role)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
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 90318a6259..324019a5e8 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
@@ -20,14 +20,7 @@
package org.openecomp.sdc.be.user;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Resource;
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -49,590 +42,592 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import javax.servlet.ServletContext;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Component("userBusinessLogic")
public class UserBusinessLogic implements IUserBusinessLogic {
- private static Logger log = LoggerFactory.getLogger(UserBusinessLogic.class.getName());
- private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance();
-
- @Resource
- private IUserAdminOperation userAdminOperation;
- @Resource
- private ComponentsUtils componentsUtils;
- @Autowired
- private TitanGenericDao titanDao;
-
- @Override
- public Either<User, ActionStatus> getUser(String userId, boolean inTransaction) {
- return userAdminOperation.getUserData(userId, inTransaction);
- }
-
- @Override
- public Either<User, ResponseFormat> createUser(User modifier, User newUser) {
-
- ResponseFormat responseFormat;
- String modifierUserId = modifier.getUserId();
-
- if (modifierUserId == null) {
- modifier.setUserId("UNKNOWN");
- log.debug("createUser method - user header is missing");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
-
- modifier = eitherCreator.left().value();
- if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("createUser method - user is not admin = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
-
- // verify user not exist
- User userFromDb = new User();
- // boolean isUserAlreadyExist = false;
- Either<User, ActionStatus> eitherUserInDB = getUser(newUser.getUserId(), false);
- if (eitherUserInDB.isRight()) {
- ActionStatus status = eitherUserInDB.right().value();
- if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) {
- responseFormat = componentsUtils.getResponseFormat(eitherUserInDB.right().value(), newUser.getUserId());
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
- } else {// User exist in DB
- userFromDb = eitherUserInDB.left().value();
- // isUserAlreadyExist = true;
- if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) {
- responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId());
- log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId());
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
- }
-
- newUser.setStatus(UserStatusEnum.ACTIVE);
-
- // validate Email
- if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) {
- log.debug("createUser method - user has invalid email = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail());
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
-
- // validate Role
- if (newUser.getRole() == null || newUser.getRole().length() == 0) {
- newUser.setRole(Role.DESIGNER.name());
- } else {
- if (!userAdminValidator.validateRole(newUser.getRole())) {
- log.debug("createUser method - user has invalid role = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole());
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
- }
-
- // handle last login if user is import
- if (newUser.getLastLoginTime() == null) {
- newUser.setLastLoginTime(0L);
- }
-
- Either<User, StorageOperationStatus> addOrUpdateUserReq;
-
- if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user
- // exist
- // with
- // inactive
- // state
- // -
- // update
- // user
- // data
- newUser.setLastLoginTime(0L);
- addOrUpdateUserReq = userAdminOperation.updateUserData(newUser);
-
- } else { // user not exist - create new user
-
- if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) {
- log.debug("createUser method - user has invalid userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId());
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.right(responseFormat);
- }
- addOrUpdateUserReq = userAdminOperation.saveUserData(newUser);
- }
-
- if (addOrUpdateUserReq.isRight() || addOrUpdateUserReq.left().value() == null) {
- log.debug("createUser method - failed to create user");
- Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addOrUpdateUserReq.right().value())));
- }
- log.debug("createUser method - user created");
- User createdUser = addOrUpdateUserReq.left().value();
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER);
- return Either.left(createdUser);
- }
-
- @Override
- public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole) {
-
- ResponseFormat responseFormat;
- String modifierUserId = modifier.getUserId();
-
- if (modifierUserId == null) {
- modifier.setUserId("UNKNOWN");
- log.debug("updateUserRole method - user header is missing");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.right(responseFormat);
- }
-
- modifier = eitherCreator.left().value();
- if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.right(responseFormat);
- }
-
- if (modifier.getUserId().equals(userIdToUpdate)) {
- log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> userToUpdateReq = getUser(userIdToUpdate, false);
- if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) {
- log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.right(responseFormat);
- }
-
- if (!userAdminValidator.validateRole(userRole)) {
- log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.right(responseFormat);
- }
-
- User newUser = new User();
- newUser.setRole(userRole);
- newUser.setUserId(userIdToUpdate);
- User userToUpdate = userToUpdateReq.left().value();
- // if(!userRole.equals(UserRoleEnum.ADMIN.getName())){ //this is in
- // comment until admin will be able to do do check-in/check-out from the
- // UI
-
- Either<List<Edge>, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate);
- if (userPendingTasksReq.isRight()) {
- log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value())));
- }
-
- List<Edge> userPendingTasks = userPendingTasksReq.left().value();
- 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);
- return Either.right(responseFormat);
- }
- // }
- Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(newUser);
-
- if (updateUserReq.isRight() || updateUserReq.left().value() == null) {
- log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value())));
- }
-
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- User updatedUser = updateUserReq.left().value();
- handleAuditing(modifier, userToUpdate, updatedUser, responseFormat, AuditingActionEnum.UPDATE_USER);
- return Either.left(updatedUser);
- }
-
- @Override
- public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context) {
- Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null);
-
- if (response.isRight()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(response.right().value());
- return Either.right(responseFormat);
- }
- return Either.left(response.left().value());
- }
-
- @Override
- public Either<List<User>, ResponseFormat> getUsersList(String modifierAttId, List<String> roles, String rolesStr) {
- ResponseFormat responseFormat;
- User user = new User();
- if (modifierAttId == null) {
- user.setUserId("UNKNOWN");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- handleGetUsersListAuditing(user, responseFormat, rolesStr);
- return Either.right(responseFormat);
- }
- Either<User, ActionStatus> userResult = getUser(modifierAttId, false);
- if (userResult.isRight()) {
- user.setUserId(modifierAttId);
- if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- } else {
- responseFormat = componentsUtils.getResponseFormat(userResult.right().value());
- }
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, "Get users per roles", modifierAttId);
- BeEcompErrorManager.getInstance().logBeUserMissingError("Get users per roles", modifierAttId);
-
- handleGetUsersListAuditing(user, responseFormat, rolesStr);
- return Either.right(responseFormat);
- }
- user = userResult.left().value();
- Either<List<User>, ResponseFormat> getResponse = null;
- List<User> resultList = new ArrayList<>();
- if (roles != null && !roles.isEmpty()) {
- for (String role : roles) {
- if (!userAdminValidator.validateRole(role)) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, role);
- handleGetUsersListAuditing(user, responseFormat, rolesStr);
- return Either.right(responseFormat);
- }
- getResponse = getUsersPerRole(role, user, rolesStr);
- resultList.addAll(getResponse.left().value());
- }
- } else {
- rolesStr = "All";
- getResponse = getUsersPerRole(null, user, rolesStr);
- resultList.addAll(getResponse.left().value());
- }
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleGetUsersListAuditing(user, responseFormat, rolesStr);
- return Either.left(resultList);
- }
-
- private Either<List<User>, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) {
- ResponseFormat responseFormat;
- Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name());
- if (response.isRight()) {
- responseFormat = componentsUtils.getResponseFormat(response.right().value());
- handleGetUsersListAuditing(user, responseFormat, rolesStr);
- return Either.right(responseFormat);
- }
- return Either.left(response.left().value());
- }
-
- private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) {
- componentsUtils.auditGetUsersList(AuditingActionEnum.GET_USERS_LIST, user, details, responseFormat);
- }
-
- private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) {
- componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat);
- }
-
- private void handleUserAccessAuditing(User user, ResponseFormat responseFormat, AuditingActionEnum actionName) {
- componentsUtils.auditUserAccess(actionName, user, responseFormat);
- }
-
- @Override
- public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive) {
-
- ResponseFormat responseFormat;
- String userId = modifier.getUserId();
-
- if (userId == null) {
- modifier.setUserId("UNKNOWN");
- log.debug("deActivateUser method - user header is missing");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> eitherCreator = getUser(userId, false);
- if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
- log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.right(responseFormat);
- }
-
- modifier = eitherCreator.left().value();
-
- if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
- log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.right(responseFormat);
- }
-
- if (modifier.getUserId().equals(userUniuqeIdToDeactive)) {
- log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId());
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> getUserToDeleteResponse = getUser(userUniuqeIdToDeactive, false);
- if (getUserToDeleteResponse.isRight() || getUserToDeleteResponse.left().value() == null) {
- log.debug("deActivateUser method - failed to get user by id {}", userUniuqeIdToDeactive);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.right(componentsUtils.getResponseFormat(getUserToDeleteResponse.right().value(), userUniuqeIdToDeactive));
- }
-
- User userToDeactivate = getUserToDeleteResponse.left().value();
- if (userToDeactivate.getStatus().equals(UserStatusEnum.INACTIVE)) {
- log.debug("deActivateUser method - User already inactive", userUniuqeIdToDeactive);
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive);
- handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.right(responseFormat);
- }
-
- Either<List<Edge>, 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())));
- }
-
- List<Edge> userPendingTasks = userPendingTasksReq.left().value();
- if (userPendingTasks.size() > 0) {
- log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive);
-
- 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);
- return Either.right(responseFormat);
- }
-
- Either<User, StorageOperationStatus> deactivateUserReq = userAdminOperation.deActivateUser(userToDeactivate);
- if (deactivateUserReq.isRight()) {
- log.debug("deActivateUser method - failed to deactivate user", userUniuqeIdToDeactive);
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deactivateUserReq.right().value())));
- }
- User deactivateUser = deactivateUserReq.left().value();
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleAuditing(modifier, userToDeactivate, null, responseFormat, AuditingActionEnum.DELETE_USER);
- return Either.left(deactivateUser);
- }
-
- @Override
- public Either<User, ResponseFormat> authorize(User authUser) {
-
- ResponseFormat responseFormat;
-
- String userId = authUser.getUserId();
-
- if (userId == null) {
- authUser.setUserId("UNKNOWN");
- log.debug("deActivateUser method - user header is missing");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> eitherCreator = getUser(userId, false);
- if (eitherCreator.isRight()) {
- if (eitherCreator.right().value() == ActionStatus.USER_NOT_FOUND || eitherCreator.right().value() == ActionStatus.USER_INACTIVE) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
- handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.right(responseFormat);
- } else {
- return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), authUser));
- }
- } else {
- if (eitherCreator.left().value() == null) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- return Either.right(responseFormat);
- }
- }
-
- User user = eitherCreator.left().value();
-
- String firstName = authUser.getFirstName();
- if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) {
- user.setFirstName(firstName);
- }
-
- String lastName = authUser.getLastName();
- if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) {
- user.setLastName(lastName);
- }
-
- String email = authUser.getEmail();
- if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) {
- user.setEmail(email);
- }
-
- // last login time stamp handle
- user.setLastLoginTime();
-
- Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user);
-
- if (updateUserReq.isRight()) {
- responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user);
- handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user));
- }
-
- User updatedUser = updateUserReq.left().value();
-
- Long lastLoginTime = user.getLastLoginTime();
- if (lastLoginTime != null) {
- updatedUser.setLastLoginTime(lastLoginTime);
- } else {
- updatedUser.setLastLoginTime(new Long(0));
- }
-
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS);
- ASDCKpiApi.countUsersAuthorizations();
- return Either.left(updatedUser);
- }
-
- /*
- * The method updates user credentials only, the role is neglected The role updated through updateRole method
- */
- public Either<User, ResponseFormat> updateUserCredentials(User updatedUserCred) {
-
- ResponseFormat responseFormat;
-
- String userId = updatedUserCred.getUserId();
-
- if (userId == null) {
- updatedUserCred.setUserId("UNKNOWN");
- log.debug("updateUserCredentials method - user header is missing");
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
- handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.right(responseFormat);
- }
-
- Either<User, ActionStatus> eitherCreator = getUser(userId, false);
- if (eitherCreator.isRight()) {
- ActionStatus status = eitherCreator.right().value();
- if (status == ActionStatus.USER_NOT_FOUND || status == ActionStatus.USER_INACTIVE) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
- handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.right(responseFormat);
- } else {
- return Either.right(componentsUtils.getResponseFormatByUser(status, updatedUserCred));
- }
- } else {
- if (eitherCreator.left().value() == null) {
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
- return Either.right(responseFormat);
- }
- }
-
- User user = eitherCreator.left().value();
-
- String firstName = updatedUserCred.getFirstName();
- if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) {
- user.setFirstName(firstName);
- }
-
- String lastName = updatedUserCred.getLastName();
- if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) {
- user.setLastName(lastName);
- }
-
- String email = updatedUserCred.getEmail();
- if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) {
- user.setEmail(email);
- }
-
- if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) {
- if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) {
- user.setLastLoginTime(updatedUserCred.getLastLoginTime());
- }
- } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) {
- user.setLastLoginTime(updatedUserCred.getLastLoginTime());
- }
-
- Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user);
-
- if (updateUserReq.isRight()) {
- responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user);
- handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user));
- }
-
- User updatedUser = updateUserReq.left().value();
-
- responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
- handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS);
- return Either.left(updatedUser);
- }
-
- private Either<List<Edge>, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) {
-
- Either<List<Edge>, StorageOperationStatus> result = null;
-
- try {
- UserRoleEnum userRole = UserRoleEnum.valueOf(user.getRole());
- Map<String, Object> properties = new HashMap<String, Object>();
- switch (userRole) {
- case DESIGNER:
- case PRODUCT_STRATEGIST:
- case PRODUCT_MANAGER:
- properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
- return userAdminOperation.getUserPendingTasksList(user, properties);
- case TESTER:
- properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
- 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.getUserPendingTasksList(user, properties);
- default:
- return Either.left(new ArrayList<>());
- }
- } finally {
- // commit will be perform outside!!!
- if (result == null || result.isRight()) {
- log.debug("getUserPendingTasksList failed to perform fetching");
- titanDao.rollback();
- } else {
- titanDao.commit();
- }
- }
- }
-
- private String getUserPendingTaskStatusByRole(UserRoleEnum role) {
-
- switch (role) {
- case DESIGNER:
- case PRODUCT_STRATEGIST:
- case PRODUCT_MANAGER:
- return "checked-out";
-
- case TESTER:
- return "in-certification";
- case ADMIN:
- return "in-certification/checked-out";
- default:
- return "";
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(UserBusinessLogic.class);
+ private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance();
+
+ @Resource
+ private IUserAdminOperation userAdminOperation;
+ @Resource
+ private ComponentsUtils componentsUtils;
+ @Autowired
+ private TitanGenericDao titanDao;
+
+ @Override
+ public Either<User, ActionStatus> getUser(String userId, boolean inTransaction) {
+ return userAdminOperation.getUserData(userId, inTransaction);
+ }
+
+ @Override
+ public Either<User, ResponseFormat> createUser(User modifier, User newUser) {
+
+ ResponseFormat responseFormat;
+ String modifierUserId = modifier.getUserId();
+
+ if (modifierUserId == null) {
+ modifier.setUserId("UNKNOWN");
+ log.debug("createUser method - user header is missing");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ log.debug("createUser method - user is not listed. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+
+ modifier = eitherCreator.left().value();
+ if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
+ log.debug("createUser method - user is not admin = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+
+ // verify user not exist
+ User userFromDb = new User();
+ Either<User, ActionStatus> eitherUserInDB = getUser(newUser.getUserId(), false);
+ if (eitherUserInDB.isRight()) {
+ ActionStatus status = eitherUserInDB.right().value();
+ if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) {
+ responseFormat = componentsUtils.getResponseFormat(eitherUserInDB.right().value(), newUser.getUserId());
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+ } else {// User exist in DB
+ userFromDb = eitherUserInDB.left().value();
+ if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) {
+ responseFormat = componentsUtils.getResponseFormatByUserId(ActionStatus.USER_ALREADY_EXIST, newUser.getUserId());
+ log.debug("createUser method - user with id {} already exist with id: {}", modifier.getUserId(), userFromDb.getUserId());
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+ }
+
+ newUser.setStatus(UserStatusEnum.ACTIVE);
+
+ // validate Email
+ if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) {
+ log.debug("createUser method - user has invalid email = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail());
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+
+ // validate Role
+ if (newUser.getRole() == null || newUser.getRole().length() == 0) {
+ newUser.setRole(Role.DESIGNER.name());
+ } else {
+ if (!userAdminValidator.validateRole(newUser.getRole())) {
+ log.debug("createUser method - user has invalid role = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, newUser.getRole());
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+ }
+
+ // handle last login if user is import
+ if (newUser.getLastLoginTime() == null) {
+ newUser.setLastLoginTime(0L);
+ }
+
+ Either<User, StorageOperationStatus> addOrUpdateUserReq;
+
+ if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user
+ // exist
+ // with
+ // inactive
+ // state
+ // -
+ // update
+ // user
+ // data
+ newUser.setLastLoginTime(0L);
+ addOrUpdateUserReq = userAdminOperation.updateUserData(newUser);
+
+ } else { // user not exist - create new user
+
+ if (newUser.getUserId() != null && !userAdminValidator.validateUserId(newUser.getUserId())) {
+ log.debug("createUser method - user has invalid userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_USER_ID, newUser.getUserId());
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.right(responseFormat);
+ }
+ addOrUpdateUserReq = userAdminOperation.saveUserData(newUser);
+ }
+
+ if (addOrUpdateUserReq.isRight() || addOrUpdateUserReq.left().value() == null) {
+ log.debug("createUser method - failed to create user");
+ Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addOrUpdateUserReq.right().value())));
+ }
+ log.debug("createUser method - user created");
+ User createdUser = addOrUpdateUserReq.left().value();
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER);
+ return Either.left(createdUser);
+ }
+
+ @Override
+ public Either<User, ResponseFormat> updateUserRole(User modifier, String userIdToUpdate, String userRole) {
+
+ ResponseFormat responseFormat;
+ String modifierUserId = modifier.getUserId();
+
+ if (modifierUserId == null) {
+ modifier.setUserId("UNKNOWN");
+ log.debug("updateUserRole method - user header is missing");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> eitherCreator = getUser(modifierUserId, false);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ log.debug("updateUserRole method - user is not listed. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.right(responseFormat);
+ }
+
+ modifier = eitherCreator.left().value();
+ if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
+ log.debug("updateUserRole method - user is not admin. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.right(responseFormat);
+ }
+
+ if (modifier.getUserId().equals(userIdToUpdate)) {
+ log.debug("updateUserRole method - admin role can only be updated by other admin. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.UPDATE_USER_ADMIN_CONFLICT);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> userToUpdateReq = getUser(userIdToUpdate, false);
+ if (userToUpdateReq.isRight() || userToUpdateReq.left().value() == null) {
+ log.debug("updateUserRole method - user not found. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userIdToUpdate);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.right(responseFormat);
+ }
+
+ if (!userAdminValidator.validateRole(userRole)) {
+ log.debug("updateUserRole method - user has invalid role = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, userRole);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.right(responseFormat);
+ }
+
+ User newUser = new User();
+ newUser.setRole(userRole);
+ newUser.setUserId(userIdToUpdate);
+ User userToUpdate = userToUpdateReq.left().value();
+ // if(!userRole.equals(UserRoleEnum.ADMIN.getName())){ //this is in
+ // comment until admin will be able to do do check-in/check-out from the
+ // UI
+
+ Either<List<Edge>, StorageOperationStatus> userPendingTasksReq = getPendingUserPendingTasksWithCommit(userToUpdate);
+ if (userPendingTasksReq.isRight()) {
+ log.debug("updateUserRole method - failed to get user pending tasks list userId {}", userIdToUpdate);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(userPendingTasksReq.right().value())));
+ }
+
+ List<Edge> userPendingTasks = userPendingTasksReq.left().value();
+ 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);
+ return Either.right(responseFormat);
+ }
+ // }
+ Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(newUser);
+
+ if (updateUserReq.isRight() || updateUserReq.left().value() == null) {
+ log.debug("updateUser method - failed to update user data. userId = {}", modifier.getUserId());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateUserReq.right().value())));
+ }
+
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ User updatedUser = updateUserReq.left().value();
+ handleAuditing(modifier, userToUpdate, updatedUser, responseFormat, AuditingActionEnum.UPDATE_USER);
+ return Either.left(updatedUser);
+ }
+
+ @Override
+ public Either<List<User>, ResponseFormat> getAllAdminUsers(ServletContext context) {
+ Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null);
+
+ if (response.isRight()) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(response.right().value());
+ return Either.right(responseFormat);
+ }
+ return Either.left(response.left().value());
+ }
+
+ @Override
+ public Either<List<User>, ResponseFormat> getUsersList(String modifierAttId, List<String> roles, String rolesStr) {
+ ResponseFormat responseFormat;
+ User user = new User();
+ if (modifierAttId == null) {
+ user.setUserId("UNKNOWN");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ handleGetUsersListAuditing(user, responseFormat, rolesStr);
+ return Either.right(responseFormat);
+ }
+ Either<User, ActionStatus> userResult = getUser(modifierAttId, false);
+ if (userResult.isRight()) {
+ user.setUserId(modifierAttId);
+ if (userResult.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ } else {
+ responseFormat = componentsUtils.getResponseFormat(userResult.right().value());
+ }
+ BeEcompErrorManager.getInstance().logBeUserMissingError("Get users per roles", modifierAttId);
+
+ handleGetUsersListAuditing(user, responseFormat, rolesStr);
+ return Either.right(responseFormat);
+ }
+ user = userResult.left().value();
+ Either<List<User>, ResponseFormat> getResponse = null;
+ List<User> resultList = new ArrayList<>();
+ if (roles != null && !roles.isEmpty()) {
+ for (String role : roles) {
+ if (!userAdminValidator.validateRole(role)) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_ROLE, role);
+ handleGetUsersListAuditing(user, responseFormat, rolesStr);
+ return Either.right(responseFormat);
+ }
+ getResponse = getUsersPerRole(role, user, rolesStr);
+ resultList.addAll(getResponse.left().value());
+ }
+ } else {
+ rolesStr = "All";
+ getResponse = getUsersPerRole(null, user, rolesStr);
+ resultList.addAll(getResponse.left().value());
+ }
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleGetUsersListAuditing(user, responseFormat, rolesStr);
+ return Either.left(resultList);
+ }
+
+ private Either<List<User>, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) {
+ ResponseFormat responseFormat;
+ Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name());
+ if (response.isRight()) {
+ responseFormat = componentsUtils.getResponseFormat(response.right().value());
+ handleGetUsersListAuditing(user, responseFormat, rolesStr);
+ return Either.right(responseFormat);
+ }
+ return Either.left(response.left().value());
+ }
+
+ private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) {
+ componentsUtils.auditGetUsersList(AuditingActionEnum.GET_USERS_LIST, user, details, responseFormat);
+ }
+
+ private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) {
+ componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat);
+ }
+
+ private void handleUserAccessAuditing(User user, ResponseFormat responseFormat, AuditingActionEnum actionName) {
+ componentsUtils.auditUserAccess(actionName, user, responseFormat);
+ }
+
+ @Override
+ public Either<User, ResponseFormat> deActivateUser(User modifier, String userUniuqeIdToDeactive) {
+
+ ResponseFormat responseFormat;
+ String userId = modifier.getUserId();
+
+ if (userId == null) {
+ modifier.setUserId("UNKNOWN");
+ log.debug("deActivateUser method - user header is missing");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> eitherCreator = getUser(userId, false);
+ if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
+ log.debug("deActivateUser method - user is not listed. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.right(responseFormat);
+ }
+
+ modifier = eitherCreator.left().value();
+
+ if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
+ log.debug("deActivateUser method - user is not admin. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.right(responseFormat);
+ }
+
+ if (modifier.getUserId().equals(userUniuqeIdToDeactive)) {
+ log.debug("deActivateUser deActivateUser - admin can only be deactivate by other admin. userId = {}", modifier.getUserId());
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.DELETE_USER_ADMIN_CONFLICT);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> getUserToDeleteResponse = getUser(userUniuqeIdToDeactive, false);
+ if (getUserToDeleteResponse.isRight() || getUserToDeleteResponse.left().value() == null) {
+ log.debug("deActivateUser method - failed to get user by id {}", userUniuqeIdToDeactive);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.right(componentsUtils.getResponseFormat(getUserToDeleteResponse.right().value(), userUniuqeIdToDeactive));
+ }
+
+ User userToDeactivate = getUserToDeleteResponse.left().value();
+ if (userToDeactivate.getStatus().equals(UserStatusEnum.INACTIVE)) {
+ log.debug("deActivateUser method - User already inactive", userUniuqeIdToDeactive);
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, userUniuqeIdToDeactive);
+ handleAuditing(modifier, null, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.right(responseFormat);
+ }
+
+ Either<List<Edge>, 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())));
+ }
+
+ List<Edge> userPendingTasks = userPendingTasksReq.left().value();
+ if (userPendingTasks.size() > 0) {
+ log.debug("deActivateUser method - User canot be deleted, user have pending projects", userUniuqeIdToDeactive);
+
+ 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);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, StorageOperationStatus> deactivateUserReq = userAdminOperation.deActivateUser(userToDeactivate);
+ if (deactivateUserReq.isRight()) {
+ log.debug("deActivateUser method - failed to deactivate user", userUniuqeIdToDeactive);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deactivateUserReq.right().value())));
+ }
+ User deactivateUser = deactivateUserReq.left().value();
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleAuditing(modifier, userToDeactivate, null, responseFormat, AuditingActionEnum.DELETE_USER);
+ return Either.left(deactivateUser);
+ }
+
+ @Override
+ public Either<User, ResponseFormat> authorize(User authUser) {
+
+ ResponseFormat responseFormat;
+
+ String userId = authUser.getUserId();
+
+ if (userId == null) {
+ authUser.setUserId("UNKNOWN");
+ log.debug("deActivateUser method - user header is missing");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> eitherCreator = getUser(userId, false);
+ if (eitherCreator.isRight()) {
+ if (eitherCreator.right().value() == ActionStatus.USER_NOT_FOUND || eitherCreator.right().value() == ActionStatus.USER_INACTIVE) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
+ handleUserAccessAuditing(authUser, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.right(responseFormat);
+ } else {
+ return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), authUser));
+ }
+ } else {
+ if (eitherCreator.left().value() == null) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(responseFormat);
+ }
+ }
+
+ User user = eitherCreator.left().value();
+
+ String firstName = authUser.getFirstName();
+ if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) {
+ user.setFirstName(firstName);
+ }
+
+ String lastName = authUser.getLastName();
+ if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) {
+ user.setLastName(lastName);
+ }
+
+ String email = authUser.getEmail();
+ if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) {
+ user.setEmail(email);
+ }
+
+ // last login time stamp handle
+ user.setLastLoginTime();
+
+ Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user);
+
+ if (updateUserReq.isRight()) {
+ responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user);
+ handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user));
+ }
+
+ User updatedUser = updateUserReq.left().value();
+
+ Long lastLoginTime = user.getLastLoginTime();
+ if (lastLoginTime != null) {
+ updatedUser.setLastLoginTime(lastLoginTime);
+ } else {
+ updatedUser.setLastLoginTime(new Long(0));
+ }
+
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS);
+ ASDCKpiApi.countUsersAuthorizations();
+ return Either.left(updatedUser);
+ }
+
+ /*
+ * The method updates user credentials only, the role is neglected The role updated through updateRole method
+ */
+ public Either<User, ResponseFormat> updateUserCredentials(User updatedUserCred) {
+
+ ResponseFormat responseFormat;
+
+ String userId = updatedUserCred.getUserId();
+
+ if (userId == null) {
+ updatedUserCred.setUserId("UNKNOWN");
+ log.debug("updateUserCredentials method - user header is missing");
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
+ handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.right(responseFormat);
+ }
+
+ Either<User, ActionStatus> eitherCreator = getUser(userId, false);
+ if (eitherCreator.isRight()) {
+ ActionStatus status = eitherCreator.right().value();
+ if (status == ActionStatus.USER_NOT_FOUND || status == ActionStatus.USER_INACTIVE) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
+ handleUserAccessAuditing(updatedUserCred, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.right(responseFormat);
+ } else {
+ return Either.right(componentsUtils.getResponseFormatByUser(status, updatedUserCred));
+ }
+ } else {
+ if (eitherCreator.left().value() == null) {
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+ return Either.right(responseFormat);
+ }
+ }
+
+ User user = eitherCreator.left().value();
+
+ String firstName = updatedUserCred.getFirstName();
+ if (firstName != null && firstName.isEmpty() == false && !firstName.equals(user.getFirstName())) {
+ user.setFirstName(firstName);
+ }
+
+ String lastName = updatedUserCred.getLastName();
+ if (lastName != null && lastName.isEmpty() == false && !lastName.equals(user.getLastName())) {
+ user.setLastName(lastName);
+ }
+
+ String email = updatedUserCred.getEmail();
+ if (email != null && false == email.isEmpty() && !email.equals(user.getEmail())) {
+ user.setEmail(email);
+ }
+
+ if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) {
+ if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) {
+ user.setLastLoginTime(updatedUserCred.getLastLoginTime());
+ }
+ } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) {
+ user.setLastLoginTime(updatedUserCred.getLastLoginTime());
+ }
+
+ Either<User, StorageOperationStatus> updateUserReq = userAdminOperation.updateUserData(user);
+
+ if (updateUserReq.isRight()) {
+ responseFormat = componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user);
+ handleUserAccessAuditing(user, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.right(componentsUtils.getResponseFormatByUser(eitherCreator.right().value(), user));
+ }
+
+ User updatedUser = updateUserReq.left().value();
+
+ responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+ handleUserAccessAuditing(updatedUser, responseFormat, AuditingActionEnum.USER_ACCESS);
+ return Either.left(updatedUser);
+ }
+
+ private Either<List<Edge>, StorageOperationStatus> getPendingUserPendingTasksWithCommit(User user) {
+
+ Either<List<Edge>, StorageOperationStatus> result = null;
+
+ try {
+ UserRoleEnum userRole = UserRoleEnum.valueOf(user.getRole());
+ Map<String, Object> properties = new HashMap<String, Object>();
+ switch (userRole) {
+ case DESIGNER:
+ case PRODUCT_STRATEGIST:
+ case PRODUCT_MANAGER:
+ properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ return userAdminOperation.getUserPendingTasksList(user, properties);
+ case TESTER:
+ properties.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ 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.getUserPendingTasksList(user, properties);
+ default:
+ return Either.left(new ArrayList<>());
+ }
+ } finally {
+ // commit will be perform outside!!!
+ if (result == null || result.isRight()) {
+ log.debug("getUserPendingTasksList failed to perform fetching");
+ titanDao.rollback();
+ } else {
+ titanDao.commit();
+ }
+ }
+ }
+
+ private String getUserPendingTaskStatusByRole(UserRoleEnum role) {
+
+ switch (role) {
+ case DESIGNER:
+ case PRODUCT_STRATEGIST:
+ case PRODUCT_MANAGER:
+ return "checked-out";
+
+ case TESTER:
+ return "in-certification";
+ case ADMIN:
+ return "in-certification/checked-out";
+ default:
+ return "";
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java
new file mode 100644
index 0000000000..451989ba36
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java
@@ -0,0 +1,7 @@
+package org.openecomp.sdc.be.view;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+
+@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
+public abstract class Mixin {
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java
new file mode 100644
index 0000000000..e3d6ca6e10
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java
@@ -0,0 +1,60 @@
+package org.openecomp.sdc.be.view;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * A class that is then responsible for converting a message payload with a dedicated mixin from an instance of a specific Java type into a json representation.
+ */
+@Provider
+@Produces(MediaType.APPLICATION_JSON)
+public class MixinModelWriter implements MessageBodyWriter<Object> {
+
+ @Override
+ public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+ return hasResponseViewAndMixinTargetAnnotations(annotations) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
+ }
+
+ @Override
+ public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+ return -1;
+ }
+
+ @Override
+ public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ List<MixinSourceTarget> mixinSourceTargets = getMixinSourceTarget(annotations);
+ mixinSourceTargets.forEach(mixinSourceTarget -> objectMapper.addMixIn(mixinSourceTarget.getTarget(), mixinSourceTarget.getMixinSource()));
+ objectMapper.writeValue(entityStream, object);
+ }
+
+ private List<MixinSourceTarget> getMixinSourceTarget(Annotation[] annotations) {
+ return Stream.of(annotations)
+ .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
+ .map(annotation -> (ResponseView) annotation)
+ .flatMap(responseView -> Stream.of(responseView.mixin()))
+ .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target()))
+ .collect(Collectors.toList());
+ }
+
+ private boolean hasResponseViewAndMixinTargetAnnotations(Annotation[] annotations) {
+ return Stream.of(annotations)
+ .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
+ .map(annotation -> (ResponseView) annotation)
+ .flatMap(responseView -> Stream.of(responseView.mixin()))
+ .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class)));
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java
new file mode 100644
index 0000000000..c04c4f88cb
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.view;
+
+/**
+ * A pojo which holds a mapping between a mixin source and its corresponding target class
+ */
+public class MixinSourceTarget {
+
+ private Class<?> mixinSource;
+ private Class<?> target;
+
+ MixinSourceTarget(Class<?> mixinSource, Class<?> target) {
+ this.mixinSource = mixinSource;
+ this.target = target;
+ }
+
+ public Class<?> getMixinSource() {
+ return mixinSource;
+ }
+
+ public Class<?> getTarget() {
+ return target;
+ }
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java
new file mode 100644
index 0000000000..cb44250331
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.be.view;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+@Inherited
+public @interface MixinTarget {
+ /**
+ *
+ * @return the class which is the target for the mixin. (i.e the class to be serialized into a json response)
+ */
+ Class<?> target();
+
+}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java b/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java
new file mode 100644
index 0000000000..16733ed019
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java
@@ -0,0 +1,17 @@
+package org.openecomp.sdc.be.view;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.METHOD)
+public @interface ResponseView {
+ /**
+ * The mixins that will be used when converting the resource's response into a specific view of that response.
+ * A number of mixins can be declared, each of which corresponds to a different object.
+ */
+ public Class<? extends Mixin>[] mixin();
+}
+
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java
index e70b33a938..d7a0f4b8d1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ICommitHandler.java
@@ -23,5 +23,5 @@ package org.openecomp.sdc.common.transaction.api;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
public interface ICommitHandler extends IDBType {
- DBActionCodeEnum doCommit();
+ DBActionCodeEnum doCommit();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java
index a36e5fe1b5..20763d04f8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBAction.java
@@ -21,5 +21,5 @@
package org.openecomp.sdc.common.transaction.api;
public interface IDBAction {
- <T> T doAction();
+ <T> T doAction();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java
index 4c19e41609..3aa2e9a9d7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/IDBType.java
@@ -23,5 +23,5 @@ package org.openecomp.sdc.common.transaction.api;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
public interface IDBType {
- DBTypeEnum getDBType();
+ DBTypeEnum getDBType();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java
index 5a10e9029c..ea041359fd 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/ITransactionSdnc.java
@@ -20,21 +20,20 @@
package org.openecomp.sdc.common.transaction.api;
+import fj.data.Either;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum;
-import fj.data.Either;
-
public interface ITransactionSdnc {
- TransactionCodeEnum finishTransaction();
+ TransactionCodeEnum finishTransaction();
- Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData);
+ Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData);
- <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction);
+ <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction);
- <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction);
+ <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java
index 97a8083e88..a44073971e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/RollbackHandler.java
@@ -20,102 +20,105 @@
package org.openecomp.sdc.common.transaction.api;
-import java.util.Stack;
-
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages;
import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.Stack;
+
public abstract class RollbackHandler implements IDBType {
- private static Logger log = LoggerFactory.getLogger(RollbackHandler.class.getName());
- private Stack<IDBAction> dbActionRollbacks;
-
- private Integer transactionId;
- private String userId, actionType;
-
- protected RollbackHandler(Integer transactionId, String userId, String actionType) {
- if (isRollbackForPersistenceData()) {
- dbActionRollbacks = new Stack<>();
- }
- this.transactionId = transactionId;
- this.userId = userId;
- this.actionType = actionType;
- }
-
- public MethodActivationStatusEnum addRollbackAction(IDBAction rollbackAction) {
- MethodActivationStatusEnum result = MethodActivationStatusEnum.SUCCESS;
- if (isRollbackForPersistenceData()) {
- dbActionRollbacks.push(rollbackAction);
- } else {
- result = MethodActivationStatusEnum.NOT_ALLOWED;
- }
- return result;
- }
-
- public DBActionCodeEnum doRollback() {
- DBActionCodeEnum result;
-
- try {
- if (isRollbackForPersistenceData()) {
- result = doPersistenceDataRollback();
- } else {
- log.debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
- log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
- result = doNonPersistenceDataRollback();
- }
- if (result != DBActionCodeEnum.SUCCESS) {
- log.error(LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType);
- log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType);
- }
-
- } catch (Exception e) {
- result = DBActionCodeEnum.FAIL_GENERAL;
- log.error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType);
- log.debug(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType, e);
- log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType);
- }
-
- return result;
- }
-
- private <T> DBActionCodeEnum doPersistenceDataRollback() {
- DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
- while (!dbActionRollbacks.empty()) {
- log.debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
- log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
- IDBAction rollbackAction = dbActionRollbacks.pop();
- T rollbackResult = rollbackAction.doAction();
- if (!isRollbackResultValid(rollbackResult)) {
- result = DBActionCodeEnum.FAIL_GENERAL;
- }
- }
- return result;
- }
-
- /**
- * Override for specific logic
- *
- * @param <T>
- */
- public <T> boolean isRollbackResultValid(T rollbackResult) {
- return true;
- }
-
- /**
- * Override for specific logic
- */
- public DBActionCodeEnum doNonPersistenceDataRollback() {
- return DBActionCodeEnum.SUCCESS;
- }
-
- protected abstract boolean isRollbackForPersistenceData();
-
- /**
- * Only Used for Unit Tests !
- */
- public static void setLog(Logger log) {
- RollbackHandler.log = log;
- }
+
+ // TODO test using slf4j-test and make this final
+ private static Logger log = LoggerFactory.getLogger(RollbackHandler.class);
+ private Stack<IDBAction> dbActionRollbacks;
+
+ private Integer transactionId;
+ private String userId, actionType;
+
+ protected RollbackHandler(Integer transactionId, String userId, String actionType) {
+ if (isRollbackForPersistenceData()) {
+ dbActionRollbacks = new Stack<>();
+ }
+ this.transactionId = transactionId;
+ this.userId = userId;
+ this.actionType = actionType;
+ }
+
+ public MethodActivationStatusEnum addRollbackAction(IDBAction rollbackAction) {
+ MethodActivationStatusEnum result = MethodActivationStatusEnum.SUCCESS;
+ if (isRollbackForPersistenceData()) {
+ dbActionRollbacks.push(rollbackAction);
+ } else {
+ result = MethodActivationStatusEnum.NOT_ALLOWED;
+ }
+ return result;
+ }
+
+ public DBActionCodeEnum doRollback() {
+ DBActionCodeEnum result;
+
+ try {
+ if (isRollbackForPersistenceData()) {
+ result = doPersistenceDataRollback();
+ } else {
+ log.debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
+ log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
+ result = doNonPersistenceDataRollback();
+ }
+ if (result != DBActionCodeEnum.SUCCESS) {
+ log.error(LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType);
+ log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB, transactionId, getDBType().name(), userId, actionType);
+ }
+
+ } catch (Exception e) {
+ result = DBActionCodeEnum.FAIL_GENERAL;
+ log.error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType);
+ log.debug(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType, e);
+ log.error(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId, getDBType().name(), e.getMessage(), userId, actionType);
+ }
+
+ return result;
+ }
+
+ private <T> DBActionCodeEnum doPersistenceDataRollback() {
+ DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
+ while (!dbActionRollbacks.empty()) {
+ log.debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
+ log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, getDBType().name(), transactionId, userId, actionType);
+ IDBAction rollbackAction = dbActionRollbacks.pop();
+ T rollbackResult = rollbackAction.doAction();
+ if (!isRollbackResultValid(rollbackResult)) {
+ result = DBActionCodeEnum.FAIL_GENERAL;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Override for specific logic
+ *
+ * @param <T>
+ */
+ public <T> boolean isRollbackResultValid(T rollbackResult) {
+ return true;
+ }
+
+ /**
+ * Override for specific logic
+ */
+ public DBActionCodeEnum doNonPersistenceDataRollback() {
+ return DBActionCodeEnum.SUCCESS;
+ }
+
+ protected abstract boolean isRollbackForPersistenceData();
+
+ /**
+ * Only Used for Unit Tests !
+ */
+ // TODO test using slf4j-test and remove this
+ public static void setLog(Logger log) {
+ RollbackHandler.log = log;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java
index e90b9618d4..fc7c90509f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/api/TransactionUtils.java
@@ -25,61 +25,61 @@ import org.slf4j.MarkerFactory;
public final class TransactionUtils {
- private TransactionUtils() {
-
- }
-
- public enum DBTypeEnum {
- ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT
- }
-
- public enum TransactionCodeEnum {
- ROLLBACK_SUCCESS, ROLLBACK_FAILED, SUCCESS, COMMIT_FAILED, MULTIPLE_LAST_ACTION, INTERNAL_ERROR, UNALLOWED_METHOD_USAGE, PREPARE_ROLLBACK_FAILED, TRANSACTION_CLOSED
- }
-
- public enum TransactionStatusEnum {
- OPEN, CLOSED, FAILED_ROLLBACK
- }
-
- public enum DBActionCodeEnum {
- SUCCESS, FAIL_GENERAL, FAIL_MULTIPLE_LAST_ACTION
- }
-
- public enum ESActionTypeEnum {
- ADD_ARTIFACT, UPDATE_ARTIFACT, REMOVE_ARTIFACT
- }
-
- public enum ActionTypeEnum {
- ADD_ARTIFACT, REMOVE_ARTIFACT, UPDATE_ARTIFACT, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE
- }
-
- public static final int MAX_SIZE_TRANSACTION_LIST = 1000;
-
- public static final int TRANSACTION_ID_RESET_LIMIT = MAX_SIZE_TRANSACTION_LIST * 10;
-
- public static final String TRANSACTION_MARKER_STR = "TRANSACTION_MARKER";
-
- public static final String DUMMY_USER = "udummy";
-
- public static final Marker TRANSACTION_MARKER = MarkerFactory.getMarker(TRANSACTION_MARKER_STR);
-
- public static class LogMessages {
- public static final String PRE_INVOKE_ACTION = "About to add Action to SdncTransaction ID:{} for DB:{}, user:{}, action:{}";
- public static final String INVOKE_ACTION = "invoking Action in SdncTransactionID:{}, on DB:{}, user:{}, action:{}";
- public static final String COMMIT_ACTION_ALL_DB = "Starting Commit for SdncTransactionID:{} for all DBs, user:{}, action:{}";
- public static final String COMMIT_ACTION_SPECIFIC_DB = "Starting Commit for SdncTransactionID:{} on DB:{}, user:{}, action:{}";
- public static final String COMMIT_ON_CLOSED_TRANSACTION = "Commit failed for SdncTransactionID:{} Transaction is in status:{}, user:{}, action:{}";
- public static final String ACTION_ON_CLOSED_TRANSACTION = "Action failed for SdncTransactionID:{} Transaction is already closed, user:{}, action:{}";
- public static final String DOUBLE_FINISH_FLAG_ACTION = "Transaction with SdncTransactionID:{} on DB:{} was called multiple times with last action flag, user:{}, action:{}";
- public static final String DB_ACTION_FAILED_WITH_EXCEPTION = "Action on DB:{} has failed for SdncTransactionID:{}, message:{}, user:{}, action:{}";
- public static final String ROLLBACK_SUCCEEDED_GENERAL = "Transaction rollback succeeded for SdncTransactionID:{}, user:{}, action:{}";
- public static final String ROLLBACK_FAILED_GENERAL = "Transaction rollback failed for SdncTransactionID:{}, user:{}, action:{}";
- public static final String ROLLBACK_FAILED_ON_DB = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, user:{}, action:{}";
- public static final String ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, exception message:{}, user:{}, action:{}";
- public static final String ROLLBACK_PERSISTENT_ACTION = "About To Rollback Action on DB{} for TransactionID:{} ... user:{}, action:{}";
- public static final String ROLLBACK_NON_PERSISTENT_ACTION = "About To Rollback Actions on DB{} for TransactionID:{} ... user:{}, action:{}";
- public static final String CREATE_ROLLBACK_HANDLER = "creating new Rollback Handler For DB:{} in SdncTransaction ID:{}, user:{}, action:{}";
- public static final String FAILED_CREATE_ROLLBACK = "failed to create new Rollback action For DB:{} with SdncTransactionID:{}, user:{}, action:{}";
- }
+ private TransactionUtils() {
+
+ }
+
+ public enum DBTypeEnum {
+ ELASTIC_SEARCH, TITAN, MYSTERY, SWIFT
+ }
+
+ public enum TransactionCodeEnum {
+ ROLLBACK_SUCCESS, ROLLBACK_FAILED, SUCCESS, COMMIT_FAILED, MULTIPLE_LAST_ACTION, INTERNAL_ERROR, UNALLOWED_METHOD_USAGE, PREPARE_ROLLBACK_FAILED, TRANSACTION_CLOSED
+ }
+
+ public enum TransactionStatusEnum {
+ OPEN, CLOSED, FAILED_ROLLBACK
+ }
+
+ public enum DBActionCodeEnum {
+ SUCCESS, FAIL_GENERAL, FAIL_MULTIPLE_LAST_ACTION
+ }
+
+ public enum ESActionTypeEnum {
+ ADD_ARTIFACT, UPDATE_ARTIFACT, REMOVE_ARTIFACT
+ }
+
+ public enum ActionTypeEnum {
+ ADD_ARTIFACT, REMOVE_ARTIFACT, UPDATE_ARTIFACT, CREATE_RESOURCE, UPDATE_RESOURCE, DELETE_RESOURCE
+ }
+
+ public static final int MAX_SIZE_TRANSACTION_LIST = 1000;
+
+ public static final int TRANSACTION_ID_RESET_LIMIT = MAX_SIZE_TRANSACTION_LIST * 10;
+
+ public static final String TRANSACTION_MARKER_STR = "TRANSACTION_MARKER";
+
+ public static final String DUMMY_USER = "udummy";
+
+ public static final Marker TRANSACTION_MARKER = MarkerFactory.getMarker(TRANSACTION_MARKER_STR);
+
+ public static class LogMessages {
+ public static final String PRE_INVOKE_ACTION = "About to add Action to SdncTransaction ID:{} for DB:{}, user:{}, action:{}";
+ public static final String INVOKE_ACTION = "invoking Action in SdncTransactionID:{}, on DB:{}, user:{}, action:{}";
+ public static final String COMMIT_ACTION_ALL_DB = "Starting Commit for SdncTransactionID:{} for all DBs, user:{}, action:{}";
+ public static final String COMMIT_ACTION_SPECIFIC_DB = "Starting Commit for SdncTransactionID:{} on DB:{}, user:{}, action:{}";
+ public static final String COMMIT_ON_CLOSED_TRANSACTION = "Commit failed for SdncTransactionID:{} Transaction is in status:{}, user:{}, action:{}";
+ public static final String ACTION_ON_CLOSED_TRANSACTION = "Action failed for SdncTransactionID:{} Transaction is already closed, user:{}, action:{}";
+ public static final String DOUBLE_FINISH_FLAG_ACTION = "Transaction with SdncTransactionID:{} on DB:{} was called multiple times with last action flag, user:{}, action:{}";
+ public static final String DB_ACTION_FAILED_WITH_EXCEPTION = "Action on DB:{} has failed for SdncTransactionID:{}, message:{}, user:{}, action:{}";
+ public static final String ROLLBACK_SUCCEEDED_GENERAL = "Transaction rollback succeeded for SdncTransactionID:{}, user:{}, action:{}";
+ public static final String ROLLBACK_FAILED_GENERAL = "Transaction rollback failed for SdncTransactionID:{}, user:{}, action:{}";
+ public static final String ROLLBACK_FAILED_ON_DB = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, user:{}, action:{}";
+ public static final String ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION = "Transaction rollback failed for SdncTransactionID:{} on DB:{}, exception message:{}, user:{}, action:{}";
+ public static final String ROLLBACK_PERSISTENT_ACTION = "About To Rollback Action on DB{} for TransactionID:{} ... user:{}, action:{}";
+ public static final String ROLLBACK_NON_PERSISTENT_ACTION = "About To Rollback Actions on DB{} for TransactionID:{} ... user:{}, action:{}";
+ public static final String CREATE_ROLLBACK_HANDLER = "creating new Rollback Handler For DB:{} in SdncTransaction ID:{}, user:{}, action:{}";
+ public static final String FAILED_CREATE_ROLLBACK = "failed to create new Rollback action For DB:{} with SdncTransactionID:{}, user:{}, action:{}";
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java
index 33a8d1163b..0d628cf264 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESAction.java
@@ -23,36 +23,42 @@ package org.openecomp.sdc.common.transaction.impl;
import org.openecomp.sdc.be.dao.impl.ESCatalogDAO;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.exception.ResourceDAOException;
+import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.common.transaction.api.IDBAction;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ESAction implements IDBAction {
- private ESCatalogDAO esCatalogDao;
- private ESArtifactData artifactData;
- private ESActionTypeEnum esActionType;
-
- public ESAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) {
- this.esCatalogDao = esCatalogDao;
- this.artifactData = artifactData;
- this.esActionType = esActiontype;
- }
-
- @Override
- public DBActionCodeEnum doAction() {
- DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
- try {
- if (esActionType == ESActionTypeEnum.ADD_ARTIFACT || esActionType == ESActionTypeEnum.UPDATE_ARTIFACT) {
- esCatalogDao.writeArtifact(artifactData);
- } else if (esActionType == ESActionTypeEnum.REMOVE_ARTIFACT) {
- esCatalogDao.deleteArtifact(artifactData.getId());
- }
-
- } catch (ResourceDAOException daoException) {
- result = DBActionCodeEnum.FAIL_GENERAL;
- }
- return result;
- }
+ private static final Logger log = LoggerFactory.getLogger(CsarUtils.class);
+
+ private ESCatalogDAO esCatalogDao;
+ private ESArtifactData artifactData;
+ private ESActionTypeEnum esActionType;
+
+ public ESAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) {
+ this.esCatalogDao = esCatalogDao;
+ this.artifactData = artifactData;
+ this.esActionType = esActiontype;
+ }
+
+ @Override
+ public DBActionCodeEnum doAction() {
+ DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
+ try {
+ if (esActionType == ESActionTypeEnum.ADD_ARTIFACT || esActionType == ESActionTypeEnum.UPDATE_ARTIFACT) {
+ esCatalogDao.writeArtifact(artifactData);
+ } else if (esActionType == ESActionTypeEnum.REMOVE_ARTIFACT) {
+ esCatalogDao.deleteArtifact(artifactData.getId());
+ }
+
+ } catch (ResourceDAOException daoException) {
+ result = DBActionCodeEnum.FAIL_GENERAL;
+ log.error("#doAction - {}, es action failed with error : ", result, daoException);
+ }
+ return result;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java
index b9fb0d31b7..e17819fcb0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/ESRollbackHandler.java
@@ -20,73 +20,79 @@
package org.openecomp.sdc.common.transaction.impl;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
import org.openecomp.sdc.be.dao.impl.ESCatalogDAO;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.be.resources.exception.ResourceDAOException;
+import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.common.transaction.api.RollbackHandler;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum;
import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
-
-import fj.data.Either;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ESRollbackHandler extends RollbackHandler {
- public ESRollbackHandler(Integer transactionId, String userId, String actionType) {
- super(transactionId, userId, actionType);
- }
-
- public DBTypeEnum getDBType() {
- return DBTypeEnum.ELASTIC_SEARCH;
- }
-
- protected boolean isRollbackForPersistenceData() {
- return true;
- }
-
- public boolean isRollbackResultValid(DBActionCodeEnum rollbackResult) {
- return rollbackResult == DBActionCodeEnum.SUCCESS;
- }
-
- public Either<ESAction, MethodActivationStatusEnum> buildEsRollbackAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) {
- Either<ESAction, MethodActivationStatusEnum> result;
-
- try {
- ESAction esRollbackAction = null;
- Either<ESArtifactData, ResourceUploadStatus> either = esCatalogDao.getArtifact(artifactData.getId());
-
- switch (esActiontype) {
- case ADD_ARTIFACT:
-
- if (either.isRight() && either.right().value() == ResourceUploadStatus.NOT_EXIST) {
- esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.REMOVE_ARTIFACT);
- }
- break;
- case REMOVE_ARTIFACT:
- if (either.isLeft()) {
- esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.ADD_ARTIFACT);
- }
- break;
- case UPDATE_ARTIFACT:
-
- if (either.isLeft()) {
- ESArtifactData originalArtifactData = either.left().value();
- esRollbackAction = new ESAction(esCatalogDao, originalArtifactData, ESActionTypeEnum.UPDATE_ARTIFACT);
- }
- break;
-
- }
- if (esRollbackAction != null) {
- result = Either.left(esRollbackAction);
- } else {
- result = Either.right(MethodActivationStatusEnum.FAILED);
- }
- } catch (Exception e) {
- result = Either.right(MethodActivationStatusEnum.FAILED);
- }
-
- return result;
- }
+ private static final Logger log = LoggerFactory.getLogger(CsarUtils.class);
+
+ public ESRollbackHandler(Integer transactionId, String userId, String actionType) {
+ super(transactionId, userId, actionType);
+ }
+
+ public DBTypeEnum getDBType() {
+ return DBTypeEnum.ELASTIC_SEARCH;
+ }
+
+ protected boolean isRollbackForPersistenceData() {
+ return true;
+ }
+
+ public boolean isRollbackResultValid(DBActionCodeEnum rollbackResult) {
+ return rollbackResult == DBActionCodeEnum.SUCCESS;
+ }
+
+ public Either<ESAction, MethodActivationStatusEnum> buildEsRollbackAction(ESCatalogDAO esCatalogDao, ESArtifactData artifactData, ESActionTypeEnum esActiontype) {
+ Either<ESAction, MethodActivationStatusEnum> result;
+
+ try {
+ ESAction esRollbackAction = null;
+ Either<ESArtifactData, ResourceUploadStatus> either = esCatalogDao.getArtifact(artifactData.getId());
+
+ switch (esActiontype) {
+ case ADD_ARTIFACT:
+
+ if (either.isRight() && either.right().value() == ResourceUploadStatus.NOT_EXIST) {
+ esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.REMOVE_ARTIFACT);
+ }
+ break;
+ case REMOVE_ARTIFACT:
+ if (either.isLeft()) {
+ esRollbackAction = new ESAction(esCatalogDao, artifactData, ESActionTypeEnum.ADD_ARTIFACT);
+ }
+ break;
+ case UPDATE_ARTIFACT:
+
+ if (either.isLeft()) {
+ ESArtifactData originalArtifactData = either.left().value();
+ esRollbackAction = new ESAction(esCatalogDao, originalArtifactData, ESActionTypeEnum.UPDATE_ARTIFACT);
+ }
+ break;
+
+ }
+ if (esRollbackAction != null) {
+ result = Either.left(esRollbackAction);
+ } else {
+ result = Either.right(MethodActivationStatusEnum.FAILED);
+ }
+ } catch (Exception e) {
+ result = Either.right(MethodActivationStatusEnum.FAILED);
+ log.error("#buildEsRollbackAction - {}, es rollback failed with error: ", result, e);
+ }
+
+ return result;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java
index 0d2ec387cf..c86241ebf1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanCommitHandler.java
@@ -28,25 +28,25 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
public class TitanCommitHandler implements ICommitHandler {
- private TitanGenericDao titanGenericDao;
-
- public TitanCommitHandler(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
- }
-
- @Override
- public DBActionCodeEnum doCommit() {
- DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
- TitanOperationStatus titanStatus = titanGenericDao.commit();
- if (titanStatus != TitanOperationStatus.OK) {
- result = DBActionCodeEnum.FAIL_GENERAL;
- }
- return result;
- }
-
- @Override
- public DBTypeEnum getDBType() {
- return DBTypeEnum.TITAN;
- }
+ private TitanGenericDao titanGenericDao;
+
+ public TitanCommitHandler(TitanGenericDao titanGenericDao) {
+ this.titanGenericDao = titanGenericDao;
+ }
+
+ @Override
+ public DBActionCodeEnum doCommit() {
+ DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
+ TitanOperationStatus titanStatus = titanGenericDao.commit();
+ if (titanStatus != TitanOperationStatus.OK) {
+ result = DBActionCodeEnum.FAIL_GENERAL;
+ }
+ return result;
+ }
+
+ @Override
+ public DBTypeEnum getDBType() {
+ return DBTypeEnum.TITAN;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java
index c0c686723c..89d2b9da8e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/impl/TitanRollbackHandler.java
@@ -28,28 +28,28 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
public class TitanRollbackHandler extends RollbackHandler {
- private TitanGenericDao titanGenericDao;
-
- public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) {
- super(transactionId, userId, actionType);
- this.titanGenericDao = titanGenericDao;
- }
-
- public DBTypeEnum getDBType() {
- return DBTypeEnum.TITAN;
- }
-
- protected boolean isRollbackForPersistenceData() {
- return false;
- }
-
- public DBActionCodeEnum doNonPersistenceDataRollback() {
- DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
- TitanOperationStatus titanStatus = titanGenericDao.rollback();
- if (titanStatus != TitanOperationStatus.OK) {
- result = DBActionCodeEnum.FAIL_GENERAL;
- }
- return result;
- }
+ private TitanGenericDao titanGenericDao;
+
+ public TitanRollbackHandler(Integer transactionId, String userId, String actionType, TitanGenericDao titanGenericDao) {
+ super(transactionId, userId, actionType);
+ this.titanGenericDao = titanGenericDao;
+ }
+
+ public DBTypeEnum getDBType() {
+ return DBTypeEnum.TITAN;
+ }
+
+ protected boolean isRollbackForPersistenceData() {
+ return false;
+ }
+
+ public DBActionCodeEnum doNonPersistenceDataRollback() {
+ DBActionCodeEnum result = DBActionCodeEnum.SUCCESS;
+ TitanOperationStatus titanStatus = titanGenericDao.rollback();
+ if (titanStatus != TitanOperationStatus.OK) {
+ result = DBActionCodeEnum.FAIL_GENERAL;
+ }
+ return result;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java
index e802e58f27..f366ae214f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/CommitManager.java
@@ -20,8 +20,6 @@
package org.openecomp.sdc.common.transaction.mngr;
-import java.util.List;
-
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.transaction.api.ICommitHandler;
@@ -31,57 +29,60 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.List;
+
public class CommitManager {
- private List<ICommitHandler> commitHandlers;
- private Integer transactionId;
- private String userId, actionType;
- private static Logger log = LoggerFactory.getLogger(CommitManager.class.getName());
- CommitManager(Integer transactionId, String userId, String actionType, List<ICommitHandler> commitHandlers) {
- this.commitHandlers = commitHandlers;
- this.transactionId = transactionId;
- this.userId = userId;
- this.actionType = actionType;
+ // TODO test using slf4j-test and make this final
+ private static Logger log = LoggerFactory.getLogger(CommitManager.class);
+ private List<ICommitHandler> commitHandlers;
+ private Integer transactionId;
+ private String userId, actionType;
+
+ CommitManager(Integer transactionId, String userId, String actionType, List<ICommitHandler> commitHandlers) {
+ this.commitHandlers = commitHandlers;
+ this.transactionId = transactionId;
+ this.userId = userId;
+ this.actionType = actionType;
- }
+ }
- public DBActionCodeEnum transactionCommit() {
- log.debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, userId, actionType);
- DBActionCodeEnum commitResult = DBActionCodeEnum.SUCCESS;
- ICommitHandler lastHandler = null;
- try {
- for (ICommitHandler handler : commitHandlers) {
- lastHandler = handler;
- log.debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, handler.getDBType().name(), userId, actionType);
- DBActionCodeEnum commitCode = handler.doCommit();
- if (commitCode == DBActionCodeEnum.FAIL_GENERAL) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit on DB " + handler.getDBType().name());
- BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit on DB " + handler.getDBType().name());
- log.debug("Commit failed for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name());
- commitResult = DBActionCodeEnum.FAIL_GENERAL;
- break;
- }
- log.debug("Commit succeeded for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name());
- }
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit - on DB " + getDBName(lastHandler));
- BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit - on DB " + getDBName(lastHandler));
- log.debug("Commit failed for SdncTransactionID:{} on DB:{}, Exception message:{}", transactionId, getDBName(lastHandler), e.getMessage(), e);
- log.info(TransactionUtils.TRANSACTION_MARKER, "Commit failed for SdncTransactionID:{} on DB:{}", transactionId, getDBName(lastHandler));
- commitResult = DBActionCodeEnum.FAIL_GENERAL;
- }
- return commitResult;
- }
+ public DBActionCodeEnum transactionCommit() {
+ log.debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, userId, actionType);
+ DBActionCodeEnum commitResult = DBActionCodeEnum.SUCCESS;
+ ICommitHandler lastHandler = null;
+ try {
+ for (ICommitHandler handler : commitHandlers) {
+ lastHandler = handler;
+ log.debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, handler.getDBType().name(), userId, actionType);
+ DBActionCodeEnum commitCode = handler.doCommit();
+ if (commitCode == DBActionCodeEnum.FAIL_GENERAL) {
+ BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit on DB " + handler.getDBType().name());
+ log.debug("Commit failed for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name());
+ commitResult = DBActionCodeEnum.FAIL_GENERAL;
+ break;
+ }
+ log.debug("Commit succeeded for SdncTransactionID:{} on DB:{}", transactionId, handler.getDBType().name());
+ }
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit - on DB " + getDBName(lastHandler));
+ log.debug("Commit failed for SdncTransactionID:{} on DB:{}, Exception message:{}", transactionId, getDBName(lastHandler), e.getMessage(), e);
+ log.info(TransactionUtils.TRANSACTION_MARKER, "Commit failed for SdncTransactionID:{} on DB:{}", transactionId, getDBName(lastHandler));
+ commitResult = DBActionCodeEnum.FAIL_GENERAL;
+ }
+ return commitResult;
+ }
- private String getDBName(ICommitHandler lastHandler) {
- String dbName = "Unknown";
- if (lastHandler != null) {
- dbName = lastHandler.getDBType().name();
- }
- return dbName;
- }
+ private String getDBName(ICommitHandler lastHandler) {
+ String dbName = "Unknown";
+ if (lastHandler != null) {
+ dbName = lastHandler.getDBType().name();
+ }
+ return dbName;
+ }
- static void setLog(Logger log) {
- CommitManager.log = log;
- }
+ // TODO test using slf4j-test and remove this
+ static void setLog(Logger log) {
+ CommitManager.log = log;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java
index 7098021d1f..80d548ef42 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java
@@ -31,56 +31,56 @@ import fj.data.HashMap;
import fj.data.List;
public class RollbackManager {
- private final HashMap<DBTypeEnum, RollbackHandler> rollbackHandlersMap;
- private final Integer transactionId;
- private final String userId;
- private final String actionType;
+ private final HashMap<DBTypeEnum, RollbackHandler> rollbackHandlersMap;
+ private final Integer transactionId;
+ private final String userId;
+ private final String actionType;
- RollbackManager(Integer transactionId, String userId, String actionType, Iterable<RollbackHandler> rollbackHandlers) {
- this.transactionId = transactionId;
- this.userId = userId;
- this.actionType = actionType;
- this.rollbackHandlersMap = HashMap.from(List.iterableList(rollbackHandlers).map(i -> P.p(i.getDBType(), i)));
- }
+ RollbackManager(Integer transactionId, String userId, String actionType, Iterable<RollbackHandler> rollbackHandlers) {
+ this.transactionId = transactionId;
+ this.userId = userId;
+ this.actionType = actionType;
+ this.rollbackHandlersMap = HashMap.from(List.iterableList(rollbackHandlers).map(i -> P.p(i.getDBType(), i)));
+ }
- public DBActionCodeEnum transactionRollback() {
- List<DBActionCodeEnum> results = rollbackHandlersMap.values().map(RollbackHandler::doRollback);
- boolean failure = results.exists(r -> r == DBActionCodeEnum.FAIL_GENERAL);
- return failure ? DBActionCodeEnum.FAIL_GENERAL : DBActionCodeEnum.SUCCESS;
- }
+ public DBActionCodeEnum transactionRollback() {
+ List<DBActionCodeEnum> results = rollbackHandlersMap.values().map(RollbackHandler::doRollback);
+ boolean failure = results.exists(r -> r == DBActionCodeEnum.FAIL_GENERAL);
+ return failure ? DBActionCodeEnum.FAIL_GENERAL : DBActionCodeEnum.SUCCESS;
+ }
- protected Either<RollbackHandler, MethodActivationStatusEnum> addRollbackHandler(RollbackHandler rollbackHandler) {
- Either<RollbackHandler, MethodActivationStatusEnum> result;
- if (rollbackHandlersMap.contains(rollbackHandler.getDBType())) {
- result = Either.right(MethodActivationStatusEnum.NOT_ALLOWED);
- } else {
- rollbackHandlersMap.set(rollbackHandler.getDBType(), rollbackHandler);
- result = Either.left(rollbackHandler);
- }
- return result;
+ protected Either<RollbackHandler, MethodActivationStatusEnum> addRollbackHandler(RollbackHandler rollbackHandler) {
+ Either<RollbackHandler, MethodActivationStatusEnum> result;
+ if (rollbackHandlersMap.contains(rollbackHandler.getDBType())) {
+ result = Either.right(MethodActivationStatusEnum.NOT_ALLOWED);
+ } else {
+ rollbackHandlersMap.set(rollbackHandler.getDBType(), rollbackHandler);
+ result = Either.left(rollbackHandler);
+ }
+ return result;
- }
+ }
- protected Either<RollbackHandler, MethodActivationStatusEnum> createRollbackHandler(final DBTypeEnum dbType) {
+ protected Either<RollbackHandler, MethodActivationStatusEnum> createRollbackHandler(final DBTypeEnum dbType) {
- RollbackHandler rollbackHandler = new RollbackHandler(transactionId, userId, actionType) {
+ RollbackHandler rollbackHandler = new RollbackHandler(transactionId, userId, actionType) {
- @Override
- public DBTypeEnum getDBType() {
- return dbType;
- }
+ @Override
+ public DBTypeEnum getDBType() {
+ return dbType;
+ }
- @Override
- protected boolean isRollbackForPersistenceData() {
- return true;
- }
- };
- return addRollbackHandler(rollbackHandler);
- }
+ @Override
+ protected boolean isRollbackForPersistenceData() {
+ return true;
+ }
+ };
+ return addRollbackHandler(rollbackHandler);
+ }
- protected Either<RollbackHandler, MethodActivationStatusEnum> getRollbackHandler(DBTypeEnum dbType) {
- // need to swap here because the uses of Either in SDC appears to be opposite of convention
- // by convention left is failure; in SDC right is failure
- return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap();
- }
+ protected Either<RollbackHandler, MethodActivationStatusEnum> getRollbackHandler(DBTypeEnum dbType) {
+ // need to swap here because the uses of Either in SDC appears to be opposite of convention
+ // by convention left is failure; in SDC right is failure
+ return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap();
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java
index c05431ac7f..f218744b84 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionManager.java
@@ -20,11 +20,8 @@
package org.openecomp.sdc.common.transaction.mngr;
-import java.util.Queue;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.annotation.Resource;
-
+import com.google.common.collect.EvictingQueue;
+import com.google.common.collect.Queues;
import org.openecomp.sdc.be.dao.impl.ESCatalogDAO;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.common.transaction.api.ITransactionSdnc;
@@ -34,70 +31,71 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import com.google.common.collect.EvictingQueue;
-import com.google.common.collect.Queues;
+import javax.annotation.Resource;
+import java.util.Queue;
+import java.util.concurrent.atomic.AtomicInteger;
@Component("transactionManager")
public class TransactionManager {
- private static Logger log = LoggerFactory.getLogger(TransactionManager.class.getName());
-
- private AtomicInteger transactionIDCounter = new AtomicInteger(0);
-
- private Queue<ITransactionSdnc> transactions;
- @Resource
- private ESCatalogDAO esCatalogDao;
- @Resource
- private TitanGenericDao titanGenericDao;
-
- /**
- * userId and actionType parameters are used only for logging purposes.
- */
- public ITransactionSdnc getTransaction(String userId, ActionTypeEnum actionType) {
- if (transactions == null) {
- init();
- }
- log.debug("TransactionManager creating new SdncTransaction");
- ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao);
- transactions.add(tx);
-
- return tx;
-
- }
-
- private Integer generateTransactionID() {
- boolean generatedSuccessfully = false;
- int nextId = 0;
-
- while (!generatedSuccessfully) {
- int prevId = transactionIDCounter.get();
- if (prevId > TransactionUtils.TRANSACTION_ID_RESET_LIMIT) {
- resetTransactionId();
- }
- nextId = prevId + 1;
- generatedSuccessfully = transactionIDCounter.compareAndSet(prevId, nextId);
- }
- return nextId;
- }
-
- private void resetTransactionId() {
-
- boolean resetSuccessfully = false;
- while (!resetSuccessfully) {
- int prevId = transactionIDCounter.get();
- resetSuccessfully = transactionIDCounter.compareAndSet(prevId, 0);
- }
-
- }
-
- private synchronized void init() {
- if (transactions == null) {
- log.info("TransactionManager Initialized");
- EvictingQueue<ITransactionSdnc> queue = EvictingQueue
- .<ITransactionSdnc>create(TransactionUtils.MAX_SIZE_TRANSACTION_LIST);
- // make thread-safe
- transactions = Queues.synchronizedQueue(queue);
- }
- }
+ private static final Logger log = LoggerFactory.getLogger(TransactionManager.class);
+
+ private AtomicInteger transactionIDCounter = new AtomicInteger(0);
+
+ private Queue<ITransactionSdnc> transactions;
+ @Resource
+ private ESCatalogDAO esCatalogDao;
+ @Resource
+ private TitanGenericDao titanGenericDao;
+
+ /**
+ * userId and actionType parameters are used only for logging purposes.
+ */
+ public ITransactionSdnc getTransaction(String userId, ActionTypeEnum actionType) {
+ if (transactions == null) {
+ init();
+ }
+ log.debug("TransactionManager creating new SdncTransaction");
+ ITransactionSdnc tx = new TransactionSdncImpl(generateTransactionID(), userId, actionType, esCatalogDao, titanGenericDao);
+ transactions.add(tx);
+
+ return tx;
+
+ }
+
+ private Integer generateTransactionID() {
+ boolean generatedSuccessfully = false;
+ int nextId = 0;
+
+ while (!generatedSuccessfully) {
+ int prevId = transactionIDCounter.get();
+ if (prevId > TransactionUtils.TRANSACTION_ID_RESET_LIMIT) {
+ resetTransactionId();
+ }
+ nextId = prevId + 1;
+ generatedSuccessfully = transactionIDCounter.compareAndSet(prevId, nextId);
+ }
+ return nextId;
+ }
+
+ private void resetTransactionId() {
+
+ boolean resetSuccessfully = false;
+ while (!resetSuccessfully) {
+ int prevId = transactionIDCounter.get();
+ resetSuccessfully = transactionIDCounter.compareAndSet(prevId, 0);
+ }
+
+ }
+
+ private synchronized void init() {
+ if (transactions == null) {
+ log.info("TransactionManager Initialized");
+ EvictingQueue<ITransactionSdnc> queue = EvictingQueue
+ .<ITransactionSdnc>create(TransactionUtils.MAX_SIZE_TRANSACTION_LIST);
+ // make thread-safe
+ transactions = Queues.synchronizedQueue(queue);
+ }
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java
index 55eff24fa9..bc7b5bde03 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/TransactionSdncImpl.java
@@ -20,26 +20,14 @@
package org.openecomp.sdc.common.transaction.mngr;
-import java.util.ArrayList;
-import java.util.List;
-
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.impl.ESCatalogDAO;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.common.config.EcompErrorName;
-import org.openecomp.sdc.common.transaction.api.ICommitHandler;
-import org.openecomp.sdc.common.transaction.api.IDBAction;
-import org.openecomp.sdc.common.transaction.api.ITransactionSdnc;
-import org.openecomp.sdc.common.transaction.api.RollbackHandler;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.ActionTypeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.ESActionTypeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.LogMessages;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCodeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum;
+import org.openecomp.sdc.common.transaction.api.*;
+import org.openecomp.sdc.common.transaction.api.TransactionUtils.*;
import org.openecomp.sdc.common.transaction.impl.ESAction;
import org.openecomp.sdc.common.transaction.impl.ESRollbackHandler;
import org.openecomp.sdc.common.transaction.impl.TitanCommitHandler;
@@ -48,266 +36,264 @@ import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
public class TransactionSdncImpl implements ITransactionSdnc {
- private boolean lastActionAlreadyCalled;
- private RollbackManager rollbackManager;
- private CommitManager commitManager;
- private ESCatalogDAO esCatalogDao;
- private TitanGenericDao titanGenericDao;
- private Integer transactionId;
- private TransactionStatusEnum status;
- private String userId, actionType;
- private static Logger log = LoggerFactory.getLogger(TransactionSdncImpl.class.getName());
-
- TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) {
- this.esCatalogDao = esCatalogDao;
- this.titanGenericDao = titanGenericDao;
- this.transactionId = transactionId;
- this.userId = userId;
- actionType = actionTypeEnum.name();
- rollbackManager = new RollbackManager(transactionId, userId, actionType, initRollbackHandlers());
- commitManager = new CommitManager(transactionId, userId, actionType, initCommitHandlers());
- status = TransactionStatusEnum.OPEN;
-
- }
-
- private List<ICommitHandler> initCommitHandlers() {
- List<ICommitHandler> commitHandlers = new ArrayList<>();
- commitHandlers.add(new TitanCommitHandler(titanGenericDao));
- return commitHandlers;
- }
-
- private List<RollbackHandler> initRollbackHandlers() {
- List<RollbackHandler> rolebackHandlers = new ArrayList<>();
- rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao));
- rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType));
- return rolebackHandlers;
- }
-
- private <T> Either<T, TransactionCodeEnum> invokeAction(boolean isLastAction, IDBAction dbAction, DBTypeEnum dbType) {
-
- Either<T, DBActionCodeEnum> actionResult;
- log.debug(LogMessages.INVOKE_ACTION, transactionId, dbType.name(), userId, actionType);
- if (isLastAction) {
- actionResult = getLastActionResult(dbAction, dbType);
- } else {
- actionResult = getActionResult(dbAction, dbType);
- }
-
- Either<T, TransactionCodeEnum> result;
- boolean isRollbackNedded = actionResult.isRight();
- if (isRollbackNedded) {
- TransactionCodeEnum transactionCode = transactionRollback();
- result = Either.right(transactionCode);
- } else {
- result = Either.left(actionResult.left().value());
- }
- return result;
- }
-
- private TransactionCodeEnum transactionRollback() {
-
- TransactionCodeEnum result;
- DBActionCodeEnum transactionRollback = rollbackManager.transactionRollback();
- if (transactionRollback == DBActionCodeEnum.SUCCESS) {
- result = TransactionCodeEnum.ROLLBACK_SUCCESS;
- log.info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType);
- log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType);
-
- } else {
- result = TransactionCodeEnum.ROLLBACK_FAILED;
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "transactionCommit for transaction " + transactionId);
- BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit for transaction " + transactionId);
-
- log.info(LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType);
- log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType);
- }
- return result;
- }
-
- public <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction) {
- Either<T, TransactionCodeEnum> result;
- if (status == TransactionStatusEnum.OPEN) {
- result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN);
- } else {
- result = handleActionOnClosedTransaction();
- }
- updateTransactionStatus(result);
- return result;
- }
-
- public <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction) {
-
- Either<T, TransactionCodeEnum> result;
- MethodActivationStatusEnum addingHandlerResult;
- if (status == TransactionStatusEnum.OPEN) {
- log.debug(LogMessages.PRE_INVOKE_ACTION, transactionId, dbType.name(), userId, actionType);
- Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.getRollbackHandler(dbType);
-
- if (eitherRollbackHandler.isLeft()) {
- RollbackHandler rollbackHandler = eitherRollbackHandler.left().value();
- addingHandlerResult = rollbackHandler.addRollbackAction(dbRollbackAction);
- } else {
- addingHandlerResult = addToNewRollbackHandler(dbType, dbRollbackAction);
- }
-
- if (addingHandlerResult == MethodActivationStatusEnum.SUCCESS) {
- result = invokeAction(isLastAction, dbAction, dbType);
- } else {
- result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED);
- }
- } else {
- result = handleActionOnClosedTransaction();
- }
- updateTransactionStatus(result);
- return result;
- }
-
- private MethodActivationStatusEnum addToNewRollbackHandler(DBTypeEnum dbType, IDBAction dbRollbackAction) {
- log.debug(LogMessages.CREATE_ROLLBACK_HANDLER, dbType.name(), transactionId, userId, actionType);
- MethodActivationStatusEnum result;
-
- Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.createRollbackHandler(dbType);
- if (eitherRollbackHandler.isRight()) {
- result = eitherRollbackHandler.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - addToNewRollbackHandler");
- BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - addToNewRollbackHandler");
- log.info(LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType);
- log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType);
- } else {
- RollbackHandler rollbackHandler = eitherRollbackHandler.left().value();
- rollbackHandler.addRollbackAction(dbRollbackAction);
- result = MethodActivationStatusEnum.SUCCESS;
- }
-
- return result;
- }
-
- public Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData) {
-
- Either<DBActionCodeEnum, TransactionCodeEnum> result;
- if (status == TransactionStatusEnum.OPEN) {
- Either<RollbackHandler, MethodActivationStatusEnum> eitherEsHandler = rollbackManager.getRollbackHandler(DBTypeEnum.ELASTIC_SEARCH);
- if (eitherEsHandler.isRight()) {
- result = Either.right(TransactionCodeEnum.INTERNAL_ERROR);
- } else {
- ESRollbackHandler esHandler = (ESRollbackHandler) eitherEsHandler.left().value();
-
- Either<ESAction, MethodActivationStatusEnum> eitherEsRollbackAction = esHandler.buildEsRollbackAction(esCatalogDao, artifactData, esActiontype);
- if (eitherEsRollbackAction.isLeft()) {
- esHandler.addRollbackAction(eitherEsRollbackAction.left().value());
- result = invokeAction(isLastAction, new ESAction(esCatalogDao, artifactData, esActiontype), DBTypeEnum.ELASTIC_SEARCH);
- } else {
- result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED);
- }
-
- }
- } else {
- result = handleActionOnClosedTransaction();
- }
- updateTransactionStatus(result);
- return result;
- }
-
- private <T> void updateTransactionStatus(Either<T, TransactionCodeEnum> result) {
- if (result.isRight()) {
- updateTransactionStatus(result.right().value());
- }
-
- }
-
- private <T> Either<T, TransactionCodeEnum> handleActionOnClosedTransaction() {
- Either<T, TransactionCodeEnum> result = Either.right(TransactionCodeEnum.TRANSACTION_CLOSED);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - handleActionOnClosedTransaction");
- log.debug(LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType);
- log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType);
- return result;
- }
-
- private <T> Either<T, DBActionCodeEnum> getLastActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) {
- Either<T, DBActionCodeEnum> result;
- if (isLastActionAlreadyCalled()) {
- result = Either.right(DBActionCodeEnum.FAIL_MULTIPLE_LAST_ACTION);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - getLastActionResult");
- BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getLastActionResult");
- log.debug(LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType);
- log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType);
- } else {
- setLastActionAlreadyCalled(true);
- result = getActionResult(dataBaseAction, dbType);
- }
- return result;
- }
-
- private <T> Either<T, DBActionCodeEnum> getActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) {
- Either<T, DBActionCodeEnum> result;
- try {
- T doAction = dataBaseAction.doAction();
- result = Either.left(doAction);
- } catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - getActionResult");
- BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getActionResult");
- log.debug(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType, e);
- log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType);
-
- result = Either.right(DBActionCodeEnum.FAIL_GENERAL);
- }
- return result;
- }
-
- public TransactionCodeEnum finishTransaction() {
- TransactionCodeEnum result;
- if (status == TransactionStatusEnum.OPEN) {
- DBActionCodeEnum transactionCommit = commitManager.transactionCommit();
- if (transactionCommit == DBActionCodeEnum.SUCCESS) {
- result = TransactionCodeEnum.SUCCESS;
- status = TransactionStatusEnum.CLOSED;
- } else {
- result = transactionRollback();
- }
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "TransactionManager - finishTransaction");
- BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - finishTransaction");
- log.debug(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType);
- log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType);
- result = TransactionCodeEnum.TRANSACTION_CLOSED;
- }
- updateTransactionStatus(result);
- return result;
- }
-
- private void updateTransactionStatus(TransactionCodeEnum result) {
- switch (result) {
- case SUCCESS:
- status = TransactionStatusEnum.CLOSED;
- break;
- case ROLLBACK_SUCCESS:
- status = TransactionStatusEnum.CLOSED;
- break;
- case ROLLBACK_FAILED:
- status = TransactionStatusEnum.FAILED_ROLLBACK;
- break;
- default:
- break;
- }
-
- }
-
- private boolean isLastActionAlreadyCalled() {
- return lastActionAlreadyCalled;
- }
-
- private void setLastActionAlreadyCalled(boolean lastAction) {
- this.lastActionAlreadyCalled = lastAction;
- }
-
- static void setLog(Logger log) {
- TransactionSdncImpl.log = log;
- }
-
- TransactionStatusEnum getStatus() {
- return status;
- }
+
+ // TODO test using slf4j-test and make this final
+ private static Logger log = LoggerFactory.getLogger(TransactionSdncImpl.class);
+ private boolean lastActionAlreadyCalled;
+ private RollbackManager rollbackManager;
+ private CommitManager commitManager;
+ private ESCatalogDAO esCatalogDao;
+ private TitanGenericDao titanGenericDao;
+ private Integer transactionId;
+ private TransactionStatusEnum status;
+ private String userId, actionType;
+
+ TransactionSdncImpl(Integer transactionId, String userId, ActionTypeEnum actionTypeEnum, ESCatalogDAO esCatalogDao, TitanGenericDao titanGenericDao) {
+ this.esCatalogDao = esCatalogDao;
+ this.titanGenericDao = titanGenericDao;
+ this.transactionId = transactionId;
+ this.userId = userId;
+ actionType = actionTypeEnum.name();
+ rollbackManager = new RollbackManager(transactionId, userId, actionType, initRollbackHandlers());
+ commitManager = new CommitManager(transactionId, userId, actionType, initCommitHandlers());
+ status = TransactionStatusEnum.OPEN;
+
+ }
+
+ private List<ICommitHandler> initCommitHandlers() {
+ List<ICommitHandler> commitHandlers = new ArrayList<>();
+ commitHandlers.add(new TitanCommitHandler(titanGenericDao));
+ return commitHandlers;
+ }
+
+ private List<RollbackHandler> initRollbackHandlers() {
+ List<RollbackHandler> rolebackHandlers = new ArrayList<>();
+ rolebackHandlers.add(new TitanRollbackHandler(transactionId, userId, actionType, titanGenericDao));
+ rolebackHandlers.add(new ESRollbackHandler(transactionId, userId, actionType));
+ return rolebackHandlers;
+ }
+
+ private <T> Either<T, TransactionCodeEnum> invokeAction(boolean isLastAction, IDBAction dbAction, DBTypeEnum dbType) {
+
+ Either<T, DBActionCodeEnum> actionResult;
+ log.debug(LogMessages.INVOKE_ACTION, transactionId, dbType.name(), userId, actionType);
+ if (isLastAction) {
+ actionResult = getLastActionResult(dbAction, dbType);
+ } else {
+ actionResult = getActionResult(dbAction, dbType);
+ }
+
+ Either<T, TransactionCodeEnum> result;
+ boolean isRollbackNedded = actionResult.isRight();
+ if (isRollbackNedded) {
+ TransactionCodeEnum transactionCode = transactionRollback();
+ result = Either.right(transactionCode);
+ } else {
+ result = Either.left(actionResult.left().value());
+ }
+ return result;
+ }
+
+ private TransactionCodeEnum transactionRollback() {
+
+ TransactionCodeEnum result;
+ DBActionCodeEnum transactionRollback = rollbackManager.transactionRollback();
+ if (transactionRollback == DBActionCodeEnum.SUCCESS) {
+ result = TransactionCodeEnum.ROLLBACK_SUCCESS;
+ log.info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType);
+ log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, userId, actionType);
+
+ } else {
+ result = TransactionCodeEnum.ROLLBACK_FAILED;
+ BeEcompErrorManager.getInstance().logBeSystemError("transactionCommit for transaction " + transactionId);
+
+ log.info(LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType);
+ log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_FAILED_GENERAL, transactionId, userId, actionType);
+ }
+ return result;
+ }
+
+ public <T> Either<T, TransactionCodeEnum> invokeTitanAction(boolean isLastAction, IDBAction dbAction) {
+ Either<T, TransactionCodeEnum> result;
+ if (status == TransactionStatusEnum.OPEN) {
+ result = invokeAction(isLastAction, dbAction, DBTypeEnum.TITAN);
+ } else {
+ result = handleActionOnClosedTransaction();
+ }
+ updateTransactionStatus(result);
+ return result;
+ }
+
+ public <T> Either<T, TransactionCodeEnum> invokeGeneralDBAction(boolean isLastAction, DBTypeEnum dbType, IDBAction dbAction, IDBAction dbRollbackAction) {
+
+ Either<T, TransactionCodeEnum> result;
+ MethodActivationStatusEnum addingHandlerResult;
+ if (status == TransactionStatusEnum.OPEN) {
+ log.debug(LogMessages.PRE_INVOKE_ACTION, transactionId, dbType.name(), userId, actionType);
+ Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.getRollbackHandler(dbType);
+
+ if (eitherRollbackHandler.isLeft()) {
+ RollbackHandler rollbackHandler = eitherRollbackHandler.left().value();
+ addingHandlerResult = rollbackHandler.addRollbackAction(dbRollbackAction);
+ } else {
+ addingHandlerResult = addToNewRollbackHandler(dbType, dbRollbackAction);
+ }
+
+ if (addingHandlerResult == MethodActivationStatusEnum.SUCCESS) {
+ result = invokeAction(isLastAction, dbAction, dbType);
+ } else {
+ result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED);
+ }
+ } else {
+ result = handleActionOnClosedTransaction();
+ }
+ updateTransactionStatus(result);
+ return result;
+ }
+
+ private MethodActivationStatusEnum addToNewRollbackHandler(DBTypeEnum dbType, IDBAction dbRollbackAction) {
+ log.debug(LogMessages.CREATE_ROLLBACK_HANDLER, dbType.name(), transactionId, userId, actionType);
+ MethodActivationStatusEnum result;
+
+ Either<RollbackHandler, MethodActivationStatusEnum> eitherRollbackHandler = rollbackManager.createRollbackHandler(dbType);
+ if (eitherRollbackHandler.isRight()) {
+ result = eitherRollbackHandler.right().value();
+ BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - addToNewRollbackHandler");
+ log.info(LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType);
+ log.debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.FAILED_CREATE_ROLLBACK, dbType.name(), transactionId, userId, actionType);
+ } else {
+ RollbackHandler rollbackHandler = eitherRollbackHandler.left().value();
+ rollbackHandler.addRollbackAction(dbRollbackAction);
+ result = MethodActivationStatusEnum.SUCCESS;
+ }
+
+ return result;
+ }
+
+ public Either<DBActionCodeEnum, TransactionCodeEnum> invokeESAction(boolean isLastAction, ESActionTypeEnum esActiontype, ESArtifactData artifactData) {
+
+ Either<DBActionCodeEnum, TransactionCodeEnum> result;
+ if (status == TransactionStatusEnum.OPEN) {
+ Either<RollbackHandler, MethodActivationStatusEnum> eitherEsHandler = rollbackManager.getRollbackHandler(DBTypeEnum.ELASTIC_SEARCH);
+ if (eitherEsHandler.isRight()) {
+ result = Either.right(TransactionCodeEnum.INTERNAL_ERROR);
+ } else {
+ ESRollbackHandler esHandler = (ESRollbackHandler) eitherEsHandler.left().value();
+
+ Either<ESAction, MethodActivationStatusEnum> eitherEsRollbackAction = esHandler.buildEsRollbackAction(esCatalogDao, artifactData, esActiontype);
+ if (eitherEsRollbackAction.isLeft()) {
+ esHandler.addRollbackAction(eitherEsRollbackAction.left().value());
+ result = invokeAction(isLastAction, new ESAction(esCatalogDao, artifactData, esActiontype), DBTypeEnum.ELASTIC_SEARCH);
+ } else {
+ result = Either.right(TransactionCodeEnum.PREPARE_ROLLBACK_FAILED);
+ }
+
+ }
+ } else {
+ result = handleActionOnClosedTransaction();
+ }
+ updateTransactionStatus(result);
+ return result;
+ }
+
+ private <T> void updateTransactionStatus(Either<T, TransactionCodeEnum> result) {
+ if (result.isRight()) {
+ updateTransactionStatus(result.right().value());
+ }
+
+ }
+
+ private <T> Either<T, TransactionCodeEnum> handleActionOnClosedTransaction() {
+ Either<T, TransactionCodeEnum> result = Either.right(TransactionCodeEnum.TRANSACTION_CLOSED);
+ log.debug(LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType);
+ log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, userId, actionType);
+ return result;
+ }
+
+ private <T> Either<T, DBActionCodeEnum> getLastActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) {
+ Either<T, DBActionCodeEnum> result;
+ if (isLastActionAlreadyCalled()) {
+ result = Either.right(DBActionCodeEnum.FAIL_MULTIPLE_LAST_ACTION);
+ BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getLastActionResult");
+ log.debug(LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType);
+ log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, dbType.name(), userId, actionType);
+ } else {
+ setLastActionAlreadyCalled(true);
+ result = getActionResult(dataBaseAction, dbType);
+ }
+ return result;
+ }
+
+ private <T> Either<T, DBActionCodeEnum> getActionResult(IDBAction dataBaseAction, DBTypeEnum dbType) {
+ Either<T, DBActionCodeEnum> result;
+ try {
+ T doAction = dataBaseAction.doAction();
+ result = Either.left(doAction);
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - getActionResult");
+ log.debug(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType, e);
+ log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, dbType.name(), transactionId, e.getMessage(), userId, actionType);
+
+ result = Either.right(DBActionCodeEnum.FAIL_GENERAL);
+ }
+ return result;
+ }
+
+ public TransactionCodeEnum finishTransaction() {
+ TransactionCodeEnum result;
+ if (status == TransactionStatusEnum.OPEN) {
+ DBActionCodeEnum transactionCommit = commitManager.transactionCommit();
+ if (transactionCommit == DBActionCodeEnum.SUCCESS) {
+ result = TransactionCodeEnum.SUCCESS;
+ status = TransactionStatusEnum.CLOSED;
+ } else {
+ result = transactionRollback();
+ }
+ } else {
+ BeEcompErrorManager.getInstance().logBeSystemError("TransactionManager - finishTransaction");
+ log.debug(LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType);
+ log.info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, status.name(), userId, actionType);
+ result = TransactionCodeEnum.TRANSACTION_CLOSED;
+ }
+ updateTransactionStatus(result);
+ return result;
+ }
+
+ private void updateTransactionStatus(TransactionCodeEnum result) {
+ switch (result) {
+ case SUCCESS:
+ status = TransactionStatusEnum.CLOSED;
+ break;
+ case ROLLBACK_SUCCESS:
+ status = TransactionStatusEnum.CLOSED;
+ break;
+ case ROLLBACK_FAILED:
+ status = TransactionStatusEnum.FAILED_ROLLBACK;
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ private boolean isLastActionAlreadyCalled() {
+ return lastActionAlreadyCalled;
+ }
+
+ private void setLastActionAlreadyCalled(boolean lastAction) {
+ this.lastActionAlreadyCalled = lastAction;
+ }
+
+ // TODO test using slf4j-test and remove this
+ static void setLog(Logger log) {
+ TransactionSdncImpl.log = log;
+ }
+
+ TransactionStatusEnum getStatus() {
+ return status;
+ }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java
new file mode 100644
index 0000000000..56527b6e9b
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java
@@ -0,0 +1,40 @@
+package org.openecomp.sdc.config;
+
+import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
+import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
+import org.openecomp.sdc.common.transaction.mngr.TransactionManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan({"org.openecomp.sdc.be.user",
+ "org.openecomp.sdc.be.impl",
+ "org.openecomp.sdc.be.auditing.impl",
+ "org.openecomp.sdc.be.distribution",
+ "org.openecomp.sdc.be.switchover.detector",
+ "org.openecomp.sdc.be.tosca",
+ "org.openecomp.sdc.be.components.validation",
+ "org.openecomp.sdc.be.components.impl",
+ "org.openecomp.sdc.be.components.path",
+ "org.openecomp.sdc.be.components.merge",
+ "org.openecomp.sdc.be.components.csar",
+ "org.openecomp.sdc.be.components.property"
+})
+public class CatalogBESpringConfig {
+ @Bean(name = "lifecycleBusinessLogic")
+ public LifecycleBusinessLogic lifecycleBusinessLogic() {
+ return new LifecycleBusinessLogic();
+ }
+
+ @Bean(name = "transactionManager")
+ public TransactionManager transactionManager() {
+ return new TransactionManager();
+ }
+
+ @Bean(name = "asset-metadata-utils")
+ public AssetMetadataConverter assetMetadataConverter() {
+ return new AssetMetadataConverter();
+ }
+
+}
diff --git a/catalog-be/src/main/resources/application-context.xml b/catalog-be/src/main/resources/application-context.xml
index 2b3603ce3b..b34ad69ffb 100644
--- a/catalog-be/src/main/resources/application-context.xml
+++ b/catalog-be/src/main/resources/application-context.xml
@@ -11,56 +11,18 @@
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:component-scan
- base-package="org.openecomp.sdc.be.dao.impl,
- org.openecomp.sdc.be.dao.es,
- org.openecomp.sdc.be.resources.impl,
- org.openecomp.sdc.be.dao.neo4j,
- org.openecomp.sdc.be.model.operations.impl,
- org.openecomp.sdc.be.model.cache,
- org.openecomp.sdc.be.dao.titan,
- org.openecomp.sdc.be.user,
- org.openecomp.sdc.be.impl,
- org.openecomp.sdc.be.auditing.impl,
- org.openecomp.sdc.be.components.impl,
- org.openecomp.sdc.be.components.merge,
- org.openecomp.sdc.be.components.distribution.engine,
- org.openecomp.sdc.be.distribution,
- org.openecomp.sdc.be.components.clean,
- org.openecomp.sdc.be.dao.cassandra,
- org.openecomp.sdc.be.switchover.detector,
- org.openecomp.sdc.be.tosca,
- org.openecomp.sdc.be.model.jsontitan.operations,
- org.openecomp.sdc.be.dao.jsongraph,
- org.openecomp.sdc.be.externalapi.servlet
- ">
-
- </context:component-scan>
-
- <bean id="resourceImportManager" class="org.openecomp.sdc.be.components.impl.ResourceImportManager" />
- <bean id="capabilityTypeImportManager" class="org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager" />
- <bean id="servletUtils" class="org.openecomp.sdc.be.impl.ServletUtils" />
- <bean id="resourceBusinessLogic" class="org.openecomp.sdc.be.components.impl.ResourceBusinessLogic" />
- <bean id="serviceBusinessLogic" class="org.openecomp.sdc.be.components.impl.ServiceBusinessLogic" />
- <bean id="productBusinessLogic" class="org.openecomp.sdc.be.components.impl.ProductBusinessLogic" />
- <bean id="artifactBusinessLogic" class="org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic" />
- <bean id="lifecycleBusinessLogic" class="org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic" />
- <bean id="serviceComponentInstanceBusinessLogic" class="org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic" />
- <bean id="productComponentInstanceBusinessLogic" class="org.openecomp.sdc.be.components.impl.ProductComponentInstanceBusinessLogic" />
- <bean id="vfComponentInstanceBusinessLogic" class="org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic" />
- <bean id="transactionManager" class="org.openecomp.sdc.common.transaction.mngr.TransactionManager" />
- <bean id="userBusinessLogic" class="org.openecomp.sdc.be.user.UserBusinessLogic" />
- <bean id="elementsBusinessLogic" class="org.openecomp.sdc.be.components.impl.ElementBusinessLogic" />
- <bean id="propertyBusinessLogic" class="org.openecomp.sdc.be.components.impl.PropertyBusinessLogic" />
- <bean id="auditingManager" class="org.openecomp.sdc.be.auditing.impl.AuditingManager" />
- <bean id="distributionBusinessLogic" class="org.openecomp.sdc.be.distribution.DistributionBusinessLogic" />
- <bean id="interfaceLifecycleTypeImportManager" class="org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager" />
- <bean id="distributionMonitoringBusinessLogic" class="org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic" />
- <bean id="additionalInformationBusinessLogic" class="org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic" />
- <bean id="distribution-engine-cluster-health" class="org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth" />
- <bean id="categoriesImportManager" class="org.openecomp.sdc.be.components.impl.CategoriesImportManager" />
- <bean id="asset-metadata-utils" class="org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter" />
+ base-package= "org.openecomp.sdc.be.components.health,
+ org.openecomp.sdc.be.servlets,
+ org.openecomp.sdc.be.externalapi.servlet,
+ org.openecomp.sdc.be.components.scheduledtasks,
+ org.openecomp.sdc.be.model.jsontitan.utils">
+ </context:component-scan>
<bean class="org.openecomp.sdc.be.dao.config.DAOSpringConfig"/>
+ <bean class="org.openecomp.sdc.be.config.CatalogModelSpringConfig"/>
+ <bean class="org.openecomp.sdc.be.components.distribution.engine.config.DistributionEngineSpringConfig"/>
+ <bean class="org.openecomp.sdc.config.CatalogBESpringConfig"/>
+
<util:properties id="elasticsearchConfig" location="file:${config.home}/elasticsearch.yml" />
diff --git a/catalog-be/src/main/resources/config/DME2preferredRouter.txt b/catalog-be/src/main/resources/config/DME2preferredRouter.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/catalog-be/src/main/resources/config/DME2preferredRouter.txt
diff --git a/catalog-be/src/main/resources/config/configuration.yaml b/catalog-be/src/main/resources/config/configuration.yaml
index 190153cb0a..aefdacea98 100644
--- a/catalog-be/src/main/resources/config/configuration.yaml
+++ b/catalog-be/src/main/resources/config/configuration.yaml
@@ -23,7 +23,7 @@ beSslPort: 8443
version: 1.1.0
released: 2012-11-30
-toscaConformanceLevel: 5.0
+toscaConformanceLevel: 7.0
minToscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
@@ -146,6 +146,7 @@ resourceTypes: &allResourceTypes
- CP
- VL
- VF
+ - CR
- VFCMT
- Abstract
- CVFC
@@ -198,7 +199,8 @@ toscaArtifacts:
excludeResourceCategory:
- Generic
excludeResourceType:
- - PNF
+ - PNF
+ - CR
informationalResourceArtifacts:
features:
displayName: Features
@@ -422,7 +424,7 @@ resourceDeploymentArtifacts:
DCAE_DOC:
acceptedTypes:
validForResourceTypes:
- - VF
+ - VF
- VFCMT
DCAE_EVENT:
acceptedTypes:
@@ -532,6 +534,7 @@ resourceInformationalArtifacts:
- CP
- VL
- VF
+ - CR
- VFCMT
- Abstract
- PNF
@@ -641,6 +644,7 @@ genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
CVFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
+ CR : org.openecomp.resource.abstract.nodes.CR
PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
@@ -662,3 +666,65 @@ environmentContext:
- Needed_Non-Revenue
- Useful_Non-Revenue
- General_Non-Revenue
+
+dmaapConsumerConfiguration:
+ hosts: olsd004.wnsnet.attws.com:3905
+ consumerGroup: asdc
+ consumerId: mama #mama - in Order To Consume Remove This String And Replace It With -> mama
+ timeoutMs: 15000
+ limit: 1
+ pollingInterval: 2
+ topic: com.att.sdc.23911-SDCforTestDev-v001
+ latitude: 32.109333
+ longitude: 34.855499
+ version: 1.0
+ serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+ environment: TEST
+ partner: BOT_R
+ routeOffer: MR1
+ protocol: https
+ contenttype: application/json
+ dme2TraceOn: true
+ aftEnvironment: AFTUAT
+ aftDme2ConnectionTimeoutMs: 15000
+ aftDme2RoundtripTimeoutMs: 240000
+ aftDme2ReadTimeoutMs: 50000
+ dme2preferredRouterFilePath: DME2preferredRouter.txt
+ timeLimitForNotificationHandleMs: 120000
+ credential:
+ username: m09875@sdc.att.com
+ password: hmXYcznAljMSisdy8zgcag==
+
+
+
+dmeConfiguration:
+ dme2Search: DME2SEARCH
+ dme2Resolve: DME2RESOLVE
+
+
+excludedPolicyTypesMapping:
+ # VF:
+ # - a.b.c
+ # - c.d.e
+ #CR:
+ # - x.y.z
+
+excludedGroupTypesMapping:
+ CR:
+ - org.openecomp.groups.VfModule
+ - org.openecomp.groups.heat.HeatStack
+ - tosca.groups.Root
+ VF:
+ - org.openecomp.groups.VfModule
+ - org.openecomp.groups.heat.HeatStack
+ - tosca.groups.Root
+ Service:
+ - org.openecomp.groups.VfModule
+ - org.openecomp.groups.heat.HeatStack
+ - tosca.groups.Root
+
+healthStatusExclude:
+ - DE
+ - ES
+ - DMAAP
+
diff --git a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml
index 60886cf40f..5ebbe82985 100644
--- a/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml
+++ b/catalog-be/src/main/resources/config/distribution-engine-configuration.yaml
@@ -45,4 +45,41 @@ createTopic:
startDistributionEngine: true
-useHttpsWithDmaap: true \ No newline at end of file
+
+useHttpsWithDmaap: false
+opEnvRecoveryIntervalSec: 180
+allowedTimeBeforeStaleSec: 300
+
+aaiConfig:
+ httpRequestConfig:
+ serverRootUrl: https://aai-uint3.test.att.com:8443
+ resourceNamespaces:
+ operationalEnvironments: /aai/v12/cloud-infrastructure/operational-environments
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 5000
+ connectTimeoutMs: 1000
+ clientCertificate:
+ keyStore: /opt/app/jetty/base/be/etc/non-prod.jks
+ keyStorePassword: hmXYcznAljMSisdy8zgcag==
+ headers:
+ X-FromAppId: asdc
+ numOfRetries: 3
+
+msoConfig:
+ httpRequestConfig:
+ serverRootUrl: http://127.0.0.1:8080/onap/mso/infra/modelDistributions/v1
+ resourceNamespaces:
+ distributions: /distributions
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 2000
+ connectTimeoutMs: 500
+ basicAuthorization:
+ userName: asdc
+ password: OTLEp5lfVhYdyw5EAtTUBQ==
+ numOfRetries: 3
+
+currentArtifactInstallationTimeout: 120
diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml
index 9dc0355212..56d0e74b73 100644
--- a/catalog-be/src/main/resources/config/error-configuration.yaml
+++ b/catalog-be/src/main/resources/config/error-configuration.yaml
@@ -8,6 +8,10 @@ errors:
code: 201,
message: "OK"
}
+ ACCEPTED: {
+ code: 202,
+ message: "Accepted"
+ }
NO_CONTENT: {
code: 204,
message: "No Content"
@@ -411,7 +415,6 @@ errors:
message: "Error: Invalid Content. Missing Capability Type '%1'.",
messageId: "SVC4115"
}
-#-----------SVC4116---------------------------
RESOURCE_INSTANCE_BAD_REQUEST: {
code: 400,
message: "Error: Invalid Content.",
@@ -595,7 +598,7 @@ errors:
}
#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
- code: 409,
+ code: 403,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
@@ -1188,6 +1191,7 @@ errors:
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 - #?&@%+;,=$<>~^`\[]{}|"*!',
@@ -1658,7 +1662,7 @@ errors:
# %1 - "groupName"
INVALID_VF_MODULE_NAME: {
code: 400,
- message: "Error: Invalid Content. VF Module name '%1' contains invalid characters",
+ message: "Error: Invalid Content. Group name '%1' contains invalid characters",
messageId: "SVC4646"
}
@@ -1877,4 +1881,154 @@ errors:
code: 404,
message: "Error: Requested relation %1 was not found on the container %2.",
messageId: "SVC4674"
- } \ No newline at end of file
+ }
+
+
+#---------SVC4675------------------------------
+ INVALID_SERVICE_STATE: {
+ code: 409,
+ message: "Service state is invalid for this action",
+ messageId: "SVC4675"
+ }
+
+#---------SVC4676------------------------------
+ INVALID_RESPONSE_FROM_PROXY: {
+ code: 502,
+ message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server",
+ messageId: "SVC4676"
+ }
+
+#---------SVC4677------------------------------
+ API_RESOURCE_NOT_FOUND: {
+ code: 404,
+ message: "Error: Requested '%1' was not found.",
+ messageId: "SVC4677"
+ }
+
+#---------SVC4678------------------------------
+ BAD_REQUEST_MISSING_RESOURCE: {
+ code: 400,
+ message: "Error: The required resource name/id is missing in the request",
+ messageId: "SVC4678"
+ }
+#---------SVC4679------------------------------
+# %1 forwarding path name maximum length
+ FORWARDING_PATH_NAME_MAXIMUM_LENGTH: {
+ code: 400,
+ message: "Forwarding path name too long, , maximum allowed 200 characters : '%1'.",
+ messageId: "SVC4679"
+ }
+#---------SVC4680------------------------------
+# %1 Forwarding path name already in use
+ FORWARDING_PATH_NAME_ALREADY_IN_USE: {
+ code: 400,
+ message: "Forwarding path name already in use : '%1'.",
+ messageId: "SVC4680"
+ }
+#---------SVC4681------------------------------
+# %1 Forwarding path name empty
+ FORWARDING_PATH_NAME_EMPTY: {
+ code: 400,
+ message: "Forwarding Path Name can't be empty .",
+ messageId: "SVC4681"
+ }
+#---------SVC4682------------------------------
+# %1 - resource uniqueId
+# %2 - resource component type
+ RESOURCE_CANNOT_CONTAIN_POLICIES: {
+ code: 400,
+ message: "Error: The resource %1 type of %2 cannot contain policies.",
+ messageId: "SVC4682"
+ }
+#---------SVC4683------------------------------
+# %1 - policy uniqueId
+# %2 - component uniqueId
+ POLICY_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested policy %1 was not found on the container %2.",
+ messageId: "SVC4683"
+}
+#---------SVC4684------------------------------
+# %1 - policy name
+ INVALID_POLICY_NAME: {
+ code: 400,
+ message: "Error: Invalid policy name %1 received.",
+ messageId: "SVC4684"
+ }
+#---------SVC4685------------------------------
+# %1 - policy name
+ POLICY_NAME_ALREADY_EXIST: {
+ code: 409,
+ message: "Error: The policy with the name %1 already exists.",
+ messageId: "SVC4685"
+ }
+#---------SVC4686------------------------------
+# %1 - policy name
+ POLICY_TARGET_DOES_NOT_EXIST: {
+ code: 400,
+ message: "Error: The targets %1 are not valid, all targets have to be on the topologyTemplate.",
+ messageId: "SVC4686"
+ }
+#---------SVC4687------------------------------
+# %1 - policy type
+# %2 - component type
+ EXCLUDED_POLICY_TYPE: {
+ code: 400,
+ message: "Error: The policy of the type %1 excluded to add to a component of the type %2.",
+ messageId: "SVC4687"
+ }
+ #---------SVC4688------------------------------
+# %1 - group type
+# %2 - component type
+ GROUP_TYPE_ILLEGAL_PER_COMPONENT: {
+ code: 400,
+ message: "Error: group type %1 not permitted in component of type %2",
+ messageId: "SVC4688"
+ }
+ #---------SVC4689------------------------------
+# %1 - group type
+# %2 - component type
+ POLICY_TARGET_TYPE_DOES_NOT_EXIST: {
+ code: 400,
+ message: "Error: The target types %1 are not valid.",
+ messageId: "SVC4689"
+ }
+
+#---------SVC4690------------------------------
+# %1 forwarding path protocol maximum length
+ FORWARDING_PATH_PROTOCOL_MAXIMUM_LENGTH: {
+ code: 400,
+ message: "Forwarding path protocol too long, , maximum allowed 200 characters : '%1'.",
+ messageId: "SVC4690"
+ }
+
+#---------SVC4691------------------------------
+# %1 forwarding path destination port maximum length
+ FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH: {
+ code: 400,
+ message: "Forwarding path destination port too long, , maximum allowed 200 characters : '%1'.",
+ messageId: "SVC4691"
+ }
+
+#---------POL4692------------------------------
+ MISSING_OLD_COMPONENT_INSTANCE: {
+ code: 400 ,
+ message: "Error: Missing 'componentInstanceId' HTTP param.",
+ messageId: "POL4692"
+ }
+
+#---------POL4693------------------------------
+ MISSING_NEW_COMPONENT_INSTANCE: {
+ code: 400 ,
+ message: "Error: Missing 'newComponentInstanceId' HTTP param.",
+ messageId: "POL4693"
+ }
+
+#---------SVC4694------------------------------
+# %1 External Reference Value
+ EXT_REF_NOT_FOUND: {
+ code: 404,
+ message: "Error: External Reference '%1' was not found.",
+ messageId: "SVC4694"
+ }
+
diff --git a/catalog-be/src/main/resources/config/logback.xml b/catalog-be/src/main/resources/config/logback.xml
index ba16783536..b436f20c31 100644
--- a/catalog-be/src/main/resources/config/logback.xml
+++ b/catalog-be/src/main/resources/config/logback.xml
@@ -11,6 +11,8 @@
<property name="default-log-pattern"
value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{BeginTimestamp}|%X{EndTimestamp}|%X{uuid}|%X{serviceInstanceID}|%thread|%X{ServerName}|%X{ServiceName}|${ECOMP-subcomponent-name}|%X{userId}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%level|%X{alarmSeverity}|%X{localAddr}|%X{ElapsedTime}|${beFqdn}|%X{remoteAddr}|%logger{35}|%X{timer}|ActivityType=&lt;%M&gt;, Desc=&lt;%msg&gt;%n" />
+ <property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| ActivityType=&lt;%M&gt;, Desc=&lt;%msg&gt;%n" />
+
<property name="asdc-debug-log-pattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%msg %n"/>
<!-- All log -->
@@ -18,13 +20,11 @@
<then>
<appender name="ALL_ROLLING"
class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log
- </file>
+ <file>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log.%i
- </fileNamePattern>
+ <fileNamePattern>${log.home}/${ECOMP-component-name}/${ECOMP-subcomponent-name}/all.log.%i</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
</rollingPolicy>
@@ -210,7 +210,7 @@
<maxFileSize>20MB</maxFileSize>
</triggeringPolicy>
<encoder>
- <pattern>${default-log-pattern}</pattern>
+ <pattern>${auditLoggerPattern}</pattern>
</encoder>
</appender>
diff --git a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml
index 4e25d735d0..50f74f8853 100644
--- a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml
+++ b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.yml
@@ -122,6 +122,8 @@ tosca.capabilities.Scalable:
type: integer
tosca.capabilities.network.Bindable:
derived_from: tosca.capabilities.Node
+
+
tosca.capabilities.Container.Docker:
derived_from: tosca.capabilities.Container
properties:
@@ -207,6 +209,16 @@ org.openecomp.capabilities.metric.SnmpTrap:
description: Object Id of the metric
required: true
status: SUPPORTED
+org.openecomp.capabilities.Forwarder:
+ derived_from: tosca.capabilities.Root
+org.openecomp.capabilities.VLANAssignment:
+ derived_from: tosca.capabilities.Root
+ description: ability to expose routing information of the internal network
+ properties:
+ vfc_instance_group_reference:
+ type: string
+ description: Ability to recognize capability per vfc instance group on vnf instance
+ required: true
#ONAP types
tosca.capabilities.nfv.VirtualStorage:
derived_from: tosca.capabilities.Root
diff --git a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip
index 84871d6a07..6c443c9662 100644
--- a/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/capability-types/capabilityTypes.zip
Binary files differ
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 449842c2f4..493f399453 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
@@ -1257,6 +1257,7 @@ org.openecomp.datatypes.flavors.DeploymentFlavor:
license_flavor:
type: org.openecomp.datatypes.flavors.LicenseFlavor
required: false
+
org.openecomp.datatypes.ImageInfo:
derived_from: tosca.datatypes.Root
properties:
@@ -1271,7 +1272,7 @@ org.openecomp.datatypes.ImageInfo:
type: string
required: false
default: md5
-#onap
+#ONAP types
tosca.datatypes.nfv.VnfcConfigurableProperties:
derived_from: tosca.datatypes.Root
properties:
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 1f79bf2c2d..75f9f73a35 100644
--- a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml
index ce457e4add..9711bfdebe 100644
--- a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml
+++ b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.yml
@@ -1,3 +1,8 @@
+tosca.groups.Root:
+ description: The TOSCA Group Type all other TOSCA Group Types derive from
+ interfaces:
+ Standard:
+ type: tosca.interfaces.node.lifecycle.Standard
org.openecomp.groups.heat.HeatStack:
derived_from: tosca.groups.Root
description: Grouped all heat resources which are in the same heat stack
@@ -77,9 +82,51 @@ org.openecomp.groups.VfModule:
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:
- Standard:
- type: tosca.interfaces.node.lifecycle.Standard
-
+org.openecomp.groups.NetworkCollection:
+ derived_from: tosca.groups.Root
+ description: groups l3-networks in network collection
+ properties:
+ network_collection_type:
+ type: string
+ required: true
+ description: network collection type, defined with default value
+ default: l3-network
+ network_collection_subtype:
+ type: string
+ required: true
+ description: network collection subtype, defined with default value
+ default: sub-interface
+ network_collection_role:
+ type: string
+ required: true
+ description: network collection role
+ network_collection_description:
+ type: string
+ required: true
+ description: network collection description, free format text
+org.openecomp.groups.VfcInstanceGroup:
+ derived_from: tosca.groups.Root
+ description: groups VFCs with same parent port role
+ properties:
+ vfc_instance_group_role:
+ type: string
+ required: true
+ description: role of this VFC group
+ vfc_parent_port_role:
+ type: string
+ required: true
+ description: common role of parent ports of VFCs in this group
+ network_collection_role:
+ type: string
+ required: true
+ description: network collection role assigned to this group
+ subinterface_role:
+ type: string
+ required: true
+ description: common role of subinterfaces of VFCs in this group, criteria the group is created
+ capabilities:
+ vlan_assignment:
+ type: org.openecomp.capabilities.VLANAssignment
+ properties:
+ vfc_instance_group_reference:
+ type: string \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip
index 7acd7a6b45..71a4af957a 100644
--- a/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/group-types/groupTypes.zip
Binary files differ
diff --git a/asdc-tests/src/test/resources/CI/importResource/root/root.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json
index 53f709bdca..4245f4dab1 100644
--- a/asdc-tests/src/test/resources/CI/importResource/root/root.json
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.json
@@ -1,9 +1,10 @@
{
- "payloadName": "normative-types-new-root.yml",
+ "payloadName": "Generic_CR.yml",
"contactId": "jh0003",
- "name": "Root",
- "description": "Represents a generic software component that can be managed and run by a Compute Node Type.",
+ "name": "Generic_CR",
+ "description": "Represents a generic CR.",
"resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
"categories": [
{
"name": "Generic",
@@ -15,6 +16,6 @@
}
],
"tags": [
- "Root"
+ "Generic_CR"
]
} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml
new file mode 100644
index 0000000000..941bc451da
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.yml
@@ -0,0 +1,15 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.CR:
+ derived_from: tosca.nodes.Root
+ properties:
+ nf_function:
+ type: string
+ nf_role:
+ type: string
+ nf_naming_code:
+ type: string
+ nf_type:
+ type: string
+ nf_naming:
+ type: org.openecomp.datatypes.Naming
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip
new file mode 100644
index 0000000000..5ea130c95e
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_CR/Generic_CR.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip
index 85adfbc2a1..d20e69e8d6 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_VF/Generic_VF.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip
index f69e5b40fb..48ebb1f610 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extVl/extVl.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json
new file mode 100644
index 0000000000..5b426db133
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "forwardingPath.yml",
+ "contactId": "jh0003",
+ "name": "Forwarding Path",
+ "description": "Forwarding Path configuration object",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+ ],
+ "tags": [
+ "Forwarding Path"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml
new file mode 100644
index 0000000000..fe1be7f1f2
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.yml
@@ -0,0 +1,24 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.nodes.ForwardingPath:
+ derived_from: tosca.nodes.Root
+ properties:
+ target_range:
+ type: list
+ required: true
+ status: SUPPORTED
+ entry_schema:
+ description: Identifier of the reciever port of the VNF or the service
+ type: integer
+ protocol:
+ type: string
+ description: protocol type that runs on the link
+ required: true
+ status: SUPPORTED
+ requirements:
+ - forwarder:
+ capability: org.openecomp.capabilities.Forwarder
+ relationship: org.openecomp.relationships.ForwardsTo
+ occurrences:
+ - 0
+ - UNBOUNDED \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip
new file mode 100644
index 0000000000..7135677bf1
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/forwardingPath/forwardingPath.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml
index 89ee9f81f0..791a0b9a3b 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.yml
@@ -73,6 +73,8 @@ node_types:
occurrences:
- 1
- UNBOUNDED
+ forwarder:
+ type: org.openecomp.capabilities.Forwarder
network.outgoing.bytes:
type: org.openecomp.capabilities.metric.Ceilometer
description: A node type that includes the Metric capability indicates that it can be monitored using ceilometer.
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip
index 8a23aa77c2..efeafe824e 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/globalPort/globalPort.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml
index ceb22da2af..57f4b45abe 100644
--- a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml
+++ b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.yml
@@ -13,7 +13,7 @@ tosca.policies.Performance:
derived_from: tosca.policies.Root
description: The TOSCA Policy Type definition that is used to declare performance requirements for TOSCA nodes or groups of nodes.
org.openecomp.policies.placement.Antilocate:
- derived_from: tosca.policy.placement
+ derived_from: tosca.policies.Placement
description: My placement policy for separation based upon container type value
properties:
name:
@@ -32,7 +32,7 @@ org.openecomp.policies.placement.Antilocate:
- region
- compute
org.openecomp.policies.placement.Colocate:
- derived_from: tosca.policy.placement
+ derived_from: tosca.policies.Placement
description: Keep associated nodes (groups of nodes) based upon affinity value
properties:
name:
@@ -51,7 +51,7 @@ org.openecomp.policies.placement.Colocate:
- region
- compute
org.openecomp.policies.placement.valet.Diversity:
- derived_from: tosca.policy.placement
+ derived_from: tosca.policies.Placement
description: Valet Diversity
properties:
level:
@@ -65,7 +65,7 @@ org.openecomp.policies.placement.valet.Diversity:
- host
- rack
org.openecomp.policies.placement.valet.Exclusivity:
- derived_from: tosca.policy.placement
+ derived_from: tosca.policies.Placement
description: Valet Exclusivity
properties:
level:
@@ -79,7 +79,7 @@ org.openecomp.policies.placement.valet.Exclusivity:
- host
- rack
org.openecomp.policies.placement.valet.Affinity:
- derived_from: tosca.policy.placement
+ derived_from: tosca.policies.Placement
description: Valet Affinity
properties:
level:
@@ -91,4 +91,27 @@ org.openecomp.policies.placement.valet.Affinity:
constraints:
- valid_values:
- host
- - rack \ No newline at end of file
+ - rack
+org.openecomp.policies.scaling.Fixed:
+ derived_from: tosca.policies.Scaling
+ properties:
+ quantity:
+ description: the exact number of instances to keep up
+ type: integer
+ required: true
+org.openecomp.policies.External:
+ derived_from: tosca.policies.Root
+ description: externally managed policy (for example, type="network assignment", source="Policy Manager", name="route target")
+ properties:
+ source:
+ type: string
+ description: The name of the server that exposes the policy with predefined type and name.
+ required: false
+ type:
+ type: string
+ description: The type (category) of the policy same as it is defined in the source.
+ required: false
+ name:
+ type: string
+ description: The name of the policy, that related to specific type, same as it is defined in the source.
+ required: false
diff --git a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip
index 5ed696e4a9..fbc09f2e0c 100644
--- a/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/policy-types/policyTypes.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml
index 5fb5390721..36325ba8e6 100644
--- a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml
+++ b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.yml
@@ -108,4 +108,7 @@
description: The relative location (e.g., path on the file system), which provides the root location to address an attached node.
type: string
status: SUPPORTED
- required: false \ No newline at end of file
+ required: false
+ org.openecomp.relationships.ForwardsTo:
+ derived_from: tosca.relationships.Root
+ valid_target_types: [org.openecomp.capabilities.Forwarder] \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip
index dbb1ca02f2..d8eb62d4d3 100644
--- a/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/relationship-types/relationshipTypes.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py
index aca21754e8..2f3237173c 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importCategoryTypes.py
@@ -6,24 +6,24 @@ import copy
from importNormativeElements import createNormativeElement
from importCommon import *
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#########################################################################################################################################################################################
+# #
+# Import categoriy types #
+# #
+# activation : #
+# python importCategoryTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importCategoryTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#########################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
-def importCategories(beHost, bePort, adminUser, exitOnSuccess, fileDir):
- result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/categories", "categoryTypes", "categoriesZip")
+def importCategories(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir):
+ result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/categories", "categoryTypes", "categoriesZip")
printFrameLine()
printNameAndReturnCode(result[0], result[1])
@@ -41,9 +41,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
adminUser = 'jh0003'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="])
+ opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -59,14 +60,16 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- importCategories(beHost, bePort, adminUser, True, "../../../import/tosca/categories/")
+ importCategories(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/categories/")
if __name__ == "__main__":
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py
index 5d7f5b7576..ef51a907d5 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importDataTypes.py
@@ -6,24 +6,24 @@ import copy
from importNormativeElements import createNormativeElement
from importCommon import *
-################################################################################################################################################
-# #
-# Import tosca data types #
-# #
-# activation : #
-# python importDataTypes.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importDataTypes.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#####################################################################################################################################################################################
+# #
+# Import tosca data types #
+# #
+# activation : #
+# python importDataTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importDataTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#####################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
-def importDataTypes(beHost, bePort, adminUser, exitOnSuccess, fileDir):
- result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/datatypes", "dataTypes", "dataTypesZip")
+def importDataTypes(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir):
+ result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/datatypes", "dataTypes", "dataTypesZip")
printFrameLine()
printNameAndReturnCode(result[0], result[1])
@@ -41,9 +41,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
adminUser = 'jh0003'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="])
+ opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -59,14 +60,16 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- importDataTypes(beHost, bePort, adminUser, True, "../../../import/tosca/data-types/")
+ importDataTypes(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/data-types/")
if __name__ == "__main__":
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py
index 2b6a5db6f8..9daa990fc5 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importGroupTypes.py
@@ -6,24 +6,24 @@ import copy
from importNormativeElements import createNormativeElement
from importCommon import *
-################################################################################################################################################
-# #
-# Import tosca data types #
-# #
-# activation : #
-# python importGroupTypes.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importGroupTypes.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#####################################################################################################################################################################################
+# #
+# Import tosca data types #
+# #
+# activation : #
+# python importGroupTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importGroupTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#####################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
-def importGroupTypes(beHost, bePort, adminUser, exitOnSuccess, fileDir):
- result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/grouptypes", "groupTypes", "groupTypesZip")
+def importGroupTypes(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir):
+ result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/grouptypes", "groupTypes", "groupTypesZip")
printFrameLine()
printNameAndReturnCode(result[0], result[1])
@@ -41,9 +41,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
adminUser = 'jh0003'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="])
+ opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -59,14 +60,16 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- importGroupTypes(beHost, bePort, adminUser, True, "../../../import/tosca/group-types/")
+ importGroupTypes(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/group-types/")
if __name__ == "__main__":
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
index 8b16a72ab3..4490fec61a 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
@@ -7,19 +7,19 @@ from importCommon import *
from importNormativeTypes import *
import importCommon
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#####################################################################################################################################################################################
+# #
+# Import heat types #
+# #
+# activation : #
+# python importHeatTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importHeatTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#####################################################################################################################################################################################
-def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
+def importHeatTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion):
heatTypes = [ "globalNetwork",
"globalPort",
@@ -38,6 +38,7 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
"abstractSubstitute",
"Generic_VFC",
"Generic_VF",
+ "Generic_CR",
"Generic_PNF",
"Generic_Service",
"contrailNetworkRules",
@@ -57,7 +58,8 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
"extCp2",
"extNeutronCP",
"extContrailCP",
- "portMirroringByPolicy"
+ "portMirroringByPolicy",
+ "forwardingPath"
]
responseCodes = [200, 201]
@@ -67,7 +69,7 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
results = []
for heatType in heatTypes:
- result = createNormativeType(beHost, bePort, adminUser, fileDir, heatType, updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, heatType, updateversion)
results.append(result)
if ( result[1] == None or result[1] not in responseCodes) :
print "Failed creating heat type " + heatType + ". " + str(result[1])
@@ -81,9 +83,10 @@ def main(argv):
bePort = '8080'
adminUser = 'jh0003'
updateversion = 'true'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
+ opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -99,17 +102,19 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-v", "--updateversion"):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- results = importHeatTypes(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion)
+ results = importHeatTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion)
print "-----------------------------"
for result in results:
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py b/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py
index f35cc7bcee..7d0b7c526a 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNodeType.py
@@ -16,7 +16,7 @@ def createZipFromYml(ymlFile, zipFile):
zip.write(ymlFile, os.path.basename(ymlFile))
zip.close()
-def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME):
+def createUserNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME):
try:
log("in create normative type ", ELEMENT_NAME)
@@ -26,7 +26,7 @@ def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME):
buffer = StringIO()
c = pycurl.Curl()
- url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
+ url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
c.setopt(c.URL, url)
c.setopt(c.POST, 1)
@@ -55,6 +55,9 @@ def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME):
c.setopt(pycurl.HTTPPOST, send)
c.setopt(c.WRITEFUNCTION, buffer.write)
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
res = c.perform()
#print("Before get response code")
@@ -73,7 +76,7 @@ def createUserNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME):
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-l <directory base location> | --location=<directory base location>] [-e <element name> | --element=<element name>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-l <directory base location> | --location=<directory base location>] [-e <element name> | --element=<element name>]'
print "----------------- Example -------------------"
print "python importNodeType.py -d false -l /home/vagrant/catalog-be-1604.0.2.15.6-SNAPSHOT/scripts/import/tosca/../../../import/tosca/user-normative-types/ -e root1"
@@ -86,9 +89,10 @@ def main(argv):
debugf = None
location = None
element = None
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:l:e:h",["ip=","port=","user=","location=","element=", "debug="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:l:e:h:s:",["ip=","port=","user=","location=","element=", "debug=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -108,11 +112,13 @@ def main(argv):
location = arg
elif opt in ("-e", "--element"):
element = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
@@ -139,7 +145,7 @@ def main(argv):
#normativeType = "root1"
- result = createUserNormativeType(beHost, bePort, adminUser, location, element)
+ result = createUserNormativeType(scheme, beHost, bePort, adminUser, location, element)
#result = createUserNormativeType(beHost, bePort, adminUser, fileDir, normativeType)
print "---------------------------------------"
print "{0:30} | {1:6}".format(result[0], result[1])
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py
index b6e390992e..d57c3d6ce4 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeAll.py
@@ -18,21 +18,21 @@ from importPolicyTypes import importPolicyTypes
from importCommon import *
import importCommon
-#################################################################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importNormativeAll.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
-# [-v <true|false> | --updateversion=<true|false>] #
-# #
-# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # #
-# python importNormativeAll.py #
-# #
-#################################################################################################################################################################################################
+#################################################################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importNormativeAll.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
+# [-v <true|false> | --updateversion=<true|false>] #
+# #
+# shortest activation (be host = localhost, be port = 8080, user = jh0003): #
+# python importNormativeAll.py #
+# #
+#################################################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -57,10 +57,11 @@ def main(argv):
adminUser = 'jh0003'
debugf = None
updateversion = 'true'
- importCommon.debugFlag = False
+ importCommon.debugFlag = False
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:v:h:s:",["ip=","port=","user=","debug=","updateversion=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -76,6 +77,8 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
@@ -84,7 +87,7 @@ def main(argv):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -101,33 +104,33 @@ def main(argv):
baseFileLocation = pathdir + "/../../../import/tosca/"
fileLocation = baseFileLocation + "data-types/"
- importDataTypes(beHost, bePort, adminUser, False, fileLocation)
+ importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
print 'sleep until data type cache is updated'
time.sleep( 70 )
fileLocation = baseFileLocation + "capability-types/"
- importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "interface-lifecycle-types/"
- importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "categories/"
- importCategories(beHost, bePort, adminUser, False, fileLocation)
+ importCategories(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "normative-types/"
- results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ results = importNormativeTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(results, updateversion)
fileLocation = baseFileLocation + "heat-types/"
- resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ resultsHeat = importHeatTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(resultsHeat, updateversion)
fileLocation = baseFileLocation + "group-types/"
- importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
+ importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "policy-types/"
- importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
+ importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
errorAndExit(0, None)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py
index bda02ddda9..e4f92139c2 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeCapabilities.py
@@ -7,25 +7,25 @@ from importNormativeElements import createNormativeElement
from importCommon import *
import importCommon
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#################################################################################################################################################################################################
+# #
+# Import normative capabilities #
+# #
+# activation : #
+# python importNormativeCapabilities.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importNormativeCapabilities.py [-f <input file> | --ifile=<input file> ] #
+# #
+#################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
-def importNormativeCapabilities(beHost, bePort, adminUser, exitOnSuccess, fileDir):
- result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/capability", "capabilityTypes", "capabilityTypeZip")
+def importNormativeCapabilities(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir):
+ result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/capability", "capabilityTypes", "capabilityTypeZip")
printFrameLine()
printNameAndReturnCode(result[0], result[1])
@@ -44,9 +44,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
adminUser = 'jh0003'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="])
+ opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="])
except getopt.GetoptError:
usage()
importCommon.errorAndExit(2, 'Invalid input')
@@ -62,14 +63,16 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- importNormativeCapabilities(beHost, bePort, adminUser, True, "../../../import/tosca/capability-types/")
+ importNormativeCapabilities(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/capability-types/")
if __name__ == "__main__":
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py
index af643da4f4..c28bbfb143 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeElements.py
@@ -4,19 +4,19 @@ from StringIO import StringIO
import json
import copy
from importCommon import *
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importUsers.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importUsers.py [-f <input file> | --ifile=<input file> ] #
+# #
+#################################################################################################################################################################################
-def createNormativeElement(beHost, bePort, adminUser, fileDir, urlSuffix, ELEMENT_NAME, elementFormName):
+def createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, urlSuffix, ELEMENT_NAME, elementFormName):
try:
log("in create normative element ", ELEMENT_NAME)
@@ -24,7 +24,7 @@ def createNormativeElement(beHost, bePort, adminUser, fileDir, urlSuffix, ELEMEN
buffer = StringIO()
c = pycurl.Curl()
- url = 'http://' + beHost + ':' + bePort + urlSuffix
+ url = scheme + '://' + beHost + ':' + bePort + urlSuffix
c.setopt(c.URL, url)
c.setopt(c.POST, 1)
@@ -45,6 +45,10 @@ def createNormativeElement(beHost, bePort, adminUser, fileDir, urlSuffix, ELEMEN
#c.setopt(c.WRITEFUNCTION, lambda x: None)
c.setopt(c.WRITEFUNCTION, buffer.write)
+
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
#print("before perform")
res = c.perform()
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py
index 33f1cc42de..a6ab5741e4 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeInterfaceLifecycleTypes.py
@@ -6,24 +6,24 @@ import copy
from importNormativeElements import createNormativeElement
from importCommon import *
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#############################################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importNormativeInterfaceLifecycleTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importNormativeInterfaceLifecycleTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#############################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
-def importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, exitOnSuccess, fileDir):
- result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle", "interfaceLifecycleTypes", "interfaceLifecycleTypeZip")
+def importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir):
+ result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/interfaceLifecycle", "interfaceLifecycleTypes", "interfaceLifecycleTypeZip")
printFrameLine()
printNameAndReturnCode(result[0], result[1])
@@ -42,9 +42,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
adminUser = 'jh0003'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="])
+ opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -60,14 +61,16 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, True, "../../../import/tosca/interface-lifecycle-types//")
+ importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/interface-lifecycle-types//")
if __name__ == "__main__":
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py
index 64a639c3c8..1061df862c 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeNoHeatAndNormativeTypes.py
@@ -17,21 +17,21 @@ from importPolicyTypes import importPolicyTypes
from importCommon import *
import importCommon
-#################################################################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importNormativeAll.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
-# [-v <true|false> | --updateversion=<true|false>] #
-# #
-# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # #
-# python importNormativeAll.py #
-# #
-#################################################################################################################################################################################################
+#####################################################################################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importNormativeNoHeatAndNormativeTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
+# [-v <true|false> | --updateversion=<true|false>] #
+# #
+# shortest activation (be host = localhost, be port = 8080, user = jh0003): #
+# python importNormativeNoHeatAndNormativeTypes.py #
+# #
+#####################################################################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -57,9 +57,10 @@ def main(argv):
debugf = None
updateversion = 'true'
importCommon.debugFlag = False
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:v:h:s:",["ip=","port=","user=","debug=","updateversion=", "scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -75,6 +76,8 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
@@ -83,7 +86,7 @@ def main(argv):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -100,16 +103,16 @@ def main(argv):
baseFileLocation = pathdir + "/../../../import/tosca/"
fileLocation = baseFileLocation + "data-types/"
- importDataTypes(beHost, bePort, adminUser, False, fileLocation)
+ importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
print 'sleep until data type cache is updated'
time.sleep( 70 )
fileLocation = baseFileLocation + "capability-types/"
- importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "interface-lifecycle-types/"
- importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation)
#fileLocation = baseFileLocation + "categories/"
#importCategories(beHost, bePort, adminUser, False, fileLocation)
@@ -123,10 +126,10 @@ def main(argv):
#handleResults(resultsHeat, updateversion)
fileLocation = baseFileLocation + "group-types/"
- importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
+ importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "policy-types/"
- importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
+ importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
errorAndExit(0, None)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py
index 1f523858b6..df2cd49687 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importNormativeTypes.py
@@ -5,19 +5,19 @@ import json
import copy
from importCommon import *
import importCommon
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# [-v <true|false> | --updateversion=<true|false>] #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
-
-def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion):
+#########################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importNormativeTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# [-v <true|false> | --updateversion=<true|false>] #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importNormativeTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#########################################################################################################################################################################################
+
+def createNormativeType(scheme, beHost, bePort, adminUser, fileDir, ELEMENT_NAME, updateversion):
try:
log("in create normative type ", ELEMENT_NAME)
@@ -27,7 +27,7 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update
buffer = StringIO()
c = pycurl.Curl()
- url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
+ url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/catalog/upload/multipart'
if updateversion != None:
url += '?createNewVersion=' + updateversion
c.setopt(c.URL, url)
@@ -58,6 +58,9 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update
#data = json.dumps(user)
#c.setopt(c.POSTFIELDS, data)
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
#c.setopt(c.WRITEFUNCTION, lambda x: None)
c.setopt(c.WRITEFUNCTION, buffer.write)
#print("before perform")
@@ -79,10 +82,10 @@ def createNormativeType(beHost, bePort, adminUser, fileDir, ELEMENT_NAME, update
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-v <true|false> | --updateversion=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-v <true|false> | --updateversion=<true|false>]'
-def importNormativeTypes(beHost, bePort, adminUser, fileDir, updateversion):
+def importNormativeTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion):
normativeTypes = [ "root", "compute", "softwareComponent", "webServer", "webApplication", "DBMS", "database", "objectStorage", "blockStorage", "containerRuntime", "containerApplication", "loadBalancer", "port", "network", "allottedResource"]
#normativeTypes = [ "root" ]
@@ -93,7 +96,7 @@ def importNormativeTypes(beHost, bePort, adminUser, fileDir, updateversion):
results = []
for normativeType in normativeTypes:
- result = createNormativeType(beHost, bePort, adminUser, fileDir, normativeType, updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, normativeType, updateversion)
results.append(result)
if ( result[1] == None or result[1] not in responseCodes ):
print "Failed creating normative type " + normativeType + ". " + str(result[1])
@@ -107,9 +110,10 @@ def main(argv):
bePort = '8080'
adminUser = 'jh0003'
updateversion = 'true'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
+ opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -125,17 +129,19 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-v", "--updateversion"):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', updateversion =', updateversion
if ( beHost == None ):
usage()
sys.exit(3)
- results = importNormativeTypes(beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion)
+ results = importNormativeTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/normative-types/", updateversion)
print "-----------------------------"
for result in results:
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py b/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py
index 3d7d9a9bbf..eb55bf84bc 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importONAPNormativeAll.py
@@ -23,7 +23,7 @@ import importCommon
# Import all users from a given file #
# #
# activation : #
-# python importNormativeAll.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
+# python importNormativeAll.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
# [-v <true|false> | --updateversion=<true|false>] #
# #
# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # #
@@ -32,7 +32,7 @@ import importCommon
#################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
+ print sys.argv[0], '[-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -58,6 +58,7 @@ def main(argv):
debugf = None
updateversion = 'true'
importCommon.debugFlag = False
+ scheme = 'http'
try:
opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="])
@@ -76,6 +77,8 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
@@ -84,7 +87,7 @@ def main(argv):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
+ print 'scheme =',scheme,',be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -101,37 +104,37 @@ def main(argv):
baseFileLocation = pathdir + "/../../../import/tosca/"
fileLocation = baseFileLocation + "data-types/"
- importDataTypes(beHost, bePort, adminUser, False, fileLocation)
+ importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
print 'sleep until data type cache is updated'
time.sleep( 70 )
fileLocation = baseFileLocation + "capability-types/"
- importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "interface-lifecycle-types/"
- importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "categories/"
- importCategories(beHost, bePort, adminUser, False, fileLocation)
+ importCategories(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "normative-types/"
- results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ results = importNormativeTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(results, updateversion)
fileLocation = baseFileLocation + "heat-types/"
- resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ resultsHeat = importHeatTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(resultsHeat, updateversion)
fileLocation = baseFileLocation + "onap-types/"
- resultsHeat = importOnapTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ resultsHeat = importOnapTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(resultsHeat, updateversion)
fileLocation = baseFileLocation + "group-types/"
- importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
+ importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "policy-types/"
- importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
+ importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
errorAndExit(0, None)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py
index 18d2270442..faad226d39 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importOnapTypes.py
@@ -7,19 +7,19 @@ from importCommon import *
from importNormativeTypes import *
import importCommon
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#####################################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importUsers.py [optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importUsers.py [-f <input file> | --ifile=<input file> ] #
+# #
+#####################################################################################################################################################################################################
-def importOnapTypes(beHost, bePort, adminUser, fileDir, updateversion):
+def importOnapTypes(scheme, beHost, bePort, adminUser, fileDir, updateversion):
onapTypes = [ "extImageFile",
"extLocalStorage",
@@ -41,7 +41,7 @@ def importOnapTypes(beHost, bePort, adminUser, fileDir, updateversion):
results = []
for onapType in onapTypes:
- result = createNormativeType(beHost, bePort, adminUser, fileDir, onapType, updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, onapType, updateversion)
results.append(result)
if ( result[1] == None or result[1] not in responseCodes) :
print "Failed creating heat type " + onapType + ". " + str(result[1])
@@ -55,6 +55,7 @@ def main(argv):
bePort = '8080'
adminUser = 'jh0003'
updateversion = 'true'
+ scheme = 'http'
try:
opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
@@ -73,17 +74,19 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-v", "--updateversion"):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,',be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- results = importOnapTypes(beHost, bePort, adminUser, "../../../import/tosca/onap-types/", updateversion)
+ results = importOnapTypes(scheme, beHost, bePort, adminUser, "../../../import/tosca/onap-types/", updateversion)
print "-----------------------------"
for result in results:
@@ -104,5 +107,3 @@ def main(argv):
if __name__ == "__main__":
main(sys.argv[1:])
-
-
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py
index c01e159264..103ad2d1da 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importPolicyTypes.py
@@ -6,24 +6,24 @@ import copy
from importNormativeElements import createNormativeElement
from importCommon import *
-################################################################################################################################################
-# #
-# Import tosca data types #
-# #
-# activation : #
-# python importPolicyTypes.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importPolicyTypes.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#####################################################################################################################################################################################
+# #
+# Import tosca data types #
+# #
+# activation : #
+# python importPolicyTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importPolicyTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+#####################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ]'
-def importPolicyTypes(beHost, bePort, adminUser, exitOnSuccess, fileDir):
- result = createNormativeElement(beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/policytypes", "policyTypes", "policyTypesZip")
+def importPolicyTypes(scheme, beHost, bePort, adminUser, exitOnSuccess, fileDir):
+ result = createNormativeElement(scheme, beHost, bePort, adminUser, fileDir, "/sdc2/rest/v1/catalog/uploadType/policytypes", "policyTypes", "policyTypesZip")
printFrameLine()
printNameAndReturnCode(result[0], result[1])
@@ -41,9 +41,10 @@ def main(argv):
beHost = 'localhost'
bePort = '8080'
adminUser = 'jh0003'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:h:",["ip=","port=","user="])
+ opts, args = getopt.getopt(argv,"i:p:u:h:s:",["ip=","port=","user=", "scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -59,14 +60,16 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- importPolicyTypes(beHost, bePort, adminUser, True, "../../../import/tosca/policy-types/")
+ importPolicyTypes(scheme, beHost, bePort, adminUser, True, "../../../import/tosca/policy-types/")
if __name__ == "__main__":
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py b/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py
index 8509855f38..8e69ffcf49 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importUsersFromYaml.py
@@ -5,22 +5,22 @@ import json
import copy
import yaml
-########################################################################################################################################################
-# #
-# Import all users from a given YAML file #
-# #
-# activation : #
-# python importUsersFromYaml.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): # #
-# python importUsersFromYaml.py [-f <input file> | --ifile=<input file> ] #
-# #
-# PyYAML module shall be added to python. #
-# pip install PyYAML>=3.1.0 --proxy=http://one.proxy.att.com:8080 #
-########################################################################################################################################################
-
-
-def importUsers(beHost, bePort, users, adminUser):
+#########################################################################################################################################################################################
+# #
+# Import all users from a given YAML file #
+# #
+# activation : #
+# python importUsersFromYaml.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importUsersFromYaml.py [-f <input file> | --ifile=<input file> ] #
+# #
+# PyYAML module shall be added to python. #
+# pip install PyYAML>=3.1.0 --proxy=http://one.proxy.att.com:8080 #
+#########################################################################################################################################################################################
+
+
+def importUsers(scheme, beHost, bePort, users, adminUser):
result = []
@@ -28,12 +28,12 @@ def importUsers(beHost, bePort, users, adminUser):
#print("Going to add user " + user['userId'])
- getRes = getUser(beHost, bePort, user)
+ getRes = getUser(scheme, beHost, bePort, user)
userId = getRes[0]
error = getRes[1]
#print error
if ( error != None and error == 404 ):
- res = createUser(beHost, bePort, user ,adminUser)
+ res = createUser(scheme, beHost, bePort, user ,adminUser)
result.append(res)
else:
if ( error == 200 ):
@@ -45,7 +45,7 @@ def importUsers(beHost, bePort, users, adminUser):
return result
-def getUser(beHost, bePort, user):
+def getUser(scheme, beHost, bePort, user):
if (user.get('userId') == None):
print "Ignoring record", user
@@ -56,9 +56,12 @@ def getUser(beHost, bePort, user):
c = pycurl.Curl()
#print type(userId)
- url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
+ url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user/' + str(userId)
c.setopt(c.URL, url)
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
+
#adminHeader = 'USER_ID: ' + adminUser
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
c.setopt(c.WRITEFUNCTION, lambda x: None)
@@ -81,7 +84,7 @@ def getUser(beHost, bePort, user):
-def createUser(beHost, bePort, user, adminUser):
+def createUser(scheme, beHost, bePort, user, adminUser):
if (user.get('userId') == None):
print "Ignoring record", user
@@ -92,7 +95,7 @@ def createUser(beHost, bePort, user, adminUser):
buffer = StringIO()
c = pycurl.Curl()
- url = 'http://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
+ url = scheme + '://' + beHost + ':' + bePort + '/sdc2/rest/v1/user'
c.setopt(c.URL, url)
c.setopt(c.POST, 1)
@@ -100,7 +103,10 @@ def createUser(beHost, bePort, user, adminUser):
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', adminHeader])
data = json.dumps(user)
- c.setopt(c.POSTFIELDS, data)
+ c.setopt(c.POSTFIELDS, data)
+
+ if scheme == 'https':
+ c.setopt(c.SSL_VERIFYPEER, 0)
c.setopt(c.WRITEFUNCTION, lambda x: None)
#print("before perform")
@@ -131,7 +137,7 @@ def errorAndExit(errorCode, errorDesc):
sys.exit(errorCode)
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ]'
def main(argv):
print 'Number of arguments:', len(sys.argv), 'arguments.'
@@ -141,9 +147,10 @@ def main(argv):
inputfile = None
adminUser = 'jh0003'
+ scheme ='http'
try:
- opts, args = getopt.getopt(argv,"i:p:f:h:",["ip=","port=","ifile="])
+ opts, args = getopt.getopt(argv,"i:p:f:h:s:",["ip=","port=","ifile=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -159,8 +166,10 @@ def main(argv):
bePort = arg
elif opt in ("-f", "--ifile"):
inputfile = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
- print 'be host =',beHost,', be port =', bePort,', users file =',inputfile
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', users file =',inputfile
if ( inputfile == None ):
usage()
@@ -187,7 +196,7 @@ def main(argv):
#activeUsers = filter(lambda x: x.get('status') == None or x['status'] == 'ACTIVE', cloneUsers)
- resultTable = importUsers(beHost, bePort, cloneUsers, adminUser)
+ resultTable = importUsers(scheme, beHost, bePort, cloneUsers, adminUser)
g = lambda x: x[1] != 201 and x[1] != 409
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json b/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json
index d239a15c72..7ea3dd4eda 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json
+++ b/catalog-be/src/main/resources/scripts/import/tosca/typesToUpgrade.json
@@ -1,19 +1,6 @@
{
"heat": [
- "contrailPort",
- "extCp",
- "contrailV2VirtualMachineInterface",
- "neutronPort",
- "Generic_PNF",
- "portMirroring",
- "Generic_VF",
- "serviceProxy",
- "extCp2",
- "extContrailCP",
- "vnfConfiguration",
- "extVl",
- "multiFlavorVFC",
- "portMirroringByPolicy"
+ "Generic_CR"
],
"normative": [
]
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py
index e35e2d28eb..5a1d1046b9 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatAndNormativeTypes.py
@@ -9,18 +9,18 @@ import importCommon
import json
-################################################################################################################################################
-# #
-# Upgrades all Heat and Normative types confiugred in "typesToUpgrade.json" file #
-# #
-# activation : #
-# python upgradeHeatAndNormativeTypes.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): #
-# python upgradeHeatAndNormativeTypes.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
-def upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseDir, updateversion):
+################################################################################################################################################################################################
+# #
+# Upgrades all Heat and Normative types confiugred in "typesToUpgrade.json" file #
+# #
+# activation #
+# python upgradeHeatAndNormativeTypes.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python upgradeHeatAndNormativeTypes.py [-f <input file> | --ifile=<input file> ] #
+# #
+################################################################################################################################################################################################
+def upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, baseDir, updateversion):
responseCodes = [200, 201]
if (updateversion == 'false'):
responseCodes = [200, 201, 409]
@@ -37,12 +37,12 @@ def upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseDir, updateversion)
debug(normativeFileDir)
results = []
for heatType in heatTypes:
- result = createNormativeType(beHost, bePort, adminUser, heatFileDir, heatType.encode('ascii', 'ignore'), updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, heatFileDir, heatType.encode('ascii', 'ignore'), updateversion)
results.append(result)
if (result[1] == None or result[1] not in responseCodes):
print "Failed creating heat type " + heatType + ". " + str(result[1])
for normativeType in normativeTypes:
- result = createNormativeType(beHost, bePort, adminUser, normativeFileDir, normativeType.encode('ascii', 'ignore'), updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, normativeFileDir, normativeType.encode('ascii', 'ignore'), updateversion)
results.append(result)
if (result[1] == None or result[1] not in responseCodes):
print "Failed creating normative type " + normativeType + ". " + str(result[1])
@@ -59,9 +59,10 @@ def main(argv):
bePort = '8080'
adminUser = 'jh0003'
updateversion = 'true'
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv, "i:p:u:v:h:", ["ip=", "port=", "user=", "updateversion="])
+ opts, args = getopt.getopt(argv, "i:p:u:v:h:s:", ["ip=", "port=", "user=", "updateversion=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -77,17 +78,19 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-v", "--updateversion"):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =', beHost, ', be port =', bePort, ', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost, ', be port =', bePort, ', user =', adminUser
if (beHost == None):
usage()
sys.exit(3)
- results = upgradeTypesPerConfigFile(beHost, bePort, adminUser, "../../../import/tosca/", updateversion)
+ results = upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, "../../../import/tosca/", updateversion)
print "-----------------------------"
for result in results:
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
index 7315ec0635..5cb0ca3b0c 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
@@ -7,19 +7,19 @@ from importCommon import *
from importNormativeTypes import *
import importCommon
-################################################################################################################################################
-# #
-# Import all users from a given file #
-# #
-# activation : #
-# python importUsers.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
-# #
-# shortest activation (be host = localhost, be port = 8080): #
-# python importUsers.py [-f <input file> | --ifile=<input file> ] #
-# #
-################################################################################################################################################
+#################################################################################################################################################################################
+# #
+# Import all users from a given file #
+# #
+# activation : #
+# python importUsers.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-f <input file> | --ifile=<input file> ] #
+# #
+# shortest activation (be host = localhost, be port = 8080): #
+# python importUsers.py [-f <input file> | --ifile=<input file> ] #
+# #
+#################################################################################################################################################################################
-def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion):
+def upgradeHeatTypes1707(scheme, beHost, bePort, adminUser, fileDir, updateversion):
heatTypes = [ "volume",
"cinderVolume",
@@ -49,7 +49,7 @@ def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion):
results = []
for heatType in heatTypes:
- result = createNormativeType(beHost, bePort, adminUser, fileDir, heatType, updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileDir, heatType, updateversion)
results.append(result)
if ( result[1] == None or result[1] not in responseCodes) :
print "Failed creating heat type " + heatType + ". " + str(result[1])
@@ -63,9 +63,10 @@ def main(argv):
bePort = '8080'
adminUser = 'jh0003'
updateversion = 'true'
-
+ scheme = 'http'
+
try:
- opts, args = getopt.getopt(argv,"i:p:u:v:h:",["ip=","port=","user=","updateversion="])
+ opts, args = getopt.getopt(argv,"i:p:u:v:h:s:",["ip=","port=","user=","updateversion=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -81,17 +82,19 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-v", "--updateversion"):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser
if ( beHost == None ):
usage()
sys.exit(3)
- results = upgradeHeatTypes1707(beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion)
+ results = upgradeHeatTypes1707(scheme, beHost, bePort, adminUser, "../../../import/tosca/heat-types/", updateversion)
print "-----------------------------"
for result in results:
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py
index 69a51f41f1..573e05b46a 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormative.py
@@ -17,21 +17,21 @@ from importOnapTypes import importOnapTypes
from importCommon import *
import importCommon
-#################################################################################################################################################################################################
-# #
-# Upgrades the normative types #
-# #
-# activation : #
-# python upgradeNormative.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
-# #
-# #
-# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # #
-# python upgradeNormative.py #
-# #
-#################################################################################################################################################################################################
+#################################################################################################################################################################################################################################
+# #
+# Upgrades the normative types #
+# #
+# activation : #
+# python upgradeNormative.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
+# #
+# #
+# shortest activation (be host = localhost, be port = 8080, user = jh0003): #
+# python upgradeNormative.py #
+# #
+#################################################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -52,9 +52,10 @@ def main(argv):
debugf = None
updateversion = 'true'
importCommon.debugFlag = False
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:h:s:",["ip=","port=","user=","debug=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -70,11 +71,13 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -91,27 +94,27 @@ def main(argv):
baseFileLocation = pathdir + "/../../../import/tosca/"
fileLocation = baseFileLocation + "categories/"
- importCategories(beHost, bePort, adminUser, False, fileLocation)
+ importCategories(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "data-types/"
- importDataTypes(beHost, bePort, adminUser, False, fileLocation)
+ importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "policy-types/"
- importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
-
- fileLocation = baseFileLocation + "group-types/"
- importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
+ importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "capability-types/"
- importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation)
+
+ fileLocation = baseFileLocation + "group-types/"
+ importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "interface-lifecycle-types/"
- importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation)
print 'sleep until data type cache is updated'
time.sleep( 70 )
- resultsHeat = upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseFileLocation, updateversion)
+ resultsHeat = upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, baseFileLocation, updateversion)
handleResults(resultsHeat, 'false')
errorAndExit(0, None)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py
index 8f8e0491ae..958416da33 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersion.py
@@ -7,21 +7,21 @@ from importCommon import *
from importNormativeTypes import createNormativeType
import importCommon
-#################################################################################################################################################################################################
-# #
-# Upgrades the normative types #
-# #
-# activation : #
-# python upgradeNormative.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
-# #
-# #
-# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # #
-# python upgradeNormative.py #
-# #
-#################################################################################################################################################################################################
+#################################################################################################################################################################################################################################
+# #
+# Upgrades the normative types #
+# #
+# activation : #
+# python upgradeNormative.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
+# #
+# #
+# shortest activation (be host = localhost, be port = 8080, user = jh0003): #
+# python upgradeNormative.py #
+# #
+#################################################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -41,10 +41,11 @@ def main(argv):
adminUser = 'jh0003'
debugf = None
updateversion = 'true'
- importCommon.debugFlag = False
+ importCommon.debugFlag = False
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:h:s:",["ip=","port=","user=","debug=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -60,11 +61,13 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -87,11 +90,11 @@ def main(argv):
##########################################################################
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion)
results.append(result)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py
index d45b27e755..805d012298 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionAll.py
@@ -10,7 +10,7 @@ from importCommon import *
import importCommon
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] [-v <true|false> | --updateversion=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -36,9 +36,10 @@ def main(argv):
debugf = None
updateversion = 'true'
importCommon.debugFlag = False
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:v:h",["ip=","port=","user=","debug=","updateversion="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:v:h:s:",["ip=","port=","user=","debug=","updateversion=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -54,6 +55,8 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
@@ -62,7 +65,7 @@ def main(argv):
if (arg.lower() == "false" or arg.lower() == "no"):
updateversion = 'false'
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf, ', updateversion =', updateversion
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -79,11 +82,11 @@ def main(argv):
baseFileLocation = pathdir + "/../../../import/tosca/"
fileLocation = baseFileLocation + "normative-types/"
- results = importNormativeTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ results = importNormativeTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(results, updateversion)
fileLocation = baseFileLocation + "heat-types/"
- resultsHeat = importHeatTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ resultsHeat = importHeatTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(resultsHeat, updateversion)
fileLocation = baseFileLocation + "onap-types/"
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py
index 13e5d7d63a..c75966cfc9 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeNormativeVersionProd1702_3537.py
@@ -7,21 +7,21 @@ from importCommon import *
from importNormativeTypes import createNormativeType
import importCommon
-#################################################################################################################################################################################################
-# #
-# Upgrades the normative types #
-# #
-# activation : #
-# python upgradeNormative.py [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
-# #
-# #
-# shortest activation (be host = localhost, be port = 8080, user = jh0003): # # #
-# python upgradeNormative.py #
-# #
-#################################################################################################################################################################################################
+#################################################################################################################################################################################################################################
+# #
+# Upgrades the normative types #
+# #
+# activation : #
+# python upgradeNormative.py [-s <scheme> | --scheme=<scheme> ] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>] #
+# #
+# #
+# shortest activation (be host = localhost, be port = 8080, user = jh0003): #
+# python upgradeNormative.py #
+# #
+#################################################################################################################################################################################################################################
def usage():
- print sys.argv[0], '[-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>]'
+ print sys.argv[0], '[optional -s <scheme> | --scheme=<scheme>, default http] [-i <be host> | --ip=<be host>] [-p <be port> | --port=<be port> ] [-u <user userId> | --user=<user userId> ] [-d <true|false> | --debug=<true|false>]'
def handleResults(results, updateversion):
printFrameLine()
@@ -42,9 +42,10 @@ def main(argv):
debugf = None
updateversion = 'true'
importCommon.debugFlag = False
+ scheme = 'http'
try:
- opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="])
+ opts, args = getopt.getopt(argv,"i:p:u:d:h:s:",["ip=","port=","user=","debug=","scheme="])
except getopt.GetoptError:
usage()
errorAndExit(2, 'Invalid input')
@@ -60,11 +61,13 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
+ print 'scheme =',scheme,', be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -88,35 +91,35 @@ def main(argv):
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailPort", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailPort", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailV2VirtualMachineInterface", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "neutronPort", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailCompute", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailCompute", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "novaServer", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "novaServer", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailV2VirtualNetwork", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "contrailVirtualNetwork", updateversion)
results.append(result)
fileLocation = baseFileLocation + "heat-types/"
- result = createNormativeType(beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion)
+ result = createNormativeType(scheme, beHost, bePort, adminUser, fileLocation, "neutronNet", updateversion)
results.append(result)
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py
index 4d0ec291f5..b272c2726c 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeONAPNormative.py
@@ -52,6 +52,7 @@ def main(argv):
debugf = None
updateversion = 'true'
importCommon.debugFlag = False
+ scheme = 'http'
try:
opts, args = getopt.getopt(argv,"i:p:u:d:h",["ip=","port=","user=","debug="])
@@ -70,11 +71,13 @@ def main(argv):
bePort = arg
elif opt in ("-u", "--user"):
adminUser = arg
+ elif opt in ("-s", "--scheme"):
+ scheme = arg
elif opt in ("-d", "--debug"):
print arg
debugf = bool(arg.lower() == "true" or arg.lower() == "yes")
- print 'be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
+ print 'scheme =',scheme,',be host =',beHost,', be port =', bePort,', user =', adminUser, ', debug =', debugf
if (debugf != None):
print 'set debug mode to ' + str(debugf)
@@ -91,31 +94,31 @@ def main(argv):
baseFileLocation = pathdir + "/../../../import/tosca/"
fileLocation = baseFileLocation + "categories/"
- importCategories(beHost, bePort, adminUser, False, fileLocation)
+ importCategories(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "data-types/"
- importDataTypes(beHost, bePort, adminUser, False, fileLocation)
+ importDataTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "policy-types/"
- importPolicyTypes(beHost, bePort, adminUser, False, fileLocation)
+ importPolicyTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "group-types/"
- importGroupTypes(beHost, bePort, adminUser, False, fileLocation)
+ importGroupTypes(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "capability-types/"
- importNormativeCapabilities(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeCapabilities(scheme, beHost, bePort, adminUser, False, fileLocation)
fileLocation = baseFileLocation + "interface-lifecycle-types/"
- importNormativeInterfaceLifecycleType(beHost, bePort, adminUser, False, fileLocation)
+ importNormativeInterfaceLifecycleType(scheme, beHost, bePort, adminUser, False, fileLocation)
print 'sleep until data type cache is updated'
time.sleep( 70 )
- resultsHeat = upgradeTypesPerConfigFile(beHost, bePort, adminUser, baseFileLocation, updateversion)
+ resultsHeat = upgradeTypesPerConfigFile(scheme, beHost, bePort, adminUser, baseFileLocation, updateversion)
handleResults(resultsHeat, 'false')
fileLocation = baseFileLocation + "onap-types/"
- resultsHeat = importOnapTypes(beHost, bePort, adminUser, fileLocation, updateversion)
+ resultsHeat = importOnapTypes(scheme, beHost, bePort, adminUser, fileLocation, updateversion)
handleResults(resultsHeat, updateversion)
errorAndExit(0, None)
diff --git a/catalog-be/src/main/webapp/WEB-INF/web.xml b/catalog-be/src/main/webapp/WEB-INF/web.xml
index 70f5ff229c..b9fd99bd4b 100644
--- a/catalog-be/src/main/webapp/WEB-INF/web.xml
+++ b/catalog-be/src/main/webapp/WEB-INF/web.xml
@@ -12,10 +12,16 @@
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
- <param-value>io.swagger.jersey.listing.ApiListingResourceJSON,
- org.glassfish.jersey.media.multipart.MultiPartFeature,
- org.openecomp.sdc.be.filters.BeServletFilter,
- org.openecomp.sdc.be.filters.ComponentsAvailabilityFilter</param-value>
+ <param-value>io.swagger.jersey.listing.ApiListingResourceJSON,
+ org.glassfish.jersey.media.multipart.MultiPartFeature,
+ org.openecomp.sdc.be.filters.BeServletFilter,
+ org.openecomp.sdc.be.filters.ComponentsAvailabilityFilter,
+ org.openecomp.sdc.be.servlets.DefaultExceptionMapper,
+ org.openecomp.sdc.be.servlets.ComponentExceptionMapper,
+ org.openecomp.sdc.be.servlets.StorageExceptionMapper,
+ org.openecomp.sdc.be.view.MixinModelWriter
+ </param-value>
+
</init-param>
<init-param>
<param-name>swagger.scanner.id</param-name>
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java b/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java
deleted file mode 100644
index 272f0d6a1d..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/AuditingMockManager.java
+++ /dev/null
@@ -1,44 +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;
-
-import java.util.EnumMap;
-
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AuditingMockManager implements IAuditingManager {
-
- private static Logger log = LoggerFactory.getLogger(AuditingMockManager.class.getName());
-
- public AuditingMockManager(String string) {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void auditEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- AuditingActionEnum actionEnum = AuditingActionEnum.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION));
- log.debug("call was made to auditEvent with event type {}", actionEnum.getName());
- }
-}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java
index 45b2317cd6..2088e8071a 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/ElementOperationMock.java
@@ -20,10 +20,7 @@
package org.openecomp.sdc;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -38,228 +35,230 @@ import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.CategoryData;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
public class ElementOperationMock implements IElementOperation {
- CategoryDefinition resourceCategory;
- CategoryDefinition serviceCategory;
- CategoryDefinition productCategory;
-
- Category oldService;
-
- public ElementOperationMock() {
- resourceCategory = new CategoryDefinition();
- resourceCategory.setName("Network Layer 2-3");
- SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition();
- subCategoryDefinition.setName("Router");
- SubCategoryDefinition subCategoryDefinition1 = new SubCategoryDefinition();
- subCategoryDefinition1.setName("Gateway");
-
- resourceCategory.addSubCategory(subCategoryDefinition);
- resourceCategory.addSubCategory(subCategoryDefinition1);
-
- serviceCategory = new CategoryDefinition();
- serviceCategory.setName("Mobility");
- oldService = new Category();
- oldService.setName("Mobility");
-
- productCategory = new CategoryDefinition();
- productCategory.setName("Network Layer 2-31");
- SubCategoryDefinition subCategoryDefinition11 = new SubCategoryDefinition();
- subCategoryDefinition11.setName("Router1");
- GroupingDefinition group = new GroupingDefinition();
- group.setName("group1");
- subCategoryDefinition11.addGrouping(group);
- productCategory.addSubCategory(subCategoryDefinition11);
-
- }
-
- @Override
- public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() {
-
- List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
- categories.add(resourceCategory);
- return Either.left(categories);
-
- }
-
- @Override
- public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() {
-
- List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
- categories.add(serviceCategory);
- return Either.left(categories);
-
- }
-
- /*
- * @Override public Either<Category, ActionStatus> getCategory(String name) { if (name.equals(resourceCategory.getName())){ return Either.left(resourceCategory); } else { return Either.right(ActionStatus.CATEGORY_NOT_FOUND); } }
- */
-
- @Override
- public Either<List<Tag>, ActionStatus> getAllTags() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Integer, ActionStatus> getDefaultHeatTimeout() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) {
-
- List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
- switch (nodeType) {
- case ResourceNewCategory:
- categories.add(resourceCategory);
- break;
- case ProductCategory:
- categories.add(productCategory);
- break;
- case ServiceNewCategory:
- categories.add(serviceCategory);
- break;
- default:
- break;
- }
- return Either.left(categories);
- }
-
- @Override
- public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<SubCategoryDefinition, ActionStatus> deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Map<String, String>, ActionStatus> getResourceTypesMap() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<List<CategoryDefinition>, ActionStatus> getAllProductCategories() {
- List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
- categories.add(productCategory);
- return Either.left(categories);
- }
-
- @Override
- public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
+ CategoryDefinition resourceCategory;
+ CategoryDefinition serviceCategory;
+ CategoryDefinition productCategory;
+
+ Category oldService;
+
+ public ElementOperationMock() {
+ resourceCategory = new CategoryDefinition();
+ resourceCategory.setName("Network Layer 2-3");
+ SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition();
+ subCategoryDefinition.setName("Router");
+ SubCategoryDefinition subCategoryDefinition1 = new SubCategoryDefinition();
+ subCategoryDefinition1.setName("Gateway");
+
+ resourceCategory.addSubCategory(subCategoryDefinition);
+ resourceCategory.addSubCategory(subCategoryDefinition1);
+
+ serviceCategory = new CategoryDefinition();
+ serviceCategory.setName("Mobility");
+ oldService = new Category();
+ oldService.setName("Mobility");
+
+ productCategory = new CategoryDefinition();
+ productCategory.setName("Network Layer 2-31");
+ SubCategoryDefinition subCategoryDefinition11 = new SubCategoryDefinition();
+ subCategoryDefinition11.setName("Router1");
+ GroupingDefinition group = new GroupingDefinition();
+ group.setName("group1");
+ subCategoryDefinition11.addGrouping(group);
+ productCategory.addSubCategory(subCategoryDefinition11);
+
+ }
+
+ @Override
+ public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() {
+
+ List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
+ categories.add(resourceCategory);
+ return Either.left(categories);
+
+ }
+
+ @Override
+ public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() {
+
+ List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
+ categories.add(serviceCategory);
+ return Either.left(categories);
+
+ }
+
+ /*
+ * @Override public Either<Category, ActionStatus> getCategory(String name) { if (name.equals(resourceCategory.getName())){ return Either.left(resourceCategory); } else { return Either.right(ActionStatus.CATEGORY_NOT_FOUND); } }
+ */
+
+ @Override
+ public Either<List<Tag>, ActionStatus> getAllTags() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<Integer, ActionStatus> getDefaultHeatTimeout() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) {
+
+ List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
+ switch (nodeType) {
+ case ResourceNewCategory:
+ categories.add(resourceCategory);
+ break;
+ case ProductCategory:
+ categories.add(productCategory);
+ break;
+ case ServiceNewCategory:
+ categories.add(serviceCategory);
+ break;
+ default:
+ break;
+ }
+ return Either.left(categories);
+ }
+
+ @Override
+ public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<SubCategoryDefinition, ActionStatus> deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<Map<String, String>, ActionStatus> getResourceTypesMap() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<List<CategoryDefinition>, ActionStatus> getAllProductCategories() {
+ List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
+ categories.add(productCategory);
+ return Either.left(categories);
+ }
+
+ @Override
+ public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java
index 5b86b9cc69..7f5b7f9853 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/ErrorConfigurationTest.java
@@ -20,10 +20,6 @@
package org.openecomp.sdc;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.config.ErrorConfiguration;
@@ -37,41 +33,45 @@ import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.File;
+
+import static org.junit.Assert.assertTrue;
+
public class ErrorConfigurationTest {
- ConfigurationSource configurationSource = null;
- private static Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class.getName());
+ ConfigurationSource configurationSource = null;
+ private static final Logger log = LoggerFactory.getLogger(ErrorConfigurationTest.class);
- @Before
- public void setup() {
+ @Before
+ public void setup() {
- ExternalConfiguration.setAppName("catalog-be");
- ExternalConfiguration.setConfigDir("src/test/resources/config");
- ExternalConfiguration.listenForChanges();
+ ExternalConfiguration.setAppName("catalog-be");
+ ExternalConfiguration.setConfigDir("src/test/resources/config");
+ ExternalConfiguration.listenForChanges();
- configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
+ configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
- }
+ }
- @Test
- public void testReadConfigurationFile() {
+ @Test
+ public void testReadConfigurationFile() {
- ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() {
+ ConfigurationListener configurationListener = new ConfigurationListener(ErrorConfiguration.class, new FileChangeCallback() {
- public void reconfigure(BasicConfiguration obj) {
- // TODO Auto-generated method stub
- log.debug("In reconfigure of {}", obj);
- }
+ public void reconfigure(BasicConfiguration obj) {
+ // TODO Auto-generated method stub
+ log.debug("In reconfigure of {}", obj);
+ }
- });
+ });
- ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener);
+ ErrorConfiguration testConfiguration = configurationSource.getAndWatchConfiguration(ErrorConfiguration.class, configurationListener);
- assertTrue(testConfiguration != null);
- ErrorInfo errorInfo = testConfiguration.getErrorInfo("USER_NOT_FOUND");
- assertTrue(errorInfo != null);
- log.debug("{}", testConfiguration);
- log.debug("{}", errorInfo);
+ assertTrue(testConfiguration != null);
+ ErrorInfo errorInfo = testConfiguration.getErrorInfo("USER_NOT_FOUND");
+ assertTrue(errorInfo != null);
+ log.debug("{}", testConfiguration);
+ log.debug("{}", errorInfo);
- }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
index f9819c72e5..4698c0eea9 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/TestExternalConfiguration.java
@@ -20,8 +20,6 @@
package org.openecomp.sdc;
-import java.io.IOException;
-
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.common.api.BasicConfiguration;
import org.openecomp.sdc.common.api.ConfigurationListener;
@@ -31,32 +29,34 @@ import org.openecomp.sdc.common.impl.ConfigFileChangeListener;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import java.io.IOException;
+
public class TestExternalConfiguration<T extends Object> {
- public static void main(String[] args) throws IOException {
+ public static void main(String[] args) throws IOException {
- ExternalConfiguration.setAppName("catalog-server");
- ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config");
- ExternalConfiguration.listenForChanges();
+ ExternalConfiguration.setAppName("catalog-server");
+ ExternalConfiguration.setConfigDir("C:\\Users\\esofer\\workspaceLuna\\catalog-server\\src\\test\\resources\\config");
+ ExternalConfiguration.listenForChanges();
- ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() {
+ ConfigurationListener configurationListener = new ConfigurationListener(Configuration.class, new FileChangeCallback() {
- @Override
- public void reconfigure(BasicConfiguration obj) {
- // TODO Auto-generated method stub
+ @Override
+ public void reconfigure(BasicConfiguration obj) {
+ // TODO Auto-generated method stub
- }
- });
+ }
+ });
- ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir());
- configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener);
+ ConfigurationSource configurationSource1 = new FSConfigurationSource(new ConfigFileChangeListener(), ExternalConfiguration.getConfigDir());
+ configurationSource1.getAndWatchConfiguration(Configuration.class, configurationListener);
- try {
- Thread.currentThread().sleep(100 * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
+ try {
+ Thread.currentThread().sleep(100 * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
- }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java
index c3f211f7ab..9ee123a840 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/ZipUtil.java
@@ -20,6 +20,9 @@
package org.openecomp.sdc;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.output.ByteArrayOutputStream;
+
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
@@ -30,100 +33,97 @@ 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.output.ByteArrayOutputStream;
-
public class ZipUtil {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- String zipFileName = "/src/test/resources/config/config.zip";
+ String zipFileName = "/src/test/resources/config/config.zip";
- zipFileName = "C:\\Git_work\\D2-SDnC\\catalog-be\\src\\test\\resources\\config\\config.zip";
- zipFileName = "src/test/resources/config/config.zip";
+ zipFileName = "C:\\Git_work\\D2-SDnC\\catalog-be\\src\\test\\resources\\config\\config.zip";
+ zipFileName = "src/test/resources/config/config.zip";
- Path path = Paths.get(zipFileName);
+ Path path = Paths.get(zipFileName);
- try {
- byte[] zipAsBytes = Files.readAllBytes(path);
- // encode to base
+ try {
+ byte[] zipAsBytes = Files.readAllBytes(path);
+ // encode to base
- byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes);
- String decodedStr = new String(decodedMd5);
+ byte[] decodedMd5 = Base64.encodeBase64(zipAsBytes);
+ String decodedStr = new String(decodedMd5);
- zipAsBytes = Base64.decodeBase64(decodedStr.getBytes());
+ zipAsBytes = Base64.decodeBase64(decodedStr.getBytes());
- // String str = new String(zipAsBytes);
+ // String str = new String(zipAsBytes);
- // readZip(str.getBytes());
- readZip(zipAsBytes);
+ // readZip(str.getBytes());
+ readZip(zipAsBytes);
- } catch (IOException e) {
- e.printStackTrace();
- }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
- }
+ }
- private static Map<String, byte[]> readZip(byte[] zipAsBytes) {
+ private static Map<String, byte[]> readZip(byte[] zipAsBytes) {
- Map<String, byte[]> fileNameToByteArray = new HashMap<String, byte[]>();
+ Map<String, byte[]> fileNameToByteArray = new HashMap<String, byte[]>();
- byte[] buffer = new byte[1024];
- ZipInputStream zis = null;
- try {
+ byte[] buffer = new byte[1024];
+ ZipInputStream zis = null;
+ try {
- zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes));
- // get the zipped file list entry
- ZipEntry ze = zis.getNextEntry();
+ zis = new ZipInputStream(new ByteArrayInputStream(zipAsBytes));
+ // get the zipped file list entry
+ ZipEntry ze = zis.getNextEntry();
- while (ze != null) {
+ while (ze != null) {
- String fileName = ze.getName();
+ String fileName = ze.getName();
- if (false == ze.isDirectory()) {
+ if (false == ze.isDirectory()) {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- try {
- int len;
- while ((len = zis.read(buffer)) > 0) {
- os.write(buffer, 0, len);
- }
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ try {
+ int len;
+ while ((len = zis.read(buffer)) > 0) {
+ os.write(buffer, 0, len);
+ }
- // aClass.outputStreamMethod(os);
- String aString = new String(os.toByteArray(), "UTF-8");
+ // aClass.outputStreamMethod(os);
+ String aString = new String(os.toByteArray(), "UTF-8");
- fileNameToByteArray.put(fileName, os.toByteArray());
+ fileNameToByteArray.put(fileName, os.toByteArray());
- } finally {
- if (os != null) {
- os.close();
- }
- }
- }
- ze = zis.getNextEntry();
+ } finally {
+ if (os != null) {
+ os.close();
+ }
+ }
+ }
+ ze = zis.getNextEntry();
- }
+ }
- zis.closeEntry();
- zis.close();
+ zis.closeEntry();
+ zis.close();
- } catch (IOException ex) {
- ex.printStackTrace();
- return null;
- } finally {
- if (zis != null) {
- try {
- zis.closeEntry();
- zis.close();
- } catch (IOException e) {
- // TODO: add log
- }
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ return null;
+ } finally {
+ if (zis != null) {
+ try {
+ zis.closeEntry();
+ zis.close();
+ } catch (IOException e) {
+ // TODO: add log
+ }
- }
- }
+ }
+ }
- return fileNameToByteArray;
+ return fileNameToByteArray;
- }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java
index a6c8dc4f0c..84c6fc118d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/DummyConfigurationManager.java
@@ -1,13 +1,13 @@
package org.openecomp.sdc.be;
-import static org.mockito.Mockito.mock;
-
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.common.api.ConfigurationListener;
import org.openecomp.sdc.common.api.ConfigurationSource;
+import static org.mockito.Mockito.mock;
+
public class DummyConfigurationManager {
private DistributionEngineConfiguration distributionConfigurationMock = mock(DistributionEngineConfiguration.class);
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java
new file mode 100644
index 0000000000..9bdf784f1c
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactoryTest.java
@@ -0,0 +1,132 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.junit.Test;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.common.api.Constants;
+
+import static org.junit.Assert.assertEquals;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESIGNER_USER_ROLE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EXTENDED_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID;
+
+public class AuditBaseEventFactoryTest {
+
+ private User user = new User();
+
+ @Test
+ public void buildUserNameWhenFullNameAndUserIdNotSet() {
+ assertEquals(Constants.EMPTY_STRING, AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenFullNameIsNotSetAndUserIdIsSet() {
+ user.setUserId(USER_ID);
+ assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenFullNameIsNullNullAndUserIdSet() {
+ user.setUserId(USER_ID);
+ user.setFirstName(Constants.NULL_STRING);
+ user.setLastName(Constants.NULL_STRING);
+ assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenFirtsNameIsNotSetAndLastNameIsNull() {
+ user.setUserId(USER_ID);
+ user.setLastName(Constants.NULL_STRING);
+ assertEquals("(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenLastNameIsNull() {
+ user.setUserId(USER_ID);
+ user.setFirstName(USER_FIRST_NAME);
+ user.setLastName(Constants.NULL_STRING);
+ assertEquals(USER_FIRST_NAME + " (" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenFirstNameIsNullAndLastNameIsSet() {
+ user.setUserId(USER_ID);
+ user.setFirstName(Constants.NULL_STRING);
+ user.setLastName(USER_LAST_NAME);
+ assertEquals(USER_LAST_NAME + "(" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenFullNameIsSetAndUserIdSet() {
+ user.setUserId(USER_ID);
+ user.setFirstName(USER_FIRST_NAME);
+ user.setLastName(USER_LAST_NAME);
+ assertEquals(USER_UID, AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildUserNameWhenFirstNameIsSetAndUserIdSet() {
+ user.setUserId(USER_ID);
+ user.setFirstName(USER_FIRST_NAME);
+ assertEquals(USER_FIRST_NAME + " (" + USER_ID + ")", AuditBaseEventFactory.buildUserName(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenNothingIsSet() {
+ assertEquals(Constants.EMPTY_STRING, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenOnlyUserIdIsSet() {
+ user.setUserId(USER_ID);
+ assertEquals(USER_ID, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameAllSet() {
+ user.setUserId(USER_ID);
+ user.setFirstName(USER_FIRST_NAME);
+ user.setLastName(USER_LAST_NAME);
+ user.setEmail(USER_EMAIL);
+ user.setRole(DESIGNER_USER_ROLE);
+ assertEquals(USER_EXTENDED_NAME, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenFirstNameAndUserIdAreSet() {
+ user.setUserId(USER_ID);
+ user.setFirstName(USER_FIRST_NAME);
+ assertEquals(USER_ID + ", " + USER_FIRST_NAME, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenLastNameAndUserIdAreSet() {
+ user.setUserId(USER_ID);
+ user.setLastName(USER_LAST_NAME);
+ assertEquals(USER_ID + ", " + USER_LAST_NAME, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenOnlyEmailAndRoleAreSet() {
+ user.setEmail(USER_EMAIL);
+ user.setRole(DESIGNER_USER_ROLE);
+ assertEquals(USER_EMAIL + ", " + DESIGNER_USER_ROLE, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenOnlyNameIsSet() {
+ user.setFirstName(USER_FIRST_NAME);
+ user.setLastName(USER_LAST_NAME);
+ assertEquals(USER_FIRST_NAME + " " + USER_LAST_NAME, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+ @Test
+ public void buildExtendedUserNameWhenOnlyRoleIsSet() {
+ user.setRole(DESIGNER_USER_ROLE);
+ assertEquals(DESIGNER_USER_ROLE, AuditBaseEventFactory.buildUserNameExtended(user));
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java
new file mode 100644
index 0000000000..0a90ffd915
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFuncTest.java
@@ -0,0 +1,200 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.model.ConsumerDefinition;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ConsumerEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_PASSWORD;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CONSUMER_SALT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_ECOMP_USER_CRED_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditConsumerEventFuncTest {
+ private AuditingManager auditingManager;
+
+ private ConsumerDefinition consumer;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ consumer = new ConsumerDefinition();
+ consumer.setConsumerName(USER_ID);
+ ThreadLocalsHolder.setUuid(REQUEST_ID);
+ }
+
+ @Test
+ public void testNewAddEcompUserCredEvent() {
+ AuditEventFactory factory = new AuditConsumerEventFactory(
+ AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ modifier, consumer);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR);
+ verifyConsumerEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName());
+ }
+
+ @Test
+ public void testOldAddEcompUserCredEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS))).isEqualTo(EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR);
+ verifyConsumerEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName());
+
+ }
+
+ @Test
+ public void testNewGetEcompUserCredEvent() {
+ AuditEventFactory factory = new AuditConsumerEventFactory(
+ AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ modifier, consumer);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_ECOMP_USER_CRED_LOG_STR);
+ verifyConsumerEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName());
+ }
+
+ @Test
+ public void testOldGetEcompUserCredEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS))).isEqualTo(EXPECTED_GET_ECOMP_USER_CRED_LOG_STR);
+ verifyConsumerEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName());
+
+ }
+
+ @Test
+ public void buildConsumerNameWhenAllFieldsAreProvided() {
+ consumer.setConsumerName(CONSUMER_NAME);
+ consumer.setConsumerSalt(CONSUMER_SALT);
+ consumer.setConsumerPassword(CONSUMER_PASSWORD);
+ assertEquals(CONSUMER_NAME + "," + CONSUMER_SALT + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer));
+ }
+
+ @Test
+ public void buildConsumerNameWhenSaltIsNull() {
+ consumer.setConsumerName(CONSUMER_NAME);
+ consumer.setConsumerPassword(CONSUMER_PASSWORD);
+ assertEquals(CONSUMER_NAME + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer));
+ }
+
+ @Test
+ public void buildConsumerNameWhenNameIsNull() {
+ consumer.setConsumerName(null);
+ consumer.setConsumerSalt(CONSUMER_SALT);
+ consumer.setConsumerPassword(CONSUMER_PASSWORD);
+ assertEquals(CONSUMER_SALT + "," + CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer));
+ }
+
+ @Test
+ public void buildConsumerNameWhenNameAndPwAreNull() {
+ consumer.setConsumerName(null);
+ consumer.setConsumerSalt(CONSUMER_SALT);
+ assertEquals(CONSUMER_SALT, AuditConsumerEventFactory.buildConsumerName(consumer));
+ }
+
+ @Test
+ public void buildConsumerNameWhenNameAndSaltAreNull() {
+ consumer.setConsumerName(null);
+ consumer.setConsumerPassword(CONSUMER_PASSWORD);
+ assertEquals(CONSUMER_PASSWORD, AuditConsumerEventFactory.buildConsumerName(consumer));
+ }
+
+ @Test
+ public void buildConsumerNameWhenConsumerObjectIsNull() {
+ assertEquals("", AuditConsumerEventFactory.buildConsumerName(null));
+ }
+
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER, USER_ID);
+
+ return auditingFields;
+ }
+
+ private void verifyConsumerEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ ConsumerEvent storedEvent = (ConsumerEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isNull();
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ assertThat(storedEvent.getEcompUser()).isEqualTo(USER_ID);
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java
new file mode 100644
index 0000000000..04bd34f289
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/AuditTestUtils.java
@@ -0,0 +1,236 @@
+package org.openecomp.sdc.be.auditing.impl;
+
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+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.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+
+
+public class AuditTestUtils {
+ public final static String USER_FIRST_NAME = "Carlos";
+ public final static String USER_LAST_NAME = "Santana";
+ public final static String USER_ID = "cs0008";
+ public final static String DESCRIPTION = "OK";
+ public final static String STATUS_OK = "200";
+ public final static String STATUS_CREATED = "201";
+ public final static String REQUEST_ID = "123456";
+ public final static String USER_UID = "Carlos Santana(cs0008)";
+ public final static String SERVICE_INSTANCE_ID = "d07fdc15-122d-4476-a349-8c9a2d80b485";
+ public final static String CURRENT_STATE = "CERTIFIED";
+ public final static String CURRENT_VERSION = "1.1";
+ public final static String RESOURCE_TYPE = ResourceTypeEnum.VF.name();
+ public final static String RESOURCE_TYPE_VFC = ResourceTypeEnum.VFC.name();
+ public final static String RESOURCE_NAME = "ciServicea184822c06e6";
+ public final static String DIST_ID = "e5765a82-e7cd-4c5c-91a0-eae58d6ae08f";
+ public final static String TOPIC_NAME = "ASDC-DISTR-NOTIF-TOPIC-PROD_TEST";
+ public final static String DESIGNER_USER_ROLE = "DESIGNER";
+ public final static String TESTER_USER_ROLE = "TESTER";
+ public final static String USER_EMAIL = "carlos@email.com";
+ public final static String MODIFIER_FIRST_NAME = "Jimmy";
+ public final static String MODIFIER_LAST_NAME = "Hendrix";
+ public final static String MODIFIER_ID = "jh0003";
+ public final static String MODIFIER_UID = "Jimmy Hendrix(jh0003)";
+ public final static String USER_EXTENDED_NAME = "cs0008, Carlos Santana, carlos@email.com, DESIGNER";
+ public final static String UPDATED_USER_EXTENDED_NAME = "cs0008, Carlos Santana, carlos@email.com, TESTER";
+ public final static String VNF_WORKLOAD_CONTEXT = "WORKLOAD";
+ public final static String DPREV_STATUS = "DPREV_STATUS";
+ public final static String DCURR_STATUS = "DCURR_STATUS";
+
+ public final static String CONSUMER_NAME = "consumer";
+ public final static String CONSUMER_SALT = "2a1f887d607d4515d4066fe0f5452a50";
+ public final static String CONSUMER_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b";
+
+ public final static String PREV_RESOURCE_VERSION = "1.0";
+ public final static String PREV_RESOURCE_STATE = "READY_FOR_CERTIFICATION";
+ public final static String COMMENT = "Attempt to perform";
+ public final static String ARTIFACT_DATA = "123456qwertasdfgljkPIPIPIOPI";
+ public final static String TOSCA_NODE_TYPE = "tosca.node.Root";
+ public final static String ARTIFACT_UUID = "1234-ASDFG_7894443";
+ public final static String INVARIANT_UUID = "INV-123456";
+ public final static String USER_DETAILS = "All";
+
+ public final static String STATUS_500 = "500";
+ public final static String DESC_ERROR = "Error";
+ public final static String MSG_ERROR = "Error: ";
+ public final static String MSG_OK = "OK: ";
+
+ public final static String DIST_CONSUMER_ID = "ABC-123445678";
+ public final static String DIST_RESOURCE_URL = "http://abc.com/res";
+ public final static String DIST_STATUS_TOPIC = "STopic";
+ public final static String DIST_NOTIFY_TOPIC = "NTopic";
+ public final static String DIST_API_KEY = "Key111";
+ public final static String DIST_ENV_NAME = "Env111";
+ public final static String DIST_ROLE = "Governer";
+ public final static String DIST_STATUS_TIME = "154567890123";
+
+ public final static String AUTH_URL = "http://abc.com/auth";
+ public final static String REALM = "12345ABSDF";
+ public final static String AUTH_STATUS = "AUTHENTICATED";
+
+ public final static String CATEGORY = "VFs";
+ public final static String SUB_CATEGORY = "Network";
+ public final static String GROUPING_NAME = "Group1";
+
+ public final static String OP_ENV_ID = "12345678";
+ public final static String OP_ENV_NAME = "Op1";
+ public final static String OP_ENV_TYPE = "ECOMP";
+ public final static String OP_ENV_ACTION = "Create";
+ public final static String TENANT_CONTEXT = "TENANT";
+
+ public final static String EXPECTED_USER_ACCESS_LOG_STR = "ACTION = \"" + AuditingActionEnum.USER_ACCESS.getName() + "\" USER = \"" + USER_UID +
+ "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DISTRIB_NOTIFICATION_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_NOTIFY.getName() +
+ "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" +
+ SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + USER_UID + "\" CURR_STATE = \"" + CURRENT_STATE +
+ "\" DID = \"" + DIST_ID + "\" TOPIC_NAME = \"" + TOPIC_NAME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION +
+ "\" TENANT = \"" + TENANT_CONTEXT + "\" VNF_WORKLOAD_CONTEXT = \"" + VNF_WORKLOAD_CONTEXT + "\" ENV_ID = \"" + OP_ENV_ID + "\"";
+
+ public final static String EXPECTED_ADD_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID +
+ "\" USER_BEFORE = \"\" USER_AFTER = \"" + USER_EXTENDED_NAME + "\" STATUS = \"" + STATUS_CREATED + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_UPDATE_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.UPDATE_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID +
+ "\" USER_BEFORE = \"" + USER_EXTENDED_NAME + "\" USER_AFTER = \"" + UPDATED_USER_EXTENDED_NAME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DELETE_USER_LOG_STR = "ACTION = \"" + AuditingActionEnum.DELETE_USER.getName() + "\" MODIFIER = \"" + MODIFIER_UID +
+ "\" USER_BEFORE = \"" + USER_EXTENDED_NAME + "\" USER_AFTER = \"\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_CHECK_IN_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CHECKIN_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" +
+ " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" +
+ PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" COMMENT = \"" + COMMENT + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_CREATE_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" +
+ " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" +
+ PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_IMPORT_RESOURCE_LOG_STR = "ACTION = \"" + AuditingActionEnum.IMPORT_RESOURCE.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" +
+ " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" +
+ PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" TOSCA_NODE_TYPE = \""
+ + TOSCA_NODE_TYPE + "\"";
+
+ public final static String EXPECTED_ARTIFACT_UPLOAD_LOG_STR = "ACTION = \"" + AuditingActionEnum.ARTIFACT_UPLOAD.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\"" + " INVARIANT_UUID = \"" + INVARIANT_UUID + "\"" +
+ " PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_STATE = \"" +
+ PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" PREV_ARTIFACT_UUID = \"" + ARTIFACT_UUID + "\" CURR_ARTIFACT_UUID = \"" +
+ ARTIFACT_UUID + "\" ARTIFACT_DATA = \"" + ARTIFACT_DATA + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DIST_STATE_CHANGE_REQUEST = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" +
+ MODIFIER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + "\" DPREV_STATUS = \"" + DPREV_STATUS + "\" DCURR_STATUS = \"" +
+ DCURR_STATUS + "\" DID = \"" + DIST_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DIST_STATE_CHANGE_APPROV = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE_VFC + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" +
+ MODIFIER_UID + "\" CURR_STATE = \"" + CURRENT_STATE + "\" DPREV_STATUS = \"" + DPREV_STATUS + "\" DCURR_STATUS = \"" +
+ DCURR_STATUS + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" COMMENT = \"" + COMMENT + "\"";
+
+ public final static String EXPECTED_GET_USER_LIST_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_USERS_LIST.getName() + "\" MODIFIER = \"" + USER_UID +
+ "\" DETAILS = \"" + USER_DETAILS + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_ACTIVATE_SERVICE_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName() + "\" RESOURCE_TYPE = \"" +
+ RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" MODIFIER = \"" +
+ MODIFIER_UID + "\" STATUS = \"" + STATUS_OK + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" INVARIANT_UUID = \"" + INVARIANT_UUID +
+ "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR = "CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" +
+ DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL +
+ "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_VERSION = \"" + PREV_RESOURCE_VERSION + "\" CURR_VERSION = \"" + CURRENT_VERSION +
+ "\" PREV_STATE = \"" + PREV_RESOURCE_STATE + "\" CURR_STATE = \"" + CURRENT_STATE + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID +
+ "\" INVARIANT_UUID = \"" + INVARIANT_UUID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR = "ACTION = \"" + AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName() + "\" RESOURCE_NAME = \"" + RESOURCE_NAME +
+ "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL +
+ "\" MODIFIER = \"" + MODIFIER_UID + "\" PREV_ARTIFACT_UUID = \"" + ARTIFACT_UUID + "\" CURR_ARTIFACT_UUID = \"" + ARTIFACT_UUID +
+ "\" ARTIFACT_DATA = \"" + ARTIFACT_DATA + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_GET_ASSET_LIST_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_ASSET_LIST.getName() + "\" CONSUMER_ID = \"" +
+ DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_GET_TOSCA_MODEL_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_TOSCA_MODEL.getName() + "\" CONSUMER_ID = \"" +
+ DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" +
+ RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" + SERVICE_INSTANCE_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_AUTH_REQUEST_LOG_STR = "ACTION = \"" + AuditingActionEnum.AUTH_REQUEST.getName() + "\" URL = \"" +
+ AUTH_URL + "\" USER = \"" + USER_ID + "\" AUTH_STATUS = \"" + AUTH_STATUS + "\" REALM = \"" + REALM + "\"";
+
+ public final static String EXPECTED_ADD_ECOMP_USER_CRED_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS.getName() +
+ "\" MODIFIER = \"" + MODIFIER_UID + "\" ECOMP_USER = \"" + USER_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_GET_ECOMP_USER_CRED_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS.getName() +
+ "\" MODIFIER = \"" + MODIFIER_UID + "\" ECOMP_USER = \"" + USER_ID + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_ADD_CATEGORY_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_CATEGORY.getName() +
+ "\" MODIFIER = \"" + MODIFIER_UID + "\" CATEGORY_NAME = \"" + CATEGORY + "\" SUB_CATEGORY_NAME = \"" + SUB_CATEGORY +
+ "\" GROUPING_NAME = \"" + GROUPING_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ private final static String OP_ENV_LOG = "\" OPERATIONAL_ENVIRONMENT_ACTION = \"" + OP_ENV_ACTION + "\" OPERATIONAL_ENVIRONMENT_ID = \"" + OP_ENV_ID +
+ "\" OPERATIONAL_ENVIRONMENT_NAME = \"" + OP_ENV_NAME + "\" OPERATIONAL_ENVIRONMENT_TYPE = \"" + OP_ENV_TYPE +
+ "\" TENANT_CONTEXT = \"" + TENANT_CONTEXT + "\"";
+
+ public final static String EXPECTED_CREATE_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_ENVIRONMENT.getName() + OP_ENV_LOG;
+
+ public final static String EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName() + OP_ENV_LOG;
+
+ public final static String EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR = "ACTION = \"" + AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName() + OP_ENV_LOG;
+
+ public final static String EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName() +
+ "\" D_ENV = \"" + DIST_ENV_NAME + "\" TOPIC_NAME = \"" + DIST_NOTIFY_TOPIC + "\" ROLE = \"" + DIST_ROLE + "\" API_KEY = \"" +
+ DIST_API_KEY + "\" STATUS = \"" + STATUS_OK + "\"";
+
+ public final static String EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName() +
+ "\" D_ENV = \"" + DIST_ENV_NAME + "\" TOPIC_NAME = \"" + DIST_NOTIFY_TOPIC + "\" STATUS = \"" + STATUS_OK + "\"";
+
+ public final static String EXPECTED_DIST_REG_ENGINE_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_REGISTER.getName() +
+ "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" API_KEY = \"" + DIST_API_KEY + "\" D_ENV = \"" + DIST_ENV_NAME + "\" STATUS = \"" +
+ STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\" DNOTIF_TOPIC = \"" + DIST_NOTIFY_TOPIC + "\" DSTATUS_TOPIC = \"" + DIST_STATUS_TOPIC + "\"";
+
+ public final static String EXPECTED_DIST_STATUS_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_STATUS.getName() +
+ "\" DID = \"" + DIST_ID + "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" TOPIC_NAME = \"" + TOPIC_NAME +
+ "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS_TIME = \"" + DIST_STATUS_TIME + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DIST_DOWNLOAD_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName() +
+ "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" RESOURCE_URL = \"" + DIST_RESOURCE_URL + "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_DISTRIB_DEPLOY_LOG_STR = "ACTION = \"" + AuditingActionEnum.DISTRIBUTION_DEPLOY.getName() +
+ "\" RESOURCE_NAME = \"" + RESOURCE_NAME + "\" RESOURCE_TYPE = \"" + RESOURCE_TYPE + "\" SERVICE_INSTANCE_ID = \"" +
+ SERVICE_INSTANCE_ID + "\" CURR_VERSION = \"" + CURRENT_VERSION + "\" MODIFIER = \"" + USER_UID + "\" DID = \"" + DIST_ID +
+ "\" STATUS = \"" + STATUS_OK + "\" DESC = \"" + DESCRIPTION + "\"";
+
+ public final static String EXPECTED_GET_UEB_CLUSTER_LOG_STR = "ACTION = \"" + AuditingActionEnum.GET_UEB_CLUSTER.getName() +
+ "\" CONSUMER_ID = \"" + DIST_CONSUMER_ID + "\" STATUS = \"" + STATUS_OK + "\" STATUS_DESC = \"" + DESCRIPTION + "\"";
+
+
+ public static User user;
+ public static User modifier;
+
+ public static void init(Configuration.ElasticSearchConfig esConfig) {
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ configurationManager.getConfiguration().setDisableAudit(false);
+ configurationManager.getConfiguration().setElasticSearch(esConfig);
+
+ user = new User();
+ modifier = new User();
+ user.setFirstName(USER_FIRST_NAME);
+ user.setLastName(USER_LAST_NAME);
+ user.setUserId(USER_ID);
+
+ modifier.setFirstName(MODIFIER_FIRST_NAME);
+ modifier.setLastName(MODIFIER_LAST_NAME);
+ modifier.setUserId(MODIFIER_ID);
+ }
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java
new file mode 100644
index 0000000000..a774dea352
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFuncTest.java
@@ -0,0 +1,127 @@
+package org.openecomp.sdc.be.auditing.impl.category;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.CategoryEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CATEGORY;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_CATEGORY_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.GROUPING_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SUB_CATEGORY;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditCategoryEventFuncTest {
+ private AuditingManager auditingManager;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ ThreadLocalsHolder.setUuid(REQUEST_ID);
+ }
+
+ @Test
+ public void testNewAddCategoryEvent() {
+ AuditEventFactory builder = new AuditAddCategoryEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ modifier, CATEGORY, SUB_CATEGORY, GROUPING_NAME, RESOURCE_TYPE);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_CATEGORY.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_ADD_CATEGORY_LOG_STR);
+ verifyCategoryEvent(AuditingActionEnum.ADD_CATEGORY.getName());
+ }
+
+ @Test
+ public void testOldAddEcompUserCredEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_CATEGORY.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_CATEGORY))).isEqualTo(EXPECTED_ADD_CATEGORY_LOG_STR);
+ verifyCategoryEvent(AuditingActionEnum.ADD_CATEGORY.getName());
+
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CATEGORY_NAME, CATEGORY);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SUB_CATEGORY_NAME, SUB_CATEGORY);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_GROUPING_NAME, GROUPING_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+
+ return auditingFields;
+ }
+
+ private void verifyCategoryEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ CategoryEvent storedEvent = (CategoryEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+// assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ assertThat(storedEvent.getCategoryName()).isEqualTo(CATEGORY);
+ assertThat(storedEvent.getSubCategoryName()).isEqualTo(SUB_CATEGORY);
+ assertThat(storedEvent.getGroupingName()).isEqualTo(GROUPING_NAME);
+ assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE);
+
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java
new file mode 100644
index 0000000000..199597b82c
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEngineFuncTest.java
@@ -0,0 +1,191 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_API_KEY;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ENV_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_NOTIFY_TOPIC;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ROLE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_STATUS_TOPIC;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_REG_ENGINE_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditDistrEngineFuncTest {
+ private AuditingManager auditingManager;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ ThreadLocalsHolder.setUuid(REQUEST_ID);
+ }
+
+ @Test
+ public void testNewAddKeyEvent() {
+ AuditEventFactory factory = new AuditAddKeyDistribEngineEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR);
+ verifyEvent(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName());
+ }
+
+ @Test
+ public void testOldAddKeyEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL))).isEqualTo(EXPECTED_DIST_ADD_KEY_ENGINE_LOG_STR);
+ verifyEvent(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL.getName());
+
+ }
+
+ @Test
+ public void testNewCreateTopicEvent() {
+ AuditEventFactory factory = new AuditCreateTopicDistribEngineEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR);
+ verifyEvent(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName());
+ }
+
+ @Test
+ public void testOldCreateTopicEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC))).isEqualTo(EXPECTED_DIST_CREATE_TOPIC_ENGINE_LOG_STR);
+ verifyEvent(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC.getName());
+ }
+
+ @Test
+ public void testNewRegisterEvent() {
+ AuditEventFactory factory = new AuditRegisterDistribEngineEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ DIST_CONSUMER_ID, DIST_STATUS_TOPIC, DIST_NOTIFY_TOPIC, DIST_API_KEY, DIST_ENV_NAME, DIST_ROLE);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_REGISTER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_REG_ENGINE_LOG_STR);
+ verifyEvent(AuditingActionEnum.DISTRIBUTION_REGISTER.getName());
+ }
+
+ @Test
+ public void testOldRegisterEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_REGISTER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_REGISTER))).isEqualTo(EXPECTED_DIST_REG_ENGINE_LOG_STR);
+ verifyEvent(AuditingActionEnum.DISTRIBUTION_REGISTER.getName());
+ }
+
+ private void verifyEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ DistributionEngineEvent storedEvent = (DistributionEngineEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getDnotifTopic()).isEqualTo(DIST_NOTIFY_TOPIC);
+ assertThat(storedEvent.getDstatusTopic()).isEqualTo(DIST_STATUS_TOPIC);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ assertThat(storedEvent.getEnvironmentName()).isEqualTo(DIST_ENV_NAME);
+ assertThat(storedEvent.getApiKey()).isEqualTo(DIST_API_KEY);
+ assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID);
+ assertThat(storedEvent.getRole()).isEqualTo(DIST_ROLE);
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME, DIST_ENV_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME, DIST_STATUS_TOPIC);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME, DIST_NOTIFY_TOPIC);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, DIST_NOTIFY_TOPIC);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY, DIST_API_KEY);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE, DIST_ROLE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+
+ return auditingFields;
+ }
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java
new file mode 100644
index 0000000000..09a168a132
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistrEventFuncTest.java
@@ -0,0 +1,387 @@
+package org.openecomp.sdc.be.auditing.impl.distribution;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGetUebClusterEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionDownloadEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
+import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
+import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_STATUS_TIME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DISTRIB_DEPLOY_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DISTRIB_NOTIFICATION_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_DOWNLOAD_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATUS_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_UEB_CLUSTER_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOPIC_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.VNF_WORKLOAD_CONTEXT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.user;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditDistrEventFuncTest {
+
+ private AuditingManager auditingManager;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ ThreadLocalsHolder.setUuid(REQUEST_ID);
+ }
+
+ @Test
+ public void testNewNotifyEvent() {
+ AuditEventFactory factory = new AuditDistribNotificationEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ CURRENT_STATE, CURRENT_VERSION, DIST_ID, user,
+ RESOURCE_NAME, RESOURCE_TYPE, TOPIC_NAME,
+ new OperationalEnvAuditData(OP_ENV_ID, VNF_WORKLOAD_CONTEXT, TENANT_CONTEXT));
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_NOTIFY.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DISTRIB_NOTIFICATION_LOG_STR);
+ verifyNotifyEvent();
+ }
+
+ @Test
+ public void testOldNotifyEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_NOTIFY.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillNotifyMap())).isEqualTo(EXPECTED_DISTRIB_NOTIFICATION_LOG_STR);
+ verifyNotifyEvent();
+
+ }
+
+ @Test
+ public void testNewStatusEvent() {
+ AuditEventFactory factory = new AuditDistribStatusEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ DIST_ID, DIST_CONSUMER_ID, TOPIC_NAME, DIST_RESOURCE_URL, DIST_STATUS_TIME);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATUS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATUS_LOG_STR);
+ verifyStatusEvent();
+ }
+
+ @Test
+ public void testOldStatusEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATUS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillStatusMap())).isEqualTo(EXPECTED_DIST_STATUS_LOG_STR);
+ verifyStatusEvent();
+ }
+
+ @Test
+ public void testNewDownloadEvent() {
+ AuditEventFactory factory = new AuditDistribDownloadEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL));
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_DOWNLOAD_LOG_STR);
+ verifyDownloadsEvent();
+ }
+
+ @Test
+ public void testOldDownloadEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillDownloadMap())).isEqualTo(EXPECTED_DIST_DOWNLOAD_LOG_STR);
+ verifyDownloadsEvent();
+ }
+
+ @Test
+ public void testNewDeployEvent() {
+ AuditEventFactory factory = new AuditDistribDeployEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ CURRENT_VERSION,
+ DIST_ID, user, RESOURCE_NAME, RESOURCE_TYPE);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_DEPLOY.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DISTRIB_DEPLOY_LOG_STR);
+ verifyDeployEvent();
+ }
+
+ @Test
+ public void testOldDeployEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_DEPLOY.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillDeployMap())).isEqualTo(EXPECTED_DISTRIB_DEPLOY_LOG_STR);
+ verifyDeployEvent();
+ }
+
+ @Test
+ public void testNewGetUebClusterEvent() {
+ AuditEventFactory factory = new AuditGetUebClusterEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ DIST_CONSUMER_ID);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_UEB_CLUSTER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_UEB_CLUSTER_LOG_STR);
+ verifyGetUebClusterEvent();
+ }
+
+ @Test
+ public void testOldGetUebClusterEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_UEB_CLUSTER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillGetUebClusterMap())).isEqualTo(EXPECTED_GET_UEB_CLUSTER_LOG_STR);
+ verifyGetUebClusterEvent();
+ }
+
+ private void verifyNotifyEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ DistributionNotificationEvent storedEvent = (DistributionNotificationEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE);
+ assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
+ assertThat(storedEvent.getDid()).isEqualTo(DIST_ID);
+ assertThat(storedEvent.getModifier()).isEqualTo(USER_UID);
+ assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE);
+ assertThat(storedEvent.getTopicName()).isEqualTo(TOPIC_NAME);
+ assertThat(storedEvent.getVnfWorkloadContext()).isEqualTo(VNF_WORKLOAD_CONTEXT);
+ assertThat(storedEvent.getEnvId()).isEqualTo(OP_ENV_ID);
+ assertThat(storedEvent.getTenant()).isEqualTo(TENANT_CONTEXT);
+ }
+
+ private void verifyStatusEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ DistributionStatusEvent storedEvent = (DistributionStatusEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID);
+ assertThat(storedEvent.getDid()).isEqualTo(DIST_ID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_STATUS.getName());
+ assertThat(storedEvent.getStatusTime()).isEqualTo(DIST_STATUS_TIME);
+ assertThat(storedEvent.getResoureURL()).isEqualTo(DIST_RESOURCE_URL);
+ assertThat(storedEvent.getTopicName()).isEqualTo(TOPIC_NAME);
+ }
+
+ private void verifyDownloadsEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ DistributionDownloadEvent storedEvent = (DistributionDownloadEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL);
+ }
+
+ private void verifyDeployEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ DistributionDeployEvent storedEvent = (DistributionDeployEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getDid()).isEqualTo(DIST_ID);
+ assertThat(storedEvent.getModifier()).isEqualTo(USER_UID);
+ assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE);
+ }
+
+ private void verifyGetUebClusterEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ AuditingGetUebClusterEvent storedEvent = (AuditingGetUebClusterEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getConsumerId()).isEqualTo(DIST_CONSUMER_ID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillNotifyMap() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, USER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, USER_FIRST_NAME + " " + USER_LAST_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, TOPIC_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT, VNF_WORKLOAD_CONTEXT);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT, TENANT_CONTEXT);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID, OP_ENV_ID);
+
+ return auditingFields;
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillStatusMap() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_STATUS.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TOPIC_NAME, TOPIC_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TIME, DIST_STATUS_TIME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID);
+
+ return auditingFields;
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillDownloadMap() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+
+ return auditingFields;
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillDeployMap() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, USER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, USER_FIRST_NAME + " " + USER_LAST_NAME);
+
+ return auditingFields;
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillGetUebClusterMap() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.GET_UEB_CLUSTER.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+
+ return auditingFields;
+ }
+
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java
new file mode 100644
index 0000000000..f859b75607
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/ecompopenv/AuditEcompOpEnvEventTest.java
@@ -0,0 +1,156 @@
+package org.openecomp.sdc.be.auditing.impl.ecompopenv;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditEcompOpEnvEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CREATE_OP_ENV_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditEcompOpEnvEventTest {
+
+ private AuditingManager auditingManager;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ }
+
+ @Test
+ public void testNewCreateOpEnvEvent() {
+ AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.CREATE_ENVIRONMENT,
+ OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_ENVIRONMENT.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CREATE_OP_ENV_LOG_STR);
+ verifyEvent(AuditingActionEnum.CREATE_ENVIRONMENT.getName());
+ }
+
+ @Test
+ public void testOldCreateOpEnvEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_ENVIRONMENT.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_ENVIRONMENT))).isEqualTo(EXPECTED_CREATE_OP_ENV_LOG_STR);
+ verifyEvent(AuditingActionEnum.CREATE_ENVIRONMENT.getName());
+
+ }
+
+ @Test
+ public void testNewUnsupportedTypeOpEnvEvent() {
+ AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE,
+ OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR);
+ verifyEvent(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName());
+ }
+
+ @Test
+ public void testOldUnsupportedTypeOpEnvEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE))).isEqualTo(EXPECTED_UNSUPPORTED_TYPE_OP_ENV_LOG_STR);
+ verifyEvent(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getName());
+ }
+
+ @Test
+ public void testNewUnknownNotificationOpEnvEvent() {
+ AuditEventFactory factory = new AuditEcompOpEnvEventFactory(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION,
+ OP_ENV_ID, OP_ENV_NAME, OP_ENV_TYPE, OP_ENV_ACTION, TENANT_CONTEXT);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR);
+ verifyEvent(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName());
+ }
+
+ @Test
+ public void testOldUnknownNotificationOpEnvEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION))).isEqualTo(EXPECTED_UNKNOWN_NOTIFICATION_OP_ENV_LOG_STR);
+ verifyEvent(AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION.getName());
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID, OP_ENV_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE, OP_ENV_TYPE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME, OP_ENV_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION, OP_ENV_ACTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT, TENANT_CONTEXT);
+
+ return auditingFields;
+ }
+
+ private void verifyEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ EcompOperationalEnvironmentEvent storedEvent = (EcompOperationalEnvironmentEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ assertThat(storedEvent.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID);
+ assertThat(storedEvent.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME);
+ assertThat(storedEvent.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE);
+ assertThat(storedEvent.getTenantContext()).isEqualTo(TENANT_CONTEXT);
+
+
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java
new file mode 100644
index 0000000000..7ddc9a0606
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFuncTest.java
@@ -0,0 +1,368 @@
+package org.openecomp.sdc.be.auditing.impl.externalapi;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ExternalApiEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ACTIVATE_SERVICE_API_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_ASSET_LIST_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_TOSCA_MODEL_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditExternalApiEventFuncTest {
+
+ private AuditingManager auditingManager;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ }
+
+ @Test
+ public void testNewActivateServiceEvent() {
+ AuditEventFactory builder = new AuditActivateServiceExternalApiEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .build(),
+ INVARIANT_UUID, modifier, ARTIFACT_DATA);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_ACTIVATE_SERVICE_API_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName());
+ }
+
+ @Test
+ public void testOldActivateServiceEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ACTIVATE_SERVICE_BY_API))).isEqualTo(EXPECTED_ACTIVATE_SERVICE_API_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.ACTIVATE_SERVICE_BY_API.getName());
+
+ }
+
+ @Test
+ public void testNewDownloadArtifactEvent() {
+ AuditEventFactory builder = new AuditDownloadArtifactExternalApiEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .build(),
+ INVARIANT_UUID, modifier, ARTIFACT_DATA);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DOWNLOAD_ARTIFACT.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.DOWNLOAD_ARTIFACT.getName());
+ }
+
+ @Test
+ public void testOldDownloadArtifactEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DOWNLOAD_ARTIFACT.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DOWNLOAD_ARTIFACT))).isEqualTo(EXPECTED_DOWNLOAD_ARTIFACT_EXTERNAL_API_LOG_STR + " ");
+ verifyExternalApiEvent(AuditingActionEnum.DOWNLOAD_ARTIFACT.getName());
+ }
+
+ @Test
+ public void testNewChangeLifecycleEvent() {
+ AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .build(),
+ INVARIANT_UUID, modifier, ARTIFACT_DATA);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName());
+ }
+
+ @Test
+ public void testOldChangeLifecycleEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API))).isEqualTo(EXPECTED_CHANGE_LIFECYCLE_EXTERNAL_API_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API.getName());
+
+ }
+
+ @Test
+ public void testNewDeleteArtifactEvent() {
+ AuditEventFactory factory = new AuditDeleteArtByApiCrudExternalApiEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .build(),
+ INVARIANT_UUID, modifier, ARTIFACT_DATA);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName());
+ }
+
+ @Test
+ public void testOldDeleteArtifactEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ARTIFACT_DELETE_BY_API))).isEqualTo(EXPECTED_DELETE_ARTIFACT_EXTERNAL_API_LOG_STR + " ");
+ verifyExternalApiEvent(AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName());
+
+ }
+
+ @Test
+ public void testNewGetAssetsListEvent() {
+ AuditEventFactory factory = new AuditGetAssetListExternalApiEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .build(),
+ INVARIANT_UUID, modifier, ARTIFACT_DATA);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_ASSET_LIST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_ASSET_LIST_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.GET_ASSET_LIST.getName());
+ }
+
+ @Test
+ public void testOldGetAssetsListEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_ASSET_LIST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_ASSET_LIST))).isEqualTo(EXPECTED_GET_ASSET_LIST_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.GET_ASSET_LIST.getName());
+ }
+
+ @Test
+ public void testNewGetToscaModelEvent() {
+ AuditEventFactory factory = new AuditGetToscaModelExternalApiEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ RESOURCE_TYPE, RESOURCE_NAME, DIST_CONSUMER_ID, DIST_RESOURCE_URL,
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .build(),
+ INVARIANT_UUID, modifier, ARTIFACT_DATA);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_TOSCA_MODEL.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_TOSCA_MODEL_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.GET_TOSCA_MODEL.getName());
+ }
+
+ @Test
+ public void testOldGetToscaModelEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_TOSCA_MODEL.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.GET_TOSCA_MODEL))).isEqualTo(EXPECTED_GET_TOSCA_MODEL_LOG_STR);
+ verifyExternalApiEvent(AuditingActionEnum.GET_TOSCA_MODEL.getName());
+ }
+
+ private void verifyExternalApiEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ ExternalApiEvent storedEvent = (ExternalApiEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ assertThat(storedEvent.getArtifactData()).isEqualTo(ARTIFACT_DATA);
+ assertThat(storedEvent.getCurrArtifactUuid()).isEqualTo(ARTIFACT_UUID);
+ assertThat(storedEvent.getPrevArtifactUuid()).isEqualTo(ARTIFACT_UUID);
+ assertThat(storedEvent.getPrevState()).isEqualTo(PREV_RESOURCE_STATE);
+ assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE);
+ assertThat(storedEvent.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION);
+ assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION);
+ assertThat(storedEvent.getInvariantUuid()).isEqualTo(INVARIANT_UUID);
+ assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE);
+
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, PREV_RESOURCE_VERSION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, PREV_RESOURCE_STATE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, INVARIANT_UUID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ARTIFACT_DATA);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ARTIFACT_UUID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ARTIFACT_UUID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, DIST_CONSUMER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, DIST_RESOURCE_URL);
+ return auditingFields;
+ }
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java
new file mode 100644
index 0000000000..18bd41c765
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFuncTest.java
@@ -0,0 +1,432 @@
+package org.openecomp.sdc.be.auditing.impl.resourceadmin;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ARTIFACT_UPLOAD_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CHECK_IN_RESOURCE_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_CREATE_RESOURCE_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATE_CHANGE_APPROV;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DIST_STATE_CHANGE_REQUEST;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_IMPORT_RESOURCE_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_TYPE_VFC;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditResourceAdminEventFuncTest {
+ private AuditingManager auditingManager;
+
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Mock
+ private static ConfigurationSource configurationSource;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private static Configuration.ElasticSearchConfig esConfig;
+
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ ThreadLocalsHolder.setUuid(REQUEST_ID);
+ }
+
+ @Test
+ public void testNewCheckInResourceAdminEvent() {
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.setUUID(SERVICE_INSTANCE_ID);
+ resource.setInvariantUUID(INVARIANT_UUID);
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resource.setVersion(CURRENT_VERSION);
+
+ AuditEventFactory factory = new AuditCertificationResourceAdminEventFactory(
+ AuditingActionEnum.CHECKIN_RESOURCE,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .distributionStatus(DPREV_STATUS)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .distributionStatus(DCURR_STATUS)
+ .build(),
+ RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier,
+ ARTIFACT_DATA, COMMENT, DIST_ID);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CHECKIN_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CHECK_IN_RESOURCE_LOG_STR);
+ verifyResourceAdminEvent(AuditingActionEnum.CHECKIN_RESOURCE.getName());
+ }
+
+ @Test
+ public void testOldCheckInResourceAdminEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CHECKIN_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CHECKIN_RESOURCE))).isEqualTo(EXPECTED_CHECK_IN_RESOURCE_LOG_STR + " ");
+ verifyResourceAdminEvent(AuditingActionEnum.CHECKIN_RESOURCE.getName());
+
+ }
+
+ private EnumMap<AuditingFieldsKeysEnum, Object> fillMap(AuditingActionEnum action) {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, action.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, RESOURCE_TYPE_VFC);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, PREV_RESOURCE_VERSION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE, PREV_RESOURCE_STATE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, RESOURCE_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, CURRENT_VERSION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE, CURRENT_STATE);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, SERVICE_INSTANCE_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID, INVARIANT_UUID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, ARTIFACT_DATA);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, ARTIFACT_UUID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, ARTIFACT_UUID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, DIST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, COMMENT);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, DCURR_STATUS);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, DPREV_STATUS);
+
+ if (action == AuditingActionEnum.IMPORT_RESOURCE) {
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, TOSCA_NODE_TYPE);
+ }
+ else {
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TOSCA_NODE_TYPE, Constants.EMPTY_STRING);
+ }
+
+ return auditingFields;
+ }
+
+ @Test
+ public void testNewCreateResourceAdminEvent() {
+
+ AuditEventFactory factory = new AuditCreateUpdateResourceAdminEventFactory(
+ AuditingActionEnum.CREATE_RESOURCE,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .distributionStatus(DPREV_STATUS)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .distributionStatus(DCURR_STATUS)
+ .build(),
+ RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier,
+ ARTIFACT_DATA, COMMENT, DIST_ID, Constants.EMPTY_STRING);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.CREATE_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_CREATE_RESOURCE_LOG_STR);
+ verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName());
+ }
+
+ @Test
+ public void testOldCreateResourceAdminEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.CREATE_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.CREATE_RESOURCE))).isEqualTo(EXPECTED_CREATE_RESOURCE_LOG_STR + " ");
+ verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName());
+
+ }
+
+ @Test
+ public void testNewImportResourceAdminEvent() {
+
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.setVersion(CURRENT_VERSION);
+ resource.setInvariantUUID(INVARIANT_UUID);
+ resource.setUUID(SERVICE_INSTANCE_ID);
+ resource.setState(LifecycleStateEnum.CERTIFIED);
+ resource.setToscaType(TOSCA_NODE_TYPE);
+
+ AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .distributionStatus(DPREV_STATUS)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .distributionStatus(DCURR_STATUS)
+ .build(),
+ RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier,
+ ARTIFACT_DATA, COMMENT, DIST_ID, TOSCA_NODE_TYPE);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_IMPORT_RESOURCE_LOG_STR);
+ verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName());
+ }
+
+ @Test
+ public void testOldImportResourceAdminEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.IMPORT_RESOURCE))).isEqualTo(EXPECTED_IMPORT_RESOURCE_LOG_STR + " ");
+ verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName());
+
+ }
+
+ @Test
+ public void testNewArtifactUploadResourceAdminEvent() {
+
+ AuditEventFactory factory = new AuditArtifactResourceAdminEventFactory(
+ AuditingActionEnum.ARTIFACT_UPLOAD,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .distributionStatus(DPREV_STATUS)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .distributionStatus(DCURR_STATUS)
+ .build(),
+ RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier,
+ ARTIFACT_DATA, COMMENT, DIST_ID);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ARTIFACT_UPLOAD.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ARTIFACT_UPLOAD_LOG_STR);
+ verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_UPLOAD.getName());
+ }
+
+ @Test
+ public void testOldArtifactUploadResourceAdminEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.IMPORT_RESOURCE.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.ARTIFACT_UPLOAD))).isEqualTo(EXPECTED_ARTIFACT_UPLOAD_LOG_STR + " ");
+ verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_UPLOAD.getName());
+
+ }
+
+ @Test
+ public void testNewDistStateChangeRequestResourceAdminEvent() {
+
+ AuditEventFactory factory = new AuditDistStateChangeRequestResourceAdminEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .distributionStatus(DPREV_STATUS)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .distributionStatus(DCURR_STATUS)
+ .build(),
+ RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier,
+ ARTIFACT_DATA, COMMENT, DIST_ID);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATE_CHANGE_REQUEST);
+ verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
+ }
+
+ @Test
+ public void testOldDistStateChangeRequestResourceAdminEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST))).isEqualTo(EXPECTED_DIST_STATE_CHANGE_REQUEST);
+ verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
+ }
+
+ @Test
+ public void testNewDistStateChangeApprovResourceAdminEvent() {
+
+ AuditEventFactory factory = new AuditDistStateChangeResourceAdminEventFactory(
+ AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .serviceInstanceId(SERVICE_INSTANCE_ID)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .distributionStatus(DPREV_STATUS)
+ .build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .distributionStatus(DCURR_STATUS)
+ .build(),
+ RESOURCE_TYPE_VFC, RESOURCE_NAME, INVARIANT_UUID, modifier,
+ ARTIFACT_DATA, COMMENT, DIST_ID);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DIST_STATE_CHANGE_APPROV);
+ verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName());
+ }
+
+ @Test
+ public void testOldDistStateChangeApprovResourceAdminEvent() {
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(fillMap(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV))).isEqualTo(EXPECTED_DIST_STATE_CHANGE_APPROV);
+ verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV.getName());
+ }
+
+
+ private void verifyResourceAdminEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ ResourceAdminEvent storedEvent = (ResourceAdminEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(storedEvent.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ assertThat(storedEvent.getArtifactData()).isEqualTo(ARTIFACT_DATA);
+ assertThat(storedEvent.getComment()).isEqualTo(COMMENT);
+ assertThat(storedEvent.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID);
+ assertThat(storedEvent.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID);
+ assertThat(storedEvent.getPrevState()).isEqualTo(PREV_RESOURCE_STATE);
+ assertThat(storedEvent.getCurrState()).isEqualTo(CURRENT_STATE);
+ assertThat(storedEvent.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION);
+ assertThat(storedEvent.getCurrVersion()).isEqualTo(CURRENT_VERSION);
+ assertThat(storedEvent.getDcurrStatus()).isEqualTo(DCURR_STATUS);
+ assertThat(storedEvent.getDprevStatus()).isEqualTo(DPREV_STATUS);
+ assertThat(storedEvent.getDid()).isEqualTo(DIST_ID);
+ assertThat(storedEvent.getInvariantUUID()).isEqualTo(INVARIANT_UUID);
+ assertThat(storedEvent.getResourceName()).isEqualTo(RESOURCE_NAME);
+ assertThat(storedEvent.getResourceType()).isEqualTo(RESOURCE_TYPE_VFC);
+
+ if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) {
+ assertThat(storedEvent.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE);
+ } else {
+ assertThat(storedEvent.getToscaNodeType()).isEmpty();
+ }
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java
new file mode 100644
index 0000000000..4a5b1bbd59
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserEventFuncTest.java
@@ -0,0 +1,395 @@
+package org.openecomp.sdc.be.auditing.impl.usersadmin;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditAuthRequestEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.impl.AuditingDao;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
+import org.openecomp.sdc.be.resources.data.auditing.AuthEvent;
+import org.openecomp.sdc.be.resources.data.auditing.GetUsersListEvent;
+import org.openecomp.sdc.be.resources.data.auditing.UserAccessEvent;
+import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import java.util.EnumMap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.AUTH_STATUS;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.AUTH_URL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESIGNER_USER_ROLE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_ADD_USER_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_AUTH_REQUEST_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_DELETE_USER_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_GET_USER_LIST_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_UPDATE_USER_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.EXPECTED_USER_ACCESS_LOG_STR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REALM;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_CREATED;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_DETAILS;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EXTENDED_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.init;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.modifier;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.user;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditUserEventFuncTest {
+ @Mock
+ private static AuditCassandraDao cassandraDao;
+ @Captor
+ private ArgumentCaptor<AuditingGenericEvent> eventCaptor;
+ @Mock
+ private static AuditingDao auditingDao;
+ @Mock
+ private Configuration.ElasticSearchConfig esConfig;
+
+ private AuditingManager auditingManager;
+
+ @Before
+ public void setUp() {
+ init(esConfig);
+ auditingManager = new AuditingManager(auditingDao, cassandraDao);
+ }
+
+ @Test
+ public void testNewUserAccessEvent() {
+ AuditEventFactory factory = new AuditUserAccessEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .build(),
+ user);
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.USER_ACCESS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_USER_ACCESS_LOG_STR);
+ verifyUserAccessEvent();
+ }
+
+ @Test
+ public void testOldUserAccessEvent() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.USER_ACCESS.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_UID, user.getFirstName() + " " + user.getLastName() + '(' + user.getUserId() + ')');
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.USER_ACCESS.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_USER_ACCESS_LOG_STR);
+ verifyUserAccessEvent();
+ }
+
+ @Test
+ public void testNewUserAdminEventForAddUser() {
+
+ user.setRole(DESIGNER_USER_ROLE);
+ user.setEmail(USER_EMAIL);
+
+ AuditEventFactory factory = new AuditUserAdminEventFactory(AuditingActionEnum.ADD_USER,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_CREATED)
+ .requestId(REQUEST_ID)
+ .build(),
+ modifier, null, user);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.ADD_USER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_ADD_USER_LOG_STR);
+ verifyUserEvent(AuditingActionEnum.ADD_USER.getName());
+ }
+
+ @Test
+ public void testOldUserAdminEventForAddUser() {
+ user.setRole(TESTER_USER_ROLE);
+ user.setEmail(USER_EMAIL);
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.ADD_USER.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_CREATED);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, null);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, USER_EXTENDED_NAME);
+
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.ADD_USER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_ADD_USER_LOG_STR);
+ verifyUserEvent(AuditingActionEnum.ADD_USER.getName());
+ }
+
+ @Test
+ public void testNewUserAdminEventForUpdateUser() {
+
+ user.setRole(DESIGNER_USER_ROLE);
+ user.setEmail(USER_EMAIL);
+
+ User updated = new User(user);
+ updated.setRole(TESTER_USER_ROLE);
+
+ AuditEventFactory builder = new AuditUserAdminEventFactory(AuditingActionEnum.UPDATE_USER,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .build(),
+ modifier, user, updated);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.UPDATE_USER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(builder)).isEqualTo(EXPECTED_UPDATE_USER_LOG_STR);
+ verifyUserEvent(AuditingActionEnum.UPDATE_USER.getName());
+ }
+
+ @Test
+ public void testOldUserAdminEventForUpdateUser() {
+ user.setRole(DESIGNER_USER_ROLE);
+ user.setEmail(USER_EMAIL);
+
+ User updated = new User(user);
+ updated.setRole(TESTER_USER_ROLE);
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.UPDATE_USER.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, USER_EXTENDED_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, UPDATED_USER_EXTENDED_NAME);
+
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.UPDATE_USER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_UPDATE_USER_LOG_STR);
+ verifyUserEvent(AuditingActionEnum.UPDATE_USER.getName());
+ }
+
+ @Test
+ public void testNewUserAdminEventForDeleteUser() {
+
+ user.setRole(DESIGNER_USER_ROLE);
+ user.setEmail(USER_EMAIL);
+
+ AuditEventFactory factory = new AuditUserAdminEventFactory(AuditingActionEnum.DELETE_USER,
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .build(),
+ modifier, user, null);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.DELETE_USER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_DELETE_USER_LOG_STR);
+ verifyUserEvent(AuditingActionEnum.DELETE_USER.getName());
+ }
+
+ @Test
+ public void testOldUserAdminEventForDeleteUser() {
+ user.setRole(TESTER_USER_ROLE);
+ user.setEmail(USER_EMAIL);
+
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.DELETE_USER.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, modifier.getFirstName() + " " + modifier.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, modifier.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_BEFORE, USER_EXTENDED_NAME);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_AFTER, null);
+
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.DELETE_USER.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_DELETE_USER_LOG_STR);
+ verifyUserEvent(AuditingActionEnum.DELETE_USER.getName());
+ }
+
+ @Test
+ public void testNewGetUserListEvent() {
+
+ AuditEventFactory factory = new AuditGetUsersListEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .build(),
+ user, USER_DETAILS);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.GET_USERS_LIST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_GET_USER_LIST_LOG_STR);
+ verifyGetUserListEvent();
+ }
+
+ @Test
+ public void testOldGetUserListEvent() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.GET_USERS_LIST.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, user.getFirstName() + " " + user.getLastName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID, user.getUserId());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS, USER_DETAILS);
+
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.GET_USERS_LIST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_GET_USER_LIST_LOG_STR);
+ verifyGetUserListEvent();
+ }
+
+ @Test
+ public void testNewAuthRequestEvent() {
+
+ AuditEventFactory factory = new AuditAuthRequestEventFactory(
+ CommonAuditData.newBuilder()
+ .description(DESCRIPTION)
+ .status(STATUS_OK)
+ .requestId(REQUEST_ID)
+ .build(),
+ USER_ID, AUTH_URL, REALM, AUTH_STATUS);
+
+ when(auditingDao.addRecord(any(AuditingGenericEvent.class), eq(AuditingActionEnum.AUTH_REQUEST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(factory)).isEqualTo(EXPECTED_AUTH_REQUEST_LOG_STR);
+ verifyAuthRequestEvent();
+ }
+
+ @Test
+ public void testOldAuthRequestEvent() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, AuditingActionEnum.AUTH_REQUEST.getName());
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_USER, USER_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_STATUS, STATUS_OK);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, DESCRIPTION);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID, REQUEST_ID);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_REALM, REALM);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL, AUTH_URL);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_STATUS, AUTH_STATUS);
+
+ when(auditingDao.addRecord(anyMap(), eq(AuditingActionEnum.AUTH_REQUEST.getAuditingEsType())))
+ .thenReturn(ActionStatus.OK);
+ when(cassandraDao.saveRecord(any(AuditingGenericEvent.class))).thenReturn(CassandraOperationStatus.OK);
+
+ assertThat(auditingManager.auditEvent(auditingFields)).isEqualTo(EXPECTED_AUTH_REQUEST_LOG_STR);
+ verifyAuthRequestEvent();
+ }
+
+
+ private void verifyUserEvent(String action) {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ UserAdminEvent storedEvent = (UserAdminEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+// assertThat(storedEvent.getRequestId()).isEqualTo(REQUEST_ID); - it is not filled out by the old code!!!
+ assertThat(storedEvent.getServiceInstanceId()).isNull();
+ assertThat(storedEvent.getAction()).isEqualTo(action);
+ if (action.equals(AuditingActionEnum.ADD_USER.getName())) {
+ //TODO enable this test after deleting the old auditEvent method
+// assertThat(storedEvent.getUserBefore()).isNull();
+ assertThat(storedEvent.getUserAfter()).isEqualTo(USER_EXTENDED_NAME);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_CREATED);
+ }
+ else if (action.equals(AuditingActionEnum.UPDATE_USER.getName())){
+ assertThat(storedEvent.getUserBefore()).isEqualTo(USER_EXTENDED_NAME);
+ assertThat(storedEvent.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ }
+ else {
+ assertThat(storedEvent.getUserBefore()).isEqualTo(USER_EXTENDED_NAME);
+ //TODO enable this test after deleting the old auditEvent method
+// assertThat(storedEvent.getUserAfter()).isNull();
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ }
+ }
+
+ private void verifyGetUserListEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ GetUsersListEvent storedEvent = (GetUsersListEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getModifier()).isEqualTo(USER_UID);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getServiceInstanceId()).isNull();
+ assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.GET_USERS_LIST.getName());
+ }
+
+ private void verifyUserAccessEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ UserAccessEvent storedEvent = (UserAccessEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getUserUid()).isEqualTo(USER_UID);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getRequestId()).isNotBlank();
+ assertThat(storedEvent.getServiceInstanceId()).isNull();
+ assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.USER_ACCESS.getName());
+ }
+
+ private void verifyAuthRequestEvent() {
+ verify(cassandraDao).saveRecord(eventCaptor.capture());
+ AuthEvent storedEvent = (AuthEvent) eventCaptor.getValue();
+ assertThat(storedEvent.getUser()).isEqualTo(USER_ID);
+ assertThat(storedEvent.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(storedEvent.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(storedEvent.getRequestId()).isNotBlank();
+ assertThat(storedEvent.getServiceInstanceId()).isNull();
+ assertThat(storedEvent.getAuthStatus()).isEqualTo(AUTH_STATUS);
+ assertThat(storedEvent.getUrl()).isEqualTo(AUTH_URL);
+ assertThat(storedEvent.getRealm()).isEqualTo(REALM);
+ assertThat(storedEvent.getAction()).isEqualTo(AuditingActionEnum.AUTH_REQUEST.getName());
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java
index 87dfbc45de..06c22bca69 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/AuditingManagerTest.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,56 +20,53 @@
package org.openecomp.sdc.be.components;
-import static org.mockito.Mockito.when;
-
-import java.util.EnumMap;
-import java.util.UUID;
-
import org.junit.Before;
import org.junit.Test;
-import org.mockito.InjectMocks;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
+import org.mockito.junit.MockitoJUnitRunner;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.impl.AuditingDao;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.util.ThreadLocalsHolder;
-import junit.framework.Assert;
+import java.util.EnumMap;
+import java.util.UUID;
-public class AuditingManagerTest extends BaseConfDependentTest{
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
- @InjectMocks
- private AuditingManager auditingManager = Mockito.spy(AuditingManager.class);
- public static final AuditingDao auditingDao = Mockito.mock(AuditingDao.class);
+@RunWith(MockitoJUnitRunner.class)
+public class AuditingManagerTest extends BeConfDependentTest {
- public AuditingManagerTest() {
- }
+ private AuditingManager auditingManager;
+ @Mock
+ private AuditingDao auditingDao;
- @SuppressWarnings("unchecked")
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK);
+ @Before
+ public void setup() {
+ auditingManager = new AuditingManager(auditingDao, null);
+ when(auditingDao.addRecord(Mockito.anyMap(), Mockito.anyString())).thenReturn(ActionStatus.OK);
- }
+ }
- @Test
- public void testNormalizeEmptyStringValuesAndUuid() {
- EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create");
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null);
- auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null ");
+ @Test
+ public void testNormalizeEmptyStringValuesAndUuid() {
+ EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<>(AuditingFieldsKeysEnum.class);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Create");
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DESC, null);
+ auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, " null ");
- String randomUUID = UUID.randomUUID().toString();
- ThreadLocalsHolder.setUuid(randomUUID);
+ String randomUUID = UUID.randomUUID().toString();
+ ThreadLocalsHolder.setUuid(randomUUID);
- auditingManager.auditEvent(auditingFields);
- // Checking normalization
- Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC), Constants.EMPTY_STRING);
- Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT), Constants.EMPTY_STRING);
- Assert.assertEquals(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID), randomUUID);
- }
+ auditingManager.auditEvent(auditingFields);
+ // Checking normalization
+ assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC).toString()).isEmpty();
+ assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT).toString()).isEmpty();
+ assertThat(auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID)).isEqualTo(randomUUID);
+ }
}
+
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java
new file mode 100644
index 0000000000..bbd827eb23
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseServiceBusinessLogicTest.java
@@ -0,0 +1,355 @@
+package org.openecomp.sdc.be.components;
+
+import com.google.common.collect.Sets;
+import fj.data.Either;
+import org.junit.Before;
+import org.mockito.Mockito;
+import org.openecomp.sdc.ElementOperationMock;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
+import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.context.WebApplicationContext;
+
+import javax.servlet.ServletContext;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+public class BaseServiceBusinessLogicTest {
+ private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class);
+ private static final String SERVICE_CATEGORY = "Mobility";
+ final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
+ WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
+ ServiceBusinessLogic bl = new ServiceBusinessLogic();
+ ResponseFormatManager responseManager = null;
+ IElementOperation mockElementDao;
+ ComponentsUtils componentsUtils;
+ AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
+ ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
+ GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
+ TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
+ ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
+ GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
+ ForwardingPathOperation forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class);
+
+ User user = null;
+ Service serviceResponse = null;
+ Resource genericService = null;
+
+ protected static final String CERTIFIED_VERSION = "1.0";
+ protected static final String UNCERTIFIED_VERSION = "0.2";
+ protected static final String COMPONNET_ID = "myUniqueId";
+ protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
+ protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<>();
+ protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<>();
+ protected static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<>();
+ @Before
+ public void setup() {
+
+ ExternalConfiguration.setAppName("catalog-be");
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+
+ // Elements
+ mockElementDao = new ElementOperationMock();
+
+ // User data and management
+ user = new User();
+ user.setUserId("jh0003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+
+ Either<User, ActionStatus> eitherGetUser = Either.left(user);
+ when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
+
+ // Servlet Context attributes
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
+ when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
+ when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
+ when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
+
+ // artifact bussinesslogic
+ ArtifactDefinition artifactDef = new ArtifactDefinition();
+ when(artifactBl.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
+
+ // createService
+ serviceResponse = createServiceObject(true);
+ Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
+ when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
+ Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
+ when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
+ Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
+ when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
+
+ genericService = setupGenericServiceMock();
+ Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
+
+ //forwardingPath
+ when(forwardingPathOperation.addForwardingPath(any(),any())).thenReturn(Either.left(createMockPath()));
+ when(forwardingPathOperation.updateForwardingPath(any(),any())).thenReturn(Either.left(createMockPath()));
+ when(forwardingPathOperation.deleteForwardingPath(any(),any())).thenReturn(Either.left(Sets.newHashSet("Wow-It-Works")));
+ when(toscaOperationFacade.getToscaElement("delete_forward_test")).thenReturn(Either.left(createServiceObject(true)));
+
+ bl = new ServiceBusinessLogic();
+ bl.setElementDao(mockElementDao);
+ bl.setUserAdmin(mockUserAdmin);
+ bl.setArtifactBl(artifactBl);
+ bl.setGraphLockOperation(graphLockOperation);
+ bl.setTitanGenericDao(mockTitanDao);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
+ bl.setComponentsUtils(componentsUtils);
+ bl.setCassandraAuditingDao(auditingDao);
+ bl.setCacheManagerOperation(cacheManager);
+ bl.setForwardingPathOperation(forwardingPathOperation);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ mockAuditingDaoLogic();
+
+ responseManager = ResponseFormatManager.getInstance();
+
+ }
+
+ protected Component createNewService() {
+
+ Service service = new Service();
+ int listSize = 3;
+ service.setName("serviceName");
+ service.setUniqueId("serviceUniqueId");
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ ComponentInstance ci;
+ for(int i= 0; i<listSize; ++i){
+ ci = new ComponentInstance();
+ ci.setName("ciName" + i);
+ ci.setUniqueId("ciId" + i);
+ List<GroupInstance> groupInstances= new ArrayList<>();
+ GroupInstance gi;
+ for(int j = 0; j<listSize; ++j){
+ gi = new GroupInstance();
+ gi.setName(ci.getName( )+ "giName" + j);
+ gi.setUniqueId(ci.getName() + "giId" + j);
+ groupInstances.add(gi);
+ }
+ ci.setGroupInstances(groupInstances);
+ componentInstances.add(ci);
+ }
+ service.setComponentInstances(componentInstances);
+ return service;
+ }
+
+ private void mockAuditingDaoLogic() {
+ FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
+ FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
+ FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
+
+ FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
+ FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
+
+ final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
+ createResourceAudit.setModifier("Carlos Santana(cs0008)");
+ createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
+ createResourceAudit.setCurrVersion("0.1");
+ createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
+ createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
+ createResourceAudit.setDesc("OK");
+ createResourceAudit.setResourceType("Resource");
+ createResourceAudit.setStatus("201");
+ createResourceAudit.setPrevVersion("");
+ createResourceAudit.setAction("Create");
+ // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
+ createResourceAudit.setPrevState("");
+ createResourceAudit.setResourceName("MyTestResource");
+ // createResourceAudit.setFields(fields);
+
+ final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
+ checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
+ checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
+ checkInResourceAudit.setCurrVersion("0.1");
+ checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
+ checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
+ checkInResourceAudit.setDesc("OK");
+ checkInResourceAudit.setComment("Stam");
+ checkInResourceAudit.setResourceType("Resource");
+ checkInResourceAudit.setStatus("200");
+ checkInResourceAudit.setPrevVersion("0.1");
+ checkInResourceAudit.setAction("Checkin");
+ // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
+ checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
+ checkInResourceAudit.setResourceName("MyTestResource");
+
+ final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
+ checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
+ checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
+ checkOutResourceAudit.setCurrVersion("0.2");
+ checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
+ checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
+ checkOutResourceAudit.setDesc("OK");
+ checkOutResourceAudit.setComment("");
+ checkOutResourceAudit.setResourceType("Resource");
+ checkOutResourceAudit.setStatus("200");
+ checkOutResourceAudit.setPrevVersion("0.1");
+ checkOutResourceAudit.setAction("Checkout");
+ // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
+ checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
+ checkOutResourceAudit.setResourceName("MyTestResource");
+ // checkOutResourceAudit.setFields(fields);
+
+ // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>,
+ // ActionStatus> >() {
+ // public Either<List<ESTimeBasedEvent>, ActionStatus>
+ // answer(InvocationOnMock invocation) {
+ // final Either<List<ESTimeBasedEvent>, ActionStatus> either;
+ // final List<ESTimeBasedEvent> list;
+ // Object[] args = invocation.getArguments();
+ // Map<AuditingFieldsKeysEnum, Object> filterMap =
+ // (Map<AuditingFieldsKeysEnum, Object>) args[0];
+ // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){
+ // list = new
+ // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}};
+ // either = Either.left(list);
+ //
+ // }
+ // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){
+ // list = new ArrayList<ESTimeBasedEvent>();
+ // either = Either.left(list);
+ // }
+ // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){
+ // list = new
+ // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}};
+ // either = Either.left(list);
+ // }
+ // else{
+ // either = null;
+ // }
+ // return either;
+ // }
+ // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap());
+ //
+ //
+ List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
+ {
+ add(createResourceAudit);
+ add(checkInResourceAudit);
+ add(checkOutResourceAudit);
+ }
+ };
+ Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
+ Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
+
+ List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
+ Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
+ Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
+
+ List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
+ {
+ add(checkOutResourceAudit);
+ }
+ };
+ Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
+ Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
+
+ }
+
+ protected Service createServiceObject(boolean afterCreate) {
+ Service service = new Service();
+ service.setName("Service");
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName(SERVICE_CATEGORY);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ service.setCategories(categories);
+
+ service.setDescription("description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add(service.getName());
+ service.setTags(tgs);
+ // service.setVendorName("Motorola");
+ // service.setVendorRelease("1.0.0");
+ service.setIcon("MyIcon");
+ // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ service.setContactId("aa1234");
+ service.setProjectCode("12345");
+
+ if (afterCreate) {
+ service.setVersion("0.1");
+ service.setUniqueId(service.getName() + ":" + service.getVersion());
+ service.setCreatorUserId(user.getUserId());
+ service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ }
+ return service;
+ }
+
+ protected Resource setupGenericServiceMock(){
+ Resource genericService = new Resource();
+ genericService.setVersion("1.0");
+ genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
+ return genericService;
+ }
+
+ protected static ForwardingPathDataDefinition forwardingPathDataDefinition;
+
+ protected static ForwardingPathDataDefinition createMockPath() {
+ if (forwardingPathDataDefinition != null){
+ return forwardingPathDataDefinition ;
+ }
+ forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo");
+ forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString());
+ forwardingPathDataDefinition.setDestinationPortNumber("414155");
+ forwardingPathDataDefinition.setProtocol("http");
+ org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition> forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>();
+ forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode","toNode", "333","444","2222","5555"));
+ forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode","toNode2", "4444","44444","4","44"));
+ forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition);
+ return forwardingPathDataDefinition;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java
index 3d242e8c52..01d003f2a4 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/BeConfDependentTest.java
@@ -18,20 +18,17 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes.enums;
+package org.openecomp.sdc.be.components;
-public enum ComponentType {
+import org.junit.BeforeClass;
+import org.openecomp.sdc.common.test.BaseConfDependent;
- RESOURCE("Resource"), SERVICE("Service"), ARTIFACT("Artifact");
+public class BeConfDependentTest extends BaseConfDependent {
+ @BeforeClass
+ public static void setupBeforeClass() {
+ componentName = "catalog-be";
+ confPath = "src/test/resources/config";
+ setUp();
+ }
- String value;
-
- private ComponentType(String value) {
- this.value = value;
- }
-
- public String getValue() {
-
- return value;
- }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java
index 7774b7f412..d7bfdcd1a4 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ComponentBusinessLogicTest.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.be.components;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,80 +42,85 @@ import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ComponentBusinessLogicTest {
- private static final User USER = new User();
- private static final String ARTIFACT_LABEL = "toscaArtifact1";
- private static final String ARTIFACT_LABEL2 = "toscaArtifact2";
-
- @InjectMocks
- private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() {
- @Override
- public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
- return null;
- }
-
- @Override
- public ComponentInstanceBusinessLogic getComponentInstanceBL() {
- return null;
- }
-
- @Override
- public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
- return null;
- }
-
- @Override
- public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) {
- return null;
- }
- };
-
- @Mock
- private ArtifactsBusinessLogic artifactsBusinessLogic;
-
- @BeforeClass
- public static void setUp() throws Exception {
- new DummyConfigurationManager();
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception {
- Resource resource = new ResourceBuilder().setUniqueId("uid")
- .setComponentType(ComponentTypeEnum.RESOURCE)
- .setSystemName("myResource")
- .build();
- Map<String, Object> artifactsFromConfig = new HashMap<>();
- artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml"));
- artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar"));
- when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig);
- when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA))
- .thenReturn(buildArtifactDef(ARTIFACT_LABEL));
- when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA))
- .thenReturn(buildArtifactDef(ARTIFACT_LABEL2));
- testInstance.setToscaArtifactsPlaceHolders(resource, USER);
-
- Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts();
- assertThat(toscaArtifacts).hasSize(2);
- ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL);
- assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml");
- ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2);
- assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar");
- }
-
- private Map<String, Object> buildArtifactMap(String artifactName) {
- Map<String, Object> artifact = new HashMap<>();
- artifact.put("artifactName", artifactName);
- return artifact;
- }
-
- private ArtifactDefinition buildArtifactDef(String artifactLabel) {
- ArtifactDefinition artifactDefinition = new ArtifactDefinition();
- artifactDefinition.setArtifactLabel(artifactLabel);
- return artifactDefinition;
- }
+ private static final User USER = new User();
+ private static final String ARTIFACT_LABEL = "toscaArtifact1";
+ private static final String ARTIFACT_LABEL2 = "toscaArtifact2";
+
+ @InjectMocks
+ private ComponentBusinessLogic testInstance = new ComponentBusinessLogic() {
+ @Override
+ public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
+ return null;
+ }
+
+ @Override
+ public ComponentInstanceBusinessLogic getComponentInstanceBL() {
+ return null;
+ }
+
+ @Override
+ public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
+ return null;
+ }
+
+ @Override
+ public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn) {
+ return null;
+ }
+ };
+
+ @Mock
+ private ArtifactsBusinessLogic artifactsBusinessLogic;
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ new DummyConfigurationManager();
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void setToscaArtifactsPlaceHolders_normalizeArtifactName() throws Exception {
+ Resource resource = new ResourceBuilder().setUniqueId("uid")
+ .setComponentType(ComponentTypeEnum.RESOURCE)
+ .setSystemName("myResource")
+ .build();
+ Map<String, Object> artifactsFromConfig = new HashMap<>();
+ artifactsFromConfig.put(ARTIFACT_LABEL, buildArtifactMap("artifact:not normalized.yml"));
+ artifactsFromConfig.put(ARTIFACT_LABEL2, buildArtifactMap("alreadyNormalized.csar"));
+ when(ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts()).thenReturn(artifactsFromConfig);
+ when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL), USER, ArtifactGroupTypeEnum.TOSCA))
+ .thenReturn(buildArtifactDef(ARTIFACT_LABEL));
+ when(artifactsBusinessLogic.createArtifactPlaceHolderInfo(resource.getUniqueId(), ARTIFACT_LABEL2, (Map<String, Object>) artifactsFromConfig.get(ARTIFACT_LABEL2), USER, ArtifactGroupTypeEnum.TOSCA))
+ .thenReturn(buildArtifactDef(ARTIFACT_LABEL2));
+ testInstance.setToscaArtifactsPlaceHolders(resource, USER);
+
+ Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts();
+ assertThat(toscaArtifacts).hasSize(2);
+ ArtifactDefinition artifactDefinition = toscaArtifacts.get(ARTIFACT_LABEL);
+ assertThat(artifactDefinition.getArtifactName()).isEqualTo("resource-myResourceartifactnot-normalized.yml");
+ ArtifactDefinition artifactDefinition2 = toscaArtifacts.get(ARTIFACT_LABEL2);
+ assertThat(artifactDefinition2.getArtifactName()).isEqualTo("resource-myResourcealreadyNormalized.csar");
+ }
+
+ private Map<String, Object> buildArtifactMap(String artifactName) {
+ Map<String, Object> artifact = new HashMap<>();
+ artifact.put("artifactName", artifactName);
+ return artifact;
+ }
+
+ private ArtifactDefinition buildArtifactDef(String artifactLabel) {
+ ArtifactDefinition artifactDefinition = new ArtifactDefinition();
+ artifactDefinition.setArtifactLabel(artifactLabel);
+ return artifactDefinition;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
index 9bf7f16a50..c114f340b8 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
@@ -20,10 +20,6 @@
package org.openecomp.sdc.be.components;
-import static org.mockito.Mockito.when;
-
-import javax.servlet.ServletContext;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -46,206 +42,193 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
+import javax.servlet.ServletContext;
+
+import static org.mockito.Mockito.when;
/**
* tests GroupBusinessLogic class
* @author ns019t
*
*/
public class GroupBusinessLogicTest {
-
- private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName());
- ComponentsUtils componentsUtils = new ComponentsUtils();
- AuditingManager auditingManager = Mockito.mock(AuditingManager.class);
- final ServletContext servletContext = Mockito.mock(ServletContext.class);
- private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class);
- private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class);
- private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class);
- private static User user = Mockito.mock(User.class);
- private static String componentId = "vfUniqueId-xxxx";
- private static String groupUniqueId = "groupUniqueId-xxxx";
- @InjectMocks
- static GroupBusinessLogic bl = new GroupBusinessLogic();
-
-
- @Before
- public void setupBeforeMethod() {
- MockitoAnnotations.initMocks(this);
- ExternalConfiguration.setAppName("catalog-be");
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
-
- componentsUtils.Init();
- componentsUtils.setAuditingManager(auditingManager);
- bl.setComponentsUtils(componentsUtils);
- }
- @BeforeClass
- public static void setupBeforeClass() {
- when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK);
-// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition));
- }
-
- public enum ResponseEnum{
- INVALID_MIN_MAX("SVC4654"),
- INVALID_INITIAL_COUNT("SVC4655");
-
- String messageId;
-
- private ResponseEnum(String messageId){
- this.messageId = messageId;
- }
- public String getMessageId() {
- return messageId;
- }
-
- }
- /**
- * tests the ValidateMinMaxAndInitialCountPropertyValues() method
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Test
- public void testValidateMinMaxAndInitialCountPropertyValues(){
-
-// Class<GroupBusinessLogic> targetClass = GroupBusinessLogic.class;
-// String methodName = "validateMinMaxAndInitialCountPropertyValues";
-// Either<Boolean, ResponseFormat> validationRes;
-//
-// Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
-// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20");
-// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100");
-// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40");
-//
-// Map<PropertyNames, String> parentPropertyValues1 = new EnumMap<>(PropertyNames.class);
-// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20");
-// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null);
-// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40");
-//
-// Map<PropertyNames, String> parentPropertyValues2 = new EnumMap<>(PropertyNames.class);
-// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20");
-// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null");
-// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40");
-//
-// Map<PropertyNames, String> validNewPropertyValues = new EnumMap<>(PropertyNames.class);
-// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20");
-// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100");
-// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50");
-//
-// Map<PropertyNames, String> validNewPropertyValues1 = new EnumMap<>(PropertyNames.class);
-// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40");
-// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90");
-// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60");
-//
-// Map<PropertyNames, String> validNewPropertyValues2 = new EnumMap<>(PropertyNames.class);
-// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40");
-// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null);
-// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60");
-//
-// Map<PropertyNames, String> validNewPropertyValues3 = new EnumMap<>(PropertyNames.class);
-// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40");
-// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null");
-// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60");
-//
-// Map<PropertyNames, String> validNewPropertyValues4 = new EnumMap<>(PropertyNames.class);
-// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null);
-// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null);
-// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60");
-//
-// Map<PropertyNames, String> invalidNewPropertyValues = new EnumMap<>(PropertyNames.class);
-// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20");
-// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10");
-// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5");
-//
-// Map<PropertyNames, String> invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class);
-// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5");
-// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10");
-// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20");
-//
-// Map<PropertyNames, String> invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class);
-// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25");
-// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95");
-// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100");
-//
-// Map<PropertyNames, String> invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class);
-// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null);
-// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95");
-// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10");
-//
-// Map<PropertyNames, String> invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class);
-// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30");
-// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80");
-// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null);
-//
-//
-// Class[] argClasses = {Map.class, Map.class};
-// try {
-// Method method = targetClass.getDeclaredMethod(methodName, argClasses);
-// method.setAccessible(true);
-//
-// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects2);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isRight());
-// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId()));
-//
-// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects3);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isRight());
-// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId()));
-//
-// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects7);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isRight());
-// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId()));
-//
-// Object[] argObjects = {validNewPropertyValues, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isLeft());
-// assertTrue(validationRes.left().value());
-//
-// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects1);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isLeft());
-// assertTrue(validationRes.left().value());
-//
-// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects5);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isLeft());
-// assertTrue(validationRes.left().value());
-//
-// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects6);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isLeft());
-// assertTrue(validationRes.left().value());
-//
-// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects9);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isLeft());
-// assertTrue(validationRes.left().value());
-//
-// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects4);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isRight());
-// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId()));
-//
-// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues};
-// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects8);
-// assertTrue(validationRes != null);
-// assertTrue(validationRes.isRight());
-// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId()));
-// }
-// catch (Exception e) {
-// e.printStackTrace();
-// }
- }
+ private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class);
+ ComponentsUtils componentsUtils;
+ final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ private static IGraphLockOperation graphLockOperation = Mockito.mock(IGraphLockOperation.class);
+ private static GroupOperation groupOperation = Mockito.mock(GroupOperation.class);
+ private static GroupDefinition groupDefenition = Mockito.mock(GroupDefinition.class);
+ private static User user = Mockito.mock(User.class);
+ private static String componentId = "vfUniqueId-xxxx";
+ private static String groupUniqueId = "groupUniqueId-xxxx";
+ @InjectMocks
+ static GroupBusinessLogic bl = new GroupBusinessLogic();
+
+
+ @Before
+ public void setupBeforeMethod() {
+ MockitoAnnotations.initMocks(this);
+ ExternalConfiguration.setAppName("catalog-be");
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+
+ bl.setComponentsUtils(componentsUtils);
+ }
+ @BeforeClass
+ public static void setupBeforeClass() {
+ when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK);
+// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition));
+ }
+
+ /**
+ * tests the ValidateMinMaxAndInitialCountPropertyValues() method
+ */
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Test
+ public void testValidateMinMaxAndInitialCountPropertyValues(){
+
+// Class<GroupBusinessLogic> targetClass = GroupBusinessLogic.class;
+// String methodName = "validateMinMaxAndInitialCountPropertyValues";
+// Either<Boolean, ResponseFormat> validationRes;
+//
+// Map<PropertyNames, String> parentPropertyValues = new EnumMap<>(PropertyNames.class);
+// parentPropertyValues.put(PropertyNames.MIN_INSTANCES, "20");
+// parentPropertyValues.put(PropertyNames.MAX_INSTANCES, "100");
+// parentPropertyValues.put(PropertyNames.INITIAL_COUNT, "40");
+//
+// Map<PropertyNames, String> parentPropertyValues1 = new EnumMap<>(PropertyNames.class);
+// parentPropertyValues1.put(PropertyNames.MIN_INSTANCES, "20");
+// parentPropertyValues1.put(PropertyNames.MAX_INSTANCES, null);
+// parentPropertyValues1.put(PropertyNames.INITIAL_COUNT, "40");
+//
+// Map<PropertyNames, String> parentPropertyValues2 = new EnumMap<>(PropertyNames.class);
+// parentPropertyValues2.put(PropertyNames.MIN_INSTANCES, "20");
+// parentPropertyValues2.put(PropertyNames.MAX_INSTANCES, "null");
+// parentPropertyValues2.put(PropertyNames.INITIAL_COUNT, "40");
+//
+// Map<PropertyNames, String> validNewPropertyValues = new EnumMap<>(PropertyNames.class);
+// validNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20");
+// validNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "100");
+// validNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "50");
+//
+// Map<PropertyNames, String> validNewPropertyValues1 = new EnumMap<>(PropertyNames.class);
+// validNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "40");
+// validNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "90");
+// validNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "60");
+//
+// Map<PropertyNames, String> validNewPropertyValues2 = new EnumMap<>(PropertyNames.class);
+// validNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "40");
+// validNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, null);
+// validNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "60");
+//
+// Map<PropertyNames, String> validNewPropertyValues3 = new EnumMap<>(PropertyNames.class);
+// validNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, "40");
+// validNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "null");
+// validNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "60");
+//
+// Map<PropertyNames, String> validNewPropertyValues4 = new EnumMap<>(PropertyNames.class);
+// validNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, null);
+// validNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, null);
+// validNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, "60");
+//
+// Map<PropertyNames, String> invalidNewPropertyValues = new EnumMap<>(PropertyNames.class);
+// invalidNewPropertyValues.put(PropertyNames.MIN_INSTANCES, "20");
+// invalidNewPropertyValues.put(PropertyNames.MAX_INSTANCES, "10");
+// invalidNewPropertyValues.put(PropertyNames.INITIAL_COUNT, "5");
+//
+// Map<PropertyNames, String> invalidNewPropertyValues1 = new EnumMap<>(PropertyNames.class);
+// invalidNewPropertyValues1.put(PropertyNames.MIN_INSTANCES, "5");
+// invalidNewPropertyValues1.put(PropertyNames.MAX_INSTANCES, "10");
+// invalidNewPropertyValues1.put(PropertyNames.INITIAL_COUNT, "20");
+//
+// Map<PropertyNames, String> invalidNewPropertyValues2 = new EnumMap<>(PropertyNames.class);
+// invalidNewPropertyValues2.put(PropertyNames.MIN_INSTANCES, "25");
+// invalidNewPropertyValues2.put(PropertyNames.MAX_INSTANCES, "95");
+// invalidNewPropertyValues2.put(PropertyNames.INITIAL_COUNT, "100");
+//
+// Map<PropertyNames, String> invalidNewPropertyValues3 = new EnumMap<>(PropertyNames.class);
+// invalidNewPropertyValues3.put(PropertyNames.MIN_INSTANCES, null);
+// invalidNewPropertyValues3.put(PropertyNames.MAX_INSTANCES, "95");
+// invalidNewPropertyValues3.put(PropertyNames.INITIAL_COUNT, "10");
+//
+// Map<PropertyNames, String> invalidNewPropertyValues4 = new EnumMap<>(PropertyNames.class);
+// invalidNewPropertyValues4.put(PropertyNames.MIN_INSTANCES, "30");
+// invalidNewPropertyValues4.put(PropertyNames.MAX_INSTANCES, "80");
+// invalidNewPropertyValues4.put(PropertyNames.INITIAL_COUNT, null);
+//
+//
+// Class[] argClasses = {Map.class, Map.class};
+// try {
+// Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+// method.setAccessible(true);
+//
+// Object[] argObjects2 = {invalidNewPropertyValues, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects2);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isRight());
+// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId()));
+//
+// Object[] argObjects3 = {invalidNewPropertyValues1, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects3);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isRight());
+// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId()));
+//
+// Object[] argObjects7 = {invalidNewPropertyValues3, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects7);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isRight());
+// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_MIN_MAX.getMessageId()));
+//
+// Object[] argObjects = {validNewPropertyValues, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isLeft());
+// assertTrue(validationRes.left().value());
+//
+// Object[] argObjects1 = {validNewPropertyValues1, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects1);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isLeft());
+// assertTrue(validationRes.left().value());
+//
+// Object[] argObjects5 = {validNewPropertyValues2, parentPropertyValues2};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects5);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isLeft());
+// assertTrue(validationRes.left().value());
+//
+// Object[] argObjects6 = {validNewPropertyValues3, parentPropertyValues1};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects6);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isLeft());
+// assertTrue(validationRes.left().value());
+//
+// Object[] argObjects9 = {validNewPropertyValues4, parentPropertyValues1};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects9);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isLeft());
+// assertTrue(validationRes.left().value());
+//
+// Object[] argObjects4 = {invalidNewPropertyValues2, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects4);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isRight());
+// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId()));
+//
+// Object[] argObjects8 = {invalidNewPropertyValues4, parentPropertyValues};
+// validationRes = (Either<Boolean, ResponseFormat>) method.invoke(bl, argObjects8);
+// assertTrue(validationRes != null);
+// assertTrue(validationRes.isRight());
+// assertTrue(validationRes.right().value().getMessageId().equals(ResponseEnum.INVALID_INITIAL_COUNT.getMessageId()));
+// }
+// catch (Exception e) {
+// e.printStackTrace();
+// }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java
index 2a34baeb0f..04c2100ed8 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java
@@ -20,66 +20,66 @@
package org.openecomp.sdc.be.components;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
import org.junit.Test;
-import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic;
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
public class HealthCheckBusinessLogicTest {
- HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic();
-
- @Test
- public void checkStausUpdated() {
+ HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic();
+
+ @Test
+ public void checkStausUpdated() {
- boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null);
- assertFalse("check false", statusChanged);
+ boolean statusChanged = healthCheckBusinessLogic.anyStatusChanged(null, null);
+ assertFalse("check false", statusChanged);
- List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>();
- List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>();
+ List<HealthCheckInfo> checkInfosLeft = new ArrayList<HealthCheckInfo>();
+ List<HealthCheckInfo> checkInfosRight = new ArrayList<HealthCheckInfo>();
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
- assertFalse("check false", statusChanged);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
+ assertFalse("check false", statusChanged);
- HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null);
- HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null);
+ HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UP, null, null);
+ HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.DOWN, null, null);
- /*
- * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null);
- */
+ /*
+ * HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null);
+ */
- checkInfosLeft.add(checkInfoTitanUp);
+ checkInfosLeft.add(checkInfoTitanUp);
- checkInfosRight.add(checkInfoTitanUp);
+ checkInfosRight.add(checkInfoTitanUp);
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
- assertFalse("check false", statusChanged);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
+ assertFalse("check false", statusChanged);
- checkInfosRight.remove(checkInfoTitanUp);
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
- assertTrue("check true", statusChanged);
+ checkInfosRight.remove(checkInfoTitanUp);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
+ assertTrue("check true", statusChanged);
- checkInfosRight.add(checkInfoTitanDown);
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
- assertTrue("check true", statusChanged);
+ checkInfosRight.add(checkInfoTitanDown);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
+ assertTrue("check true", statusChanged);
- checkInfosRight.remove(checkInfoTitanDown);
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
- assertTrue("check true", statusChanged);
+ checkInfosRight.remove(checkInfoTitanDown);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
+ assertTrue("check true", statusChanged);
- checkInfosRight.add(checkInfoTitanUp);
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
- assertFalse("check false", statusChanged);
+ checkInfosRight.add(checkInfoTitanUp);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
+ assertFalse("check false", statusChanged);
- statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null);
- assertTrue("check true", statusChanged);
+ statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, null);
+ assertTrue("check true", statusChanged);
- }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java
new file mode 100644
index 0000000000..f9412c1643
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PathTest.java
@@ -0,0 +1,143 @@
+package org.openecomp.sdc.be.components;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.datamodel.ServiceRelations;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+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 java.util.UUID;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class PathTest extends BaseServiceBusinessLogicTest {
+ public static final String fromNode = "fromNode";
+
+ @Override
+ protected Service createServiceObject(boolean afterCreate) {
+ Service service = super.createServiceObject(afterCreate);
+ ArrayList<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>();
+ String toNode = "toNode";
+ resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode, "1", toNode, "2", "capability", "3", "requirement", "4"));
+ String fromNode1 = "fromNode1";
+ String toNode1 = "toNode1";
+ resourceInstancesRelations.add(createRequirementCapabilityRelDef(fromNode1, "11", toNode1, "21", "capability1", "31", "requirement1", "41"));
+ service.setComponentInstances(new java.util.ArrayList<>());
+ service.getComponentInstances().add(getComponentInstance(fromNode, "fromNode"));
+ service.getComponentInstances().add(getComponentInstance(fromNode1, "fromNode1"));
+ service.getComponentInstances().add(getComponentInstance(toNode, toNode));
+ service.getComponentInstances().add(getComponentInstance(toNode1, toNode1));
+
+ service.setComponentInstancesRelations(resourceInstancesRelations);
+ return service;
+ }
+
+ private ComponentInstance getComponentInstance(String uniquId, String normalizedName) {
+ ComponentInstance ci = new ComponentInstance();
+ ci.setUniqueId(uniquId);
+ ci.setNormalizedName(normalizedName);
+ ci.setName(normalizedName);
+ HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
+ CapabilityDefinition capabilityDefinition = getCapabilityDefinition(ci);
+ capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition));
+ capabilityDefinition = getCapabilityDefinition(ci);
+ capabilities.put(capabilityDefinition.getUniqueId(), Arrays.asList(capabilityDefinition));
+ ci.setCapabilities(capabilities);
+ return ci;
+ }
+
+ private static int i = 0;
+
+ private CapabilityDefinition getCapabilityDefinition(ComponentInstance ci) {
+ CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
+ capabilityDefinition.setUniqueId(UUID.randomUUID().toString());
+ capabilityDefinition.setName("My name " + i++);
+ capabilityDefinition.setType(ForwardingPathUtils.FORWARDER_CAPABILITY);
+ capabilityDefinition.setOwnerId(ci.getUniqueId());
+ return capabilityDefinition;
+ }
+
+
+ protected RequirementCapabilityRelDef createRequirementCapabilityRelDef(String fromNode, String fromNodeId, String toNode, String toNodeId, String capability, String capabilityId, String requirement, String requirementId) {
+ RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
+ requirementCapabilityRelDef.setFromNode(fromNode);
+ requirementCapabilityRelDef.setRelationships(new ArrayList<>());
+ CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship();
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType("something.LINK");
+ requirementCapabilityRelDef.getRelationships().add(capabilityRequirementRelationship);
+ requirementCapabilityRelDef.setToNode(toNode);
+ return requirementCapabilityRelDef;
+ }
+
+ @Test
+ public void validateSerialization() throws IOException {
+ Service service = new Service();
+ ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("Name");
+ String protocol = "protocol";
+ forwardingPath.setProtocol(protocol);
+ forwardingPath.setDestinationPortNumber("DestinationPortNumber");
+ ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>();
+ String nodeA = "nodeA";
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>();
+ forwardingPaths.put("NEW", forwardingPath);
+ service.setForwardingPaths(forwardingPaths);
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonResult = mapper.writerWithDefaultPrettyPrinter()
+ .writeValueAsString(service);
+ System.out.println(jsonResult);
+
+ Either<Service, ResponseFormat> serviceResponseFormatEither = new ComponentsUtils(Mockito.mock(AuditingManager.class)).convertJsonToObjectUsingObjectMapper(jsonResult, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+ assertTrue(serviceResponseFormatEither.isLeft());
+ Map<String, ForwardingPathDataDefinition> paths = serviceResponseFormatEither.left().value().getForwardingPaths();
+ assertEquals(paths.size(), 1);
+ ForwardingPathDataDefinition forwardingPathDataDefinition = paths.values().stream().findAny().get();
+ assertEquals(protocol, forwardingPathDataDefinition.getProtocol());
+ List<ForwardingPathElementDataDefinition> listToscaDataDefinition = forwardingPathDataDefinition.getPathElements().getListToscaDataDefinition();
+ assertEquals(3, listToscaDataDefinition.size());
+ assertTrue(listToscaDataDefinition.get(0).getFromNode().equals(nodeA));
+ }
+
+ @Test
+ public void shouldReturnEmptyRelationsObjectsWhenNoComponentInstanceExist() {
+ ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(super.createServiceObject(false));
+ assertTrue(serviceRelations.isEmpty());
+ }
+
+ @Test
+ public void convertServiceToServiceRelations() {
+ ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(createServiceObject(false));
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ String resultString = gson.toJson(serviceRelations);
+ System.out.println(" RESPONSE BODY: " + resultString);
+ assertTrue(resultString.contains(fromNode));
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
index 572804636d..38aaf92335 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
@@ -20,17 +20,8 @@
package org.openecomp.sdc.be.components;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
+import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -38,6 +29,7 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
+import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -60,171 +52,152 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.servlet.ServletContext;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
-import fj.data.Either;
-import junit.framework.Assert;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
public class PropertyBusinessLogicTest {
- private static Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class.getName());
- @Mock
- private ServletContext servletContext;
- @Mock
- private IPropertyOperation propertyOperation;
- @Mock
- private WebAppContextWrapper webAppContextWrapper;
- @Mock
- private UserBusinessLogic mockUserAdmin;
- @Mock
- private WebApplicationContext webAppContext;
- @Mock
- private ComponentsUtils componentsUtils;
- @Mock
- private ToscaOperationFacade toscaOperationFacade;
-
- @InjectMocks
- private PropertyBusinessLogic bl = new PropertyBusinessLogic();
- private User user = null;
- private String resourceId = "resourceforproperty.0.1";
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- ExternalConfiguration.setAppName("catalog-be");
-
- // Init Configuration
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
- // User data and management
- user = new User();
- user.setUserId("jh003");
- user.setFirstName("Jimmi");
- user.setLastName("Hendrix");
- user.setRole(Role.ADMIN.name());
-
- Either<User, ActionStatus> eitherGetUser = Either.left(user);
- when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser);
-
- // Servlet Context attributes
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
-// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
-
- // Resource Operation mock methods
- // getCount
-// Either<Integer, StorageOperationStatus> eitherCount = Either.left(0);
-// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount);
-// Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1);
-// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist);
-// Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
-// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot);
+ private static final Logger log = LoggerFactory.getLogger(PropertyBusinessLogicTest.class);
+ @Mock
+ private ServletContext servletContext;
+ @Mock
+ private IPropertyOperation propertyOperation;
+ @Mock
+ private WebAppContextWrapper webAppContextWrapper;
+ @Mock
+ private UserBusinessLogic mockUserAdmin;
+ @Mock
+ private WebApplicationContext webAppContext;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Mock
+ private UserValidations userValidations;
+
+ @InjectMocks
+ private PropertyBusinessLogic bl = new PropertyBusinessLogic();
+ private User user = null;
+ private String resourceId = "resourceforproperty.0.1";
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ ExternalConfiguration.setAppName("catalog-be");
+
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+
+ // User data and management
+ user = new User();
+ user.setUserId("jh003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+
+ Either<User, ActionStatus> eitherGetUser = Either.left(user);
+ when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser);
+ when(userValidations.validateUserExists(eq("jh003"), anyString(), eq(false))).thenReturn(Either.left(user));
+
+ // Servlet Context attributes
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+ when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
+
+ // Resource Operation mock methods
+ // getCount
+// Either<Integer, StorageOperationStatus> eitherCount = Either.left(0);
+// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount);
+// Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1);
+// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist);
+// Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
+// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot);
//
-// Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true));
-// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource);
-
- }
-
- private Resource createResourceObject(boolean afterCreate) {
- Resource resource = new Resource();
- resource.setName("MyResourceName");
- resource.addCategory("Generic", "VoIP");
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<String>();
- tgs.add("test");
- resource.setTags(tgs);
- List<String> template = new ArrayList<String>();
- template.add("Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setContactId("yavivi");
- resource.setIcon("MyIcon.jpg");
-
- if (afterCreate) {
- resource.setName(resource.getName().toLowerCase());
- resource.setVersion("0.1");
- ;
- resource.setUniqueId(resourceId);
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- }
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- log.debug(gson.toJson(resource));
- return resource;
- }
-
- // @Test
- public void testHappyScenario() {
-
- String propertyName = "disk_size";
- PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId);
- Either<EntryData<String, PropertyDefinition>, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId());
-
- if (either.isRight()) {
- Assert.assertFalse(true);
- }
- Assert.assertEquals(newPropertyDefinition, either.left().value());
- }
-
- @Test
- public void getProperty_propertyNotFound() throws Exception {
- Resource resource = new Resource();
- PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
- PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource");
- resource.setProperties(Arrays.asList(property1, property2));
- String resourceId = "myResource";
- resource.setUniqueId(resourceId);
-
- Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
- Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId());
- assertTrue(nonExistingProperty.isRight());
- Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "");
- }
-
- @Test
- public void getProperty_propertyNotBelongsToResource() throws Exception {
- Resource resource = new Resource();
- PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
- resource.setProperties(Arrays.asList(property1));
- String resourceId = "myResource";
- resource.setUniqueId(resourceId);
-
- Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
- Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId());
- assertTrue(notFoundProperty.isRight());
- Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "");
- }
-
- @Test
- public void getProperty() throws Exception {
- Resource resource = new Resource();
- resource.setUniqueId(resourceId);
- PropertyDefinition property1 = createPropertyObject("someProperty", null);
- resource.setProperties(Arrays.asList(property1));
-
- Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
- Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId());
- assertTrue(foundProperty.isLeft());
- assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId());
- }
-
- private PropertyDefinition createPropertyObject(String propertyName, String resourceId) {
- PropertyDefinition pd = new PropertyDefinition();
- List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
- pd.setConstraints(null);
- pd.setDefaultValue("100");
- pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node");
- pd.setPassword(false);
- pd.setRequired(true);
- pd.setType("Integer");
- pd.setOwnerId(resourceId);
- pd.setUniqueId(resourceId + "." + propertyName);
- return pd;
- }
+// Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true));
+// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource);
+
+ }
+
+ // @Test
+ public void testHappyScenario() {
+
+ String propertyName = "disk_size";
+ PropertyDefinition newPropertyDefinition = createPropertyObject(propertyName, resourceId);
+ Either<EntryData<String, PropertyDefinition>, ResponseFormat> either = bl.createProperty(resourceId, propertyName, newPropertyDefinition, user.getUserId());
+
+ if (either.isRight()) {
+ Assert.assertFalse(true);
+ }
+ Assert.assertEquals(newPropertyDefinition, either.left().value());
+ }
+
+ @Test
+ public void getProperty_propertyNotFound() throws Exception {
+ Resource resource = new Resource();
+ PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
+ PropertyDefinition property2 = createPropertyObject("someProperty2", "myResource");
+ resource.setProperties(Arrays.asList(property1, property2));
+ String resourceId = "myResource";
+ resource.setUniqueId(resourceId);
+
+ Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
+ Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId());
+ assertTrue(nonExistingProperty.isRight());
+ Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "");
+ }
+
+ @Test
+ public void getProperty_propertyNotBelongsToResource() throws Exception {
+ Resource resource = new Resource();
+ PropertyDefinition property1 = createPropertyObject("someProperty", "someResource");
+ resource.setProperties(Arrays.asList(property1));
+ String resourceId = "myResource";
+ resource.setUniqueId(resourceId);
+
+ Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
+ Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId());
+ assertTrue(notFoundProperty.isRight());
+ Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "");
+ }
+
+ @Test
+ public void getProperty() throws Exception {
+ Resource resource = new Resource();
+ resource.setUniqueId(resourceId);
+ PropertyDefinition property1 = createPropertyObject("someProperty", null);
+ resource.setProperties(Arrays.asList(property1));
+
+ Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource));
+ Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId());
+ assertTrue(foundProperty.isLeft());
+ assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId());
+ }
+
+ private PropertyDefinition createPropertyObject(String propertyName, String resourceId) {
+ PropertyDefinition pd = new PropertyDefinition();
+ List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
+ pd.setConstraints(null);
+ pd.setDefaultValue("100");
+ pd.setDescription("Size of thasdasdasdasde local disk, in Gigabytes (GB), available to applications running on the Compute node");
+ pd.setPassword(false);
+ pd.setRequired(true);
+ pd.setType("Integer");
+ pd.setOwnerId(resourceId);
+ pd.setUniqueId(resourceId + "." + propertyName);
+ return pd;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
index 30e12e85d0..82389822f3 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
@@ -20,16 +20,7 @@
package org.openecomp.sdc.be.components;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -37,7 +28,7 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.components.impl.ImportUtils;
import org.openecomp.sdc.be.components.impl.ImportUtilsTest;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
@@ -63,310 +54,313 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.PolicyException;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import fj.data.Either;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class ResourceImportManagerTest {
- private static ConfigurationManager configurationManager;
- static ResourceImportManager importManager;
- static IAuditingManager auditingManager = Mockito.mock(IAuditingManager.class);
- static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class);
- static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
- static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
- static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
- static Logger log = Mockito.spy(Logger.class);
-
- @BeforeClass
- public static void beforeClass() throws IOException {
- importManager = new ResourceImportManager();
- importManager.setAuditingManager(auditingManager);
- when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null));
- importManager.setResponseFormatManager(responseFormatManager);
- importManager.setResourceBusinessLogic(resourceBusinessLogic);
- importManager.setToscaOperationFacade(toscaOperationFacade);
- ResourceImportManager.setLog(log);
-
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- configurationManager = new ConfigurationManager(configurationSource);
-
- Configuration configuration = new Configuration();
- configuration.setTitanInMemoryGraph(true);
- configurationManager.setConfiguration(configuration);
- }
+ private static ConfigurationManager configurationManager;
+ static ResourceImportManager importManager;
+ static AuditingManager auditingManager = Mockito.mock(AuditingManager.class);
+ static ResponseFormatManager responseFormatManager = Mockito.mock(ResponseFormatManager.class);
+ static ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
+ static UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
+ static ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+
+ @BeforeClass
+ public static void beforeClass() throws IOException {
+ importManager = new ResourceImportManager();
+ importManager.setAuditingManager(auditingManager);
+ when(toscaOperationFacade.getLatestByToscaResourceName(Mockito.anyString())).thenReturn(Either.left(null));
+ importManager.setResponseFormatManager(responseFormatManager);
+ importManager.setResourceBusinessLogic(resourceBusinessLogic);
+ importManager.setToscaOperationFacade(toscaOperationFacade);
+
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+
+ Configuration configuration = new Configuration();
+ configuration.setTitanInMemoryGraph(true);
+ configurationManager.setConfiguration(configuration);
+ }
+
+ @Before
+ public void beforeTest() {
+ Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin);
+ }
+
+ @Test
+ public void testBasicResourceCreation() throws IOException {
+ UploadResourceInfo resourceMD = createDummyResourceMD();
- @Before
- public void beforeTest() {
- Mockito.reset(auditingManager, responseFormatManager, resourceBusinessLogic, userAdmin, log);
- }
+ User user = new User();
+ user.setUserId(resourceMD.getContactId());
+ user.setRole("ADMIN");
+ user.setFirstName("Jhon");
+ user.setLastName("Doh");
+ Either<User, ActionStatus> eitherUser = Either.left(user);
- @Test
- public void testBasicResourceCreation() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
+ when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
- User user = new User();
- user.setUserId(resourceMD.getContactId());
- user.setRole("ADMIN");
- user.setFirstName("Jhon");
- user.setLastName("Doh");
- Either<User, ActionStatus> eitherUser = Either.left(user);
+ setResourceBusinessLogicMock();
- when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml");
- setResourceBusinessLogicMock();
-
- String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-blockStorage.yml");
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
- assertTrue(createResource.isLeft());
- Resource resource = createResource.left().value().left;
-
- testSetConstantMetaData(resource);
- testSetMetaDataFromJson(resource, resourceMD);
-
- testSetDerivedFrom(resource);
- testSetProperties(resource);
-
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
- }
-
- @Test
- public void testResourceCreationFailed() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
- user.setUserId(resourceMD.getContactId());
- Either<User, ActionStatus> eitherUser = Either.left(user);
- when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
- ResponseFormat dummyResponseFormat = createGeneralErrorInfo();
-
- when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat);
- setResourceBusinessLogicMock();
-
- String jsonContent = "this is an invalid yml!";
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
- assertTrue(createResource.isRight());
- ResponseFormat errorInfoFromTest = createResource.right().value();
- assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus()));
- assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId()));
- assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage()));
- Mockito.verify(log).debug(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Exception.class));
- // Mockito.verify(log).error(Mockito.anyString(), Mockito.anyString(),
- // Mockito.anyString());
-
- Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false));
-
- Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
-
- }
-
- @Test
- public void testResourceCreationWithCapabilities() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
- user.setUserId(resourceMD.getContactId());
- Either<User, ActionStatus> eitherUser = Either.left(user);
-
- when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
-
- setResourceBusinessLogicMock();
-
- String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
- assertTrue(createResource.isLeft());
- Resource resource = createResource.left().value().left;
- testSetCapabilities(resource);
-
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false);
-
- }
-
- @Test
- public void testResourceCreationWithRequirments() throws IOException {
- UploadResourceInfo resourceMD = createDummyResourceMD();
- User user = new User();
- user.setUserId(resourceMD.getContactId());
- Either<User, ActionStatus> eitherUser = Either.left(user);
-
- when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
-
- setResourceBusinessLogicMock();
-
- String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml");
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
- assertTrue(createResource.isLeft());
- testSetRequirments(createResource.left().value().left);
-
- }
-
- private void setResourceBusinessLogicMock() {
- when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin);
- when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)))
- .thenAnswer(new Answer<Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat>>() {
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
- Object[] args = invocation.getArguments();
- return Either.left(new ImmutablePair<Resource, ActionStatus>((Resource) args[0], ActionStatus.CREATED));
-
- }
- });
- when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)))
- .thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
- public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
- Object[] args = invocation.getArguments();
- return Either.left((Resource) args[1]);
-
- }
- });
- when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(EnumMap.class))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
- public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
- Object[] args = invocation.getArguments();
- return Either.left((Resource) args[0]);
-
- }
- });
- when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false), Mockito.eq(null))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
- public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
- Object[] args = invocation.getArguments();
- return Either.left((Resource) args[0]);
-
- }
- });
-
- Either<Boolean, ResponseFormat> either = Either.left(true);
- when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either);
- }
-
- public ResponseFormat createGeneralErrorInfo() {
- ResponseFormat responseFormat = new ResponseFormat(500);
- responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null));
- return responseFormat;
- }
-
- private UploadResourceInfo createDummyResourceMD() {
- UploadResourceInfo resourceMD = new UploadResourceInfo();
- resourceMD.setName("tosca.nodes.BlockStorage");
- resourceMD.setPayloadName("payLoad");
- resourceMD.addSubCategory("Generic", "Infrastructure");
- resourceMD.setContactId("ya107f");
- resourceMD.setResourceIconPath("defaulticon");
- resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" }));
- resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.");
- return resourceMD;
- }
-
- private void testSetProperties(Resource resource) {
- List<PropertyDefinition> propertiesList = resource.getProperties();
-
- Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
- for (PropertyDefinition propertyDefinition : propertiesList) {
- properties.put(propertyDefinition.getName(), propertyDefinition);
- }
-
- assertTrue(properties.size() == 3);
- assertTrue(properties.containsKey("size"));
- PropertyDefinition propertyDefinition = properties.get("size");
- assertTrue(propertyDefinition.getType().equals("scalar-unit.size"));
- assertTrue(propertyDefinition.getConstraints().size() == 1);
- PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0);
- assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint);
-
- assertTrue(properties.containsKey("volume_id"));
- propertyDefinition = properties.get("volume_id");
- assertTrue(propertyDefinition.getType().equals("string"));
- assertTrue(propertyDefinition.isRequired() == false);
-
- assertTrue(properties.containsKey("snapshot_id"));
- propertyDefinition = properties.get("snapshot_id");
- assertTrue(propertyDefinition.getType().equals("string"));
- assertTrue(propertyDefinition.isRequired() == false);
-
- }
-
- private void testSetCapabilities(Resource resource) {
- Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
- assertTrue(capabilities.size() == 3);
- assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint"));
- List<CapabilityDefinition> capabilityList = capabilities.get("tosca.capabilities.Endpoint");
- CapabilityDefinition capability = capabilityList.get(0);
- assertTrue(capability.getType().equals("tosca.capabilities.Endpoint"));
- assertTrue(capability.getName().equals("data_endpoint"));
-
- assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin"));
- capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin");
- capability = capabilityList.get(0);
- assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin"));
- assertTrue(capability.getName().equals("admin_endpoint"));
-
- assertTrue(capabilities.containsKey("tosca.capabilities.Container"));
- capabilityList = capabilities.get("tosca.capabilities.Container");
- capability = capabilityList.get(0);
- assertTrue(capability.getType().equals("tosca.capabilities.Container"));
- assertTrue(capability.getName().equals("host"));
-
- List<String> validSourceTypes = capability.getValidSourceTypes();
- assertTrue(validSourceTypes.size() == 1);
- assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication"));
-
- }
-
- private void testSetRequirments(Resource resource) {
- Map<String, List<RequirementDefinition>> requirements = resource.getRequirements();
- assertTrue(requirements.size() == 2);
-
- assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable"));
- List<RequirementDefinition> requirementList = requirements.get("tosca.capabilities.network.Linkable");
- RequirementDefinition requirement = requirementList.get(0);
- assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable"));
- assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo"));
- assertTrue(requirement.getName().equals("link"));
-
- assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable"));
- requirementList = requirements.get("tosca.capabilities.network.Bindable");
- requirement = requirementList.get(0);
- assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable"));
- assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo"));
- assertTrue(requirement.getName().equals("binding"));
-
- }
-
- private void testSetDerivedFrom(Resource resource) {
- assertTrue(resource.getDerivedFrom().size() == 1);
- assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root"));
-
- }
-
- private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) {
-
- // assertTrue( resource.getCategory().equals(resourceMD.getCategory())
- // );
- assertTrue(resource.getDescription().equals(resourceMD.getDescription()));
- assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath()));
- assertTrue(resource.getName().equals(resourceMD.getName()));
-
- assertTrue(resource.getContactId().equals(resourceMD.getContactId()));
- assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId()));
-
- // assertTrue( resource.isAbstract() ==
- // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory()));
-
- assertTrue(resourceMD.getTags().size() == resource.getTags().size());
- for (String tag : resource.getTags()) {
- assertTrue(resourceMD.getTags().contains(tag));
- }
-
- }
-
- private void testSetConstantMetaData(Resource resource) {
- assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION));
- assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE);
- assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
- assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME));
- assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE));
- }
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
+ assertTrue(createResource.isLeft());
+ Resource resource = createResource.left().value().left;
+
+ testSetConstantMetaData(resource);
+ testSetMetaDataFromJson(resource, resourceMD);
+
+ testSetDerivedFrom(resource);
+ testSetProperties(resource);
+
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
+ }
+
+ @Test
+ public void testResourceCreationFailed() throws IOException {
+ UploadResourceInfo resourceMD = createDummyResourceMD();
+ User user = new User();
+ user.setUserId(resourceMD.getContactId());
+ Either<User, ActionStatus> eitherUser = Either.left(user);
+ when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
+ ResponseFormat dummyResponseFormat = createGeneralErrorInfo();
+
+ when(responseFormatManager.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(dummyResponseFormat);
+ setResourceBusinessLogicMock();
+
+ String jsonContent = "this is an invalid yml!";
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
+ assertTrue(createResource.isRight());
+ ResponseFormat errorInfoFromTest = createResource.right().value();
+ assertTrue(errorInfoFromTest.getStatus().equals(dummyResponseFormat.getStatus()));
+ assertTrue(errorInfoFromTest.getMessageId().equals(dummyResponseFormat.getMessageId()));
+ assertTrue(errorInfoFromTest.getFormattedMessage().equals(dummyResponseFormat.getFormattedMessage()));
+
+ Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false));
+
+ Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
+
+ }
+
+ @Test
+ public void testResourceCreationWithCapabilities() throws IOException {
+ UploadResourceInfo resourceMD = createDummyResourceMD();
+ User user = new User();
+ user.setUserId(resourceMD.getContactId());
+ Either<User, ActionStatus> eitherUser = Either.left(user);
+
+ when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
+
+ setResourceBusinessLogicMock();
+
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-webServer.yml");
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
+ assertTrue(createResource.isLeft());
+ Resource resource = createResource.left().value().left;
+ testSetCapabilities(resource);
+
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true, null, null, false);
+
+ }
+
+ @Test
+ public void testResourceCreationWithRequirments() throws IOException {
+ UploadResourceInfo resourceMD = createDummyResourceMD();
+ User user = new User();
+ user.setUserId(resourceMD.getContactId());
+ Either<User, ActionStatus> eitherUser = Either.left(user);
+
+ when(userAdmin.getUser(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherUser);
+
+ setResourceBusinessLogicMock();
+
+ String jsonContent = ImportUtilsTest.loadFileNameToJsonString("normative-types-new-port.yml");
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResource = importManager.importNormativeResource(jsonContent, resourceMD, user, true, true);
+ assertTrue(createResource.isLeft());
+ testSetRequirments(createResource.left().value().left);
+
+ }
+
+ private void setResourceBusinessLogicMock() {
+ when(resourceBusinessLogic.getUserAdmin()).thenReturn(userAdmin);
+ when(resourceBusinessLogic.createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.eq(null), Mockito.eq(null), Mockito.eq(false)))
+ .thenAnswer(new Answer<Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat>>() {
+ public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
+ Object[] args = invocation.getArguments();
+ return Either.left(new ImmutablePair<Resource, ActionStatus>((Resource) args[0], ActionStatus.CREATED));
+
+ }
+ });
+ when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)))
+ .thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
+ public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
+ Object[] args = invocation.getArguments();
+ return Either.left((Resource) args[1]);
+
+ }
+ });
+ when(resourceBusinessLogic.createResourceByDao(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
+ public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
+ Object[] args = invocation.getArguments();
+ return Either.left((Resource) args[0]);
+
+ }
+ });
+ when(resourceBusinessLogic.validateResourceBeforeCreate(Mockito.any(Resource.class), Mockito.any(User.class), Mockito.any(AuditingActionEnum.class), Mockito.eq(false), Mockito.eq(null))).thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
+ public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
+ Object[] args = invocation.getArguments();
+ return Either.left((Resource) args[0]);
+
+ }
+ });
+
+ Either<Boolean, ResponseFormat> either = Either.left(true);
+ when(resourceBusinessLogic.validatePropertiesDefaultValues(Mockito.any(Resource.class))).thenReturn(either);
+ }
+
+ public ResponseFormat createGeneralErrorInfo() {
+ ResponseFormat responseFormat = new ResponseFormat(500);
+ responseFormat.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later", null));
+ return responseFormat;
+ }
+
+ private UploadResourceInfo createDummyResourceMD() {
+ UploadResourceInfo resourceMD = new UploadResourceInfo();
+ resourceMD.setName("tosca.nodes.BlockStorage");
+ resourceMD.setPayloadName("payLoad");
+ resourceMD.addSubCategory("Generic", "Infrastructure");
+ resourceMD.setContactId("ya107f");
+ resourceMD.setResourceIconPath("defaulticon");
+ resourceMD.setTags(Arrays.asList(new String[] { "BlockStorage" }));
+ resourceMD.setDescription("Represents a server-local block storage device (i.e., not shared) offering evenly sized blocks of data from which raw storage volumes can be created.");
+ resourceMD.setResourceVendorModelNumber("vendorReleaseNumber");
+ return resourceMD;
+ }
+
+ private void testSetProperties(Resource resource) {
+ List<PropertyDefinition> propertiesList = resource.getProperties();
+
+ Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
+ for (PropertyDefinition propertyDefinition : propertiesList) {
+ properties.put(propertyDefinition.getName(), propertyDefinition);
+ }
+
+ assertTrue(properties.size() == 3);
+ assertTrue(properties.containsKey("size"));
+ PropertyDefinition propertyDefinition = properties.get("size");
+ assertTrue(propertyDefinition.getType().equals("scalar-unit.size"));
+ assertTrue(propertyDefinition.getConstraints().size() == 1);
+ PropertyConstraint propertyConstraint = propertyDefinition.getConstraints().get(0);
+ assertTrue(propertyConstraint instanceof GreaterOrEqualConstraint);
+
+ assertTrue(properties.containsKey("volume_id"));
+ propertyDefinition = properties.get("volume_id");
+ assertTrue(propertyDefinition.getType().equals("string"));
+ assertTrue(propertyDefinition.isRequired() == false);
+
+ assertTrue(properties.containsKey("snapshot_id"));
+ propertyDefinition = properties.get("snapshot_id");
+ assertTrue(propertyDefinition.getType().equals("string"));
+ assertTrue(propertyDefinition.isRequired() == false);
+
+ }
+
+ private void testSetCapabilities(Resource resource) {
+ Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
+ assertTrue(capabilities.size() == 3);
+ assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint"));
+ List<CapabilityDefinition> capabilityList = capabilities.get("tosca.capabilities.Endpoint");
+ CapabilityDefinition capability = capabilityList.get(0);
+ assertTrue(capability.getType().equals("tosca.capabilities.Endpoint"));
+ assertTrue(capability.getName().equals("data_endpoint"));
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin"));
+ capabilityList = capabilities.get("tosca.capabilities.Endpoint.Admin");
+ capability = capabilityList.get(0);
+ assertTrue(capability.getType().equals("tosca.capabilities.Endpoint.Admin"));
+ assertTrue(capability.getName().equals("admin_endpoint"));
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.Container"));
+ capabilityList = capabilities.get("tosca.capabilities.Container");
+ capability = capabilityList.get(0);
+ assertTrue(capability.getType().equals("tosca.capabilities.Container"));
+ assertTrue(capability.getName().equals("host"));
+
+ List<String> validSourceTypes = capability.getValidSourceTypes();
+ assertTrue(validSourceTypes.size() == 1);
+ assertTrue(validSourceTypes.get(0).equals("tosca.nodes.WebApplication"));
+
+ }
+
+ private void testSetRequirments(Resource resource) {
+ Map<String, List<RequirementDefinition>> requirements = resource.getRequirements();
+ assertTrue(requirements.size() == 2);
+
+ assertTrue(requirements.containsKey("tosca.capabilities.network.Linkable"));
+ List<RequirementDefinition> requirementList = requirements.get("tosca.capabilities.network.Linkable");
+ RequirementDefinition requirement = requirementList.get(0);
+ assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Linkable"));
+ assertTrue(requirement.getRelationship().equals("tosca.relationships.network.LinksTo"));
+ assertTrue(requirement.getName().equals("link"));
+
+ assertTrue(requirements.containsKey("tosca.capabilities.network.Bindable"));
+ requirementList = requirements.get("tosca.capabilities.network.Bindable");
+ requirement = requirementList.get(0);
+ assertTrue(requirement.getCapability().equals("tosca.capabilities.network.Bindable"));
+ assertTrue(requirement.getRelationship().equals("tosca.relationships.network.BindsTo"));
+ assertTrue(requirement.getName().equals("binding"));
+
+ }
+
+ private void testSetDerivedFrom(Resource resource) {
+ assertTrue(resource.getDerivedFrom().size() == 1);
+ assertTrue(resource.getDerivedFrom().get(0).equals("tosca.nodes.Root"));
+
+ }
+
+ private void testSetMetaDataFromJson(Resource resource, UploadResourceInfo resourceMD) {
+
+ // assertTrue( resource.getCategory().equals(resourceMD.getCategory())
+ // );
+ assertTrue(resource.getDescription().equals(resourceMD.getDescription()));
+ assertTrue(resource.getIcon().equals(resourceMD.getResourceIconPath()));
+ assertTrue(resource.getName().equals(resourceMD.getName()));
+ assertEquals(resource.getResourceVendorModelNumber(), resourceMD.getResourceVendorModelNumber());
+ assertTrue(resource.getContactId().equals(resourceMD.getContactId()));
+ assertTrue(resource.getCreatorUserId().equals(resourceMD.getContactId()));
+
+ // assertTrue( resource.isAbstract() ==
+ // Constants.ABSTRACT_CATEGORY.equals(resourceMD.getCategory()));
+
+ assertTrue(resourceMD.getTags().size() == resource.getTags().size());
+ for (String tag : resource.getTags()) {
+ assertTrue(resourceMD.getTags().contains(tag));
+ }
+
+ }
+
+ private void testSetConstantMetaData(Resource resource) {
+ assertTrue(resource.getVersion().equals(ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION));
+ assertTrue(resource.getLifecycleState() == ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE);
+ assertTrue(resource.isHighestVersion() == ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+ assertTrue(resource.getVendorName().equals(ImportUtils.Constants.VENDOR_NAME));
+ assertTrue(resource.getVendorRelease().equals(ImportUtils.Constants.VENDOR_RELEASE));
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java
index 9a8f1c5ad8..e750d3ab51 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceTestUtils.java
@@ -20,71 +20,71 @@
package org.openecomp.sdc.be.components;
-import java.util.ArrayList;
-import java.util.List;
-
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.category.CategoryDefinition;
+import java.util.ArrayList;
+import java.util.List;
+
public class ResourceTestUtils {
- public static Resource prepareResource(int resourceIndex) {
- Resource r = new Resource();
- r.setName("resource_" + resourceIndex);
- r.setDescription("description");
- r.setVendorName("vendor name");
- r.setVendorRelease("vendor release");
- r.setContactId("as123y");
- r.addCategory("Generic", "Infrastructure");
- List<String> arr = new ArrayList<String>();
- arr.add("tosca.nodes.Root");
- r.setDerivedFrom(arr);
- List<String> arr1 = new ArrayList<String>();
- arr1.add(r.getName());
- r.setTags(arr1);
- r.setIcon("borderElement");
- return r;
- }
+ public static Resource prepareResource(int resourceIndex) {
+ Resource r = new Resource();
+ r.setName("resource_" + resourceIndex);
+ r.setDescription("description");
+ r.setVendorName("vendor name");
+ r.setVendorRelease("vendor release");
+ r.setContactId("as123y");
+ r.addCategory("Generic", "Infrastructure");
+ List<String> arr = new ArrayList<String>();
+ arr.add("tosca.nodes.Root");
+ r.setDerivedFrom(arr);
+ List<String> arr1 = new ArrayList<String>();
+ arr1.add(r.getName());
+ r.setTags(arr1);
+ r.setIcon("borderElement");
+ return r;
+ }
- public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) {
- Resource r = new Resource();
- r.setName("resource_" + resourceIndex);
- r.setToscaResourceName("resource_" + resourceIndex);
- r.setDescription("description");
- r.setVendorName("vendor name");
- r.setVendorRelease("vendor release");
- r.setContactId("as123y");
- r.setResourceType(resourceType);
- r.addCategory("Generic", "Infrastructure");
- List<String> arr = new ArrayList<String>();
- arr.add("tosca.nodes.Root");
- r.setDerivedFrom(arr);
- List<String> arr1 = new ArrayList<String>();
- arr1.add(r.getName());
- r.setTags(arr1);
- r.setIcon("borderElement");
- return r;
- }
+ public static Resource prepareResource(int resourceIndex, ResourceTypeEnum resourceType) {
+ Resource r = new Resource();
+ r.setName("resource_" + resourceIndex);
+ r.setToscaResourceName("resource_" + resourceIndex);
+ r.setDescription("description");
+ r.setVendorName("vendor name");
+ r.setVendorRelease("vendor release");
+ r.setContactId("as123y");
+ r.setResourceType(resourceType);
+ r.addCategory("Generic", "Infrastructure");
+ List<String> arr = new ArrayList<String>();
+ arr.add("tosca.nodes.Root");
+ r.setDerivedFrom(arr);
+ List<String> arr1 = new ArrayList<String>();
+ arr1.add(r.getName());
+ r.setTags(arr1);
+ r.setIcon("borderElement");
+ return r;
+ }
- public static Service prepareService(int serviceIndex) {
- Service service = new Service();
- service.setName("service_" + serviceIndex);
- service.setDescription("desc");
- service.setIcon("icon-service-red1");
- List<String> tags = new ArrayList<String>();
- tags.add(service.getName());
- service.setTags(tags);
- CategoryDefinition category = new CategoryDefinition();
- category.setName("Mobility");
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- service.setCategories(categories);
- service.setContactId("as123y");
- service.setProjectCode("123456");
+ public static Service prepareService(int serviceIndex) {
+ Service service = new Service();
+ service.setName("service_" + serviceIndex);
+ service.setDescription("desc");
+ service.setIcon("icon-service-red1");
+ List<String> tags = new ArrayList<String>();
+ tags.add(service.getName());
+ service.setTags(tags);
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName("Mobility");
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ service.setCategories(categories);
+ service.setContactId("as123y");
+ service.setProjectCode("123456");
- return service;
- }
+ return service;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java
index 1af1ac3070..bbb381bad3 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java
@@ -20,31 +20,19 @@
package org.openecomp.sdc.be.components;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.ElementOperationMock;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
+import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
@@ -83,940 +71,881 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
-
-public class ServiceBusinessLogicTest {
-
- private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class.getName());
- private static final String SERVICE_CATEGORY = "Mobility";
- final ServletContext servletContext = Mockito.mock(ServletContext.class);
- IAuditingManager iAuditingManager = null;
- UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
- WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
- ServiceBusinessLogic bl = new ServiceBusinessLogic();
- ResponseFormatManager responseManager = null;
- IElementOperation mockElementDao;
- AuditingManager auditingManager = Mockito.mock(AuditingManager.class);
- ComponentsUtils componentsUtils = new ComponentsUtils();
- AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
- ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
- GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
- TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
- ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
- CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
- GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
-
- User user = null;
- Service serviceResponse = null;
- Resource genericService = null;
-
- private static final String CERTIFIED_VERSION = "1.0";
- private static final String UNCERTIFIED_VERSION = "0.2";
- private static final String COMPONNET_ID = "myUniqueId";
- private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
- private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>();
- private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>();
- private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>();
-
- public ServiceBusinessLogicTest() {
-
- }
-
- @Before
- public void setup() {
-
- ExternalConfiguration.setAppName("catalog-be");
- // Init Configuration
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
- // Elements
- mockElementDao = new ElementOperationMock();
-
- // User data and management
- user = new User();
- user.setUserId("jh0003");
- user.setFirstName("Jimmi");
- user.setLastName("Hendrix");
- user.setRole(Role.ADMIN.name());
-
- Either<User, ActionStatus> eitherGetUser = Either.left(user);
- when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
-
- // Servlet Context attributes
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
-// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
- when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
- when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
- when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
-
- // artifact bussinesslogic
- ArtifactDefinition artifactDef = new ArtifactDefinition();
- when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
-
- // createService
- serviceResponse = createServiceObject(true);
- Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
- when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
- Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
- when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
- Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
- when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
-
- genericService = setupGenericServiceMock();
- Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
- when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
-
-
- bl = new ServiceBusinessLogic();
- bl.setElementDao(mockElementDao);
- bl.setUserAdmin(mockUserAdmin);
- bl.setArtifactBl(artifactBl);
- bl.setGraphLockOperation(graphLockOperation);
- bl.setTitanGenericDao(mockTitanDao);
- bl.setToscaOperationFacade(toscaOperationFacade);
- bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
- componentsUtils.Init();
- componentsUtils.setAuditingManager(auditingManager);
- bl.setComponentsUtils(componentsUtils);
- bl.setCassandraAuditingDao(auditingDao);
- bl.setCacheManagerOperation(cacheManager);
-
- mockAuditingDaoLogic();
-
- responseManager = ResponseFormatManager.getInstance();
-
- }
-
- @Test
- public void testGetComponentAuditRecordsCertifiedVersion() {
- Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
- assertTrue(componentAuditRecords.isLeft());
- int size = componentAuditRecords.left().value().size();
- assertTrue(size == 3);
- }
-
- @Test
- public void testGetComponentAuditRecordsUnCertifiedVersion() {
- Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
- assertTrue(componentAuditRecords.isLeft());
- int size = componentAuditRecords.left().value().size();
- assertTrue(size == 1);
- }
-
- @Test
- public void testHappyScenario() {
- Service service = createServiceObject(false);
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
- Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
-
- if (createResponse.isRight()) {
- assertEquals(new Integer(200), createResponse.right().value().getStatus());
- }
- assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
- }
-
- private void assertEqualsServiceObject(Service origService, Service newService) {
- assertEquals(origService.getContactId(), newService.getContactId());
- assertEquals(origService.getCategories(), newService.getCategories());
- assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
- assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
- assertEquals(origService.getDescription(), newService.getDescription());
- assertEquals(origService.getIcon(), newService.getIcon());
- assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
- assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
- assertEquals(origService.getName(), newService.getName());
- assertEquals(origService.getName(), newService.getName());
- assertEquals(origService.getUniqueId(), newService.getUniqueId());
- assertEquals(origService.getVersion(), newService.getVersion());
- assertEquals(origService.getArtifacts(), newService.getArtifacts());
- assertEquals(origService.getCreationDate(), newService.getCreationDate());
- assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
- assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
- assertEquals(origService.getTags(), newService.getTags());
- }
-
- private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
- ResponseFormat actualResponse = createResponse.right().value();
- assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
- assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
- }
-
- /* CREATE validations - start ***********************/
- // Service name - start
-
- @Test
- public void testFailedServiceValidations() {
- testServiceNameAlreadyExists();
- testServiceNameEmpty();
- // testServiceNameExceedsLimit();
- testServiceNameWrongFormat();
- testServiceDescriptionEmpty();
- testServiceDescriptionMissing();
- testServiceDescExceedsLimitCreate();
- testServiceDescNotEnglish();
- testServiceIconEmpty();
- testServiceIconMissing();
- testResourceIconInvalid();
- testResourceIconExceedsLimit();
- // testTagsExceedsLimitCreate();
- // testTagsSingleExcessLimit();
- testTagsNoServiceName();
- testInvalidTag();
- testServiceTagNotExist();
- testServiceTagEmpty();
-
- testContactIdTooLong();
- testContactIdWrongFormatCreate();
- testInvalidProjectCode();
- testProjectCodeTooLong();
- testProjectCodeTooShort();
-
- testResourceContactIdMissing();
- testServiceCategoryExist();
- testServiceBadCategoryCreate();
- testMissingProjectCode();
- }
-
- private void testServiceNameAlreadyExists() {
- String serviceName = "alreadyExist";
- Service serviceExccedsNameLimit = createServiceObject(false);
- // 51 chars, the limit is 50
- serviceExccedsNameLimit.setName(serviceName);
- List<String> tgs = new ArrayList<String>();
- tgs.add(serviceName);
- serviceExccedsNameLimit.setTags(tgs);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
- }
-
- private void testServiceNameEmpty() {
- Service serviceExccedsNameLimit = createServiceObject(false);
- serviceExccedsNameLimit.setName(null);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testServiceNameExceedsLimit() {
- Service serviceExccedsNameLimit = createServiceObject(false);
- // 51 chars, the limit is 50
- String tooLongServiceName = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxdsafefegesse";
- serviceExccedsNameLimit.setName(tooLongServiceName);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
- }
-
- private void testServiceNameWrongFormat() {
- Service service = createServiceObject(false);
- // contains :
- String nameWrongFormat = "ljg\fd";
- service.setName(nameWrongFormat);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
- }
-
- // Service name - end
- // Service description - start
- private void testServiceDescriptionEmpty() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setDescription("");
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testServiceDescriptionMissing() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setDescription(null);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testServiceDescExceedsLimitCreate() {
- Service serviceExccedsDescLimit = createServiceObject(false);
- // 1025 chars, the limit is 1024
- String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
- + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
- + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
- + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
- + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
- + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
- + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
- + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
-
- serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
- }
-
- private void testServiceDescNotEnglish() {
- Service notEnglish = createServiceObject(false);
- // Not english
- String tooLongServiceDesc = "\uC2B5";
- notEnglish.setDescription(tooLongServiceDesc);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
- }
-
- // Service description - stop
- // Service icon - start
- private void testServiceIconEmpty() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setIcon("");
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testServiceIconMissing() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setIcon(null);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testResourceIconInvalid() {
- Service resourceExist = createServiceObject(false);
- resourceExist.setIcon("kjk3453^&");
-
- Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testResourceIconExceedsLimit() {
- Service resourceExist = createServiceObject(false);
- resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
-
- Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
- }
-
- // Service icon - stop
- // Service tags - start
- private void testTagsExceedsLimitCreate() {
- Service serviceExccedsNameLimit = createServiceObject(false);
- String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
- String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
- String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
- String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
- String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
- String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
- String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
- String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
- String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
- String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
- String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
- String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
- String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
- String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
- String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
- String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
- String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
-
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- tagsList.add(tag2);
- tagsList.add(tag3);
- tagsList.add(tag4);
- tagsList.add(tag5);
- tagsList.add(tag6);
- tagsList.add(tag7);
- tagsList.add(tag8);
- tagsList.add(tag9);
- tagsList.add(tag10);
- tagsList.add(tag11);
- tagsList.add(tag12);
- tagsList.add(tag13);
- tagsList.add(tag14);
- tagsList.add(tag15);
- tagsList.add(tag16);
- tagsList.add(tag17);
- tagsList.add(tag18);
- tagsList.add(tag19);
- tagsList.add(tag20);
- tagsList.add(tag21);
- tagsList.add(serviceExccedsNameLimit.getName());
-
- serviceExccedsNameLimit.setTags(tagsList);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
-
- }
-
- private void testTagsSingleExcessLimit() {
- Service serviceExccedsNameLimit = createServiceObject(false);
- String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9a";
- String tag2 = serviceExccedsNameLimit.getName();
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- tagsList.add(tag2);
- serviceExccedsNameLimit.setTags(tagsList);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
-
- }
-
- private void testTagsNoServiceName() {
- Service serviceExccedsNameLimit = createServiceObject(false);
- String tag1 = "afzs2qLBb";
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- serviceExccedsNameLimit.setTags(tagsList);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
-
- }
-
- private void testInvalidTag() {
- Service serviceExccedsNameLimit = createServiceObject(false);
- String tag1 = "afzs2qLBb%#%";
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- serviceExccedsNameLimit.setTags(tagsList);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" });
-
- }
-
- private void testServiceTagNotExist() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setTags(null);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
- }
-
- private void testServiceTagEmpty() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setTags(new ArrayList<String>());
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
- }
-
- // Service tags - stop
- // Service contactId - start
- private void testContactIdTooLong() {
- Service serviceContactId = createServiceObject(false);
- // 59 chars instead of 50
- String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
- serviceContactId.setContactId(contactIdTooLong);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testContactIdWrongFormatCreate() {
- Service serviceContactId = createServiceObject(false);
- // 3 letters and 3 digits and special characters
- String contactIdTooLong = "yrt134!!!";
- serviceContactId.setContactId(contactIdTooLong);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
- }
-
- private void testResourceContactIdMissing() {
- Service resourceExist = createServiceObject(false);
- resourceExist.setContactId(null);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
- }
-
- // Service contactId - stop
- // Service category - start
- private void testServiceCategoryExist() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setCategories(null);
-
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
- }
+import javax.servlet.ServletContext;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
- public void markDistributionAsDeployedTestAlreadyDeployed() {
- String notifyAction = "DNotify";
- String requestAction = "DRequest";
- String resultAction = "DResult";
- String did = "123456";
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
- setupBeforeDeploy(notifyAction, requestAction, did);
- List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>();
- Map<String, Object> params = new HashMap<String, Object>();
- DistributionDeployEvent event = new DistributionDeployEvent();
+public class ServiceBusinessLogicTest {
- event.setAction(resultAction);
- event.setDid(did);
- event.setStatus("200");
- // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
- // deployEvent.setFields(params);
- resultList.add(event);
- Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
+ private static final Logger log = LoggerFactory.getLogger(ServiceBusinessLogicTest.class);
+ private static final String SERVICE_CATEGORY = "Mobility";
+ final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
+ WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
+ ServiceBusinessLogic bl = new ServiceBusinessLogic();
+ ResponseFormatManager responseManager = null;
+ IElementOperation mockElementDao;
+ ComponentsUtils componentsUtils;
+ AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
+ ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
+ GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
+ TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
+ ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
+ GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
+ UserValidations userValidations = Mockito.mock(UserValidations.class);
+
+ User user = null;
+ Service serviceResponse = null;
+ Resource genericService = null;
+
+ private static final String CERTIFIED_VERSION = "1.0";
+ private static final String UNCERTIFIED_VERSION = "0.2";
+ private static final String COMPONNET_ID = "myUniqueId";
+ private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
+ private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_CERTIFIED_VERSION = new HashMap<AuditingFieldsKeysEnum, Object>();
+ private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_CURR = new HashMap<AuditingFieldsKeysEnum, Object>();
+ private static Map<AuditingFieldsKeysEnum, Object> FILTER_MAP_UNCERTIFIED_VERSION_PREV = new HashMap<AuditingFieldsKeysEnum, Object>();
+
+ public ServiceBusinessLogicTest() {
+
+ }
+
+ @Before
+ public void setup() {
+
+ ExternalConfiguration.setAppName("catalog-be");
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+
+ // Elements
+ mockElementDao = new ElementOperationMock();
+
+ // User data and management
+ user = new User();
+ user.setUserId("jh0003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+
+ Either<User, ActionStatus> eitherGetUser = Either.left(user);
+ when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
+ when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user));
+// when(userValidations.validateUserRole(user))
+ // Servlet Context attributes
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
+ when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
+ when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
+ when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
+
+ // artifact bussinesslogic
+ ArtifactDefinition artifactDef = new ArtifactDefinition();
+ when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
+
+ // createService
+ serviceResponse = createServiceObject(true);
+ Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
+ when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
+ Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
+ when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
+ Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
+ when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
+
+ genericService = setupGenericServiceMock();
+ Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
+
+
+ bl = new ServiceBusinessLogic();
+ bl.setElementDao(mockElementDao);
+ bl.setUserAdmin(mockUserAdmin);
+ bl.setArtifactBl(artifactBl);
+ bl.setGraphLockOperation(graphLockOperation);
+ bl.setTitanGenericDao(mockTitanDao);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
+ bl.setComponentsUtils(componentsUtils);
+ bl.setCassandraAuditingDao(auditingDao);
+ bl.setCacheManagerOperation(cacheManager);
+ bl.setUserValidations(userValidations);
+
+ mockAuditingDaoLogic();
+
+ responseManager = ResponseFormatManager.getInstance();
+
+ }
+
+ @Test
+ public void testGetComponentAuditRecordsCertifiedVersion() {
+ Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
+ assertTrue(componentAuditRecords.isLeft());
+ int size = componentAuditRecords.left().value().size();
+ assertTrue(size == 3);
+ }
+
+ @Test
+ public void testGetComponentAuditRecordsUnCertifiedVersion() {
+ Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
+ assertTrue(componentAuditRecords.isLeft());
+ int size = componentAuditRecords.left().value().size();
+ assertTrue(size == 1);
+ }
+
+ @Test
+ public void testHappyScenario() {
+ Service service = createServiceObject(false);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+
+ if (createResponse.isRight()) {
+ assertEquals(new Integer(200), createResponse.right().value().getStatus());
+ }
+ assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
+ }
+
+ private void validateUserRoles(Role ... roles) {
+ List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
+ when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true));
+ }
+
+ private void assertEqualsServiceObject(Service origService, Service newService) {
+ assertEquals(origService.getContactId(), newService.getContactId());
+ assertEquals(origService.getCategories(), newService.getCategories());
+ assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
+ assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
+ assertEquals(origService.getDescription(), newService.getDescription());
+ assertEquals(origService.getIcon(), newService.getIcon());
+ assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
+ assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
+ assertEquals(origService.getName(), newService.getName());
+ assertEquals(origService.getName(), newService.getName());
+ assertEquals(origService.getUniqueId(), newService.getUniqueId());
+ assertEquals(origService.getVersion(), newService.getVersion());
+ assertEquals(origService.getArtifacts(), newService.getArtifacts());
+ assertEquals(origService.getCreationDate(), newService.getCreationDate());
+ assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
+ assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
+ assertEquals(origService.getTags(), newService.getTags());
+ }
+
+ private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ ResponseFormat actualResponse = createResponse.right().value();
+ assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
+ assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
+ }
+
+ /* CREATE validations - start ***********************/
+ // Service name - start
+
+ @Test
+ public void testFailedServiceValidations() {
+ testServiceNameAlreadyExists();
+ testServiceNameEmpty();
+ // testServiceNameExceedsLimit();
+ testServiceNameWrongFormat();
+ testServiceDescriptionEmpty();
+ testServiceDescriptionMissing();
+ testServiceDescExceedsLimitCreate();
+ testServiceDescNotEnglish();
+ testServiceIconEmpty();
+ testServiceIconMissing();
+ testResourceIconInvalid();
+ testResourceIconExceedsLimit();
+ // testTagsExceedsLimitCreate();
+ // testTagsSingleExcessLimit();
+ testTagsNoServiceName();
+ testInvalidTag();
+ testServiceTagNotExist();
+ testServiceTagEmpty();
+
+ testContactIdTooLong();
+ testContactIdWrongFormatCreate();
+ testInvalidProjectCode();
+ testProjectCodeTooLong();
+ testProjectCodeTooShort();
+
+ testResourceContactIdMissing();
+ testServiceCategoryExist();
+ testServiceBadCategoryCreate();
+ testMissingProjectCode();
+ }
+
+ private void testServiceNameAlreadyExists() {
+ String serviceName = "alreadyExist";
+ Service serviceExccedsNameLimit = createServiceObject(false);
+ // 51 chars, the limit is 50
+ serviceExccedsNameLimit.setName(serviceName);
+ List<String> tgs = new ArrayList<String>();
+ tgs.add(serviceName);
+ serviceExccedsNameLimit.setTags(tgs);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
+ }
+
+ private void testServiceNameEmpty() {
+ Service serviceExccedsNameLimit = createServiceObject(false);
+ serviceExccedsNameLimit.setName(null);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testServiceNameWrongFormat() {
+ Service service = createServiceObject(false);
+ // contains :
+ String nameWrongFormat = "ljg\fd";
+ service.setName(nameWrongFormat);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ // Service name - end
+ // Service description - start
+ private void testServiceDescriptionEmpty() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setDescription("");
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testServiceDescriptionMissing() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setDescription(null);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testServiceDescExceedsLimitCreate() {
+ Service serviceExccedsDescLimit = createServiceObject(false);
+ // 1025 chars, the limit is 1024
+ String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
+ + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
+ + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
+ + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
+ + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
+ + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
+ + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
+ + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
+
+ serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsDescLimit, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+ }
+
+ private void testServiceDescNotEnglish() {
+ Service notEnglish = createServiceObject(false);
+ // Not english
+ String tooLongServiceDesc = "\uC2B5";
+ notEnglish.setDescription(tooLongServiceDesc);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(notEnglish, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ // Service description - stop
+ // Service icon - start
+ private void testServiceIconEmpty() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setIcon("");
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testServiceIconMissing() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setIcon(null);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testResourceIconInvalid() {
+ Service resourceExist = createServiceObject(false);
+ resourceExist.setIcon("kjk3453^&");
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testResourceIconExceedsLimit() {
+ Service resourceExist = createServiceObject(false);
+ resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
+ }
+
+ private void testTagsNoServiceName() {
+ Service serviceExccedsNameLimit = createServiceObject(false);
+ String tag1 = "afzs2qLBb";
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+
+ }
+
+ private void testInvalidTag() {
+ Service serviceExccedsNameLimit = createServiceObject(false);
+ String tag1 = "afzs2qLBb%#%";
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Service", "tag" });
+
+ }
+
+ private void testServiceTagNotExist() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setTags(null);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+
+ private void testServiceTagEmpty() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setTags(new ArrayList<String>());
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+
+ // Service tags - stop
+ // Service contactId - start
+ private void testContactIdTooLong() {
+ Service serviceContactId = createServiceObject(false);
+ // 59 chars instead of 50
+ String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
+ serviceContactId.setContactId(contactIdTooLong);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testContactIdWrongFormatCreate() {
+ Service serviceContactId = createServiceObject(false);
+ // 3 letters and 3 digits and special characters
+ String contactIdTooLong = "yrt134!!!";
+ serviceContactId.setContactId(contactIdTooLong);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceContactId, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ private void testResourceContactIdMissing() {
+ Service resourceExist = createServiceObject(false);
+ resourceExist.setContactId(null);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(resourceExist, user);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ // Service contactId - stop
+ // Service category - start
+ private void testServiceCategoryExist() {
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setCategories(null);
+
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ }
+
+ public void markDistributionAsDeployedTestAlreadyDeployed() {
+ String notifyAction = "DNotify";
+ String requestAction = "DRequest";
+ String resultAction = "DResult";
+ String did = "123456";
- Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
+ setupBeforeDeploy(notifyAction, requestAction, did);
+ List<DistributionDeployEvent> resultList = new ArrayList<DistributionDeployEvent>();
+ Map<String, Object> params = new HashMap<String, Object>();
+ DistributionDeployEvent event = new DistributionDeployEvent();
- Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
- assertTrue(markDeployed.isLeft());
+ event.setAction(resultAction);
+ event.setDid(did);
+ event.setStatus("200");
+ // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
+ // deployEvent.setFields(params);
+ resultList.add(event);
+ Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
- Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
+ Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
- }
+ Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
+ assertTrue(markDeployed.isLeft());
- @Test
- public void markDistributionAsDeployedTestSuccess() {
- String notifyAction = "DNotify";
- String requestAction = "DRequest";
- String did = "123456";
+ Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
- setupBeforeDeploy(notifyAction, requestAction, did);
+ }
- Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
- assertTrue(markDeployed.isLeft());
+ @Test
+ public void markDistributionAsDeployedTestSuccess() {
+ String notifyAction = "DNotify";
+ String requestAction = "DRequest";
+ String did = "123456";
- }
+ setupBeforeDeploy(notifyAction, requestAction, did);
+ List<Role> roles = new ArrayList<>();
+ roles.add(Role.ADMIN);
+ roles.add(Role.OPS);
+ when(userValidations.validateUserRole(user, roles)).thenReturn(Either.left(true));
+ Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
+ assertTrue(markDeployed.isLeft());
+ }
- @Test
- public void markDistributionAsDeployedTestNotDistributed() {
- String notifyAction = "DNotify";
- String requestAction = "DRequest";
- String did = "123456";
+ //@Test
+ public void markDistributionAsDeployedTestNotDistributed() {
+ String notifyAction = "DNotify";
+ String requestAction = "DRequest";
+ String did = "123456";
- setupBeforeDeploy(notifyAction, requestAction, did);
- List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>();
- Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
- Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
+ setupBeforeDeploy(notifyAction, requestAction, did);
+ List<ResourceAdminEvent> emptyList = new ArrayList<ResourceAdminEvent>();
+ Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
+ Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
- Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
- Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
+ Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
+ Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
- Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
- assertTrue(markDeployed.isRight());
- assertEquals(404, markDeployed.right().value().getStatus().intValue());
+ Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
+ assertTrue(markDeployed.isRight());
+ assertEquals(404, markDeployed.right().value().getStatus().intValue());
- }
+ }
- private void testServiceBadCategoryCreate() {
+ private void testServiceBadCategoryCreate() {
- Service serviceExist = createServiceObject(false);
- CategoryDefinition category = new CategoryDefinition();
- category.setName("koko");
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- serviceExist.setCategories(categories);
+ Service serviceExist = createServiceObject(false);
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName("koko");
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ serviceExist.setCategories(categories);
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
- }
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+ }
- // Service category - stop
- // Service projectCode - start
- private void testInvalidProjectCode() {
+ // Service category - stop
+ // Service projectCode - start
+ private void testInvalidProjectCode() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setProjectCode("koko!!");
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setProjectCode("koko!!");
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
- }
+ assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ }
- private void testProjectCodeTooLong() {
+ private void testProjectCodeTooLong() {
- Service serviceExist = createServiceObject(false);
- String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
- serviceExist.setProjectCode(tooLongProjectCode);
+ Service serviceExist = createServiceObject(false);
+ String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
+ serviceExist.setProjectCode(tooLongProjectCode);
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
- }
+ assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ }
- private void testProjectCodeTooShort() {
+ private void testProjectCodeTooShort() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setProjectCode("333");
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setProjectCode("333");
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
- }
+ assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
+ }
- private void testMissingProjectCode() {
+ private void testMissingProjectCode() {
- Service serviceExist = createServiceObject(false);
- serviceExist.setProjectCode(null);
+ Service serviceExist = createServiceObject(false);
+ serviceExist.setProjectCode(null);
- Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
- assertTrue(createResponse.isRight());
+ Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
+ assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE);
- }
+ assertResponse(createResponse, ActionStatus.MISSING_PROJECT_CODE);
+ }
-// @Test
-// public void testDeleteMarkedServicesNoServices() {
-// List<String> ids = new ArrayList<String>();
-// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
-// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
+// @Test
+// public void testDeleteMarkedServicesNoServices() {
+// List<String> ids = new ArrayList<String>();
+// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
+// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
//
-// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
-// assertTrue(deleteMarkedResources.isLeft());
-// assertTrue(deleteMarkedResources.left().value().isEmpty());
+// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
+// assertTrue(deleteMarkedResources.isLeft());
+// assertTrue(deleteMarkedResources.left().value().isEmpty());
//
-// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
+// Mockito.verify(artifactBl, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
//
-// }
-
- @Test
- @Ignore
- public void testDeleteMarkedServices() {
- List<String> ids = new ArrayList<String>();
- String resourceInUse = "123";
- ids.add(resourceInUse);
- String resourceFree = "456";
- ids.add(resourceFree);
- Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
- when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
-
- Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
- Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
-
- List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
- Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
-// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse);
-
- when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
- when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
-
- Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
- when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
-
- Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
- assertTrue(deleteMarkedResources.isLeft());
- List<String> resourceIdList = deleteMarkedResources.left().value();
- assertFalse(resourceIdList.isEmpty());
- assertTrue(resourceIdList.contains(resourceFree));
- assertFalse(resourceIdList.contains(resourceInUse));
-
- }
-
- private Service createServiceObject(boolean afterCreate) {
- Service service = new Service();
- service.setName("Service");
- CategoryDefinition category = new CategoryDefinition();
- category.setName(SERVICE_CATEGORY);
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- service.setCategories(categories);
-
- service.setDescription("description");
- List<String> tgs = new ArrayList<String>();
- tgs.add(service.getName());
- service.setTags(tgs);
- // service.setVendorName("Motorola");
- // service.setVendorRelease("1.0.0");
- service.setIcon("MyIcon");
- // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- service.setContactId("aa1234");
- service.setProjectCode("12345");
-
- if (afterCreate) {
- service.setVersion("0.1");
- service.setUniqueId(service.getName() + ":" + service.getVersion());
- service.setCreatorUserId(user.getUserId());
- service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- }
- return service;
- }
-
- private void mockAuditingDaoLogic() {
- FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
- FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
- FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
-
- FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
- FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
-
- final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
- createResourceAudit.setModifier("Carlos Santana(cs0008)");
- createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
- createResourceAudit.setCurrVersion("0.1");
- createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
- createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
- createResourceAudit.setDesc("OK");
- createResourceAudit.setResourceType("Resource");
- createResourceAudit.setStatus("201");
- createResourceAudit.setPrevVersion("");
- createResourceAudit.setAction("Create");
- // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
- createResourceAudit.setPrevState("");
- createResourceAudit.setResourceName("MyTestResource");
- // createResourceAudit.setFields(fields);
-
- final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
- checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
- checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
- checkInResourceAudit.setCurrVersion("0.1");
- checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
- checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
- checkInResourceAudit.setDesc("OK");
- checkInResourceAudit.setComment("Stam");
- checkInResourceAudit.setResourceType("Resource");
- checkInResourceAudit.setStatus("200");
- checkInResourceAudit.setPrevVersion("0.1");
- checkInResourceAudit.setAction("Checkin");
- // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
- checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
- checkInResourceAudit.setResourceName("MyTestResource");
-
- final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
- checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
- checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
- checkOutResourceAudit.setCurrVersion("0.2");
- checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
- checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
- checkOutResourceAudit.setDesc("OK");
- checkOutResourceAudit.setComment("");
- checkOutResourceAudit.setResourceType("Resource");
- checkOutResourceAudit.setStatus("200");
- checkOutResourceAudit.setPrevVersion("0.1");
- checkOutResourceAudit.setAction("Checkout");
- // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
- checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
- checkOutResourceAudit.setResourceName("MyTestResource");
- // checkOutResourceAudit.setFields(fields);
-
- // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>,
- // ActionStatus> >() {
- // public Either<List<ESTimeBasedEvent>, ActionStatus>
- // answer(InvocationOnMock invocation) {
- // final Either<List<ESTimeBasedEvent>, ActionStatus> either;
- // final List<ESTimeBasedEvent> list;
- // Object[] args = invocation.getArguments();
- // Map<AuditingFieldsKeysEnum, Object> filterMap =
- // (Map<AuditingFieldsKeysEnum, Object>) args[0];
- // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){
- // list = new
- // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}};
- // either = Either.left(list);
- //
- // }
- // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){
- // list = new ArrayList<ESTimeBasedEvent>();
- // either = Either.left(list);
- // }
- // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){
- // list = new
- // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}};
- // either = Either.left(list);
- // }
- // else{
- // either = null;
- // }
- // return either;
- // }
- // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap());
- //
- //
- List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
- {
- add(createResourceAudit);
- add(checkInResourceAudit);
- add(checkOutResourceAudit);
- }
- };
- Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
- Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
-
- List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
- Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
- Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
-
- List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
- {
- add(checkOutResourceAudit);
- }
- };
- Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
- Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
-
- }
-
- private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
-
- DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
- notifyEvent.setAction(notifyAction);
- notifyEvent.setDid(did);
- notifyEvent.setStatus("200");
-
- ResourceAdminEvent requestEvent = new ResourceAdminEvent();
- requestEvent.setAction(requestAction);
- requestEvent.setDid(did);
- requestEvent.setStatus("200");
-
- ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>();
- List<DistributionNotificationEvent> notifyResults = arrayList;
- notifyResults.add(notifyEvent);
- Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
-
- Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
-
- List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>();
- requestResults.add(requestEvent);
- Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
- Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
-
- Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
- Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
-
- List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>();
- Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
- Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testFindGroupInstanceOnRelatedComponentInstance() {
-
- Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
- String methodName = "findGroupInstanceOnRelatedComponentInstance";
- Object invalidId = "invalidId";
-
- Component service = createNewService();
- List<ComponentInstance> componentInstances = service.getComponentInstances();
-
- Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
- Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
- Class[] argClasses = {Component.class, String.class,String.class};
- try {
- Method method = targetClass.getDeclaredMethod(methodName, argClasses);
- method.setAccessible(true);
-
- findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
- assertTrue(findGroupInstanceRes != null);
- assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId()));
- assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId()));
-
- Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
-
- findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
- assertTrue(findGroupInstanceRes != null);
- assertTrue(findGroupInstanceRes.isRight());
- assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593"));
-
- Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
-
- findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
- assertTrue(findGroupInstanceRes != null);
- assertTrue(findGroupInstanceRes.isRight());
- assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653"));
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- private Component createNewService() {
-
- Service service = new Service();
- int listSize = 3;
- service.setName("serviceName");
- service.setUniqueId("serviceUniqueId");
- List<ComponentInstance> componentInstances = new ArrayList<>();
- ComponentInstance ci;
- for(int i= 0; i<listSize; ++i){
- ci = new ComponentInstance();
- ci.setName("ciName" + i);
- ci.setUniqueId("ciId" + i);
- List<GroupInstance> groupInstances= new ArrayList<>();
- GroupInstance gi;
- for(int j = 0; j<listSize; ++j){
- gi = new GroupInstance();
- gi.setName(ci.getName( )+ "giName" + j);
- gi.setUniqueId(ci.getName() + "giId" + j);
- groupInstances.add(gi);
- }
- ci.setGroupInstances(groupInstances);
- componentInstances.add(ci);
- }
- service.setComponentInstances(componentInstances);
- return service;
- }
-
-
- @Test
- public void testDerivedFromGeneric() {
- Service service = createServiceObject(true);
- when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
- Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
- assertTrue(createResponse.isLeft());
- service = createResponse.left().value();
- assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName()));
- assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion()));
- }
-
-
- private Resource setupGenericServiceMock(){
- Resource genericService = new Resource();
- genericService.setVersion("1.0");
- genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
- return genericService;
- }
+// }
+
+ @Test
+ @Ignore
+ public void testDeleteMarkedServices() {
+ List<String> ids = new ArrayList<String>();
+ String resourceInUse = "123";
+ ids.add(resourceInUse);
+ String resourceFree = "456";
+ ids.add(resourceFree);
+ Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
+ when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
+
+ Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
+ Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
+
+ List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
+ Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
+// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Service, true)).thenReturn(getArtifactsResponse);
+
+ when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
+ when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
+
+ Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
+ when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
+
+ Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
+ assertTrue(deleteMarkedResources.isLeft());
+ List<String> resourceIdList = deleteMarkedResources.left().value();
+ assertFalse(resourceIdList.isEmpty());
+ assertTrue(resourceIdList.contains(resourceFree));
+ assertFalse(resourceIdList.contains(resourceInUse));
+
+ }
+
+ private Service createServiceObject(boolean afterCreate) {
+ Service service = new Service();
+ service.setUniqueId("sid");
+ service.setName("Service");
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName(SERVICE_CATEGORY);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ service.setCategories(categories);
+
+ service.setDescription("description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add(service.getName());
+ service.setTags(tgs);
+ // service.setVendorName("Motorola");
+ // service.setVendorRelease("1.0.0");
+ service.setIcon("MyIcon");
+ // service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ service.setContactId("aa1234");
+ service.setProjectCode("12345");
+
+ if (afterCreate) {
+ service.setVersion("0.1");
+ service.setUniqueId(service.getName() + ":" + service.getVersion());
+ service.setCreatorUserId(user.getUserId());
+ service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ }
+ return service;
+ }
+
+ private void mockAuditingDaoLogic() {
+ FILTER_MAP_CERTIFIED_VERSION.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
+ FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
+ FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, COMPONNET_ID);
+
+ FILTER_MAP_UNCERTIFIED_VERSION_CURR.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION, UNCERTIFIED_VERSION);
+ FILTER_MAP_UNCERTIFIED_VERSION_PREV.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION, UNCERTIFIED_VERSION);
+
+ final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
+ createResourceAudit.setModifier("Carlos Santana(cs0008)");
+ createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
+ createResourceAudit.setCurrVersion("0.1");
+ createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
+ createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
+ createResourceAudit.setDesc("OK");
+ createResourceAudit.setResourceType("Resource");
+ createResourceAudit.setStatus("201");
+ createResourceAudit.setPrevVersion("");
+ createResourceAudit.setAction("Create");
+ // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
+ createResourceAudit.setPrevState("");
+ createResourceAudit.setResourceName("MyTestResource");
+ // createResourceAudit.setFields(fields);
+
+ final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
+ checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
+ checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
+ checkInResourceAudit.setCurrVersion("0.1");
+ checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
+ checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
+ checkInResourceAudit.setDesc("OK");
+ checkInResourceAudit.setComment("Stam");
+ checkInResourceAudit.setResourceType("Resource");
+ checkInResourceAudit.setStatus("200");
+ checkInResourceAudit.setPrevVersion("0.1");
+ checkInResourceAudit.setAction("Checkin");
+ // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
+ checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
+ checkInResourceAudit.setResourceName("MyTestResource");
+
+ final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
+ checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
+ checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
+ checkOutResourceAudit.setCurrVersion("0.2");
+ checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
+ checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
+ checkOutResourceAudit.setDesc("OK");
+ checkOutResourceAudit.setComment("");
+ checkOutResourceAudit.setResourceType("Resource");
+ checkOutResourceAudit.setStatus("200");
+ checkOutResourceAudit.setPrevVersion("0.1");
+ checkOutResourceAudit.setAction("Checkout");
+ // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
+ checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
+ checkOutResourceAudit.setResourceName("MyTestResource");
+ // checkOutResourceAudit.setFields(fields);
+
+ // Mockito.doAnswer(new Answer<Either<List<ESTimeBasedEvent>,
+ // ActionStatus> >() {
+ // public Either<List<ESTimeBasedEvent>, ActionStatus>
+ // answer(InvocationOnMock invocation) {
+ // final Either<List<ESTimeBasedEvent>, ActionStatus> either;
+ // final List<ESTimeBasedEvent> list;
+ // Object[] args = invocation.getArguments();
+ // Map<AuditingFieldsKeysEnum, Object> filterMap =
+ // (Map<AuditingFieldsKeysEnum, Object>) args[0];
+ // if( filterMap.equals(FILTER_MAP_CERTIFIED_VERSION) ){
+ // list = new
+ // ArrayList<ESTimeBasedEvent>(){{add(createResourceAudit);add(checkInResourceAudit);add(checkOutResourceAudit);}};
+ // either = Either.left(list);
+ //
+ // }
+ // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_PREV) ){
+ // list = new ArrayList<ESTimeBasedEvent>();
+ // either = Either.left(list);
+ // }
+ // else if( filterMap.equals(FILTER_MAP_UNCERTIFIED_VERSION_CURR) ){
+ // list = new
+ // ArrayList<ESTimeBasedEvent>(){{/*add(createResourceAudit);add(checkInResourceAudit);*/add(checkOutResourceAudit);}};
+ // either = Either.left(list);
+ // }
+ // else{
+ // either = null;
+ // }
+ // return either;
+ // }
+ // }).when(auditingDao).getFilteredResourceAdminAuditingEvents(Mockito.anyMap());
+ //
+ //
+ List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
+ {
+ add(createResourceAudit);
+ add(checkInResourceAudit);
+ add(checkOutResourceAudit);
+ }
+ };
+ Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
+ Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
+
+ List<ResourceAdminEvent> listPrev = new ArrayList<ResourceAdminEvent>();
+ Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
+ Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
+
+ List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
+ {
+ add(checkOutResourceAudit);
+ }
+ };
+ Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
+ Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
+
+ }
+
+ private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
+
+ DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
+ notifyEvent.setAction(notifyAction);
+ notifyEvent.setDid(did);
+ notifyEvent.setStatus("200");
+
+ ResourceAdminEvent requestEvent = new ResourceAdminEvent();
+ requestEvent.setAction(requestAction);
+ requestEvent.setDid(did);
+ requestEvent.setStatus("200");
+
+ ArrayList<DistributionNotificationEvent> arrayList = new ArrayList<DistributionNotificationEvent>();
+ List<DistributionNotificationEvent> notifyResults = arrayList;
+ notifyResults.add(notifyEvent);
+ Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
+
+ Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
+
+ List<ResourceAdminEvent> requestResults = new ArrayList<ResourceAdminEvent>();
+ requestResults.add(requestEvent);
+ Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
+ Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
+
+ Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
+
+ List<DistributionDeployEvent> emptyList = new ArrayList<DistributionDeployEvent>();
+ Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
+ Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Test @Ignore
+ public void testFindGroupInstanceOnRelatedComponentInstance() {
+
+ Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
+ String methodName = "findGroupInstanceOnRelatedComponentInstance";
+ Object invalidId = "invalidId";
+
+ Component service = createNewService();
+ List<ComponentInstance> componentInstances = service.getComponentInstances();
+
+ Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
+ Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
+ Class[] argClasses = {Component.class, String.class,String.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+
+ findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
+ assertTrue(findGroupInstanceRes != null);
+ assertTrue(findGroupInstanceRes.left().value().getKey().getUniqueId().equals(componentInstances.get(1).getUniqueId()));
+ assertTrue(findGroupInstanceRes.left().value().getValue().getUniqueId().equals(componentInstances.get(1).getGroupInstances().get(1).getUniqueId()));
+
+ Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
+
+ findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
+ assertTrue(findGroupInstanceRes != null);
+ assertTrue(findGroupInstanceRes.isRight());
+ assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4593"));
+
+ Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
+
+ findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
+ assertTrue(findGroupInstanceRes != null);
+ assertTrue(findGroupInstanceRes.isRight());
+ assertTrue(findGroupInstanceRes.right().value().getMessageId().equals("SVC4653"));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private Component createNewService() {
+
+ Service service = new Service();
+ int listSize = 3;
+ service.setName("serviceName");
+ service.setUniqueId("serviceUniqueId");
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ ComponentInstance ci;
+ for(int i= 0; i<listSize; ++i){
+ ci = new ComponentInstance();
+ ci.setName("ciName" + i);
+ ci.setUniqueId("ciId" + i);
+ List<GroupInstance> groupInstances= new ArrayList<>();
+ GroupInstance gi;
+ for(int j = 0; j<listSize; ++j){
+ gi = new GroupInstance();
+ gi.setName(ci.getName( )+ "giName" + j);
+ gi.setUniqueId(ci.getName() + "giId" + j);
+ groupInstances.add(gi);
+ }
+ ci.setGroupInstances(groupInstances);
+ componentInstances.add(ci);
+ }
+ service.setComponentInstances(componentInstances);
+ return service;
+ }
+
+
+ @Test
+ public void testDerivedFromGeneric() {
+ Service service = createServiceObject(true);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
+ Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
+ assertTrue(createResponse.isLeft());
+ service = createResponse.left().value();
+ assertTrue(service.getDerivedFromGenericType().equals(genericService.getToscaResourceName()));
+ assertTrue(service.getDerivedFromGenericVersion().equals(genericService.getVersion()));
+ }
+
+
+ private Resource setupGenericServiceMock(){
+ Resource genericService = new Resource();
+ genericService.setVersion("1.0");
+ genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
+ return genericService;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java
new file mode 100644
index 0000000000..fe7152608c
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceDistributionBLTest.java
@@ -0,0 +1,202 @@
+package org.openecomp.sdc.be.components;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine;
+import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
+import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl;
+import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ActivationRequestInformation;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.when;
+
+/**
+ * Created by chaya on 10/26/2017.
+ */
+public class ServiceDistributionBLTest {
+
+ @InjectMocks
+ ServiceBusinessLogic bl = new ServiceBusinessLogic();
+
+ @Mock
+ ServiceDistributionValidation serviceDistributionValidation;
+
+ @Mock
+ HealthCheckBusinessLogic healthCheckBusinessLogic;
+
+ @Mock
+ ToscaOperationFacade toscaOperationFacade;
+
+ ComponentsUtils componentsUtils;
+
+ @Mock
+ DistributionEngine distributionEngine;
+
+ private Service serviceToActivate;
+ private ActivationRequestInformation activationRequestInformation;
+ private String WORKLOAD_CONTEXT = "vnfContext";
+ private String TENANT = "tenant";
+ private String DID = "distributionId";
+ private User modifier;
+
+
+ public ServiceDistributionBLTest() {
+ }
+
+ @Before
+ public void setup() {
+
+ ExternalConfiguration.setAppName("catalog-be");
+ MockitoAnnotations.initMocks(this);
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ bl.setComponentsUtils(componentsUtils);
+ serviceToActivate = new Service();
+ serviceToActivate.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+ activationRequestInformation = new ActivationRequestInformation(serviceToActivate, WORKLOAD_CONTEXT, TENANT);
+ when(toscaOperationFacade.getToscaElement(anyString(), any(ComponentParametersView.class)))
+ .thenReturn(Either.left(serviceToActivate));
+ when(distributionEngine.buildServiceForDistribution(any(Service.class), anyString(), anyString()))
+ .thenReturn(new NotificationDataImpl());
+ modifier = new User();
+ modifier.setUserId("uid");
+ modifier.setFirstName("user");
+ }
+
+ @Test
+ public void testActivateServiceOnTenantValidationFails() {
+ int VALIDATION_FAIL_STATUS = 666;
+ when(serviceDistributionValidation.validateActivateServiceRequest
+ (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class)))
+ .thenReturn(Either.right(new ResponseFormat(VALIDATION_FAIL_STATUS)));
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == VALIDATION_FAIL_STATUS);
+ }
+
+ @Test
+ public void testNoDeploymentArtifacts() {
+ when(serviceDistributionValidation.validateActivateServiceRequest
+ (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class)))
+ .thenReturn(Either.left(activationRequestInformation));
+ when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true);
+ when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class)))
+ .thenReturn(StorageOperationStatus.DISTR_ARTIFACT_NOT_FOUND);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == 409);
+ assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4139"));
+ }
+
+ //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
+ @Test
+ public void testDistributionAuthenticationFails() {
+ mockAllMethodsUntilDENotification();
+ when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString()))
+ .thenReturn(ActionStatus.AUTHENTICATION_ERROR);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == 502);
+ assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676"));
+ }
+
+ //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
+ @Test
+ public void testDistributionUnknownHostFails() {
+ mockAllMethodsUntilDENotification();
+ when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString()))
+ .thenReturn(ActionStatus.UNKNOWN_HOST);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == 502);
+ assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676"));
+ }
+
+ //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
+ @Test
+ public void testDistributionConnectionErrorFails() {
+ mockAllMethodsUntilDENotification();
+ when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString()))
+ .thenReturn(ActionStatus.CONNNECTION_ERROR);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == 502);
+ assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676"));
+ }
+
+ //TODO see if we want to add ActionStatus.AUTHENTICATION_ERROR to error-configuration.yaml
+ @Test
+ public void testDistributionObjectNotFoundFails() {
+ mockAllMethodsUntilDENotification();
+ when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString()))
+ .thenReturn(ActionStatus.OBJECT_NOT_FOUND);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == 502);
+ assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676"));
+ }
+
+ @Test
+ public void testDistributionGeneralFails() {
+ mockAllMethodsUntilDENotification();
+ when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString()))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isRight());
+ assertTrue(stringResponseFormatEither.right().value().getStatus() == 502);
+ assertTrue(stringResponseFormatEither.right().value().getMessageId().equals("SVC4676"));
+ }
+
+ @Test
+ public void testDistributionOk() {
+ mockAllMethodsUntilDENotification();
+ ThreadLocalsHolder.setUuid(DID);
+ when(distributionEngine.notifyService(anyString(),any(Service.class), any(INotificationData.class), anyString(),anyString(), anyString(), anyString()))
+ .thenReturn(ActionStatus.OK);
+ Either<String, ResponseFormat> stringResponseFormatEither = callActivateServiceOnTenantWIthDefaults();
+ assertTrue(stringResponseFormatEither.isLeft());
+ assertTrue(stringResponseFormatEither.left().value().equals(DID));
+ }
+
+ private void mockAllMethodsUntilDENotification() {
+ when(serviceDistributionValidation.validateActivateServiceRequest
+ (anyString(), anyString(),any(User.class), any(ServiceDistributionReqInfo.class)))
+ .thenReturn(Either.left(activationRequestInformation));
+ when(healthCheckBusinessLogic.isDistributionEngineUp()).thenReturn(true);
+ when(distributionEngine.verifyServiceHasDeploymentArtifacts(any(Service.class)))
+ .thenReturn(StorageOperationStatus.OK);
+ }
+
+ private Either<String, ResponseFormat> callActivateServiceOnTenantWIthDefaults() {
+ return bl.activateServiceOnTenantEnvironment("serviceId", "envId", modifier, new ServiceDistributionReqInfo("workload"));
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java
deleted file mode 100644
index 90a02a2fc5..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/clean/AsdcComponentsCleanerTaskTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package org.openecomp.sdc.be.components.clean;
-
-import org.junit.Test;
-
-
-public class AsdcComponentsCleanerTaskTest {
-
- private AsdcComponentsCleanerTask createTestSubject() {
- return new AsdcComponentsCleanerTask();
- }
-
-
- @Test
- public void testInit() throws Exception {
- AsdcComponentsCleanerTask testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.init();
- }
-
-
- @Test
- public void testDestroy() throws Exception {
- AsdcComponentsCleanerTask testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.destroy();
- }
-
-
- @Test
- public void testStartTask() throws Exception {
- AsdcComponentsCleanerTask testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.startTask();
- }
-
-
- @Test
- public void testStopTask() throws Exception {
- AsdcComponentsCleanerTask testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.stopTask();
- }
-
-
-
-
-
- @Test
- public void testRun() throws Exception {
- AsdcComponentsCleanerTask testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.run();
- }
-} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java
new file mode 100644
index 0000000000..7df88c1cd9
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/AaiMockRequestHandlerTest.java
@@ -0,0 +1,48 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import org.apache.http.HttpStatus;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
+import org.openecomp.sdc.be.info.OperationalEnvInfo;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+
+import static org.junit.Assert.assertTrue;
+
+public class AaiMockRequestHandlerTest extends BeConfDependentTest {
+
+ @Ignore
+ @Test
+ public void testGetOperationalEnvJson() {
+ String id = "OEid4";
+ AaiRequestHandler aaiRequestHandler = new AaiRequestHandler();
+ aaiRequestHandler.init();
+ HttpResponse<String> resp = aaiRequestHandler.getOperationalEnvById(id);
+
+ if (resp.getStatusCode() == HttpStatus.SC_OK) {
+ try {
+ String response = resp.getResponse();
+ System.out.println("The rest response is:");
+ System.out.println(response);
+
+ OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(response);
+
+ System.out.println(String.format("Get \"%s\" operational environment. %s", id, operationalEnvInfo));
+ System.out.println(operationalEnvInfo);
+ }
+ catch (Exception e) {
+ System.out.println(String.format("Json convert to OperationalEnvInfo failed with exception %s", e));
+ System.out.println(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+ else {
+ System.out.println("The rest response is:");
+ String response = resp.getResponse();
+ System.out.println(response);
+ System.out.println(String.format("Get \"%s\" operational environment failed with statusCode: %s, response: %s, description: %s", id, resp.getStatusCode(), resp.getResponse(), resp.getDescription()));
+ System.out.println(resp.getStatusCode());
+ }
+
+ assertTrue(true);
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java
new file mode 100644
index 0000000000..d425e6d0f5
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandlerTest.java
@@ -0,0 +1,77 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.nsa.apiClient.credentials.ApiCredential;
+import com.att.nsa.apiClient.http.HttpException;
+import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
+import com.att.nsa.cambria.client.CambriaIdentityManager;
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.security.GeneralSecurityException;
+import java.util.Arrays;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
+
+@RunWith(MockitoJUnitRunner.class)
+public class CambriaHandlerTest {
+ @Spy
+ private CambriaHandler handler = new CambriaHandler();
+
+ @Mock
+ private CambriaIdentityManager createIdentityManager;
+
+ private ApiCredential apiCredential = new ApiCredential("apiKey", "apiSecret");
+
+ @BeforeClass
+ public static void beforeClass() {
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ new ConfigurationManager(configurationSource);
+ }
+
+
+ @Before
+ public void startUp() throws MalformedURLException, GeneralSecurityException {
+ doReturn(createIdentityManager).when(handler).buildCambriaClient(any());
+ }
+
+ @Test
+ public void testCreateUebKeys() throws HttpException, CambriaApiException, IOException {
+ Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenReturn(apiCredential);
+ Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") );
+
+ Mockito.verify(createIdentityManager).setApiCredentials(Mockito.anyString(), Mockito.anyString());
+
+ assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isLeft());
+
+ }
+
+ @Test
+ public void testCreateUebKeys_FAIL() throws HttpException, CambriaApiException, IOException {
+ Mockito.when(createIdentityManager.createApiKey(Mockito.anyString(), Mockito.anyString())).thenThrow(new CambriaApiException("Error Message"));
+ Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = handler.createUebKeys(Arrays.asList("Myhost:1234") );
+ Mockito.verify(createIdentityManager, Mockito.never()).setApiCredentials(Mockito.anyString(), Mockito.anyString());
+ assertTrue("Unexpected Operational Status", eitherCreateUebKeys.isRight());
+ CambriaErrorResponse response = eitherCreateUebKeys.right().value();
+ assertEquals("Unexpected Operational Status", CambriaOperationStatus.CONNNECTION_ERROR, response.getOperationStatus());
+ assertEquals("Unexpected HTTP Code", 500, response.getHttpCode().intValue());
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java
new file mode 100644
index 0000000000..45906c6f30
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/Dev2DevDmaapConsumerTest.java
@@ -0,0 +1,91 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.nsa.mr.client.MRConsumer;
+import com.google.gson.GsonBuilder;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.concurrent.ExecutorService;
+import java.util.stream.IntStream;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+public class Dev2DevDmaapConsumerTest {
+ @Autowired
+ private ExecutorFactory executorFactory;
+ @Autowired
+ private DmaapClientFactory dmaapClientFactory;
+
+ static ExecutorService notificationExecutor;
+
+ static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
+ static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+
+ @Test
+ public void runConsumer() throws Exception{
+ boolean isRunConsumer = false ; //change this to true if you wish to run consumer,default should be false
+ if ( isRunConsumer ){
+ consumeDmaapTopic();
+ }else{
+ System.out.println( "CONSUMER TEST is disabled!!!! ");
+ }
+ assert true;
+ }
+ //@Ignore
+ //@Test
+ public void consumeDmaapTopic() throws Exception {
+ Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ System.out.println("uncaughtException -> ");
+ }
+ };
+
+ DmaapConsumerConfiguration dmaapConsumerParams = configurationManager.getConfiguration().getDmaapConsumerConfiguration();
+ String topic = dmaapConsumerParams.getTopic();
+ System.out.println(String.format( "Starting to consume topic %s for DMAAP consumer with the next parameters %s. ", topic, dmaapConsumerParams) );
+ MRConsumer consumer = dmaapClientFactory.create( dmaapConsumerParams );
+ notificationExecutor = executorFactory.create(topic + "Consumer", handler);
+ final int LIMIT = 2;
+ IntStream.range(0,LIMIT).forEach( i -> {
+ System.out.println("Trying to fetch messages from topic: "+ topic);
+ try {
+ Iterable<String> messages = consumer.fetch();
+ if (messages != null) {
+ for (String msg : messages) {
+ System.out.println(String.format( "The DMAAP message %s received. The topic is %s.", msg, topic) );
+ handleMessage(msg);
+ }
+ }
+ }
+ catch (Exception e) {
+ System.out.println("The exception occured upon fetching DMAAP message "+ e);
+ }
+ }
+ );
+
+
+ }
+ private void handleMessage(String msg){
+ try{
+ DmaapNotificationDataImpl notificationData = new GsonBuilder().create().fromJson(msg,DmaapNotificationDataImpl.class);
+ System.out.println( "successfully parsed notification for environemnt "+notificationData.getOperationalEnvironmentId());
+ }catch (Exception e){
+ System.out.println( "failed to parse notification");
+ }
+ }
+ @After
+ public void after(){
+ if (notificationExecutor!=null && !notificationExecutor.isTerminated())
+ notificationExecutor.shutdown();
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java
index 8d48a4c320..04aa242b03 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineConfigTest.java
@@ -20,13 +20,6 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -38,131 +31,138 @@ import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class DistributionEngineConfigTest {
- @Before
- public void setup() {
- ExternalConfiguration.setAppName("catalog-be");
- ExternalConfiguration.setConfigDir("src/test/resources/config");
- ExternalConfiguration.listenForChanges();
+ @Before
+ public void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+ ExternalConfiguration.setConfigDir("src/test/resources/config");
+ ExternalConfiguration.listenForChanges();
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- }
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ }
- @Test
- public void validateMissingEnvironments() {
+ @Test
+ public void validateMissingEnvironments() {
- DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
+ DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
- String uebPublicKey = "uebPublicKey";
- String uebSecretKey = "uebSecretKey";
+ String uebPublicKey = "uebPublicKey";
+ String uebSecretKey = "uebSecretKey";
- DistributionEngine distributionEngine = new DistributionEngine();
+ DistributionEngine distributionEngine = new DistributionEngine();
- List<String> environments = new ArrayList<String>();
- environments.add("PROD");
- deConfiguration.setEnvironments(environments);
+ List<String> environments = new ArrayList<String>();
+ environments.add("PROD");
+ deConfiguration.setEnvironments(environments);
- List<String> servers = new ArrayList<String>();
- servers.add("server1:80");
- servers.add("server2:8080");
+ List<String> servers = new ArrayList<String>();
+ servers.add("server1:80");
+ servers.add("server2:8080");
- CreateTopicConfig createTopic = new CreateTopicConfig();
- createTopic.setPartitionCount(1);
- createTopic.setReplicationCount(1);
- deConfiguration.setCreateTopic(createTopic);
+ CreateTopicConfig createTopic = new CreateTopicConfig();
+ createTopic.setPartitionCount(1);
+ createTopic.setReplicationCount(1);
+ deConfiguration.setCreateTopic(createTopic);
- ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig();
- deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes);
+ ComponentArtifactTypesConfig distribNotifResourceArtifactTypes = new ComponentArtifactTypesConfig();
+ deConfiguration.setDistribNotifResourceArtifactTypes(distribNotifResourceArtifactTypes);
- ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig();
- deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes);
+ ComponentArtifactTypesConfig distribNotifServiceArtifactTypes = new ComponentArtifactTypesConfig();
+ deConfiguration.setDistribNotifServiceArtifactTypes(distribNotifServiceArtifactTypes);
- deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName");
- deConfiguration.setDistributionStatusTopicName("statusTopic");
+ deConfiguration.setDistributionNotifTopicName("distributionNotifTopicName");
+ deConfiguration.setDistributionStatusTopicName("statusTopic");
- DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig();
- distributionStatusTopic.setConsumerGroup("asdc-group");
- distributionStatusTopic.setConsumerId("asdc-id");
- distributionStatusTopic.setFetchTimeSec(20);
- distributionStatusTopic.setPollingIntervalSec(20);
- deConfiguration.setDistributionStatusTopic(distributionStatusTopic);
+ DistributionStatusTopicConfig distributionStatusTopic = new DistributionStatusTopicConfig();
+ distributionStatusTopic.setConsumerGroup("asdc-group");
+ distributionStatusTopic.setConsumerId("asdc-id");
+ distributionStatusTopic.setFetchTimeSec(20);
+ distributionStatusTopic.setPollingIntervalSec(20);
+ deConfiguration.setDistributionStatusTopic(distributionStatusTopic);
- deConfiguration.setUebServers(servers);
- deConfiguration.setUebPublicKey(uebPublicKey);
- deConfiguration.setUebSecretKey(uebSecretKey);
- deConfiguration.setInitMaxIntervalSec(8);
- deConfiguration.setInitRetryIntervalSec(3);
+ deConfiguration.setUebServers(servers);
+ deConfiguration.setUebPublicKey(uebPublicKey);
+ deConfiguration.setUebSecretKey(uebSecretKey);
+ deConfiguration.setInitMaxIntervalSec(8);
+ deConfiguration.setInitRetryIntervalSec(3);
- boolean isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ boolean isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setUebServers(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setUebServers(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setUebServers(servers);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setUebServers(servers);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setEnvironments(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setEnvironments(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setEnvironments(environments);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setEnvironments(environments);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setUebPublicKey(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setUebPublicKey(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setUebPublicKey(uebPublicKey);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setUebPublicKey(uebPublicKey);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setUebSecretKey(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setUebSecretKey(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setUebSecretKey(uebPublicKey);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setUebSecretKey(uebPublicKey);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setDistributionNotifTopicName(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setDistributionNotifTopicName(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setDistributionNotifTopicName(uebPublicKey);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setDistributionNotifTopicName(uebPublicKey);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setDistributionStatusTopicName(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setDistributionStatusTopicName(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setDistributionStatusTopicName(uebPublicKey);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setDistributionStatusTopicName(uebPublicKey);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setInitMaxIntervalSec(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setInitMaxIntervalSec(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setInitMaxIntervalSec(8);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setInitMaxIntervalSec(8);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- deConfiguration.setInitRetryIntervalSec(null);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertFalse("check empty configuration", isValid);
+ deConfiguration.setInitRetryIntervalSec(null);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertFalse("check empty configuration", isValid);
- deConfiguration.setInitRetryIntervalSec(8);
- isValid = distributionEngine.validateConfiguration(deConfiguration);
- assertTrue("check empty configuration", isValid);
+ deConfiguration.setInitRetryIntervalSec(8);
+ isValid = distributionEngine.validateConfiguration(deConfiguration);
+ assertTrue("check empty configuration", isValid);
- }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java
index 990ea4f99b..1fa0fc60b7 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineHealthCheckTest.java
@@ -20,115 +20,114 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.List;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.openecomp.sdc.be.components.BaseConfDependentTest;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
-public class DistributionEngineHealthCheckTest extends BaseConfDependentTest {
-
- @Mock
- private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class);
-
- DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth();
-
- Gson gson = new Gson();
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
- //
- // @Test
- // public void validateDownWhenEnvAreDown() {
- //
- // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
- // envNamePerStatus.put("PROD1", new AtomicBoolean(false));
- // envNamePerStatus.put("PROD2", new AtomicBoolean(false));
- //
- // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus);
- //
- // HealthCheckInfo healthCheckInfo =
- // distributionEngineClusterHealth.getHealthCheckInfo();
- // assertEquals("verify down", HealthCheckStatus.DOWN,
- // healthCheckInfo.getHealthCheckStatus());
- // assertEquals("verify DE component", HealthCheckComponent.DE,
- // healthCheckInfo.getHealthCheckComponent());
- //
- // }
-
- @Test
- public void validateUpWhenQuerySucceed() {
-
- // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
- // envNamePerStatus.put("PROD1", new AtomicBoolean(true));
- // envNamePerStatus.put("PROD2", new AtomicBoolean(false));
- //
- // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus,
- // false);
-
- CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
- CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403);
-
- List<String> uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers();
- if (uebServers.size() >= 2) {
- when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse);
- when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse);
- }
-
- UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey");
- healthCheckCall1.setCambriaHandler(cambriaHandler);
- Boolean call1 = healthCheckCall1.call();
- assertTrue("check response okay", call1);
-
- UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey");
- healthCheckCall2.setCambriaHandler(cambriaHandler);
-
- Boolean call2 = healthCheckCall2.call();
- assertTrue("check response okay", call2);
-
- if (uebServers.size() >= 2) {
- when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse);
- when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse);
- }
- healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey");
- healthCheckCall1.setCambriaHandler(cambriaHandler);
-
- call1 = healthCheckCall1.call();
- assertFalse("check response okay", call1);
-
- healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey");
- healthCheckCall2.setCambriaHandler(cambriaHandler);
-
- call2 = healthCheckCall2.call();
- assertTrue("check response okay", call2);
-
- if (uebServers.size() >= 2) {
- when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse);
- when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse);
- }
- healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey");
- healthCheckCall1.setCambriaHandler(cambriaHandler);
-
- call1 = healthCheckCall1.call();
- assertFalse("check response okay", call1);
-
- healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey");
- healthCheckCall2.setCambriaHandler(cambriaHandler);
-
- call2 = healthCheckCall2.call();
- assertTrue("check response okay", call2);
-
- }
+public class DistributionEngineHealthCheckTest extends BeConfDependentTest {
+
+ @Mock
+ private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class);
+
+ DistributionEngineClusterHealth distributionEngineClusterHealth = new DistributionEngineClusterHealth();
+
+ Gson gson = new Gson();
+
+ Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
+
+ //
+ // @Test
+ // public void validateDownWhenEnvAreDown() {
+ //
+ // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
+ // envNamePerStatus.put("PROD1", new AtomicBoolean(false));
+ // envNamePerStatus.put("PROD2", new AtomicBoolean(false));
+ //
+ // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus);
+ //
+ // HealthCheckInfo healthCheckInfo =
+ // distributionEngineClusterHealth.getHealthCheckInfo();
+ // assertEquals("verify down", HealthCheckStatus.DOWN,
+ // healthCheckInfo.getHealthCheckStatus());
+ // assertEquals("verify DE component", HealthCheckComponent.DE,
+ // healthCheckInfo.getHealthCheckComponent());
+ //
+ // }
+
+ @Test
+ public void validateUpWhenQuerySucceed() {
+
+ // Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
+ // envNamePerStatus.put("PROD1", new AtomicBoolean(true));
+ // envNamePerStatus.put("PROD2", new AtomicBoolean(false));
+ //
+ // distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus,
+ // false);
+
+ CambriaErrorResponse cambriaOkResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
+ CambriaErrorResponse cambriaNotErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, 403);
+
+ List<String> uebServers = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getUebServers();
+ if (uebServers.size() >= 2) {
+ when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaOkResponse);
+ when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse);
+ }
+
+ UebHealthCheckCall healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey");
+ healthCheckCall1.setCambriaHandler(cambriaHandler);
+ Boolean call1 = healthCheckCall1.call();
+ assertTrue("check response okay", call1);
+
+ UebHealthCheckCall healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey");
+ healthCheckCall2.setCambriaHandler(cambriaHandler);
+
+ Boolean call2 = healthCheckCall2.call();
+ assertTrue("check response okay", call2);
+
+ if (uebServers.size() >= 2) {
+ when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse);
+ when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaOkResponse);
+ }
+ healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey");
+ healthCheckCall1.setCambriaHandler(cambriaHandler);
+
+ call1 = healthCheckCall1.call();
+ assertFalse("check response okay", call1);
+
+ healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey");
+ healthCheckCall2.setCambriaHandler(cambriaHandler);
+
+ call2 = healthCheckCall2.call();
+ assertTrue("check response okay", call2);
+
+ if (uebServers.size() >= 2) {
+ when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(0)), Mockito.any(String.class))).thenReturn(cambriaErrorResponse);
+ when(cambriaHandler.getApiKey(Mockito.eq(uebServers.get(1)), Mockito.any(String.class))).thenReturn(cambriaNotErrorResponse);
+ }
+ healthCheckCall1 = new UebHealthCheckCall(uebServers.get(0), "publicKey");
+ healthCheckCall1.setCambriaHandler(cambriaHandler);
+
+ call1 = healthCheckCall1.call();
+ assertFalse("check response okay", call1);
+
+ healthCheckCall2 = new UebHealthCheckCall(uebServers.get(1), "publicKey");
+ healthCheckCall2.setCambriaHandler(cambriaHandler);
+
+ call2 = healthCheckCall2.call();
+ assertTrue("check response okay", call2);
+
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java
index 5bf12d56bc..03a6625cae 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTaskTest.java
@@ -20,19 +20,9 @@
package org.openecomp.sdc.be.components.distribution.engine;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.junit.BeforeClass;
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
+import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -41,224 +31,252 @@ import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig;
import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
-import fj.data.Either;
-
-public class DistributionEngineInitTaskTest {
-
- @Mock
- private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
-
- @Mock
- private CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class);
-
- // public static final IAuditingDao iAuditingDao =
- // Mockito.mock(AuditingDao.class);
-
- @BeforeClass
- public static void setup() {
- // ExternalConfiguration.setAppName("distribEngine1");
- ExternalConfiguration.setAppName("catalog-be");
- ExternalConfiguration.setConfigDir("src/test/resources/config");
- ExternalConfiguration.listenForChanges();
-
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
-
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- }
-
- @Test
- public void checkIncrement() {
-
- String envName = "PrOD";
-
- DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
- int retry = 2;
- int maxRetry = 40;
- deConfiguration.setInitRetryIntervalSec(retry);
- deConfiguration.setInitMaxIntervalSec(maxRetry);
- DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null);
-
- for (int i = 1; i < 5; i++) {
- initTask.incrementRetryInterval();
- assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i));
- }
-
- initTask.incrementRetryInterval();
- assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry);
-
- }
-
- @Test
- public void testInitFlowScenarioSuccess() {
-
- String notifTopic = "notif";
- String statusTopic = "status";
-
- List<String> uebServers = new ArrayList<>();
- uebServers.add("server1");
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND);
- Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse);
- when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right);
-
- String envName = "PrOD";
-
- DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
- deConfiguration.setUebServers(uebServers);
- int retry = 2;
- int maxRetry = 40;
- deConfiguration.setInitRetryIntervalSec(retry);
- deConfiguration.setInitMaxIntervalSec(maxRetry);
- deConfiguration.setDistributionNotifTopicName(notifTopic);
- deConfiguration.setDistributionStatusTopicName(statusTopic);
- CreateTopicConfig createTopic = new CreateTopicConfig();
- createTopic.setPartitionCount(1);
- createTopic.setReplicationCount(1);
- deConfiguration.setCreateTopic(createTopic);
-
- cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
-
- String realNotifTopic = notifTopic + "-" + envName.toUpperCase();
- String realStatusTopic = statusTopic + "-" + envName.toUpperCase();
- when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
- when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
-
- cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
- when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
- .thenReturn(cambriaErrorResponse);
-
- DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null);
- initTask.setCambriaHandler(cambriaHandler);
-
- boolean initFlow = initTask.initFlow();
- assertTrue("check init flow succeed", initFlow);
-
- }
-
- @Test
- public void testInitFlowScenarioSuccessTopicsAlreadyExists() {
-
- String envName = "PrOD";
- String notifTopic = "notif";
- String statusTopic = "status";
-
- String realNotifTopic = notifTopic + "-" + envName.toUpperCase();
- String realStatusTopic = statusTopic + "-" + envName.toUpperCase();
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
- Set<String> topics = new HashSet<String>();
- topics.add(realNotifTopic);
- topics.add(realStatusTopic);
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
- List<String> uebServers = new ArrayList<>();
- uebServers.add("server1");
- Either<Set<String>, CambriaErrorResponse> left = Either.left(topics);
-
- when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left);
-
- DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
- deConfiguration.setUebServers(uebServers);
- int retry = 2;
- int maxRetry = 40;
- deConfiguration.setInitRetryIntervalSec(retry);
- deConfiguration.setInitMaxIntervalSec(maxRetry);
- deConfiguration.setDistributionNotifTopicName(notifTopic);
- deConfiguration.setDistributionStatusTopicName(statusTopic);
- CreateTopicConfig createTopic = new CreateTopicConfig();
- createTopic.setPartitionCount(1);
- createTopic.setReplicationCount(1);
- deConfiguration.setCreateTopic(createTopic);
-
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
- when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
- .thenReturn(cambriaErrorResponse);
-
- DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null);
- initTask.setCambriaHandler(cambriaHandler);
-
- try {
- boolean initFlow = initTask.initFlow();
- assertTrue("check init flow succeed", initFlow);
- } catch (Exception e) {
- assertTrue("Should not throw exception", false);
- }
-
- }
+public class DistributionEngineInitTaskTest {
- @Test
- public void testInitFlowScenarioFailToRegister() {
+ @Mock
+ private ComponentsUtils componentsUtils;
- String notifTopic = "notif";
- String statusTopic = "status";
-
- List<String> uebServers = new ArrayList<>();
- uebServers.add("server1");
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND);
- Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse);
- when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right);
-
- String envName = "PrOD";
-
- DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
- deConfiguration.setUebServers(uebServers);
- int retry = 2;
- int maxRetry = 40;
- deConfiguration.setInitRetryIntervalSec(retry);
- deConfiguration.setInitMaxIntervalSec(maxRetry);
- deConfiguration.setDistributionNotifTopicName(notifTopic);
- deConfiguration.setDistributionStatusTopicName(statusTopic);
- CreateTopicConfig createTopic = new CreateTopicConfig();
- createTopic.setPartitionCount(1);
- createTopic.setReplicationCount(1);
- deConfiguration.setCreateTopic(createTopic);
+ @Mock
+ private CambriaHandler cambriaHandler;
- cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
+ @Before
+ public void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+ ExternalConfiguration.setConfigDir("src/test/resources/config");
+ ExternalConfiguration.listenForChanges();
- String realNotifTopic = notifTopic + "-" + envName.toUpperCase();
- String realStatusTopic = statusTopic + "-" + envName.toUpperCase();
- when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
- when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
+ new ConfigurationManager(configurationSource);
- when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class)))
- .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK));
+ componentsUtils = Mockito.mock(ComponentsUtils.class);
+ cambriaHandler = Mockito.mock(CambriaHandler.class);
+ }
+
+ @Test
+ public void checkIncrement() {
- when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(SubscriberTypeEnum.class)))
- .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR));
+ String envName = "PrOD";
+
+ DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
+ int retry = 2;
+ int maxRetry = 40;
+ deConfiguration.setInitRetryIntervalSec(retry);
+ deConfiguration.setInitMaxIntervalSec(maxRetry);
+ DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration));
+
+ for (int i = 1; i < 5; i++) {
+ initTask.incrementRetryInterval();
+ assertEquals("check next retry interval", initTask.getCurrentRetryInterval(), retry * (long) Math.pow(2, i));
+ }
+
+ initTask.incrementRetryInterval();
+ assertEquals("check next retry interval reach max retry interval", initTask.getCurrentRetryInterval(), maxRetry);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testInitFlowScenarioSuccess() {
+ String notifTopic = "notif";
+ String statusTopic = "status";
+
+ List<String> uebServers = new ArrayList<>();
+ uebServers.add("server1");
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND);
+ Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse);
+ when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right);
- DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null);
- initTask.setCambriaHandler(cambriaHandler);
+ String envName = "PrOD";
+
+ DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
+ deConfiguration.setUebServers(uebServers);
+ int retry = 2;
+ int maxRetry = 40;
+ deConfiguration.setInitRetryIntervalSec(retry);
+ deConfiguration.setInitMaxIntervalSec(maxRetry);
+ deConfiguration.setDistributionNotifTopicName(notifTopic);
+ deConfiguration.setDistributionStatusTopicName(statusTopic);
+ CreateTopicConfig createTopic = new CreateTopicConfig();
+ createTopic.setPartitionCount(1);
+ createTopic.setReplicationCount(1);
+ deConfiguration.setCreateTopic(createTopic);
+
+ cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
+
+ String realNotifTopic = notifTopic + "-" + envName.toUpperCase();
+ String realStatusTopic = statusTopic + "-" + envName.toUpperCase();
+ when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
+ when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
+
+ cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
+ when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(cambriaErrorResponse);
+
+ DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration));
+ initTask.setCambriaHandler(cambriaHandler);
+
+ boolean initFlow = initTask.initFlow();
+ assertTrue("check init flow succeed", initFlow);
- boolean initFlow = initTask.initFlow();
- assertFalse("check init flow failed", initFlow);
+ }
- }
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testInitFlowScenarioSuccessTopicsAlreadyExists() {
- @Test
- public void testInitFlowScenario1GetTopicsFailed() {
-
- List<String> uebServers = new ArrayList<>();
- uebServers.add("server1");
- CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR);
- Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse);
- when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right);
-
- String envName = "PrOD";
-
- DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
- deConfiguration.setUebServers(uebServers);
- int retry = 2;
- int maxRetry = 40;
- deConfiguration.setInitRetryIntervalSec(retry);
- deConfiguration.setInitMaxIntervalSec(maxRetry);
- DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null);
- initTask.setCambriaHandler(cambriaHandler);
-
- boolean initFlow = initTask.initFlow();
- assertFalse("check init flow failed", initFlow);
-
- }
+ String envName = "PrOD";
+ String notifTopic = "notif";
+ String statusTopic = "status";
+
+ String realNotifTopic = notifTopic + "-" + envName.toUpperCase();
+ String realStatusTopic = statusTopic + "-" + envName.toUpperCase();
+
+ Set<String> topics = new HashSet<String>();
+ topics.add(realNotifTopic);
+ topics.add(realStatusTopic);
+
+ List<String> uebServers = new ArrayList<>();
+ uebServers.add("server1");
+ Either<Set<String>, CambriaErrorResponse> left = Either.left(topics);
+
+ when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(left);
+
+ DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
+ deConfiguration.setUebServers(uebServers);
+ int retry = 2;
+ int maxRetry = 40;
+ deConfiguration.setInitRetryIntervalSec(retry);
+ deConfiguration.setInitMaxIntervalSec(maxRetry);
+ deConfiguration.setDistributionNotifTopicName(notifTopic);
+ deConfiguration.setDistributionStatusTopicName(statusTopic);
+ CreateTopicConfig createTopic = new CreateTopicConfig();
+ createTopic.setPartitionCount(1);
+ createTopic.setReplicationCount(1);
+ deConfiguration.setCreateTopic(createTopic);
+
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
+ when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(cambriaErrorResponse);
+
+ DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration));
+ initTask.setCambriaHandler(cambriaHandler);
+
+ try {
+ boolean initFlow = initTask.initFlow();
+ assertTrue("check init flow succeed", initFlow);
+ } catch (Exception e) {
+ assertTrue("Should not throw exception", false);
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testInitFlowScenarioFailToRegister() {
+
+ String notifTopic = "notif";
+ String statusTopic = "status";
+
+ List<String> uebServers = new ArrayList<>();
+ uebServers.add("server1");
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND);
+ Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse);
+ when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right);
+
+ String envName = "PrOD";
+
+ DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
+ deConfiguration.setUebServers(uebServers);
+ int retry = 2;
+ int maxRetry = 40;
+ deConfiguration.setInitRetryIntervalSec(retry);
+ deConfiguration.setInitMaxIntervalSec(maxRetry);
+ deConfiguration.setDistributionNotifTopicName(notifTopic);
+ deConfiguration.setDistributionStatusTopicName(statusTopic);
+ CreateTopicConfig createTopic = new CreateTopicConfig();
+ createTopic.setPartitionCount(1);
+ createTopic.setReplicationCount(1);
+ deConfiguration.setCreateTopic(createTopic);
+
+ cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.OK);
+
+ String realNotifTopic = notifTopic + "-" + envName.toUpperCase();
+ String realStatusTopic = statusTopic + "-" + envName.toUpperCase();
+ when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
+ when(cambriaHandler.createTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic), Mockito.eq(1), Mockito.eq(1))).thenReturn(cambriaErrorResponse);
+
+ when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realNotifTopic)))
+ .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.OK));
+
+ when(cambriaHandler.registerToTopic(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.eq(realStatusTopic)))
+ .thenReturn(new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR));
+
+
+ DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration));
+ initTask.setCambriaHandler(cambriaHandler);
+
+ boolean initFlow = initTask.initFlow();
+ assertFalse("check init flow failed", initFlow);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testInitFlowScenario1GetTopicsFailed() {
+
+ List<String> uebServers = new ArrayList<>();
+ uebServers.add("server1");
+ CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR);
+ Either<Set<String>, CambriaErrorResponse> right = Either.right(cambriaErrorResponse);
+ when(cambriaHandler.getTopics(Mockito.any(List.class))).thenReturn(right);
+
+ String envName = "PrOD";
+
+ DistributionEngineConfiguration deConfiguration = new DistributionEngineConfiguration();
+ deConfiguration.setUebServers(uebServers);
+ int retry = 2;
+ int maxRetry = 40;
+ deConfiguration.setInitRetryIntervalSec(retry);
+ deConfiguration.setInitMaxIntervalSec(maxRetry);
+ DistributionEngineInitTask initTask = new DistributionEngineInitTask(0l, deConfiguration, envName, new AtomicBoolean(false), componentsUtils, null, readEnvFromConfig(deConfiguration));
+ initTask.setCambriaHandler(cambriaHandler);
+
+ boolean initFlow = initTask.initFlow();
+ assertFalse("check init flow failed", initFlow);
+
+ }
+
+ private OperationalEnvironmentEntry readEnvFromConfig(DistributionEngineConfiguration distributionEngineConfiguration) {
+ OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
+ entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey());
+ entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey());
+ Set<String> puebEndpoints = new HashSet<>();
+ if(distributionEngineConfiguration.getUebServers() != null)
+ puebEndpoints.addAll(distributionEngineConfiguration.getUebServers());
+ entry.setDmaapUebAddress(puebEndpoints);
+ String envName = "UNKNOWN";
+ if(CollectionUtils.isNotEmpty(distributionEngineConfiguration.getEnvironments()))
+ envName = distributionEngineConfiguration.getEnvironments().get(0);
+ entry.setEnvironmentId(envName);
+ return entry;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java
new file mode 100644
index 0000000000..b1a43eaa57
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineTest.java
@@ -0,0 +1,95 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.utils.OperationalEnvironmentBuilder;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+public class DistributionEngineTest {
+
+ public static final String DISTRIBUTION_ID = "distId";
+ public static final String ENV_ID = "envId";
+ public static final String USER_ID = "userId";
+ public static final String MODIFIER = "modifier";
+
+ @InjectMocks
+ private DistributionEngine testInstance;
+
+ @Mock
+ private EnvironmentsEngine environmentsEngine;
+
+ @Mock
+ private DistributionNotificationSender distributionNotificationSender;
+
+ private DummyDistributionConfigurationManager distributionEngineConfigurationMock;
+
+ private Map<String, OperationalEnvironmentEntry> envs;
+
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ distributionEngineConfigurationMock = new DummyDistributionConfigurationManager();
+ envs = getEnvs(ENV_ID);
+ }
+
+ @Test
+ public void notifyService() throws Exception {
+ NotificationDataImpl notificationData = new NotificationDataImpl();
+ Service service = new Service();
+ when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID));
+ when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic");
+ when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class),
+ any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER)))
+ .thenReturn(ActionStatus.OK);
+ ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER);
+ assertEquals(ActionStatus.OK, actionStatus);
+ }
+
+ @Test
+ public void notifyService_couldNotResolveEnvironment() throws Exception {
+ when(environmentsEngine.getEnvironments()).thenReturn(envs);
+ ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, new Service(), new NotificationDataImpl(), "someNonExisitngEnv", USER_ID, MODIFIER);
+ assertEquals(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, actionStatus);
+ verifyZeroInteractions(distributionNotificationSender);
+ }
+
+ @Test
+ public void notifyService_failedWhileSendingNotification() throws Exception {
+ NotificationDataImpl notificationData = new NotificationDataImpl();
+ Service service = new Service();
+ when(environmentsEngine.getEnvironmentById(ENV_ID)).thenReturn(envs.get(ENV_ID));
+ when(distributionEngineConfigurationMock.getConfigurationMock().getDistributionNotifTopicName()).thenReturn("topic");
+ when(distributionNotificationSender.sendNotification(eq("topic-ENVID"), eq(DISTRIBUTION_ID), any(EnvironmentMessageBusData.class),
+ any(NotificationDataImpl.class), any(Service.class), eq(USER_ID), eq(MODIFIER)))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.notifyService(DISTRIBUTION_ID, service, notificationData, ENV_ID, USER_ID, MODIFIER);
+ assertEquals(ActionStatus.GENERAL_ERROR, actionStatus);
+ }
+
+ private Map<String, OperationalEnvironmentEntry> getEnvs(String ... environmentIds) {
+ Set<String> uebAddress = new HashSet<>();
+ uebAddress.add("someAddress");
+ return Stream.of(environmentIds)
+ .map(id -> new OperationalEnvironmentBuilder().setEnvId(id).setDmaapUebAddress(uebAddress).build())
+ .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity()));
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java
new file mode 100644
index 0000000000..1118385143
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/DummyDistributionConfigurationManager.java
@@ -0,0 +1,37 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import org.mockito.Mockito;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
+import org.openecomp.sdc.common.api.ConfigurationListener;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+
+public class DummyDistributionConfigurationManager {
+
+ private DistributionEngineConfiguration configurationMock = Mockito.mock(DistributionEngineConfiguration.class);
+
+ public DummyDistributionConfigurationManager() {
+ new ConfigurationManager(new DummyConfigurationSource());
+ }
+
+ public class DummyConfigurationSource implements ConfigurationSource {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T getAndWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) {
+ if (className.equals(DistributionEngineConfiguration.class)) {
+ return (T)configurationMock;
+ }
+ return null;
+ }
+
+ @Override
+ public <T> void addWatchConfiguration(Class<T> className, ConfigurationListener configurationListener) {
+
+ }
+ }
+
+ public DistributionEngineConfiguration getConfigurationMock() {
+ return configurationMock;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java
new file mode 100644
index 0000000000..514618c89a
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngineTest.java
@@ -0,0 +1,190 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import fj.data.Either;
+import org.apache.http.HttpStatus;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.info.OperationalEnvInfo;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+@RunWith(value = MockitoJUnitRunner.class)
+public class EnvironmentsEngineTest {
+
+ @InjectMocks
+ private EnvironmentsEngine envEngine;
+ @Mock
+ private DmaapConsumer dmaapConsumer;
+ @Mock
+ private OperationalEnvironmentDao operationalEnvironmentDao;
+ @Mock
+ private DME2EndpointIteratorCreator epIterCreator;
+ @Mock
+ private ConfigurationManager configurationManager;
+ @Mock
+ private DistributionEngineConfiguration distributionEngineConfiguration;
+ @Mock
+ private AaiRequestHandler aaiRequestHandler;
+
+ @Before
+ public void preStart() {
+ when(configurationManager.getDistributionEngineConfiguration()).thenReturn(distributionEngineConfiguration);
+ envEngine.setConfigurationManager(configurationManager);
+ }
+
+ @Test
+ public void testInit() {
+ List<OperationalEnvironmentEntry> entryList = Arrays.asList(createOpEnvEntry("Env1"), createOpEnvEntry("Env2"));
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> successEither = Either.left(entryList);
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(successEither);
+
+ when(distributionEngineConfiguration.getEnvironments()).thenReturn(Arrays.asList("Env Loaded From Configuration"));
+ when(distributionEngineConfiguration.getUebPublicKey()).thenReturn("Dummy Public Key");
+ when(distributionEngineConfiguration.getUebSecretKey()).thenReturn("Dummy Private Key");
+ when(distributionEngineConfiguration.getUebServers()).thenReturn(
+ Arrays.asList("uebsb91kcdc.it.att.com:3904", "uebsb92kcdc.it.att.com:3904", "uebsb91kcdc.it.att.com:3904"));
+
+ envEngine.init();
+
+ Map<String, OperationalEnvironmentEntry> mapEnvs = envEngine.getEnvironments();
+ assertEquals("unexpected size of map",3, mapEnvs.size());
+ }
+
+
+ @Test
+ public void testGetFullOperationalEnvByIdSuccess() {
+ String json = getFullOperationalEnvJson();
+
+ HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed");
+ when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
+
+ Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
+ assertTrue("The operational environment request ran as not expected", response.isLeft());
+
+ OperationalEnvInfo operationalEnvInfo = response.left().value();
+
+ assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json);
+ }
+
+ @Test
+ public void testGetPartialOperationalEnvByIdSuccess() {
+ String json = getPartialOperationalEnvJson();
+
+ HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_OK, "Successfully completed");
+ when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
+
+ Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
+ assertTrue("The operational environment request ran as not expected", response.isLeft());
+
+ OperationalEnvInfo operationalEnvInfo = response.left().value();
+
+ assertEquals("The operational environment json is not as expected", operationalEnvInfo.toString(), json);
+ }
+
+
+ @Test
+ public void testGetOperationalEnvByIdFailedByJsonConvert() {
+ String jsonCorrupted = getCorruptedOperationalEnvJson();
+
+ HttpResponse<String> restResponse = new HttpResponse<String>(jsonCorrupted, HttpStatus.SC_OK, "Successfully Completed");
+ when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
+
+ Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
+ assertTrue("The operational environment request ran as not expected", response.isRight());
+ assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_INTERNAL_SERVER_ERROR, response.right().value());
+ }
+
+ @Test
+ public void testGetOperationalEnvByIdFailed404() {
+ String json = getFullOperationalEnvJson();
+ HttpResponse<String> restResponse = new HttpResponse<String>(json, HttpStatus.SC_NOT_FOUND, "Not Found");
+ when(aaiRequestHandler.getOperationalEnvById(Mockito.anyString())).thenReturn(restResponse);
+
+ Either<OperationalEnvInfo, Integer> response = envEngine.getOperationalEnvById("DummyId");
+ assertTrue("The operational environment request ran as not expected", response.isRight());
+ assertEquals("The operational environment request status code is not as expected", (Integer)HttpStatus.SC_NOT_FOUND, response.right().value());
+ }
+
+
+ @Test(expected = IOException.class)
+ public void testCorruptedOperationalEnvJson() throws IOException {
+ String jsonCorrupted = getCorruptedOperationalEnvJson();
+ OperationalEnvInfo.createFromJson(jsonCorrupted);
+ }
+
+ private String getCorruptedOperationalEnvJson() {
+ return "{\"OPERATIONAL-environment-name\":\"Op Env Name\","
+ + "\"OPERATIONAL-environment-type\":\"VNF\","
+ + "\"OPERATIONAL-environment-status\":\"Activate\","
+ + "\"tenant-context\":\"Test\"}";
+ }
+
+ private String getPartialOperationalEnvJson() {
+ return "{" +
+ "\"operational-environment-id\":\"UUID of Operational Environment\"," +
+ "\"operational-environment-name\":\"Op Env Name\"," +
+ "\"operational-environment-type\":\"VNF\"," +
+ "\"operational-environment-status\":\"Activate\"," +
+ "\"tenant-context\":\"Test\"," +
+ "\"workload-context\":\"VNF_Development\"," +
+ "\"resource-version\":\"1505228226913\"," +
+ "\"relationship-list\":{" +
+ "\"relationship\":[]" +
+ "}" +
+ "}";
+ }
+
+ private String getFullOperationalEnvJson() {
+ return "{" +
+ "\"operational-environment-id\":\"OEid1\"," +
+ "\"operational-environment-name\":\"OEname1\"," +
+ "\"operational-environment-type\":\"OEtype1\"," +
+ "\"operational-environment-status\":\"OEstatus1\"," +
+ "\"tenant-context\":\"OEtenantcontext1\"," +
+ "\"workload-context\":\"OEworkloadcontext1\"," +
+ "\"resource-version\":\"1511363173278\"," +
+ "\"relationship-list\":{" +
+ "\"relationship\":[" +
+ "{" +
+ "\"related-to\":\"operational-environment\"," +
+ "\"relationship-label\":\"managedBy\"," +
+ "\"related-link\":\"/aai/v12/cloud-infrastructure/operational-environments/operational-environment/OEid3\"," +
+ "\"relationship-data\":[" +
+ "{" +
+ "\"relationship-key\":\"operational-environment.operational-environment-id\"," +
+ "\"relationship-value\":\"OEid3\"" +
+ "}" +
+ "]," +
+ "\"related-to-property\":[" +
+ "{" +
+ "\"property-key\":\"operational-environment.operational-environment-name\"," +
+ "\"property-value\":\"OEname3\"" +
+ "}]}]}}";
+ }
+
+ private OperationalEnvironmentEntry createOpEnvEntry(String name) {
+ OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
+ entry.setEnvironmentId(name);
+ return entry;
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java
new file mode 100644
index 0000000000..1a2ca4840d
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/StepsTenantIsolation.java
@@ -0,0 +1,310 @@
+package org.openecomp.sdc.be.components.distribution.engine;
+
+import com.att.aft.dme2.api.DME2Exception;
+import com.att.aft.dme2.iterator.DME2EndpointIterator;
+import com.att.nsa.apiClient.credentials.ApiCredential;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import cucumber.api.java.Before;
+import cucumber.api.java.en.Given;
+import cucumber.api.java.en.Then;
+import cucumber.api.java.en.When;
+import fj.data.Either;
+import org.apache.commons.lang.NotImplementedException;
+import org.apache.commons.lang.math.NumberUtils;
+import org.apache.http.HttpStatus;
+import org.junit.Assert;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+
+import static java.util.Objects.isNull;
+import static org.apache.commons.lang3.StringUtils.isEmpty;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class StepsTenantIsolation {
+
+ // Notification Fields
+ private String operationalEnvironmentId = "28122015552391";
+ private String operationalEnvironmentName = "Operational Environment Name";
+ private String operationalEnvironmentType;
+ private String tenantContext ;
+ private String workloadContext;
+ private String action;
+
+ @Mock
+ private DmaapConsumer dmaapConsumer;
+ @Mock
+ private OperationalEnvironmentDao operationalEnvironmentDao;
+ @Mock
+ private DME2EndpointIteratorCreator epIterCreator;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private AaiRequestHandler aaiRequestHandler;
+ @Mock
+ private CambriaHandler cambriaHandler;
+ @InjectMocks
+ @Spy
+ private EnvironmentsEngine envEngine;
+
+ private boolean isSuccessful;
+ private boolean cassandraUp;
+
+ @Before
+ public void beforeScenario() {
+ MockitoAnnotations.initMocks(this);
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED))
+ .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND));
+ doNothing().when(envEngine).createUebTopicsForEnvironments();
+ envEngine.init();
+ }
+
+ // ############################# Given - Start #############################
+ @Given("^Dmaap consumer recieved notification with fields (.*)$")
+ public void dmaap_consumer_recieved_notification_with_fields(String notificationFields) throws Throwable {
+ Gson gson = new GsonBuilder().create();
+ IDmaapNotificationData notification = gson.fromJson(notificationFields, DmaapNotificationDataImpl.class);
+ if (!isNull(notification.getOperationalEnvironmentType())) {
+ this.operationalEnvironmentType = notification.getOperationalEnvironmentType().getEventTypenName();
+ }
+ if( !isEmpty(notification.getOperationalEnvironmentId()) ){
+ this.operationalEnvironmentId = notification.getOperationalEnvironmentId();
+ }
+ if( !isNull(notification.getAction()) ){
+ this.action = notification.getAction().getActionName();
+ }
+
+ }
+
+ @Given("^Cassandra service status is (.*)$")
+ public void cassandra_service_status_is(String status) throws Throwable {
+ switch (status) {
+ case "UP":
+ this.cassandraUp = true;
+ break;
+ case "DOWN":
+ when(operationalEnvironmentDao.get(operationalEnvironmentId))
+ .thenReturn(Either.right(CassandraOperationStatus.GENERAL_ERROR));
+ when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class)))
+ .thenReturn(CassandraOperationStatus.GENERAL_ERROR);
+ break;
+ default:
+ throw new NotImplementedException();
+ }
+ }
+
+ @Given("^Record status is (.*)$")
+ public void record_status_is(String status) throws Throwable {
+ if (!cassandraUp) {
+ return;
+ }
+ Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherResult;
+ final OperationalEnvironmentEntry entryMock = Mockito.mock(OperationalEnvironmentEntry.class);
+ switch (status) {
+ case "FOUND_IN_PROGRESS":
+ when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.IN_PROGRESS.getName());
+ eitherResult = Either.left(entryMock);
+ break;
+ case "FOUND_COMPLETED":
+ when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.COMPLETED.getName());
+ eitherResult = Either.left(entryMock);
+ break;
+ case "FOUND_FAILED":
+ when(entryMock.getStatus()).thenReturn(EnvironmentStatusEnum.FAILED.getName());
+ eitherResult = Either.left(entryMock);
+ break;
+ case "NOT_FOUND":
+ eitherResult = Either.right(CassandraOperationStatus.NOT_FOUND);
+ break;
+ default:
+ throw new NotImplementedException();
+ }
+
+ when(operationalEnvironmentDao.get(operationalEnvironmentId)).thenReturn(eitherResult);
+ when(operationalEnvironmentDao.save(Mockito.any(OperationalEnvironmentEntry.class)))
+ .thenReturn(CassandraOperationStatus.OK);
+ }
+
+ @Given("^AAI service status is (.*) and Tenant returned is (.*) and worload returned is (.*)$")
+ public void aai_service_status_is(String aaiServiceStatus, String tenant, String workload) throws Throwable {
+ this.tenantContext = tenant;
+ this.workloadContext = workload;
+ HttpResponse<String> resp = Mockito.mock(HttpResponse.class);
+ when(aaiRequestHandler.getOperationalEnvById(operationalEnvironmentId)).thenReturn(resp);
+ switch (aaiServiceStatus) {
+ case "UP":
+ when(resp.getStatusCode()).thenReturn(HttpStatus.SC_OK);
+ String aaiResponseTemplate =
+ //@formatter:off
+ "{\r\n"
+ + " \"operational-environment-id\": \"%s\",\r\n"
+ + " \"operational-environment-name\": \"%s\",\r\n"
+ + " \"operational-environment-type\": \"%s\",\r\n"
+ + " \"operational-environment-status\": \"IN-PROGRESS\",\r\n"
+ + " \"tenant-context\": \"%s\",\r\n"
+ + " \"workload-context\": \"%s\"\r\n"
+ + " }";
+ //@formatter:on
+ when(resp.getResponse()).thenReturn(String.format(aaiResponseTemplate, operationalEnvironmentId,
+ operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext));
+
+ break;
+ case "DOWN":
+ when(resp.getStatusCode()).thenReturn(HttpStatus.SC_REQUEST_TIMEOUT);
+ break;
+ default:
+ throw new NotImplementedException();
+ }
+ }
+
+ @Given("^AFT_DME service status is (.*)$")
+ public void aft_dme_service_status_is(String aftDmeStatus) throws Throwable {
+ switch (aftDmeStatus) {
+ case "UP":
+ DME2EndpointIterator mockItr = Mockito.mock(DME2EndpointIterator.class);
+ when(mockItr.hasNext()).thenReturn(false);
+ when(epIterCreator.create(Mockito.anyString())).thenReturn(mockItr);
+ break;
+ case "DOWN":
+ when(epIterCreator.create(Mockito.anyString()))
+ .thenThrow(new DME2Exception("dummyCode", new NotImplementedException()));
+ break;
+ default:
+ throw new NotImplementedException();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Given("^UEB service status is (.*)$")
+ public void ueb_service_status_is(String status) throws Throwable {
+
+ Either<ApiCredential, CambriaErrorResponse> response;
+ switch (status) {
+ case "UP":
+ ApiCredential apiCredential = Mockito.mock(ApiCredential.class);
+ when(apiCredential.getApiKey()).thenReturn("MockAPIKey");
+ when(apiCredential.getApiSecret()).thenReturn("MockSecretKey");
+ response = Either.left(apiCredential);
+ break;
+ case "DOWN":
+ CambriaErrorResponse cambriaError = Mockito.mock(CambriaErrorResponse.class);
+ response = Either.right(cambriaError);
+ break;
+ default:
+ throw new NotImplementedException();
+ }
+ when(cambriaHandler.createUebKeys(Mockito.anyList())).thenReturn(response);
+ }
+ // ############################# Given - End #############################
+
+ // ############################# When - Start #############################
+
+ @When("^handle message is activated$")
+ public void handle_message_is_activated() throws Throwable {
+ this.isSuccessful = envEngine.handleMessage(buildNotification());
+ }
+ // ############################# When - End #############################
+
+ // ############################# Then - Start #############################
+ @SuppressWarnings("unchecked")
+ @Then("^handle message activates validation of eventType (.*)$")
+ public void handle_message_activates_validation_of_eventType(boolean isValidated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
+ .validateEnvironmentType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class),
+ Mockito.any(IDmaapAuditNotificationData.class));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^trying to write message to audit log and table (.*)$")
+ public void trying_to_write_message_to_audit_log_and_table(boolean isUnsupportedTypeEventRecorded) throws Throwable {
+ int count = isUnsupportedTypeEventRecorded ? 2 : 1;
+ verify(componentsUtils, Mockito.atLeast(count))
+ .auditEnvironmentEngine(Mockito.any(AuditingActionEnum.class), Mockito.eq(operationalEnvironmentId),
+ Mockito.any(String.class), Mockito.any(String.class), Mockito.eq(operationalEnvironmentName), Mockito.eq(tenantContext));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^handle message activates validation of action (.*)$")
+ public void handle_message_activates_validation_of_action(boolean isValidated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
+ .validateActionType(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^handle message activates validation of state (.*)$")
+ public void handle_message_activates_validation_of_state(boolean isValidated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isValidated)))
+ .validateState(Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^trying to save in-progress record (.*)$")
+ public void trying_to_save_in_progress_record(boolean isActivated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
+ .saveEntryWithInProgressStatus(Mockito.any(Wrapper.class), Mockito.any(Wrapper.class), Mockito.any(IDmaapNotificationData.class));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^trying to get environment info from A&AI API (.*)$")
+ public void trying_to_get_environment_info_from_AAI_AP(boolean isActivated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
+ .retrieveOpEnvInfoFromAAI(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^trying to retrieve Ueb Addresses From AftDme (.*)$")
+ public void trying_to_retrieve_ueb_addresses_from_AftDme(boolean isActivated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated))).discoverUebHosts(
+ Mockito.anyString(), Mockito.anyString());
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Then("^trying to create Ueb keys (.*)$")
+ public void trying_to_create_ueb_keys(boolean isActivated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
+ .createUebKeys(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
+ }
+
+ @Then("^trying to create Ueb Topics (.*)$")
+ public void trying_to_create_ueb_topics(boolean isActivated) throws Throwable {
+ verify(envEngine, Mockito.times(getNumberOfCallsToValidate(isActivated)))
+ .createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class));
+ }
+
+ @Then("^handle message finished successfully (.*)$")
+ public void handle_message_finished_successfully(boolean isSuccessfull) throws Throwable {
+ Assert.assertTrue(this.isSuccessful == isSuccessfull);
+ }
+
+ // ############################# Then - End #############################
+
+ private String buildNotification() {
+ String notificationTemplate = "{ \"operationalEnvironmentId\": \"%s\",\r\n"
+ + " \"operationalEnvironmentName\": \"%s\",\r\n"
+ + " \"operationalEnvironmentType\": \"%s\",\r\n" + " \"tenantContext\": \"%s\",\r\n"
+ + " \"workloadContext\": \"%s\",\r\n" + " \"action\": \"%s\"}";
+
+ String notification = String.format(notificationTemplate, operationalEnvironmentId, operationalEnvironmentName,
+ operationalEnvironmentType, tenantContext, workloadContext, action);
+ return notification;
+ }
+
+ private int getNumberOfCallsToValidate(boolean isValidated) {
+ return isValidated ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java
deleted file mode 100644
index 712e16d97a..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/TestSuite.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.openecomp.sdc.be.components.distribution.engine;
-
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
-
-@RunWith(Suite.class)
-@Suite.SuiteClasses(
-
-{ DistributionEngineInitTaskTest.class, DistributionEngineConfigTest.class, DistributionEngineHealthCheckTest.class,
- VfModuleArtifactPayloadTest.class })
-public class TestSuite { // nothing
-}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java
new file mode 100644
index 0000000000..9d0e8cd683
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/distribution/engine/rest/MsoRestClientTest.java
@@ -0,0 +1,135 @@
+package org.openecomp.sdc.be.components.distribution.engine.rest;
+
+import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
+import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.matching.AnythingPattern;
+import com.github.tomakehurst.wiremock.matching.UrlPattern;
+import fj.data.Either;
+import org.apache.http.HttpHeaders;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotificationEnum;
+import org.openecomp.sdc.be.components.distribution.engine.DummyDistributionConfigurationManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.config.*;
+import org.openecomp.sdc.security.SecurityUtil;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.*;
+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+public class MsoRestClientTest {
+
+ private static final String MSO_HOST = "127.0.0.1";
+ private static final String MSO_API_URL = "onap/mso/infra/modelDistributions/v1";
+ private static final String DISTRIBUTION_ID = "1000";
+
+ private MSORestClient msoRestClient;
+
+ @ClassRule
+ public static WireMockRule msoRestServer = new WireMockRule(options()
+ .dynamicPort()
+ .bindAddress(MSO_HOST));
+
+ @Before
+ public void setupMsoServer() throws Exception {
+ String encodedPw = "";
+ Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(getPwd());
+ if(passkey.isLeft()) {
+ encodedPw = passkey.left().value();
+ }
+ else {
+ throw new IllegalArgumentException(passkey.right().value());
+ }
+
+ msoRestServer.resetToDefaultMappings();
+ msoRestServer.stubFor(patch(urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl())))
+ .withBasicAuth(getUserName(), encodedPw)
+ .withHeader(HttpHeaders.CONTENT_TYPE, containing("application/json"))
+ .withRequestBody(matchingJsonPath("$.status"))
+ .withRequestBody(matchingJsonPath("$.errorReason", new AnythingPattern()))//error reason is not mandatory
+ .willReturn(aResponse().withStatus(200)));
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ DummyDistributionConfigurationManager distributionEngineConfigurationMock = new DummyDistributionConfigurationManager();
+ when(distributionEngineConfigurationMock.getConfigurationMock().getMsoConfig()).thenReturn(new MsoDummyConfig(msoRestServer.port()));
+ msoRestClient = new MSORestClient();
+ }
+
+ @Test
+ public void notifyDistributionComplete_emptyErrReason() throws Exception {
+ HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, "");
+ assertThat(response.getStatusCode()).isEqualTo(200);
+ }
+
+ private int getNumOfRetries() {
+ return ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getNumOfRetries();
+ }
+
+ @Test
+ public void notifyDistributionComplete_noErrReason() throws Exception {
+ HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK, null);
+ assertThat(response.getStatusCode()).isEqualTo(200);
+ }
+
+ @Test
+ public void notifyDistributionComplete_completeWithError() throws Exception {
+ HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason");
+ assertThat(response.getStatusCode()).isEqualTo(200);
+ }
+
+ @Test
+ public void testRetries() throws Exception {
+ int readTimeout = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig().getHttpClientConfig().getTimeouts().getReadTimeoutMs();
+ int expectedNumOfRetries = getNumOfRetries();
+
+ UrlPattern msoReqUrlPattern = urlMatching(String.format("/%s%s/(.*)", MSO_API_URL, getDistributionsUrl()));
+ msoRestServer.stubFor(patch(msoReqUrlPattern)
+ .willReturn(new ResponseDefinitionBuilder().withFixedDelay(readTimeout + 1)));
+ HttpResponse<String> response = msoRestClient.notifyDistributionComplete(DISTRIBUTION_ID, DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR, "my reason");
+ verify(expectedNumOfRetries + 1, patchRequestedFor(msoReqUrlPattern));
+ assertThat(response.getStatusCode()).isEqualTo(500);
+ }
+
+ private static String getDistributionsUrl() {
+ return "/distributions";
+ }
+
+ private static String getUserName() {
+ return "asdc";
+ }
+
+ private static String getPwd() {
+ return "OTLEp5lfVhYdyw5EAtTUBQ==";
+ }
+
+ private static class MsoDummyConfig extends ExternalServiceConfig {
+ int port;
+
+ MsoDummyConfig(int port) {
+ this.port = port;
+
+ BasicAuthorization basicAuthorization = new BasicAuthorization();
+ basicAuthorization.setUserName(MsoRestClientTest.getUserName());
+ basicAuthorization.setPassword(getPwd());
+ HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(500, 2000), basicAuthorization);
+ httpClientConfig.setNumOfRetries(getNumOfRetries());
+ super.setHttpClientConfig(httpClientConfig);
+
+ HttpRequestConfig httpRequestConfig = new HttpRequestConfig();
+ httpRequestConfig.setServerRootUrl(String.format("http://%s:%s/%s", MSO_HOST, this.port, MSO_API_URL));
+ httpRequestConfig.getResourceNamespaces().put(MSORestClient.DISTRIBUTIONS_RESOURCE_CONFIG_PARAM, getDistributionsUrl());
+ super.setHttpRequestConfig(httpRequestConfig);
+ }
+
+ int getNumOfRetries() {
+ return 1;
+ }
+ }
+
+}
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 c57f2a65af..bebe29f13e 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
@@ -20,28 +20,14 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyBoolean;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME;
-import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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 com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -55,6 +41,7 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -70,6 +57,7 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -84,294 +72,359 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-import fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_ENV_NAME;
+import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.HEAT_VF_ENV_NAME;
public class ArtifactBusinessLogicTest {
- public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis());
- static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
- static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
- @InjectMocks
- private static ArtifactsBusinessLogic artifactBL;
- @Mock
- private ArtifactOperation artifactOperation;
- @Mock
- public ComponentsUtils componentsUtils;
- @Mock
- private IInterfaceLifecycleOperation lifecycleOperation;
- @Mock
- private IUserAdminOperation userOperation;
- @Mock
- private IElementOperation elementOperation;
- @Mock
- private ArtifactCassandraDao artifactCassandraDao;
- @Mock
- public ToscaOperationFacade toscaOperationFacade;
- @Mock
- private UserBusinessLogic userBusinessLogic;
- @Mock
- private NodeTemplateOperation nodeTemplateOperation;
- @Mock
- private ArtifactsOperations artifactsOperations;
-
- // public static final InformationDeployedArtifactsBusinessLogic
- // informationDeployedArtifactsBusinessLogic =
- // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class);
-
- public static final Resource resource = Mockito.mock(Resource.class);
- private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
-
- private static List<ArtifactType> getAllTypes() {
- List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
- List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes();
- for (String artifactType : artifactTypesList) {
- ArtifactType artifactT = new ArtifactType();
- artifactT.setName(artifactType);
- artifactTypes.add(artifactT);
- }
- return artifactTypes;
- }
-
- @Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND);
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND);
- when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2);
- when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2);
-
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND);
- when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces);
-
- Either<User, ActionStatus> getUserResult = Either.left(USER);
-
- when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult);
-
- Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes());
- when(elementOperation.getAllArtifactTypes()).thenReturn(getType);
-
- when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC);
- }
-
- @Test
- public void testValidJson() {
- ArtifactDefinition ad = createArtifactDef();
-
- String jsonArtifact = "";
-
- 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);
-
- try {
- jsonArtifact = mapper.writeValueAsString(ad);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class);
- assertEquals(ad, afterConvert);
- }
-
- private ArtifactDefinition createArtifactDef() {
- ArtifactDefinition ad = new ArtifactDefinition();
- ad.setArtifactName("artifact1.yaml");
- ad.setArtifactLabel("label1");
- ad.setDescription("description");
- ad.setArtifactType(ArtifactTypeEnum.HEAT.getType());
- ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
- ad.setCreationDate(System.currentTimeMillis());
- ad.setMandatory(false);
- ad.setTimeout(15);
- return ad;
- }
-
- @Test
- public void testInvalidStringGroupType() {
- ArtifactDefinition ad = new ArtifactDefinition();
- ad.setArtifactName("artifact1");
- ad.setCreationDate(System.currentTimeMillis());
- ad.setMandatory(false);
- ad.setTimeout(15);
-
- JsonElement jsonArtifact = gson.toJsonTree(ad);
- jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www");
-
- ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
- assertNull(afterConvert);
- }
-
- @Test
- public void testInvalidNumberGroupType() {
- ArtifactDefinition ad = new ArtifactDefinition();
- ad.setArtifactName("artifact1");
- ad.setCreationDate(System.currentTimeMillis());
- ad.setMandatory(false);
- ad.setTimeout(15);
-
- JsonElement jsonArtifact = gson.toJsonTree(ad);
- jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123);
-
- ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
- assertNull(afterConvert);
- }
-
- @Test
- public void testInvalidGroupTypeWithSpace() {
- ArtifactDefinition ad = new ArtifactDefinition();
- ad.setArtifactName("artifact1");
- ad.setCreationDate(System.currentTimeMillis());
- ad.setMandatory(false);
- ad.setTimeout(15);
-
- JsonElement jsonArtifact = gson.toJsonTree(ad);
- jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT");
-
- ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
- assertNull(afterConvert);
- }
-
- @Test
- public void testInvalidTimeoutWithSpace() {
- ArtifactDefinition ad = new ArtifactDefinition();
- ad.setArtifactName("artifact1");
- ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
- ad.setCreationDate(System.currentTimeMillis());
- ad.setMandatory(false);
-
- JsonElement jsonArtifact = gson.toJsonTree(ad);
- jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15");
-
- ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
- assertNull(afterConvert);
- }
-
- @Test
- public void testValidMibAritactsConfiguration() {
- Map<String, ArtifactTypeConfig> componentDeploymentArtifacts =
- ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
- Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts =
- ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
- assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType()));
- assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType()));
- assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType()));
- assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType()));
- }
-
- @Test
- public void testDownloadServiceArtifactByNames() {
- Service service = new Service();
- String serviceName = "myService";
- String serviceVersion = "1.0";
- String serviceId = "serviceId";
- service.setName(serviceName);
- service.setVersion(serviceVersion);
- service.setUniqueId(serviceId);
-
- String artifactName = "service-Myservice-template.yml";
- String artifactLabel = "assettoscatemplate";
- String esArtifactId = "123123dfgdfgd0";
- byte[] payload = "some payload".getBytes();
- ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition();
- toscaTemplateArtifact.setArtifactName(artifactName);
- toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType());
- toscaTemplateArtifact.setArtifactLabel(artifactLabel);
- toscaTemplateArtifact.setEsId(esArtifactId);
- toscaTemplateArtifact.setPayload(payload);
-
- Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();
- toscaArtifacts.put(artifactLabel, toscaTemplateArtifact);
- service.setToscaArtifacts(toscaArtifacts);
-
- ESArtifactData esArtifactData =new ESArtifactData(esArtifactId);
- esArtifactData.setDataAsArray(payload);
- Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData);
- when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres);
- List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>();
- serviceList.add(service);
- Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList);
- when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes);
- Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes =
- artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
- assertTrue(downloadServiceArtifactByNamesRes.isLeft());
- assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length);
- }
-
- @Test
- public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception {
- ArtifactDefinition heatArtifact = new ArtifactBuilder()
- .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1"))
- .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2"))
- .build();
-
- Resource component = new Resource();
- when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER));
- when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId")))
- .thenReturn(Either.left(new ArtifactDefinition()));
- Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap());
- assertTrue(heatEnvPlaceHolder.isLeft());
- assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters());
- }
-
- @Test
- public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception {
- HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1");
- HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2");
- HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3");
- ArtifactDefinition heatArtifact = new ArtifactBuilder()
- .addHeatParam(heatParam1)
- .addHeatParam(heatParam2)
- .addHeatParam(heatParam3)
- .build();
-
- Resource component = new Resource();
-
- when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER));
- when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId")))
- .thenReturn(Either.left(new ArtifactDefinition()));
-
- Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap());
-
- assertTrue(heatEnvPlaceHolder.isLeft());
- ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value();
- List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters();
- assertEquals(listHeatParameters.size(), 3);
- verifyHeatParam(listHeatParameters.get(0), heatParam1);
- verifyHeatParam(listHeatParameters.get(1), heatParam2);
- verifyHeatParam(listHeatParameters.get(2), heatParam3);
- }
-
- private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) {
- assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue());
- assertNull(heatEnvParam.getCurrentValue());
- }
+ public static final User USER = new User("John", "Doh", "jh0003", "jh0003@gmail.com", "ADMIN", System.currentTimeMillis());
+ private final static String RESOURCE_INSTANCE_NAME = "Service-111";
+ private final static String INSTANCE_ID = "S-123-444-ghghghg";
+
+ private final static String ARTIFACT_NAME = "service-Myservice-template.yml";
+ private final static String ARTIFACT_LABEL = "assettoscatemplate";
+ private final static String ES_ARTIFACT_ID = "123123dfgdfgd0";
+ private final static byte[] PAYLOAD = "some payload".getBytes();
+
+ static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
+ static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+
+ @InjectMocks
+ private static ArtifactsBusinessLogic artifactBL;
+ @Mock
+ private ArtifactOperation artifactOperation;
+ @Mock
+ public ComponentsUtils componentsUtils;
+ @Mock
+ private IInterfaceLifecycleOperation lifecycleOperation;
+ @Mock
+ private IUserAdminOperation userOperation;
+ @Mock
+ private IElementOperation elementOperation;
+ @Mock
+ private ArtifactCassandraDao artifactCassandraDao;
+ @Mock
+ public ToscaOperationFacade toscaOperationFacade;
+ @Mock
+ private UserBusinessLogic userBusinessLogic;
+ @Mock
+ private NodeTemplateOperation nodeTemplateOperation;
+ @Mock
+ private ArtifactsOperations artifactsOperations;
+ @Mock
+ private IGraphLockOperation graphLockOperation;
+ @Mock
+ TitanDao titanDao;
+
+ // public static final InformationDeployedArtifactsBusinessLogic
+ // informationDeployedArtifactsBusinessLogic =
+ // Mockito.mock(InformationDeployedArtifactsBusinessLogic.class);
+
+ public static final Resource resource = Mockito.mock(Resource.class);
+ private Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+
+ private static List<ArtifactType> getAllTypes() {
+ List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
+ List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes();
+ for (String artifactType : artifactTypesList) {
+ ArtifactType artifactT = new ArtifactType();
+ artifactT.setName(artifactType);
+ artifactTypes.add(artifactT);
+ }
+ return artifactTypes;
+ }
+
+ @Before
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND);
+
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2);
+ when(artifactOperation.getArtifacts(Mockito.anyString(), eq(NodeTypeEnum.Resource), Mockito.anyBoolean())).thenReturn(NotFoundResult2);
+
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> notFoundInterfaces = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(lifecycleOperation.getAllInterfacesOfResource(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(notFoundInterfaces);
+
+ Either<User, ActionStatus> getUserResult = Either.left(USER);
+
+ when(userOperation.getUserData("jh0003", false)).thenReturn(getUserResult);
+
+ Either<List<ArtifactType>, ActionStatus> getType = Either.left(getAllTypes());
+ when(elementOperation.getAllArtifactTypes()).thenReturn(getType);
+
+ when(resource.getResourceType()).thenReturn(ResourceTypeEnum.VFC);
+ }
+
+ @Test
+ public void testValidJson() {
+ ArtifactDefinition ad = createArtifactDef();
+
+ String jsonArtifact = "";
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+
+ try {
+ jsonArtifact = mapper.writeValueAsString(ad);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact, ArtifactDefinition.class);
+ assertEquals(ad, afterConvert);
+ }
+
+ private ArtifactDefinition createArtifactDef() {
+ ArtifactDefinition ad = new ArtifactDefinition();
+ ad.setArtifactName("artifact1.yaml");
+ ad.setArtifactLabel("label1");
+ ad.setDescription("description");
+ ad.setArtifactType(ArtifactTypeEnum.HEAT.getType());
+ ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
+ ad.setCreationDate(System.currentTimeMillis());
+ ad.setMandatory(false);
+ ad.setTimeout(15);
+ return ad;
+ }
+
+ @Test
+ public void testInvalidStringGroupType() {
+ ArtifactDefinition ad = new ArtifactDefinition();
+ ad.setArtifactName("artifact1");
+ ad.setCreationDate(System.currentTimeMillis());
+ ad.setMandatory(false);
+ ad.setTimeout(15);
+
+ JsonElement jsonArtifact = gson.toJsonTree(ad);
+ jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", "www");
+
+ ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
+ assertNull(afterConvert);
+ }
+
+ @Test
+ public void testInvalidNumberGroupType() {
+ ArtifactDefinition ad = new ArtifactDefinition();
+ ad.setArtifactName("artifact1");
+ ad.setCreationDate(System.currentTimeMillis());
+ ad.setMandatory(false);
+ ad.setTimeout(15);
+
+ JsonElement jsonArtifact = gson.toJsonTree(ad);
+ jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", 123);
+
+ ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
+ assertNull(afterConvert);
+ }
+
+ @Test
+ public void testInvalidGroupTypeWithSpace() {
+ ArtifactDefinition ad = new ArtifactDefinition();
+ ad.setArtifactName("artifact1");
+ ad.setCreationDate(System.currentTimeMillis());
+ ad.setMandatory(false);
+ ad.setTimeout(15);
+
+ JsonElement jsonArtifact = gson.toJsonTree(ad);
+ jsonArtifact.getAsJsonObject().addProperty("artifactGroupType", " DEPLOYMENT");
+
+ ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
+ assertNull(afterConvert);
+ }
+
+ @Test
+ public void testInvalidTimeoutWithSpace() {
+ ArtifactDefinition ad = new ArtifactDefinition();
+ ad.setArtifactName("artifact1");
+ ad.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
+ ad.setCreationDate(System.currentTimeMillis());
+ ad.setMandatory(false);
+
+ JsonElement jsonArtifact = gson.toJsonTree(ad);
+ jsonArtifact.getAsJsonObject().addProperty("timeout", "dfsdf15");
+
+ ArtifactDefinition afterConvert = RepresentationUtils.convertJsonToArtifactDefinition(jsonArtifact.toString(), ArtifactDefinition.class);
+ assertNull(afterConvert);
+ }
+
+ @Test
+ public void testValidMibAritactsConfiguration() {
+ Map<String, ArtifactTypeConfig> componentDeploymentArtifacts =
+ ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
+ Map<String, ArtifactTypeConfig> componentInstanceDeploymentArtifacts =
+ ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
+ assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType()));
+ assertTrue(componentDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType()));
+ assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_POLL.getType()));
+ assertTrue(componentInstanceDeploymentArtifacts.containsKey(ArtifactTypeEnum.SNMP_TRAP.getType()));
+ }
+
+ @Test
+ public void testDownloadServiceArtifactByNames() {
+ Service service = new Service();
+ String serviceName = "myService";
+ String serviceVersion = "1.0";
+ String serviceId = "serviceId";
+ service.setName(serviceName);
+ service.setVersion(serviceVersion);
+ service.setUniqueId(serviceId);
+
+ String artifactName = "service-Myservice-template.yml";
+ String artifactLabel = "assettoscatemplate";
+ String esArtifactId = "123123dfgdfgd0";
+ byte[] payload = "some payload".getBytes();
+ ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition();
+ toscaTemplateArtifact.setArtifactName(artifactName);
+ toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType());
+ toscaTemplateArtifact.setArtifactLabel(artifactLabel);
+ toscaTemplateArtifact.setEsId(esArtifactId);
+ toscaTemplateArtifact.setPayload(payload);
+
+ Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();
+ toscaArtifacts.put(artifactLabel, toscaTemplateArtifact);
+ service.setToscaArtifacts(toscaArtifacts);
+
+ ESArtifactData esArtifactData =new ESArtifactData(esArtifactId);
+ esArtifactData.setDataAsArray(payload);
+ Either<ESArtifactData, CassandraOperationStatus> artifactfromESres = Either.left(esArtifactData);
+ when(artifactCassandraDao.getArtifact(esArtifactId)).thenReturn(artifactfromESres);
+ List<org.openecomp.sdc.be.model.Component> serviceList = new ArrayList<>();
+ serviceList.add(service);
+ Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> getServiceRes = Either.left(serviceList);
+ when(toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName)).thenReturn(getServiceRes);
+ Either<byte[], ResponseFormat> downloadServiceArtifactByNamesRes =
+ artifactBL.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
+ assertTrue(downloadServiceArtifactByNamesRes.isLeft());
+ assertTrue(downloadServiceArtifactByNamesRes.left().value() !=null && downloadServiceArtifactByNamesRes.left().value().length == payload.length);
+ }
+
+ @Test
+ public void createHeatEnvPlaceHolder_vf_emptyHeatParameters() throws Exception {
+ ArtifactDefinition heatArtifact = new ArtifactBuilder()
+ .addHeatParam(ObjectGenerator.buildHeatParam("defVal1", "val1"))
+ .addHeatParam(ObjectGenerator.buildHeatParam("defVal2", "val2"))
+ .build();
+
+ Resource component = new Resource();
+ when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER));
+ when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId")))
+ .thenReturn(Either.left(new ArtifactDefinition()));
+ Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_VF_ENV_NAME, "parentId", NodeTypeEnum.Resource, "parentName", USER, component, Collections.emptyMap());
+ assertTrue(heatEnvPlaceHolder.isLeft());
+ assertNull(heatEnvPlaceHolder.left().value().getListHeatParameters());
+ }
+
+ @Test
+ public void createHeatEnvPlaceHolder_resourceInstance_copyHeatParamasCurrValuesToHeatEnvDefaultVal() throws Exception {
+ HeatParameterDefinition heatParam1 = ObjectGenerator.buildHeatParam("defVal1", "val1");
+ HeatParameterDefinition heatParam2 = ObjectGenerator.buildHeatParam("defVal2", "val2");
+ HeatParameterDefinition heatParam3 = ObjectGenerator.buildHeatParam("defVal3", "val3");
+ ArtifactDefinition heatArtifact = new ArtifactBuilder()
+ .addHeatParam(heatParam1)
+ .addHeatParam(heatParam2)
+ .addHeatParam(heatParam3)
+ .build();
+
+ Resource component = new Resource();
+
+ when(userBusinessLogic.getUser(anyString(), anyBoolean())).thenReturn(Either.left(USER));
+ when(artifactsOperations.addHeatEnvArtifact(any(ArtifactDefinition.class), any(ArtifactDefinition.class), eq(component.getUniqueId()), eq(NodeTypeEnum.Resource), eq(true), eq("parentId")))
+ .thenReturn(Either.left(new ArtifactDefinition()));
+
+ Either<ArtifactDefinition, ResponseFormat> heatEnvPlaceHolder = artifactBL.createHeatEnvPlaceHolder(heatArtifact, HEAT_ENV_NAME, "parentId", NodeTypeEnum.ResourceInstance, "parentName", USER, component, Collections.emptyMap());
+
+ assertTrue(heatEnvPlaceHolder.isLeft());
+ ArtifactDefinition heatEnvArtifact = heatEnvPlaceHolder.left().value();
+ List<HeatParameterDefinition> listHeatParameters = heatEnvArtifact.getListHeatParameters();
+ assertEquals(listHeatParameters.size(), 3);
+ verifyHeatParam(listHeatParameters.get(0), heatParam1);
+ verifyHeatParam(listHeatParameters.get(1), heatParam2);
+ verifyHeatParam(listHeatParameters.get(2), heatParam3);
+ }
+
+ @Test
+ public void buildArtifactPayloadWhenShouldLockAndInTransaction() {
+ ArtifactDefinition artifactDefinition = new ArtifactDefinition();
+ artifactDefinition.setArtifactName(ARTIFACT_NAME);
+ artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType());
+ artifactDefinition.setArtifactLabel(ARTIFACT_LABEL);
+ artifactDefinition.setEsId(ES_ARTIFACT_ID);
+ artifactDefinition.setPayload(PAYLOAD);
+ artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA);
+
+ when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK);
+ when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class)
+ , any(String.class))).thenReturn(Either.left(artifactDefinition));
+ when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK);
+ when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat());
+ artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME,
+ USER, INSTANCE_ID, true, true);
+ }
+
+ @Test
+ public void buildArtifactPayloadWhenShouldLockAndNotInTransaction() {
+ ArtifactDefinition artifactDefinition = new ArtifactDefinition();
+ artifactDefinition.setArtifactName(ARTIFACT_NAME);
+ artifactDefinition.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType());
+ artifactDefinition.setArtifactLabel(ARTIFACT_LABEL);
+ artifactDefinition.setEsId(ES_ARTIFACT_ID);
+ artifactDefinition.setPayload(PAYLOAD);
+ artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.TOSCA);
+
+ when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK);
+ when(artifactsOperations.updateArifactOnResource(any(ArtifactDefinition.class), any(), any(), any(NodeTypeEnum.class)
+ , any(String.class))).thenReturn(Either.left(artifactDefinition));
+ when(artifactCassandraDao.saveArtifact(any())).thenReturn(CassandraOperationStatus.OK);
+ when(componentsUtils.getResponseFormat(any(ActionStatus.class))).thenReturn(new ResponseFormat());
+ artifactBL.generateAndSaveHeatEnvArtifact(artifactDefinition, String.valueOf(PAYLOAD), ComponentTypeEnum.SERVICE, new Service(), RESOURCE_INSTANCE_NAME,
+ USER, INSTANCE_ID, true, false);
+ verify(titanDao, times(1)).commit();
+ }
+
+ private void verifyHeatParam(HeatParameterDefinition heatEnvParam, HeatParameterDefinition heatYamlParam) {
+ assertEquals(heatEnvParam.getDefaultValue(), heatYamlParam.getCurrentValue());
+ assertNull(heatEnvParam.getCurrentValue());
+ }
// @Test
- // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){
- // ArtifactDefinition createArtifactDef = createArtifactDef();
- // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType());
- //
- // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL
- //
- // assertTrue(validateResult.isLeft());
- // ArtifactDefinition validatedArtifact = validateResult.left().value();
- //
- // assertEquals(createArtifactDef.getArtifactGroupType(),
- // validatedArtifact.getArtifactGroupType());
- // assertEquals(new Integer(0), validatedArtifact.getTimeout());
- // assertFalse(validatedArtifact.getMandatory());
- // assertFalse(validatedArtifact.getServiceApi());
- //
- // }
+ // public void convertAndValidateDeploymentArtifactNonHeatSuccess(){
+ // ArtifactDefinition createArtifactDef = createArtifactDef();
+ // createArtifactDef.setArtifactType(ArtifactTypeEnum.YANG_XML.getType());
+ //
+ // Either<ArtifactDefinition, ResponseFormat> validateResult = artifactBL
+ //
+ // assertTrue(validateResult.isLeft());
+ // ArtifactDefinition validatedArtifact = validateResult.left().value();
+ //
+ // assertEquals(createArtifactDef.getArtifactGroupType(),
+ // validatedArtifact.getArtifactGroupType());
+ // assertEquals(new Integer(0), validatedArtifact.getTimeout());
+ // assertFalse(validatedArtifact.getMandatory());
+ // assertFalse(validatedArtifact.getServiceApi());
+ //
+ // }
}
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
index 8ad9bf80b2..18af7a035a 100644
--- 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
@@ -20,12 +20,6 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.util.Collections;
-import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -34,12 +28,21 @@ 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;
+ private Service service;
+ private Service noArtifactsService;
+ private Resource resource;
+ private Resource noArtifactsResource;
+ private ComponentInstance componentInstance;
+ private ComponentInstance noArtifactsInstance;
@Before
public void setUp() throws Exception {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java
index 41835a6cdc..9b2fb3773b 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManagerTest.java
@@ -20,17 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-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 fj.data.Either;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -46,58 +36,68 @@ import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
import org.openecomp.sdc.common.util.CapabilityTypeNameEnum;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+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 static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class CapabilityTypeImportManagerTest {
- @InjectMocks
- private CapabilityTypeImportManager manager = new CapabilityTypeImportManager();
- public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class);
- public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class);
- public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+ @InjectMocks
+ private CapabilityTypeImportManager manager = new CapabilityTypeImportManager();
+ public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class);
+ public static final CapabilityTypeOperation capabilityTypeOperation = Mockito.mock(CapabilityTypeOperation.class);
+ public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
- @BeforeClass
- public static void beforeClass() {
- when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() {
- public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]);
- return ans;
- }
+ @BeforeClass
+ public static void beforeClass() {
+ when(capabilityTypeOperation.addCapabilityType(Mockito.any(CapabilityTypeDefinition.class))).thenAnswer(new Answer<Either<CapabilityTypeDefinition, StorageOperationStatus>>() {
+ public Either<CapabilityTypeDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ Either<CapabilityTypeDefinition, StorageOperationStatus> ans = Either.left((CapabilityTypeDefinition) args[0]);
+ return ans;
+ }
- });
- when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod();
- }
+ });
+ when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod();
+ when(commonImportManager.createElementTypesFromToscaJsonMap(Mockito.any(), Mockito.any())).thenCallRealMethod();
+ }
- @Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- }
+ @Before
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
- @Test
- public void testCreateCapabilityTypes() throws IOException {
- String ymlContent = getCapabilityTypesYml();
- Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent);
- assertTrue(createCapabilityTypes.isLeft());
+ @Test
+ public void testCreateCapabilityTypes() throws IOException {
+ String ymlContent = getCapabilityTypesYml();
+ Either<List<CapabilityTypeDefinition>, ResponseFormat> createCapabilityTypes = manager.createCapabilityTypes(ymlContent);
+ assertTrue(createCapabilityTypes.isLeft());
- List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value();
- assertTrue(capabilityTypesList.size() == 14);
- Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>();
- for (CapabilityTypeDefinition capType : capabilityTypesList) {
- capibilityTypeMap.put(capType.getType(), capType);
- }
- assertTrue(capabilityTypesList.size() == 14);
+ List<CapabilityTypeDefinition> capabilityTypesList = createCapabilityTypes.left().value();
+ assertTrue(capabilityTypesList.size() == 14);
+ Map<String, CapabilityTypeDefinition> capibilityTypeMap = new HashMap<>();
+ for (CapabilityTypeDefinition capType : capabilityTypesList) {
+ capibilityTypeMap.put(capType.getType(), capType);
+ }
+ assertTrue(capabilityTypesList.size() == 14);
- for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) {
- assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName()));
- }
+ for (CapabilityTypeNameEnum curr : CapabilityTypeNameEnum.values()) {
+ assertTrue(capibilityTypeMap.containsKey(curr.getCapabilityName()));
+ }
- }
+ }
- private String getCapabilityTypesYml() throws IOException {
- Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml");
- byte[] fileContent = Files.readAllBytes(filePath);
- String ymlContent = new String(fileContent);
- return ymlContent;
- }
+ private String getCapabilityTypesYml() throws IOException {
+ Path filePath = Paths.get("src/test/resources/types/capabilityTypes.yml");
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String ymlContent = new String(fileContent);
+ return ymlContent;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java
index 2c83c60fc6..8a07e26161 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CategoriesImportManagerTest.java
@@ -20,16 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -45,64 +36,66 @@ 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.exception.ResponseFormat;
-import org.slf4j.Logger;
-
-import fj.data.Either;
-
-public class CategoriesImportManagerTest {
- @InjectMocks
- static CategoriesImportManager importManager = new CategoriesImportManager();
- public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class);
- public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
-
- static Logger log = Mockito.spy(Logger.class);
- private static SubCategoryDefinition subcategory;
-
- @BeforeClass
- public static void beforeClass() throws IOException {
- InterfaceLifecycleTypeImportManager.setLog(log);
-
- subcategory = new SubCategoryDefinition();
- subcategory.setUniqueId("123");
-
- when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> {
- Object[] args = invocation.getArguments();
- CategoryDefinition category = (CategoryDefinition) args[0];
- category.setUniqueId("123");
- Either<CategoryDefinition, ActionStatus> ans = Either.left(category);
- return ans;
- });
- when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() {
- public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- // subcategory.setName(((SubCategoryDefinition)args[0]).getName());
- Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory);
- return ans;
- }
-
- });
-
- // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123");
- }
-
- @Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void importCategoriesTest() throws IOException {
- String ymlContent = getYmlContent();
- Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent);
- assertTrue(createCapabilityTypes.isLeft());
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Map;
- }
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
- private String getYmlContent() throws IOException {
- Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml");
- byte[] fileContent = Files.readAllBytes(filePath);
- String ymlContent = new String(fileContent);
- return ymlContent;
- }
+public class CategoriesImportManagerTest {
+ @InjectMocks
+ static CategoriesImportManager importManager = new CategoriesImportManager();
+ public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class);
+ public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+ private static SubCategoryDefinition subcategory;
+
+ @BeforeClass
+ public static void beforeClass() throws IOException {
+ subcategory = new SubCategoryDefinition();
+ subcategory.setUniqueId("123");
+
+ when(elementOperation.createCategory(Mockito.any(CategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer((Answer<Either<CategoryDefinition, ActionStatus>>) invocation -> {
+ Object[] args = invocation.getArguments();
+ CategoryDefinition category = (CategoryDefinition) args[0];
+ category.setUniqueId("123");
+ Either<CategoryDefinition, ActionStatus> ans = Either.left(category);
+ return ans;
+ });
+ when(elementOperation.createSubCategory(Mockito.any(String.class), Mockito.any(SubCategoryDefinition.class), Mockito.any(NodeTypeEnum.class))).thenAnswer(new Answer<Either<SubCategoryDefinition, ActionStatus>>() {
+ public Either<SubCategoryDefinition, ActionStatus> answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ // subcategory.setName(((SubCategoryDefinition)args[0]).getName());
+ Either<SubCategoryDefinition, ActionStatus> ans = Either.left(subcategory);
+ return ans;
+ }
+
+ });
+
+ // when(Mockito.any(SubCategoryDefinition.class).getUniqueId()).thenReturn("123");
+ }
+
+ @Before
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void importCategoriesTest() throws IOException {
+ String ymlContent = getYmlContent();
+ Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCapabilityTypes = importManager.createCategories(ymlContent);
+ assertTrue(createCapabilityTypes.isLeft());
+
+ }
+
+ private String getYmlContent() throws IOException {
+ Path filePath = Paths.get("src/test/resources/types/categoryTypes.yml");
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String ymlContent = new String(fileContent);
+ return ymlContent;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java
index 65f7ac46b6..a5d05eff2c 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java
@@ -1,23 +1,22 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.BiPredicate;
-
+import fj.data.Either;
import org.assertj.core.util.Lists;
+import org.junit.Assert;
+import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.ServletUtils;
import org.openecomp.sdc.be.model.CapabilityDefinition;
@@ -32,214 +31,354 @@ import org.openecomp.sdc.be.model.RequirementDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.BiPredicate;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anySet;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
/**
* The test suite designed for test functionality of ComponentInstanceBusinessLogic class
*/
public class ComponentInstanceBusinessLogicTest {
-
- private final static String USER_ID = "jh0003";
- private final static String COMPONENT_ID = "componentId";
- private final static String TO_INSTANCE_ID = "toInstanceId";
- private final static String FROM_INSTANCE_ID = "fromInstanceId";
- private final static String RELATION_ID = "relationId";
- private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId";
- private final static String CAPABILITY_UID = "capabilityUid";
- private final static String CAPABILITY_NAME = "capabilityName";
- private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId";
- private final static String REQUIREMENT_UID = "requirementUid";
- private final static String REQUIREMENT_NAME = "requirementName";
- private final static String RELATIONSHIP_TYPE = "relationshipType";
-
- private static ComponentsUtils componentsUtils;
- private static ServletUtils servletUtils;
- private static ResponseFormat responseFormat;
- private static ToscaOperationFacade toscaOperationFacade;
- private static UserBusinessLogic userAdmin;
-
- private static ComponentInstanceBusinessLogic serviceBusinessLogic;
- private static ComponentInstanceBusinessLogic resourceBusinessLogic;
- private static User user;
- private static Component service;
- private static Component resource;
- private static ComponentInstance toInstance;
- private static ComponentInstance fromInstance;
- private static CapabilityDataDefinition capability;
- private static RequirementDataDefinition requirement;
- private static RequirementCapabilityRelDef relation;
-
- @BeforeClass
- public static void setup() {
- createMocks();
- setMocks();
- stubMethods();
- createComponents();
- }
-
- @Test
- public void testGetRelationByIdSuccess(){
- getServiceRelationByIdSuccess(service);
- getServiceRelationByIdSuccess(resource);
- }
-
- @Test
- public void testGetRelationByIdUserValidationFailure(){
- getServiceRelationByIdUserValidationFailure(service);
- getServiceRelationByIdUserValidationFailure(resource);
- }
-
- @Test
- public void testGetRelationByIdComponentNotFoundFailure(){
- getRelationByIdComponentNotFoundFailure(service);
- getRelationByIdComponentNotFoundFailure(resource);
- }
-
- @SuppressWarnings("unchecked")
- private void getServiceRelationByIdSuccess(Component component){
- Either<User, ActionStatus> eitherCreator = Either.left(user);
- when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator);
- Either<Component, StorageOperationStatus> getComponentRes = Either.left(component);
- when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes);
-
- Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement);
- when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes);
-
- Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability);
- when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes);
-
- Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
- assertTrue(response.isLeft());
- }
-
- private void getServiceRelationByIdUserValidationFailure(Component component){
- Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND);
- when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator);
-
- Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
- assertTrue(response.isRight());
- }
-
- private void getRelationByIdComponentNotFoundFailure(Component component){
- Either<User, ActionStatus> eitherCreator = Either.left(user);
- when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator);
- Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND);
- when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes);
-
- Either<RequirementCapabilityRelDef, ResponseFormat> response = serviceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
- assertTrue(response.isRight());
- }
-
- private static void createMocks() {
- componentsUtils = Mockito.mock(ComponentsUtils.class);
- servletUtils = Mockito.mock(ServletUtils.class);
- responseFormat = Mockito.mock(ResponseFormat.class);
- toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
- userAdmin = Mockito.mock(UserBusinessLogic.class);
- user = Mockito.mock(User.class);
- }
-
- private static void setMocks() {
- serviceBusinessLogic = new ServiceComponentInstanceBusinessLogic();
- serviceBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
- serviceBusinessLogic.setUserAdmin(userAdmin);
- serviceBusinessLogic.setComponentsUtils(componentsUtils);
-
- resourceBusinessLogic = new VFComponentInstanceBusinessLogic();
- resourceBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
- resourceBusinessLogic.setUserAdmin(userAdmin);
- resourceBusinessLogic.setComponentsUtils(componentsUtils);
- }
-
- private static void stubMethods() {
- when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
- when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat);
- }
-
- private static void createComponents() {
- createRelation();
- createInstances();
- createService();
- createResource();
- }
-
- private static void createResource() {
- resource = new Resource();
- resource.setUniqueId(COMPONENT_ID);
- resource.setComponentInstancesRelations(Lists.newArrayList(relation));
- resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance));
- resource.setCapabilities(toInstance.getCapabilities());
- resource.setRequirements(fromInstance.getRequirements());
- resource.setComponentType(ComponentTypeEnum.RESOURCE);
- }
-
-
- private static void createService() {
- service = new Service();
- service.setUniqueId(COMPONENT_ID);
- service.setComponentInstancesRelations(Lists.newArrayList(relation));
- service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance));
- service.setCapabilities(toInstance.getCapabilities());
- service.setRequirements(fromInstance.getRequirements());
- service.setComponentType(ComponentTypeEnum.SERVICE);
- }
-
-
- private static void createInstances() {
- toInstance = new ComponentInstance();
- toInstance.setUniqueId(TO_INSTANCE_ID);
-
- fromInstance = new ComponentInstance();
- fromInstance.setUniqueId(FROM_INSTANCE_ID);
-
- capability = new CapabilityDataDefinition();
- capability.setOwnerId(CAPABILITY_OWNER_ID);
- capability.setUniqueId(CAPABILITY_UID);
- capability.setName(CAPABILITY_NAME);
-
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability)));
-
- requirement = new RequirementDataDefinition();
- requirement.setOwnerId(REQUIREMENT_OWNER_ID);
- requirement.setUniqueId(REQUIREMENT_UID);
- requirement.setName(REQUIREMENT_NAME);
- requirement.setRelationship(RELATIONSHIP_TYPE);
-
-
- Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
- requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement)));
-
- toInstance.setCapabilities(capabilities);
- fromInstance.setRequirements(requirements);
- }
-
-
- private static void createRelation() {
-
- relation = new RequirementCapabilityRelDef();
- CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship();
- RelationshipInfo relationInfo = new RelationshipInfo();
- relationInfo.setId(RELATION_ID);
- relationship.setRelation(relationInfo);
-
- relation.setRelationships(Lists.newArrayList(relationship));
- relation.setToNode(TO_INSTANCE_ID);
- relation.setFromNode(FROM_INSTANCE_ID);
-
- relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID);
- relationInfo.setCapabilityUid(CAPABILITY_UID);
- relationInfo.setCapability(CAPABILITY_NAME);
- relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID);
- relationInfo.setRequirementUid(REQUIREMENT_UID);
- relationInfo.setRequirement(REQUIREMENT_NAME);
- RelationshipImpl relationshipImpl = new RelationshipImpl();
- relationshipImpl.setType(RELATIONSHIP_TYPE);
- relationInfo.setRelationships(relationshipImpl);
- }
+
+ private final static String USER_ID = "jh0003";
+ private final static String COMPONENT_ID = "componentId";
+ private final static String TO_INSTANCE_ID = "toInstanceId";
+ private final static String FROM_INSTANCE_ID = "fromInstanceId";
+ private final static String RELATION_ID = "relationId";
+ private final static String CAPABILITY_OWNER_ID = "capabilityOwnerId";
+ private final static String CAPABILITY_UID = "capabilityUid";
+ private final static String CAPABILITY_NAME = "capabilityName";
+ private final static String REQUIREMENT_OWNER_ID = "requirementOwnerId";
+ private final static String REQUIREMENT_UID = "requirementUid";
+ private final static String REQUIREMENT_NAME = "requirementName";
+ private final static String RELATIONSHIP_TYPE = "relationshipType";
+
+ private static ComponentsUtils componentsUtils;
+ private static ServletUtils servletUtils;
+ private static ResponseFormat responseFormat;
+ private static ToscaOperationFacade toscaOperationFacade;
+ private static UserBusinessLogic userAdmin;
+
+ private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ private static ForwardingPathOperation forwardingPathOperation;
+ private static User user;
+ private static UserValidations userValidations;
+ private static Component service;
+ private static Component resource;
+ private static ComponentInstance toInstance;
+ private static ComponentInstance fromInstance;
+ private static CapabilityDataDefinition capability;
+ private static RequirementDataDefinition requirement;
+ private static RequirementCapabilityRelDef relation;
+
+ @BeforeClass
+ public static void setup() {
+ createMocks();
+ setMocks();
+ stubMethods();
+ createComponents();
+
+ }
+
+ @Before
+ public void init(){
+ MockitoAnnotations.initMocks(this);
+ }
+ @Test
+ public void testGetRelationByIdSuccess(){
+ getServiceRelationByIdSuccess(service);
+ getServiceRelationByIdSuccess(resource);
+ }
+
+ @Test
+ public void testGetRelationByIdUserValidationFailure(){
+ getServiceRelationByIdUserValidationFailure(service);
+ getServiceRelationByIdUserValidationFailure(resource);
+ }
+
+ @Test
+ public void testGetRelationByIdComponentNotFoundFailure(){
+ getRelationByIdComponentNotFoundFailure(service);
+ getRelationByIdComponentNotFoundFailure(resource);
+ }
+
+
+
+
+ @Test
+ public void testForwardingPathOnVersionChange(){
+ getforwardingPathOnVersionChange();
+ }
+
+ private void getforwardingPathOnVersionChange(){
+ String containerComponentParam="services";
+ String containerComponentID="121-cont";
+ String componentInstanceID="121-cont-1-comp";
+ Service component=new Service();
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = generateForwardingPath(componentInstanceID);
+
+ //Add existing componentInstance to component
+ List<ComponentInstance> componentInstanceList=new ArrayList<>();
+ ComponentInstance oldComponentInstance=new ComponentInstance();
+ oldComponentInstance.setName("OLD_COMP_INSTANCE");
+ oldComponentInstance.setUniqueId(componentInstanceID);
+ oldComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,"1-comp");
+ componentInstanceList.add(oldComponentInstance);
+ component.setComponentInstances(componentInstanceList);
+ component.setForwardingPaths(forwardingPaths);
+
+ List<ComponentInstance> componentInstanceListNew=new ArrayList<>();
+ ComponentInstance newComponentInstance=new ComponentInstance();
+ String new_Comp_UID="2-comp";
+ newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,new_Comp_UID);
+ newComponentInstance.setUniqueId(new_Comp_UID);
+ componentInstanceListNew.add(newComponentInstance);
+ Component component2=new Service();
+ component2.setComponentInstances(componentInstanceListNew);
+
+ //Mock for getting component
+ when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component));
+ when(toscaOperationFacade.validateComponentExists(any(String.class))).thenReturn(Either.left(Boolean.TRUE));
+ //Mock for getting component for componentInstance
+ when(toscaOperationFacade.getToscaFullElement(eq("1-comp"))).thenReturn(Either.left(component));
+ when(toscaOperationFacade.getToscaFullElement(eq(new_Comp_UID))).thenReturn(Either.left(component2));
+
+ Either<Set<String>, ResponseFormat> resultOp = componentInstanceBusinessLogic.forwardingPathOnVersionChange
+ (containerComponentParam,containerComponentID,componentInstanceID,newComponentInstance);
+ Assert.assertEquals(1,resultOp.left().value().size());
+ Assert.assertEquals("FP-ID-1",resultOp.left().value().iterator().next());
+
+ }
+
+
+ @Test
+ public void testDeleteForwardingPathsWhenComponentinstanceDeleted(){
+
+ ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services");
+ String containerComponentID = "Service-comp";
+ String componentInstanceID = "NodeA1";
+ Service component = new Service();
+
+ component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1"));
+ component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2"));
+ when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component));
+ when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component));
+ when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>()));
+ Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance(
+ containerComponentID, componentInstanceID, containerComponentType, Either.left(new ComponentInstance()));
+ Assert.assertTrue(responseFormatEither.isLeft());
+
+ }
+
+ @Test
+ public void testDeleteForwardingPathsWhenErrorInComponentinstanceDelete(){
+
+ ComponentTypeEnum containerComponentType = ComponentTypeEnum.findByParamName("services");
+ String containerComponentID = "Service-comp";
+ String componentInstanceID = "NodeA1";
+ Service component = new Service();
+
+ component.addForwardingPath(createPath("path1", "NodeA1", "NodeB1", "1"));
+ component.addForwardingPath(createPath("Path2", "NodeA2","NodeB2", "2"));
+ when(toscaOperationFacade.getToscaElement(eq(containerComponentID),any(ComponentParametersView.class))).thenReturn(Either.left(component));
+ when(toscaOperationFacade.getToscaElement(eq(containerComponentID))).thenReturn(Either.left(component));
+ when(forwardingPathOperation.deleteForwardingPath(any(Service.class), anySet())).thenReturn(Either.left(new HashSet<>()));
+ Either<ComponentInstance, ResponseFormat> responseFormatEither = componentInstanceBusinessLogic.deleteForwardingPathsRelatedTobeDeletedComponentInstance(
+ containerComponentID, componentInstanceID, containerComponentType, Either.right(new ResponseFormat()));
+ Assert.assertTrue(responseFormatEither.isRight());
+
+ }
+
+
+ private ForwardingPathDataDefinition createPath(String pathName, String fromNode, String toNode , String uniqueId){
+ ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName);
+ forwardingPath.setProtocol("protocol");
+ forwardingPath.setDestinationPortNumber("port");
+ forwardingPath.setUniqueId(uniqueId);
+ ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>();
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(fromNode, toNode,
+ "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
+
+ return forwardingPath;
+ }
+
+
+
+ private Map<String, ForwardingPathDataDefinition> generateForwardingPath(String componentInstanceID) {
+ ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition("fpName");
+ String protocol = "protocol";
+ forwardingPath.setProtocol(protocol);
+ forwardingPath.setDestinationPortNumber("DestinationPortNumber");
+ forwardingPath.setUniqueId("FP-ID-1");
+ ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition =
+ new ListDataDefinition<>();
+ forwardingPathElementListDataDefinition.add(
+ new ForwardingPathElementDataDefinition(componentInstanceID, "nodeB", "nodeA_FORWARDER_CAPABILITY",
+ "nodeBcpType" , "nodeDcpName",
+ "nodeBcpName"));
+ forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>();
+ forwardingPaths.put("1122", forwardingPath);
+ return forwardingPaths;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void getServiceRelationByIdSuccess(Component component){
+ Either<User, ActionStatus> eitherCreator = Either.left(user);
+ when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator);
+ Either<Component, StorageOperationStatus> getComponentRes = Either.left(component);
+ when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes);
+
+ Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = Either.left(requirement);
+ when(toscaOperationFacade.getFulfilledRequirementByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledRequirementRes);
+
+ Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledCapabilityRes = Either.left(capability);
+ when(toscaOperationFacade.getFulfilledCapabilityByRelation(eq(COMPONENT_ID), eq(FROM_INSTANCE_ID), eq(relation), any(BiPredicate.class))).thenReturn(getfulfilledCapabilityRes);
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
+ assertTrue(response.isLeft());
+ }
+
+ private void getServiceRelationByIdUserValidationFailure(Component component){
+ //Either<User, ActionStatus> eitherCreator = Either.right(ActionStatus.USER_NOT_FOUND);
+ //when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator);
+ when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.right(new ResponseFormat(404)));
+ Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
+ assertTrue(response.isRight());
+ }
+
+ private void getRelationByIdComponentNotFoundFailure(Component component){
+ Either<User, ActionStatus> eitherCreator = Either.left(user);
+ when(userAdmin.getUser(eq(USER_ID), eq(false))).thenReturn(eitherCreator);
+ Either<Component, StorageOperationStatus> getComponentRes = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(getComponentRes);
+
+ Either<RequirementCapabilityRelDef, ResponseFormat> response = componentInstanceBusinessLogic.getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType());
+ assertTrue(response.isRight());
+ }
+
+ private static void createMocks() {
+ componentsUtils = Mockito.mock(ComponentsUtils.class);
+ servletUtils = Mockito.mock(ServletUtils.class);
+ responseFormat = Mockito.mock(ResponseFormat.class);
+ toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ userAdmin = Mockito.mock(UserBusinessLogic.class);
+ user = Mockito.mock(User.class);
+ userValidations = Mockito.mock(UserValidations.class);
+ forwardingPathOperation = Mockito.mock(ForwardingPathOperation.class);
+ }
+
+ private static void setMocks() {
+ componentInstanceBusinessLogic = new ComponentInstanceBusinessLogic();
+ componentInstanceBusinessLogic.setToscaOperationFacade(toscaOperationFacade);
+ componentInstanceBusinessLogic.setUserAdmin(userAdmin);
+ componentInstanceBusinessLogic.setComponentsUtils(componentsUtils);
+ componentInstanceBusinessLogic.setUserValidations(userValidations);
+ componentInstanceBusinessLogic.setForwardingPathOperation(forwardingPathOperation);
+ }
+
+ private static void stubMethods() {
+ when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
+ when(userValidations.validateUserExists(eq(USER_ID), eq("get relation by Id"), eq(false))).thenReturn(Either.left(user));
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.RELATION_NOT_FOUND), eq(RELATION_ID), eq(COMPONENT_ID))).thenReturn(responseFormat);
+ }
+
+ private static void createComponents() {
+ createRelation();
+ createInstances();
+ createService();
+ createResource();
+ }
+
+ private static void createResource() {
+ resource = new Resource();
+ resource.setUniqueId(COMPONENT_ID);
+ resource.setComponentInstancesRelations(Lists.newArrayList(relation));
+ resource.setComponentInstances(Lists.newArrayList(toInstance,fromInstance));
+ resource.setCapabilities(toInstance.getCapabilities());
+ resource.setRequirements(fromInstance.getRequirements());
+ resource.setComponentType(ComponentTypeEnum.RESOURCE);
+ }
+
+
+ private static void createService() {
+ service = new Service();
+ service.setUniqueId(COMPONENT_ID);
+ service.setComponentInstancesRelations(Lists.newArrayList(relation));
+ service.setComponentInstances(Lists.newArrayList(toInstance,fromInstance));
+ service.setCapabilities(toInstance.getCapabilities());
+ service.setRequirements(fromInstance.getRequirements());
+ service.setComponentType(ComponentTypeEnum.SERVICE);
+ }
+
+
+ private static void createInstances() {
+ toInstance = new ComponentInstance();
+ toInstance.setUniqueId(TO_INSTANCE_ID);
+
+ fromInstance = new ComponentInstance();
+ fromInstance.setUniqueId(FROM_INSTANCE_ID);
+
+ capability = new CapabilityDataDefinition();
+ capability.setOwnerId(CAPABILITY_OWNER_ID);
+ capability.setUniqueId(CAPABILITY_UID);
+ capability.setName(CAPABILITY_NAME);
+
+ Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
+ capabilities.put(capability.getName(), Lists.newArrayList(new CapabilityDefinition(capability)));
+
+ requirement = new RequirementDataDefinition();
+ requirement.setOwnerId(REQUIREMENT_OWNER_ID);
+ requirement.setUniqueId(REQUIREMENT_UID);
+ requirement.setName(REQUIREMENT_NAME);
+ requirement.setRelationship(RELATIONSHIP_TYPE);
+
+
+ Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
+ requirements.put(requirement.getCapability(), Lists.newArrayList(new RequirementDefinition(requirement)));
+
+ toInstance.setCapabilities(capabilities);
+ fromInstance.setRequirements(requirements);
+ }
+
+
+ private static void createRelation() {
+
+ relation = new RequirementCapabilityRelDef();
+ CapabilityRequirementRelationship relationship = new CapabilityRequirementRelationship();
+ RelationshipInfo relationInfo = new RelationshipInfo();
+ relationInfo.setId(RELATION_ID);
+ relationship.setRelation(relationInfo);
+
+ relation.setRelationships(Lists.newArrayList(relationship));
+ relation.setToNode(TO_INSTANCE_ID);
+ relation.setFromNode(FROM_INSTANCE_ID);
+
+ relationInfo.setCapabilityOwnerId(CAPABILITY_OWNER_ID);
+ relationInfo.setCapabilityUid(CAPABILITY_UID);
+ relationInfo.setCapability(CAPABILITY_NAME);
+ relationInfo.setRequirementOwnerId(REQUIREMENT_OWNER_ID);
+ relationInfo.setRequirementUid(REQUIREMENT_UID);
+ relationInfo.setRequirement(REQUIREMENT_NAME);
+ RelationshipImpl relationshipImpl = new RelationshipImpl();
+ relationshipImpl.setType(RELATIONSHIP_TYPE);
+ relationInfo.setRelationships(relationshipImpl);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java
new file mode 100644
index 0000000000..a9245d2897
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentsUtilsTest.java
@@ -0,0 +1,402 @@
+package org.openecomp.sdc.be.components.impl;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.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.be.resources.data.auditing.DistributionDownloadEvent;
+import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent;
+import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.UserAdminEvent;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_DATA;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.ARTIFACT_UUID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.COMMENT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.CURRENT_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DCURR_STATUS;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESCRIPTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DESC_ERROR;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_CONSUMER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DIST_RESOURCE_URL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.DPREV_STATUS;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.INVARIANT_UUID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_FIRST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_LAST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.MODIFIER_UID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ACTION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.OP_ENV_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_STATE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.PREV_RESOURCE_VERSION;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.REQUEST_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_500;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.STATUS_OK;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TENANT_CONTEXT;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TESTER_USER_ROLE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.TOSCA_NODE_TYPE;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.UPDATED_USER_EXTENDED_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_EMAIL;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_FIRST_NAME;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_ID;
+import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.USER_LAST_NAME;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ComponentsUtilsTest {
+
+ private static User modifier = new User();
+ private Component service = new Service();
+ private Resource resource = new Resource();
+
+ @Mock
+ private AuditingManager manager;
+
+ @Mock
+ private ResponseFormat responseFormat;
+
+ @Captor
+ private ArgumentCaptor<AuditBaseEventFactory> factoryCaptor;
+
+ @InjectMocks
+ private static ComponentsUtils utils;
+
+ @BeforeClass
+ public static void setUpClass() {
+ modifier.setFirstName(MODIFIER_FIRST_NAME);
+ modifier.setLastName(MODIFIER_LAST_NAME);
+ modifier.setUserId(MODIFIER_ID);
+ }
+
+
+ @Before
+ public void setUp() {
+ ThreadLocalsHolder.setUuid(REQUEST_ID);
+ utils = new ComponentsUtils(manager);
+ }
+
+ @Test
+ public void auditComponentWhenAllParamsPassed() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+ service.setUUID(SERVICE_INSTANCE_ID);
+ service.setInvariantUUID(INVARIANT_UUID);
+
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.ARTIFACT_DELETE, service.getComponentType(),
+ ResourceAuditData.newBuilder()
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .artifactUuid(ARTIFACT_UUID)
+ .distributionStatus(DPREV_STATUS).build(),
+ ResourceAuditData.newBuilder()
+ .state(CURRENT_STATE)
+ .version(CURRENT_VERSION)
+ .artifactUuid(ARTIFACT_UUID)
+ .distributionStatus(DCURR_STATUS).build(),
+ RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID);
+ verifyResourceAdminEvent(AuditingActionEnum.ARTIFACT_DELETE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(),
+ false, true, true, true, true, true);
+ }
+
+ @Test
+ public void auditComponentWhenAllParamsPassedAndMostFromComponent() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+
+ service.setUUID(SERVICE_INSTANCE_ID);
+ service.setInvariantUUID(INVARIANT_UUID);
+ service.setState(LifecycleStateEnum.CERTIFIED);
+ service.setVersion(CURRENT_VERSION);
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType(),
+ ResourceAuditData.newBuilder()
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .artifactUuid(ARTIFACT_UUID)
+ .distributionStatus(DPREV_STATUS).build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .distributionStatus(DCURR_STATUS).build(),
+ RESOURCE_NAME, COMMENT, ARTIFACT_DATA, DIST_ID);
+ verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_OK, DESCRIPTION, service.getComponentType().getValue(),
+ false, true, true, true, true, true);
+
+ }
+
+ @Test
+ public void auditComponentDistStateWithoutArtDataCommentAndDid() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+
+ service.setUUID(SERVICE_INSTANCE_ID);
+ service.setInvariantUUID(INVARIANT_UUID);
+ service.setState(LifecycleStateEnum.CERTIFIED);
+ service.setName(RESOURCE_NAME);
+ service.setVersion(CURRENT_VERSION);
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, service.getComponentType(),
+ ResourceAuditData.newBuilder()
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .artifactUuid(ARTIFACT_UUID)
+ .distributionStatus(DPREV_STATUS).build(),
+ ResourceAuditData.newBuilder()
+ .artifactUuid(ARTIFACT_UUID)
+ .distributionStatus(DCURR_STATUS).build());
+ verifyResourceAdminEvent(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(),
+ STATUS_OK, DESCRIPTION, service.getComponentType().getValue(),
+ false, true, true, false, false, true);
+ }
+
+ @Test
+ public void auditComponentWhenError() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ service.setUUID(SERVICE_INSTANCE_ID);
+ service.setInvariantUUID(INVARIANT_UUID);
+ service.setState(LifecycleStateEnum.CERTIFIED);
+ service.setName(RESOURCE_NAME);
+ service.setVersion(CURRENT_VERSION);
+
+ utils.auditComponent(responseFormat, modifier, service, AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE,
+ ComponentTypeEnum.SERVICE,
+ ResourceAuditData.newBuilder().state(PREV_RESOURCE_STATE).version(PREV_RESOURCE_VERSION).artifactUuid(ARTIFACT_UUID).build());
+ verifyResourceAdminEvent(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName(), STATUS_500, DESC_ERROR,
+ service.getComponentType().getValue(), false, true, false, false, false, false);
+ }
+
+ @Test
+ public void auditComponentWhenCompIsNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ utils.auditComponent(responseFormat, modifier, AuditingActionEnum.START_CERTIFICATION_RESOURCE,
+ RESOURCE_NAME, ComponentTypeEnum.SERVICE, COMMENT);
+ verifyResourceAdminEvent(AuditingActionEnum.START_CERTIFICATION_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(),
+ true, false, false, false, true, false);
+ }
+
+ @Test
+ public void auditComponentAdmin() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ service.setUUID(SERVICE_INSTANCE_ID);
+ service.setInvariantUUID(INVARIANT_UUID);
+ service.setName(RESOURCE_NAME);
+ service.setState(LifecycleStateEnum.CERTIFIED);
+ service.setVersion(CURRENT_VERSION);
+ utils.auditComponentAdmin(responseFormat, modifier, service, AuditingActionEnum.CREATE_RESOURCE, service.getComponentType());
+ verifyResourceAdminEvent(AuditingActionEnum.CREATE_RESOURCE.getName(), STATUS_500, DESC_ERROR, service.getComponentType().getValue(),
+ false, false, false, false, false, false);
+ }
+
+ @Test
+ public void auditResourceWhenAllParamsPassed() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+
+ resource.setUUID(SERVICE_INSTANCE_ID);
+ resource.setInvariantUUID(INVARIANT_UUID);
+ resource.setName(RESOURCE_NAME);
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resource.setVersion(CURRENT_VERSION);
+ resource.setToscaResourceName(TOSCA_NODE_TYPE);
+ utils.auditResource(responseFormat, modifier, resource, null, AuditingActionEnum.IMPORT_RESOURCE,
+ ResourceAuditData.newBuilder()
+ .state(PREV_RESOURCE_STATE)
+ .version(PREV_RESOURCE_VERSION)
+ .artifactUuid(ARTIFACT_UUID)
+ .build(),
+ ARTIFACT_UUID, ARTIFACT_DATA);
+ verifyResourceAdminEvent(AuditingActionEnum.IMPORT_RESOURCE.getName(), STATUS_OK, DESCRIPTION, resource.getResourceType().name(),
+ false, true, true, true, false, false);
+ }
+
+ @Test
+ public void auditResourceWithoutPrevFields() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ resource.setUUID(SERVICE_INSTANCE_ID);
+ resource.setInvariantUUID(INVARIANT_UUID);
+ resource.setName(RESOURCE_NAME);
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resource.setVersion(CURRENT_VERSION);
+
+ utils.auditResource(responseFormat, modifier, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+ verifyResourceAdminEvent(AuditingActionEnum.UPDATE_RESOURCE_METADATA.getName(), STATUS_500, DESC_ERROR, resource.getResourceType().name(),
+ false, false, false, false, false, false);
+ }
+
+ @Test
+ public void auditResourceWhenResourceIsNull() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_500));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESC_ERROR);
+
+ utils.auditResource(responseFormat, modifier, RESOURCE_NAME, AuditingActionEnum.CHECKOUT_RESOURCE);
+ verifyResourceAdminEvent(AuditingActionEnum.CHECKOUT_RESOURCE.getName(), STATUS_500, DESC_ERROR, ComponentTypeEnum.RESOURCE.getValue(),
+ true, false, false, false, false, false);
+ }
+
+ @Test
+ public void auditUserAdminEvent() {
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+
+ User userAfter = new User();
+ userAfter.setFirstName(USER_FIRST_NAME);
+ userAfter.setUserId(USER_ID);
+ userAfter.setLastName(USER_LAST_NAME);
+ userAfter.setRole(TESTER_USER_ROLE);
+ userAfter.setEmail(USER_EMAIL);
+
+ utils.auditAdminUserAction(AuditingActionEnum.ADD_USER, modifier, null, userAfter, responseFormat);
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditEventFactory factory = factoryCaptor.getValue();
+ UserAdminEvent event = (UserAdminEvent)factory.getDbEvent();
+ assertThat(event.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(event.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(event.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(event.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.ADD_USER.getName());
+ assertThat(event.getUserBefore()).isNull();
+ assertThat(event.getUserAfter()).isEqualTo(UPDATED_USER_EXTENDED_NAME);
+ }
+
+ @Test
+ public void auditEcompOpEnvEvent() {
+ utils.auditEnvironmentEngine(AuditingActionEnum.CREATE_ENVIRONMENT, OP_ENV_ID, OP_ENV_TYPE, OP_ENV_ACTION, OP_ENV_NAME, TENANT_CONTEXT);
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditEventFactory factory = factoryCaptor.getValue();
+ EcompOperationalEnvironmentEvent event = (EcompOperationalEnvironmentEvent)factory.getDbEvent();
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.CREATE_ENVIRONMENT.getName());
+ assertThat(event.getOperationalEnvironmentId()).isEqualTo(OP_ENV_ID);
+ assertThat(event.getOperationalEnvironmentType()).isEqualTo(OP_ENV_TYPE);
+ assertThat(event.getOperationalEnvironmentName()).isEqualTo(OP_ENV_NAME);
+ assertThat(event.getOperationalEnvironmentAction()).isEqualTo(OP_ENV_ACTION);
+ assertThat(event.getTenantContext()).isEqualTo(TENANT_CONTEXT);
+ }
+
+ @Test
+ public void auditDistrDownloadEvent(){
+ when(responseFormat.getStatus()).thenReturn(Integer.valueOf(STATUS_OK));
+ when(responseFormat.getFormattedMessage()).thenReturn(DESCRIPTION);
+
+ utils.auditDistributionDownload(responseFormat, new DistributionData(DIST_CONSUMER_ID, DIST_RESOURCE_URL));
+
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditEventFactory factory = factoryCaptor.getValue();
+ DistributionDownloadEvent event = (DistributionDownloadEvent)factory.getDbEvent();
+ assertThat(event.getResourceUrl()).isEqualTo(DIST_RESOURCE_URL);
+ assertThat(event.getConsumerId()).isEqualTo(DIST_CONSUMER_ID);
+ assertThat(event.getStatus()).isEqualTo(STATUS_OK);
+ assertThat(event.getDesc()).isEqualTo(DESCRIPTION);
+ assertThat(event.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(event.getAction()).isEqualTo(AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD.getName());
+ }
+
+ private void verifyResourceAdminEvent(String action, String status, String desc, String resourceType, boolean isComponentNull,
+ boolean isPrevStateAndVersionSet, boolean isCurrFieldsProvided, boolean isArtDataProvided, boolean isCommentProvided,
+ boolean isDistStatusProvided) {
+ verify(manager).auditEvent(factoryCaptor.capture());
+ AuditEventFactory factory = factoryCaptor.getValue();
+ ResourceAdminEvent event = (ResourceAdminEvent)factory.getDbEvent();
+ assertThat(event.getModifier()).isEqualTo(MODIFIER_UID);
+ assertThat(event.getStatus()).isEqualTo(status);
+ assertThat(event.getDesc()).isEqualTo(desc);
+ assertThat(event.getRequestId()).isEqualTo(REQUEST_ID);
+ assertThat(event.getAction()).isEqualTo(action);
+ assertThat(event.getResourceName()).isEqualTo(RESOURCE_NAME);
+
+ if (isComponentNull) {
+ assertThat(event.getServiceInstanceId()).isNull();
+ assertThat(event.getCurrState()).isNull();
+ assertThat(event.getCurrVersion()).isNull();
+ assertThat(event.getInvariantUUID()).isNull();
+ assertThat(event.getResourceType()).isEqualTo(resourceType);
+ }
+ else {
+ assertThat(event.getServiceInstanceId()).isEqualTo(SERVICE_INSTANCE_ID);
+ assertThat(event.getCurrState()).isEqualTo(CURRENT_STATE);
+ assertThat(event.getCurrVersion()).isEqualTo(CURRENT_VERSION);
+ assertThat(event.getInvariantUUID()).isEqualTo(INVARIANT_UUID);
+ }
+ if (action.equals(AuditingActionEnum.IMPORT_RESOURCE.getName())) {
+ assertThat(event.getToscaNodeType()).isEqualTo(TOSCA_NODE_TYPE);
+ }
+ else {
+ assertThat(event.getToscaNodeType()).isEmpty();
+ }
+ if (isPrevStateAndVersionSet) {
+ assertThat(event.getPrevState()).isEqualTo(PREV_RESOURCE_STATE);
+ assertThat(event.getPrevVersion()).isEqualTo(PREV_RESOURCE_VERSION);
+ assertThat(event.getPrevArtifactUUID()).isEqualTo(ARTIFACT_UUID);
+ }
+ else {
+ assertThat(event.getPrevState()).isNull();
+ assertThat(event.getPrevVersion()).isNull();
+ assertThat(event.getPrevArtifactUUID()).isNull();
+ }
+ if (isCurrFieldsProvided) {
+ assertThat(event.getCurrArtifactUUID()).isEqualTo(ARTIFACT_UUID);
+ }
+ else {
+ assertThat(event.getCurrArtifactUUID()).isNull();
+ }
+ if (isArtDataProvided) {
+ assertThat(event.getArtifactData()).isEqualTo(ARTIFACT_DATA);
+ if (resourceType.equals(ResourceTypeEnum.VFC.name())) {
+ assertThat(event.getDid()).isNull();
+ }
+ else {
+ assertThat(event.getDid()).isEqualTo(DIST_ID);
+ }
+ }
+ else {
+ assertThat(event.getArtifactData()).isNull();
+ assertThat(event.getDid()).isNull();
+ }
+ if (isCommentProvided) {
+ assertThat(event.getComment()).isEqualTo(COMMENT);
+ }
+ else {
+ assertThat(event.getComment()).isEmpty();
+ }
+ if (isDistStatusProvided) {
+ assertThat(event.getDcurrStatus()).isEqualTo(DCURR_STATUS);
+ assertThat(event.getDprevStatus()).isEqualTo(DPREV_STATUS);
+ }
+ else {
+ assertThat(event.getDcurrStatus()).isNull();
+ assertThat(event.getDprevStatus()).isNull();
+ }
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java
index 4f1f929382..7b37b0e96a 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogicTest.java
@@ -20,7 +20,13 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertTrue;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.junit.Test;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
import java.util.ArrayList;
import java.util.HashMap;
@@ -29,126 +35,120 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Test;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
+import static org.junit.Assert.assertTrue;
public class CompositionBusinessLogicTest {
- CompositionBusinessLogic compBl = new CompositionBusinessLogic();
-
- @Test
- public void testBuildSpiralPatternPositioningForComponentInstances() {
- int instancesNum = 10;
- Resource createVF = FactoryUtils.createVF();
- for (int i = 0; i < instancesNum; i++) {
- FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance());
- }
- Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF);
- assertTrue(componentInstances.size() == instancesNum);
- // Verify Spiral Pattern
- ImmutablePair<Double, Double> key;
- key = new ImmutablePair<>(0D, 0D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(-1D, 0D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(-1D, 1D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(0D, 1D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(1D, 1D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(1D, 0D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(1D, -1D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(0D, -1D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(-1D, -1D);
- assertTrue(componentInstances.containsKey(key));
- key = new ImmutablePair<>(-2D, -1D);
- assertTrue(componentInstances.containsKey(key));
- }
-
- @Test
- public void testGetCpsConnectedToVFC() {
- List<ComponentInstance> allComponentInstances = new ArrayList<>();
- Resource createVF = FactoryUtils.createVF();
- ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF);
-
- Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF);
- assertTrue(cpsConnectedToVFC.size() == 1);
- assertTrue(cpsConnectedToVFC.containsKey(vfc));
- Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet());
- assertTrue(cps.size() == 3);
- cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP));
-
- }
-
- @Test
- public void testBuildCirclePatternForCps() {
- List<ComponentInstance> allComponentInstances = new ArrayList<>();
- Resource createVF = FactoryUtils.createVF();
- ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF);
- Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF);
-
- Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>();
- componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance);
- compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC);
- assertTrue(componentInstLocations.size() == 4);
-
- Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet());
- // Verify that all cps are located at different positions
- assertTrue(cpsLocations.size() == 3);
- Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet());
- // Verify that all cps are at the same distance from center
- assertTrue(distances.size() == 1);
-
- }
-
- /**
- * Adds 4 instances to the vf.<br>
- * vfc instance and 3 cps instances.<br>
- * the cp instances are connected to the vfc instance.<br>
- *
- * @param allComponentInstances
- * @param createVF
- * @return vfc instance
- */
- private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) {
- ComponentInstance vfc = FactoryUtils.createResourceInstance();
- vfc.setOriginType(OriginTypeEnum.VFC);
- FactoryUtils.addComponentInstanceToVF(createVF, vfc);
- allComponentInstances.add(vfc);
-
- connectCpToVfc(allComponentInstances, createVF, vfc);
- connectCpToVfc(allComponentInstances, createVF, vfc);
- connectCpToVfc(allComponentInstances, createVF, vfc);
- return vfc;
- }
-
- private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) {
- List<RequirementCapabilityRelDef> allRelations;
- if (createVF.getComponentInstancesRelations() != null) {
- allRelations = createVF.getComponentInstancesRelations();
- } else {
- allRelations = new ArrayList<>();
- createVF.setComponentInstancesRelations(allRelations);
- }
- ComponentInstance cp1 = FactoryUtils.createResourceInstance();
- cp1.setOriginType(OriginTypeEnum.CP);
- addVfcCpRelation(vfc, cp1, allRelations);
- FactoryUtils.addComponentInstanceToVF(createVF, cp1);
- allComponentInstances.add(cp1);
- }
-
- private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) {
- RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef();
- rel.setToNode(vfc.getComponentUid());
- rel.setFromNode(cp.getComponentUid());
- allRelations.add(rel);
- }
+ CompositionBusinessLogic compBl = new CompositionBusinessLogic();
+
+ @Test
+ public void testBuildSpiralPatternPositioningForComponentInstances() {
+ int instancesNum = 10;
+ Resource createVF = FactoryUtils.createVF();
+ for (int i = 0; i < instancesNum; i++) {
+ FactoryUtils.addComponentInstanceToVF(createVF, FactoryUtils.createResourceInstance());
+ }
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstances = compBl.buildSpiralPatternPositioningForComponentInstances(createVF);
+ assertTrue(componentInstances.size() == instancesNum);
+ // Verify Spiral Pattern
+ ImmutablePair<Double, Double> key;
+ key = new ImmutablePair<>(0D, 0D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(-1D, 0D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(-1D, 1D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(0D, 1D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(1D, 1D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(1D, 0D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(1D, -1D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(0D, -1D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(-1D, -1D);
+ assertTrue(componentInstances.containsKey(key));
+ key = new ImmutablePair<>(-2D, -1D);
+ assertTrue(componentInstances.containsKey(key));
+ }
+
+ @Test
+ public void testGetCpsConnectedToVFC() {
+ List<ComponentInstance> allComponentInstances = new ArrayList<>();
+ Resource createVF = FactoryUtils.createVF();
+ ComponentInstance vfc = populateVfWithVfcAndCps(allComponentInstances, createVF);
+
+ Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF);
+ assertTrue(cpsConnectedToVFC.size() == 1);
+ assertTrue(cpsConnectedToVFC.containsKey(vfc));
+ Set<ComponentInstance> cps = cpsConnectedToVFC.get(vfc).stream().collect(Collectors.toSet());
+ assertTrue(cps.size() == 3);
+ cps.stream().forEach(e -> assertTrue(e.getOriginType() == OriginTypeEnum.CP));
+
+ }
+
+ @Test
+ public void testBuildCirclePatternForCps() {
+ List<ComponentInstance> allComponentInstances = new ArrayList<>();
+ Resource createVF = FactoryUtils.createVF();
+ ComponentInstance vfcInstance = populateVfWithVfcAndCps(allComponentInstances, createVF);
+ Map<ComponentInstance, List<ComponentInstance>> cpsConnectedToVFC = compBl.getCpsConnectedToVFC(allComponentInstances, createVF);
+
+ Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations = new HashMap<>();
+ componentInstLocations.put(new ImmutablePair<Double, Double>(0D, 0D), vfcInstance);
+ compBl.buildCirclePatternForCps(componentInstLocations, cpsConnectedToVFC);
+ assertTrue(componentInstLocations.size() == 4);
+
+ Set<ImmutablePair<Double, Double>> cpsLocations = componentInstLocations.entrySet().stream().filter(entry -> entry.getValue().getOriginType() == OriginTypeEnum.CP).map(e -> e.getKey()).collect(Collectors.toSet());
+ // Verify that all cps are located at different positions
+ assertTrue(cpsLocations.size() == 3);
+ Set<Double> distances = cpsLocations.stream().map(cpLocation -> Math.sqrt(Math.pow(cpLocation.left, 2) + Math.pow(cpLocation.right, 2))).collect(Collectors.toSet());
+ // Verify that all cps are at the same distance from center
+ assertTrue(distances.size() == 1);
+
+ }
+
+ /**
+ * Adds 4 instances to the vf.<br>
+ * vfc instance and 3 cps instances.<br>
+ * the cp instances are connected to the vfc instance.<br>
+ *
+ * @param allComponentInstances
+ * @param createVF
+ * @return vfc instance
+ */
+ private ComponentInstance populateVfWithVfcAndCps(List<ComponentInstance> allComponentInstances, Resource createVF) {
+ ComponentInstance vfc = FactoryUtils.createResourceInstance();
+ vfc.setOriginType(OriginTypeEnum.VFC);
+ FactoryUtils.addComponentInstanceToVF(createVF, vfc);
+ allComponentInstances.add(vfc);
+
+ connectCpToVfc(allComponentInstances, createVF, vfc);
+ connectCpToVfc(allComponentInstances, createVF, vfc);
+ connectCpToVfc(allComponentInstances, createVF, vfc);
+ return vfc;
+ }
+
+ private void connectCpToVfc(List<ComponentInstance> allComponentInstances, Resource createVF, ComponentInstance vfc) {
+ List<RequirementCapabilityRelDef> allRelations;
+ if (createVF.getComponentInstancesRelations() != null) {
+ allRelations = createVF.getComponentInstancesRelations();
+ } else {
+ allRelations = new ArrayList<>();
+ createVF.setComponentInstancesRelations(allRelations);
+ }
+ ComponentInstance cp1 = FactoryUtils.createResourceInstance();
+ cp1.setOriginType(OriginTypeEnum.CP);
+ addVfcCpRelation(vfc, cp1, allRelations);
+ FactoryUtils.addComponentInstanceToVF(createVF, cp1);
+ allComponentInstances.add(cp1);
+ }
+
+ private void addVfcCpRelation(ComponentInstance vfc, ComponentInstance cp, List<RequirementCapabilityRelDef> allRelations) {
+ RequirementCapabilityRelDef rel = new RequirementCapabilityRelDef();
+ rel.setToNode(vfc.getComponentUid());
+ rel.setFromNode(cp.getComponentUid());
+ allRelations.add(rel);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java
index 50ad990560..d91fa7995b 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/CsarValidationUtilsTest.java
@@ -20,18 +20,18 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.Arrays;
-
import org.junit.Assert;
import org.junit.Test;
+import java.util.Arrays;
+
public class CsarValidationUtilsTest {
- private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" };
- private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" };
+ private String[] invalidExtensions = { null, ".bla", ".yaml", ".yml", ".txt", ".zip" };
+ private String[] validExtensions = { ".csar", ".cSAr", ".Csar", ".CSAR" };
- @Test
- public void testIsCsarPayloadName() {
- Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e)));
- Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e)));
- }
+ @Test
+ public void testIsCsarPayloadName() {
+ Arrays.stream(invalidExtensions).forEach(e -> Assert.assertFalse(CsarValidationUtils.isCsarPayloadName(e)));
+ Arrays.stream(validExtensions).forEach(e -> Assert.assertTrue(CsarValidationUtils.isCsarPayloadName(e)));
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java
new file mode 100644
index 0000000000..46ee852aa0
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ElementBLTest.java
@@ -0,0 +1,165 @@
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
+import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
+import org.openecomp.sdc.be.resources.data.category.CategoryData;
+import org.openecomp.sdc.common.util.ValidationUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+/**
+ * Created by chaya on 12/7/2017.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class ElementBLTest {
+
+ private static final String CATAGORY_NAME = "categoryName";
+ private static final String CATEGORY_UNIQUE_ID = "catUniqueId";
+ private static final String SERVICE_NOT_DELETED_ID = "notDeletedId";
+ private static final String DELETED_SERVICE_ID = "deletedId";
+ private List<CategoryData> categories = new ArrayList<>();
+ private List<ImmutablePair<ServiceMetadataData, GraphEdge>> services = new ArrayList<>();
+ private List<ImmutablePair<ResourceMetadataData, GraphEdge>> resources = new ArrayList<>();
+ private Service notDeletedService = new Service();
+ private Resource notDeletedResource = new Resource();
+
+ @Mock
+ private TitanGenericDao titanGenericDao;
+
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Mock
+ private TitanDao titanDao;
+
+ @InjectMocks
+ private ElementBusinessLogic elementBusinessLogic;
+
+ @Before
+ public void setup() {
+
+ initCategoriesList();
+ initServicesList();
+ initResourceslist();
+
+ when(titanDao.commit()).thenReturn(TitanOperationStatus.OK);
+ }
+
+ private void initCategoriesList() {
+ CategoryData categoryData = new CategoryData(NodeTypeEnum.ServiceNewCategory);
+ categoryData.getCategoryDataDefinition().setUniqueId(CATEGORY_UNIQUE_ID);
+ categories.add(categoryData);
+ }
+
+ private void initServicesList() {
+ ServiceMetadataData serviceNotDeleted = new ServiceMetadataData();
+ ComponentMetadataDataDefinition componentMetadataDataDefinition1 = new ServiceMetadataDataDefinition();
+ componentMetadataDataDefinition1.setIsDeleted(false);
+ componentMetadataDataDefinition1.setHighestVersion(true);
+ componentMetadataDataDefinition1.setUniqueId(SERVICE_NOT_DELETED_ID);
+ serviceNotDeleted.setMetadataDataDefinition(componentMetadataDataDefinition1);
+ services.add(new ImmutablePair<>(serviceNotDeleted, null));
+
+ ServiceMetadataData deletedService = new ServiceMetadataData();
+ ComponentMetadataDataDefinition componentMetadataDataDefinition2 = new ServiceMetadataDataDefinition();
+ componentMetadataDataDefinition2.setIsDeleted(true);
+ componentMetadataDataDefinition2.setHighestVersion(true);
+ componentMetadataDataDefinition2.setUniqueId(DELETED_SERVICE_ID);
+ deletedService.setMetadataDataDefinition(componentMetadataDataDefinition2);
+ services.add(new ImmutablePair<>(deletedService, null));
+ }
+
+ private void initResourceslist() {
+ ResourceMetadataData notDeletedResource = new ResourceMetadataData();
+ ComponentMetadataDataDefinition componentMetadataDataDefinition3 = new ResourceMetadataDataDefinition();
+ componentMetadataDataDefinition3.setIsDeleted(false);
+ componentMetadataDataDefinition3.setHighestVersion(true);
+ componentMetadataDataDefinition3.setUniqueId(SERVICE_NOT_DELETED_ID);
+ notDeletedResource.setMetadataDataDefinition(componentMetadataDataDefinition3);
+ resources.add(new ImmutablePair<>(notDeletedResource, null));
+
+ ResourceMetadataData deletedResource = new ResourceMetadataData();
+ ComponentMetadataDataDefinition componentMetadataDataDefinition4 = new ResourceMetadataDataDefinition();
+ componentMetadataDataDefinition4.setIsDeleted(true);
+ componentMetadataDataDefinition4.setHighestVersion(true);
+ componentMetadataDataDefinition4.setUniqueId(DELETED_SERVICE_ID);
+ deletedResource.setMetadataDataDefinition(componentMetadataDataDefinition4);
+ resources.add(new ImmutablePair<>(deletedResource, null));
+ }
+
+ @Test
+ public void testFetchElementsByCategoryName_filterDeleted() {
+ ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class);
+
+ when(titanGenericDao.getByCriteria(eq(NodeTypeEnum.ServiceNewCategory), criteriaCapture.capture(), eq(CategoryData.class)))
+ .thenReturn(Either.left(categories));
+ when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ServiceNewCategory),
+ CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Service, ServiceMetadataData.class))
+ .thenReturn(Either.left(services));
+ when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata))
+ .thenReturn(Either.left(notDeletedService));
+
+ Either<List<Object>, StorageOperationStatus> elementsByCategoryEither =
+ elementBusinessLogic.fetchByCategoryOrSubCategoryName(CATAGORY_NAME, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(),
+ NodeTypeEnum.Service, false, ServiceMetadataData.class, null);
+
+ List<Object> elementsByCategory = elementsByCategoryEither.left().value();
+ assertThat(elementsByCategory.get(0)).isSameAs(notDeletedService);
+ assertThat(elementsByCategory.size()).isEqualTo(1);
+ verifyCriteriaProperties(criteriaCapture);
+ }
+
+ private void verifyCriteriaProperties(ArgumentCaptor<Map> propsCapture) {
+ Map<String, Object> props = propsCapture.getValue();
+ assertThat(props.size()).isEqualTo(1);
+ assertThat(props.get(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty())).isEqualTo(ValidationUtils.normalizeCategoryName4Uniqueness(CATAGORY_NAME));
+ }
+
+ @Test
+ public void testFetchResourcesBySubcategoryUid_filterDeleted() {
+
+ when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory),
+ CATEGORY_UNIQUE_ID, GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class))
+ .thenReturn(Either.left(resources));
+
+ when(toscaOperationFacade.getToscaElement(SERVICE_NOT_DELETED_ID, JsonParseFlagEnum.ParseMetadata))
+ .thenReturn(Either.left(notDeletedResource));
+
+ Either<List<Object>, StorageOperationStatus> resourcesBySubCategoryUidEither = elementBusinessLogic.fetchByCategoryOrSubCategoryUid(CATEGORY_UNIQUE_ID, NodeTypeEnum.ResourceSubcategory,
+ GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, false, ResourceMetadataData.class, null);
+ List<Object> resourcesBySubCategoryUid = resourcesBySubCategoryUidEither.left().value();
+ assertThat(resourcesBySubCategoryUid.size()).isEqualTo(1);
+ assertThat(resourcesBySubCategoryUid.get(0)).isSameAs(notDeletedResource);
+ }
+}
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 5edf448cc2..b65e77c57f 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
@@ -20,21 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.nio.file.FileSystems;
-import java.nio.file.Files;
-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 fj.data.Either;
import org.junit.Test;
import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
@@ -46,462 +32,475 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
public class ImportUtilsTest {
- @Test
- public void testStringTypeFindToscaElements() throws IOException {
- Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>());
- assertTrue(toscaElements.isLeft());
- List<Object> list = toscaElements.left().value();
- assertTrue(list.size() == 4);
- int count = 1;
- for (Object element : list) {
- assertTrue(element instanceof String);
- String value = (String) element;
- assertTrue(value.equals("stringVal" + count));
- count++;
- }
- }
-
- @Test
- public void testBooleanTypeFindToscaElements() throws IOException {
- Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>());
- assertTrue(toscaElements.isLeft());
- List<Object> list = toscaElements.left().value();
- assertTrue(list.size() == 3);
- int count = 1;
- for (Object element : list) {
- assertTrue(element instanceof Boolean);
- Boolean value = (Boolean) element;
- if (count == 1 || count == 3) {
- assertFalse(value);
- } else if (count == 2) {
- assertTrue(value);
- }
-
- count++;
- }
- }
-
- @Test
- public void testListTypeFindToscaElements() throws IOException {
- Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>());
- assertTrue(toscaElements.isLeft());
- List<Object> list = toscaElements.left().value();
- assertTrue(list.size() == 3);
- int count = 1;
- for (Object element : list) {
- assertTrue(element instanceof List);
-
- if (count == 1) {
- verifyListElement1(element);
- } else if (count == 2) {
- verifyListElement2(element);
- }
-
- else if (count == 3) {
- verifyListElement3(element);
- }
- count++;
- }
- }
-
- @Test
- public void testAllTypeFindToscaElements() throws IOException {
- Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>());
- assertTrue(toscaElements.isLeft());
- List<Object> list = toscaElements.left().value();
- assertTrue(list.size() == 5);
- int count = 1;
- for (Object element : list) {
- if (count == 1) {
- assertTrue(element instanceof String);
- assertTrue(element.equals("tosca.nodes.Root"));
- } else if (count == 2) {
- assertTrue(element instanceof Map);
- Map<String, Object> mapElement = (Map<String, Object>) element;
- assertTrue(mapElement.size() == 2);
- Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator();
- Entry<String, Object> elementEntry = elementEntries.next();
- assertTrue(elementEntry.getKey().equals("mapTestTag"));
- assertTrue(elementEntry.getValue().equals("string"));
-
- elementEntry = elementEntries.next();
- assertTrue(elementEntry.getKey().equals("required"));
- assertTrue(elementEntry.getValue() instanceof Boolean);
- assertTrue((Boolean) elementEntry.getValue());
- }
-
- else if (count == 3) {
- assertTrue(element instanceof String);
- assertTrue(element.equals("1 MB"));
- }
-
- else if (count == 4) {
- assertTrue(element instanceof List);
- List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 2);
-
- assertTrue(listElement.get(0) instanceof Map);
- Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
- Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("greater_or_equal"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
-
- assertTrue(listElement.get(1) instanceof Map);
- innerElement = (Map<String, Object>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
- innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("stringTestTag"));
- assertTrue(innerEntry.getValue().equals("stringVal3"));
- } else if (count == 5) {
- assertTrue(element instanceof Boolean);
- assertFalse((Boolean) element);
- }
- count++;
- }
- }
-
- @Test
- public void testMapTypeFindToscaElements() throws IOException {
- Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>());
- assertTrue(toscaElements.isLeft());
- List<Object> list = toscaElements.left().value();
- assertTrue(list.size() == 2);
- int count = 1;
- for (Object element : list) {
- assertTrue(element instanceof Map);
-
- if (count == 1) {
- Map<String, Object> mapElement = (Map<String, Object>) element;
- assertTrue(mapElement.size() == 2);
- Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator();
- Entry<String, Object> inerElementEntry = iterator.next();
- assertTrue(inerElementEntry.getKey().equals("stringTestTag"));
- assertTrue(inerElementEntry.getValue().equals("stringVal1"));
-
- inerElementEntry = iterator.next();
- assertTrue(inerElementEntry.getKey().equals("listTestTag"));
- assertTrue(inerElementEntry.getValue() instanceof List);
- List<Object> innerValue = (List<Object>) inerElementEntry.getValue();
-
- assertTrue(innerValue.size() == 3);
-
- } else if (count == 2) {
- Map<String, Object> mapElement = (Map<String, Object>) element;
- assertTrue(mapElement.size() == 2);
- Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator();
- Entry<String, Object> inerElementEntry = entryItr.next();
- assertTrue(inerElementEntry.getKey().equals("type"));
- assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment"));
- inerElementEntry = entryItr.next();
- assertTrue(inerElementEntry.getKey().equals("allTestTag"));
- assertTrue(inerElementEntry.getValue() instanceof Boolean);
- }
-
- count++;
- }
- }
-
- @Test
- public void testCreateFullHeatParameterModuleWithString() {
-
- testCreateFullHeatParameterModule("string", "default value");
-
- }
-
- @Test
- public void testCreateFullHeatParameterModuleWithNumber() {
-
- testCreateFullHeatParameterModule("number", "777");
- testCreateFullHeatParameterModule("number", "777.23");
-
- }
-
- @Test
- public void testCreateFullHeatParameterModuleWithBoolean() {
-
- testCreateFullHeatParameterModule("boolean", "true");
- testCreateFullHeatParameterModule("boolean", "on");
- testCreateFullHeatParameterModule("boolean", "n");
-
- }
-
- @Test
- public void testCreateFullHeatParameterModuleWithList() {
-
- testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]");
-
- }
-
- // @Test
- // public void testCreateFullHeatParameterModuleWithInvalidType(){
- //
- // String name = "fullParameter";
- // String description = "description_text";
- //
- // Map<String, Object> parametersMap = new HashMap<String, Object>();
- // Map<String, Object> firstParam = createParameterMap("aaa", "aaa",
- // name, description);
- // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(),
- // firstParam);
- //
- // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters =
- // ImportUtils.getHeatParameters(parametersMap);
- // assertTrue(heatParameters.isRight());
- // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE,
- // heatParameters.right().value());
- //
- // }
-
- @Test
- public void testCreateFullHeatParameterModuleWithMissingType() {
-
- String name = "fullParameter";
- String description = "description_text";
-
- Map<String, Object> parametersMap = new HashMap<String, Object>();
- Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description);
- parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
-
- Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
- assertTrue(heatParameters.isRight());
- assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value());
+ @Test
+ public void testStringTypeFindToscaElements() throws IOException {
+ Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "stringTestTag", ToscaElementTypeEnum.STRING, new ArrayList<>());
+ assertTrue(toscaElements.isLeft());
+ List<Object> list = toscaElements.left().value();
+ assertTrue(list.size() == 4);
+ int count = 1;
+ for (Object element : list) {
+ assertTrue(element instanceof String);
+ String value = (String) element;
+ assertTrue(value.equals("stringVal" + count));
+ count++;
+ }
+ }
+
+ @Test
+ public void testBooleanTypeFindToscaElements() throws IOException {
+ Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "required", ToscaElementTypeEnum.BOOLEAN, new ArrayList<>());
+ assertTrue(toscaElements.isLeft());
+ List<Object> list = toscaElements.left().value();
+ assertTrue(list.size() == 3);
+ int count = 1;
+ for (Object element : list) {
+ assertTrue(element instanceof Boolean);
+ Boolean value = (Boolean) element;
+ if (count == 1 || count == 3) {
+ assertFalse(value);
+ } else if (count == 2) {
+ assertTrue(value);
+ }
+
+ count++;
+ }
+ }
+
+ @Test
+ public void testListTypeFindToscaElements() throws IOException {
+ Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-string-list-test.yml"), "listTestTag", ToscaElementTypeEnum.LIST, new ArrayList<>());
+ assertTrue(toscaElements.isLeft());
+ List<Object> list = toscaElements.left().value();
+ assertTrue(list.size() == 3);
+ int count = 1;
+ for (Object element : list) {
+ assertTrue(element instanceof List);
+
+ if (count == 1) {
+ verifyListElement1(element);
+ } else if (count == 2) {
+ verifyListElement2(element);
+ }
+
+ else if (count == 3) {
+ verifyListElement3(element);
+ }
+ count++;
+ }
+ }
+
+ @Test
+ public void testAllTypeFindToscaElements() throws IOException {
+ Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "allTestTag", ToscaElementTypeEnum.ALL, new ArrayList<>());
+ assertTrue(toscaElements.isLeft());
+ List<Object> list = toscaElements.left().value();
+ assertTrue(list.size() == 5);
+ int count = 1;
+ for (Object element : list) {
+ if (count == 1) {
+ assertTrue(element instanceof String);
+ assertTrue(element.equals("tosca.nodes.Root"));
+ } else if (count == 2) {
+ assertTrue(element instanceof Map);
+ Map<String, Object> mapElement = (Map<String, Object>) element;
+ assertTrue(mapElement.size() == 2);
+ Iterator<Entry<String, Object>> elementEntries = mapElement.entrySet().iterator();
+ Entry<String, Object> elementEntry = elementEntries.next();
+ assertTrue(elementEntry.getKey().equals("mapTestTag"));
+ assertTrue(elementEntry.getValue().equals("string"));
+
+ elementEntry = elementEntries.next();
+ assertTrue(elementEntry.getKey().equals("required"));
+ assertTrue(elementEntry.getValue() instanceof Boolean);
+ assertTrue((Boolean) elementEntry.getValue());
+ }
+
+ else if (count == 3) {
+ assertTrue(element instanceof String);
+ assertTrue(element.equals("1 MB"));
+ }
+
+ else if (count == 4) {
+ assertTrue(element instanceof List);
+ List<Object> listElement = (List<Object>) element;
+ assertTrue(listElement.size() == 2);
+
+ assertTrue(listElement.get(0) instanceof Map);
+ Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0);
+ assertTrue(innerElement.size() == 1);
+ Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("greater_or_equal"));
+ assertTrue(innerEntry.getValue().equals("1 MB"));
+
+ assertTrue(listElement.get(1) instanceof Map);
+ innerElement = (Map<String, Object>) listElement.get(1);
+ assertTrue(innerElement.size() == 1);
+ innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("stringTestTag"));
+ assertTrue(innerEntry.getValue().equals("stringVal3"));
+ } else if (count == 5) {
+ assertTrue(element instanceof Boolean);
+ assertFalse((Boolean) element);
+ }
+ count++;
+ }
+ }
+
+ @Test
+ public void testMapTypeFindToscaElements() throws IOException {
+ Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements((Map<String, Object>) loadJsonFromFile("normative-types-all-map-test.yml"), "mapTestTag", ToscaElementTypeEnum.MAP, new ArrayList<>());
+ assertTrue(toscaElements.isLeft());
+ List<Object> list = toscaElements.left().value();
+ assertTrue(list.size() == 2);
+ int count = 1;
+ for (Object element : list) {
+ assertTrue(element instanceof Map);
+
+ if (count == 1) {
+ Map<String, Object> mapElement = (Map<String, Object>) element;
+ assertTrue(mapElement.size() == 2);
+ Iterator<Entry<String, Object>> iterator = mapElement.entrySet().iterator();
+ Entry<String, Object> inerElementEntry = iterator.next();
+ assertTrue(inerElementEntry.getKey().equals("stringTestTag"));
+ assertTrue(inerElementEntry.getValue().equals("stringVal1"));
+
+ inerElementEntry = iterator.next();
+ assertTrue(inerElementEntry.getKey().equals("listTestTag"));
+ assertTrue(inerElementEntry.getValue() instanceof List);
+ List<Object> innerValue = (List<Object>) inerElementEntry.getValue();
+
+ assertTrue(innerValue.size() == 3);
+
+ } else if (count == 2) {
+ Map<String, Object> mapElement = (Map<String, Object>) element;
+ assertTrue(mapElement.size() == 2);
+ Iterator<Entry<String, Object>> entryItr = mapElement.entrySet().iterator();
+ Entry<String, Object> inerElementEntry = entryItr.next();
+ assertTrue(inerElementEntry.getKey().equals("type"));
+ assertTrue(inerElementEntry.getValue().equals("tosca.capabilities.Attachment"));
+ inerElementEntry = entryItr.next();
+ assertTrue(inerElementEntry.getKey().equals("allTestTag"));
+ assertTrue(inerElementEntry.getValue() instanceof Boolean);
+ }
+
+ count++;
+ }
+ }
+
+ @Test
+ public void testCreateFullHeatParameterModuleWithString() {
+
+ testCreateFullHeatParameterModule("string", "default value");
+
+ }
+
+ @Test
+ public void testCreateFullHeatParameterModuleWithNumber() {
+
+ testCreateFullHeatParameterModule("number", "777");
+ testCreateFullHeatParameterModule("number", "777.23");
+
+ }
+
+ @Test
+ public void testCreateFullHeatParameterModuleWithBoolean() {
+
+ testCreateFullHeatParameterModule("boolean", "true");
+ testCreateFullHeatParameterModule("boolean", "on");
+ testCreateFullHeatParameterModule("boolean", "n");
+
+ }
+
+ @Test
+ public void testCreateFullHeatParameterModuleWithList() {
+
+ testCreateFullHeatParameterModule("comma_delimited_list", "[one, two]");
+
+ }
+
+ // @Test
+ // public void testCreateFullHeatParameterModuleWithInvalidType(){
+ //
+ // String name = "fullParameter";
+ // String description = "description_text";
+ //
+ // Map<String, Object> parametersMap = new HashMap<String, Object>();
+ // Map<String, Object> firstParam = createParameterMap("aaa", "aaa",
+ // name, description);
+ // parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(),
+ // firstParam);
+ //
+ // Either<List<HeatParameterDefinition>,ResultStatusEnum> heatParameters =
+ // ImportUtils.getHeatParameters(parametersMap);
+ // assertTrue(heatParameters.isRight());
+ // assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE,
+ // heatParameters.right().value());
+ //
+ // }
+
+ @Test
+ public void testCreateFullHeatParameterModuleWithMissingType() {
+
+ String name = "fullParameter";
+ String description = "description_text";
+
+ Map<String, Object> parametersMap = new HashMap<String, Object>();
+ Map<String, Object> firstParam = createParameterMap(null, "aaa", name, description);
+ parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
+
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
+ assertTrue(heatParameters.isRight());
+ assertEquals(ResultStatusEnum.INVALID_PROPERTY_TYPE, heatParameters.right().value());
- }
+ }
- @Test
- public void testCreateFullHeatParameterModuleWithMissingFields() {
+ @Test
+ public void testCreateFullHeatParameterModuleWithMissingFields() {
- String name = "fullParameter";
+ String name = "fullParameter";
- Map<String, Object> parametersMap = new HashMap<String, Object>();
- String type = "number";
- String defValue = "defvalue";
- // default value cannot be empty in heat in case tag exists
- Map<String, Object> firstParam = createParameterMap(type, defValue, name, null);
- parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
+ Map<String, Object> parametersMap = new HashMap<String, Object>();
+ String type = "number";
+ String defValue = "defvalue";
+ // default value cannot be empty in heat in case tag exists
+ Map<String, Object> firstParam = createParameterMap(type, defValue, name, null);
+ parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
- Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
- assertTrue(heatParameters.isLeft());
- List<HeatParameterDefinition> parameterDefList = heatParameters.left().value();
- assertFalse(parameterDefList.isEmpty());
- HeatParameterDefinition parameterDefinition = parameterDefList.get(0);
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
+ assertTrue(heatParameters.isLeft());
+ List<HeatParameterDefinition> parameterDefList = heatParameters.left().value();
+ assertFalse(parameterDefList.isEmpty());
+ HeatParameterDefinition parameterDefinition = parameterDefList.get(0);
- assertParameter(parameterDefinition, name, type, null, defValue);
+ assertParameter(parameterDefinition, name, type, null, defValue);
- }
+ }
- @Test
- public void testGetAttributesFromYml() throws IOException {
+ @Test
+ public void testGetAttributesFromYml() throws IOException {
- Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml");
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson);
- assertTrue(actualAttributes.isLeft());
- Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES);
- compareAttributes(expectedAttributes, actualAttributes.left().value());
+ Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaWithAttribute.yml");
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson);
+ assertTrue(actualAttributes.isLeft());
+ Map<String, Map<String, Object>> expectedAttributes = getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES);
+ compareAttributes(expectedAttributes, actualAttributes.left().value());
- }
+ }
- @Test
- public void testGetPropertiesFromYml() throws IOException {
+ @Test
+ public void testGetPropertiesFromYml() throws IOException {
- Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml");
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson);
- assertTrue(actualProperties.isLeft());
- Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES);
- compareProperties(expectedProperties, actualProperties.left().value());
+ Map<String, Object> toscaJson = (Map<String, Object>) loadJsonFromFile("importToscaProperties.yml");
+ Either<Map<String, PropertyDefinition>, ResultStatusEnum> actualProperties = ImportUtils.getProperties(toscaJson);
+ assertTrue(actualProperties.isLeft());
+ Map<String, Map<String, Object>> expectedProperties = getElements(toscaJson, ToscaTagNamesEnum.PROPERTIES);
+ compareProperties(expectedProperties, actualProperties.left().value());
- }
+ }
- private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) {
+ private void compareAttributes(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) {
- Map<String, Object> singleExpectedAttribute;
- PropertyDefinition actualAttribute, expectedAttributeModel;
- // attributes of resource
- for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) {
+ Map<String, Object> singleExpectedAttribute;
+ PropertyDefinition actualAttribute, expectedAttributeModel;
+ // attributes of resource
+ for (Map.Entry<String, Map<String, Object>> expectedAttribute : expected.entrySet()) {
- singleExpectedAttribute = expectedAttribute.getValue();
- assertNotNull(singleExpectedAttribute);
- actualAttribute = actual.get(expectedAttribute.getKey());
- assertNotNull(actualAttribute);
- actualAttribute.setName(expectedAttribute.getKey().toString());
- expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute);
- expectedAttributeModel.setName(expectedAttribute.getKey().toString());
+ singleExpectedAttribute = expectedAttribute.getValue();
+ assertNotNull(singleExpectedAttribute);
+ actualAttribute = actual.get(expectedAttribute.getKey());
+ assertNotNull(actualAttribute);
+ actualAttribute.setName(expectedAttribute.getKey().toString());
+ expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute);
+ expectedAttributeModel.setName(expectedAttribute.getKey().toString());
- assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue());
- assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription());
- assertEquals(expectedAttributeModel.getName(), actualAttribute.getName());
- assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus());
- assertEquals(expectedAttributeModel.getType(), actualAttribute.getType());
+ assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue());
+ assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription());
+ assertEquals(expectedAttributeModel.getName(), actualAttribute.getName());
+ assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus());
+ assertEquals(expectedAttributeModel.getType(), actualAttribute.getType());
- compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema());
+ compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema());
- }
+ }
- }
+ }
- private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) {
+ private void compareProperties(Map<String, Map<String, Object>> expected, Map<String, PropertyDefinition> actual) {
- Map<String, Object> singleExpectedProperty;
- PropertyDefinition actualProperty, expectedPropertyModel;
- // attributes of resource
- for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) {
+ Map<String, Object> singleExpectedProperty;
+ PropertyDefinition actualProperty, expectedPropertyModel;
+ // attributes of resource
+ for (Map.Entry<String, Map<String, Object>> expectedProperty : expected.entrySet()) {
- singleExpectedProperty = expectedProperty.getValue();
- assertNotNull(singleExpectedProperty);
- actualProperty = actual.get(expectedProperty.getKey());
- assertNotNull(actualProperty);
- actualProperty.setName(expectedProperty.getKey().toString());
- expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty);
- expectedPropertyModel.setName(expectedProperty.getKey().toString());
+ singleExpectedProperty = expectedProperty.getValue();
+ assertNotNull(singleExpectedProperty);
+ actualProperty = actual.get(expectedProperty.getKey());
+ assertNotNull(actualProperty);
+ actualProperty.setName(expectedProperty.getKey().toString());
+ expectedPropertyModel = ImportUtils.createModuleProperty(singleExpectedProperty);
+ expectedPropertyModel.setName(expectedProperty.getKey().toString());
- assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue());
- assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription());
- assertEquals(expectedPropertyModel.getName(), actualProperty.getName());
- assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus());
- assertEquals(expectedPropertyModel.getType(), actualProperty.getType());
+ assertEquals(expectedPropertyModel.getDefaultValue(), actualProperty.getDefaultValue());
+ assertEquals(expectedPropertyModel.getDescription(), actualProperty.getDescription());
+ assertEquals(expectedPropertyModel.getName(), actualProperty.getName());
+ assertEquals(expectedPropertyModel.getStatus(), actualProperty.getStatus());
+ assertEquals(expectedPropertyModel.getType(), actualProperty.getType());
- compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema());
+ compareSchemas(expectedPropertyModel.getSchema(), actualProperty.getSchema());
- }
+ }
- }
+ }
- private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) {
+ private void compareSchemas(SchemaDefinition expected, SchemaDefinition actual) {
- if (expected == null && actual == null) {
- return;
- }
- PropertyDataDefinition actualPropertySchema = actual.getProperty();
- PropertyDataDefinition expectedPropertySchema = expected.getProperty();
- assertNotNull(actualPropertySchema);
- assertNotNull(expectedPropertySchema);
- assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription());
- assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType());
-
- }
+ if (expected == null && actual == null) {
+ return;
+ }
+ PropertyDataDefinition actualPropertySchema = actual.getProperty();
+ PropertyDataDefinition expectedPropertySchema = expected.getProperty();
+ assertNotNull(actualPropertySchema);
+ assertNotNull(expectedPropertySchema);
+ assertEquals(expectedPropertySchema.getDescription(), actualPropertySchema.getDescription());
+ assertEquals(expectedPropertySchema.getType(), actualPropertySchema.getType());
+
+ }
- private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) {
-
- Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType);
- assertTrue(toscaExpectedElements.isLeft());
-
- return toscaExpectedElements.left().value();
-
- }
-
- private void testCreateFullHeatParameterModule(String type, Object defaultVal) {
-
- String name = "fullParameter";
- String description = "description_text";
-
- Map<String, Object> parametersMap = new HashMap<String, Object>();
- Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description);
- parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
-
- Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
- assertTrue(heatParameters.isLeft());
- List<HeatParameterDefinition> parameterDefList = heatParameters.left().value();
- assertFalse(parameterDefList.isEmpty());
- HeatParameterDefinition parameterDefinition = parameterDefList.get(0);
-
- assertParameter(parameterDefinition, name, type, description, defaultVal);
-
- }
-
- private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) {
- Map<String, Object> firstParam = new HashMap<String, Object>();
- Map<String, Object> valuesMap = new HashMap<String, Object>();
-
- valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type);
- valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description);
- valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal);
-
- firstParam.put(name, valuesMap);
- return firstParam;
- }
-
- private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) {
- assertEquals(name, parameterDefinition.getName());
- assertEquals(description, parameterDefinition.getDescription());
- assertEquals(type, parameterDefinition.getType());
- assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue());
- assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue());
- }
-
- private void verifyListElement3(Object element) {
- List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 2);
-
- Map<String, String> innerElement = (Map<String, String>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
- Entry<String, String> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("testTag1"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
-
- innerElement = (Map<String, String>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
- innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("type"));
- assertTrue(innerEntry.getValue().equals("stringVal2"));
- }
-
- private void verifyListElement2(Object element) {
- List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 2);
-
- Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
- Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("testTag1"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
-
- assertTrue(listElement.get(1) instanceof Map);
- innerElement = (Map<String, Object>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
- innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("listTestTag"));
- assertTrue(innerEntry.getValue() instanceof List);
- }
-
- private void verifyListElement1(Object element) {
- List<Object> listElement = (List<Object>) element;
- assertTrue(listElement.size() == 3);
-
- Map<String, String> innerElement = (Map<String, String>) listElement.get(0);
- assertTrue(innerElement.size() == 1);
- Entry<String, String> innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("listTestTag"));
- assertTrue(innerEntry.getValue().equals("1 MB"));
-
- innerElement = (Map<String, String>) listElement.get(1);
- assertTrue(innerElement.size() == 1);
- innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("listTestTag"));
- assertTrue(innerEntry.getValue().equals("2 MB"));
-
- innerElement = (Map<String, String>) listElement.get(2);
- assertTrue(innerElement.size() == 1);
- innerEntry = innerElement.entrySet().iterator().next();
- assertTrue(innerEntry.getKey().equals("stringTestTag"));
- assertTrue(innerEntry.getValue().equals("stringVal2"));
- }
-
- public static String loadFileNameToJsonString(String fileName) throws IOException {
- String sourceDir = "src/test/resources/normativeTypes";
- java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName);
- byte[] fileContent = Files.readAllBytes(filePath);
- String content = new String(fileContent);
- return content;
- }
-
- private static Object loadJsonFromFile(String fileName) throws IOException {
- String content = loadFileNameToJsonString(fileName);
- Object load = new Yaml().load(content);
- return load;
- }
+ private <T> Map<String, T> getElements(Map<String, Object> toscaJson, ToscaTagNamesEnum elementType) {
+
+ Either<Map<String, T>, ResultStatusEnum> toscaExpectedElements = ImportUtils.findFirstToscaMapElement(toscaJson, elementType);
+ assertTrue(toscaExpectedElements.isLeft());
+
+ return toscaExpectedElements.left().value();
+
+ }
+
+ private void testCreateFullHeatParameterModule(String type, Object defaultVal) {
+
+ String name = "fullParameter";
+ String description = "description_text";
+
+ Map<String, Object> parametersMap = new HashMap<String, Object>();
+ Map<String, Object> firstParam = createParameterMap(type, defaultVal, name, description);
+ parametersMap.put(ToscaTagNamesEnum.PARAMETERS.getElementName(), firstParam);
+
+ Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParameters(parametersMap, ArtifactTypeEnum.HEAT.getType());
+ assertTrue(heatParameters.isLeft());
+ List<HeatParameterDefinition> parameterDefList = heatParameters.left().value();
+ assertFalse(parameterDefList.isEmpty());
+ HeatParameterDefinition parameterDefinition = parameterDefList.get(0);
+
+ assertParameter(parameterDefinition, name, type, description, defaultVal);
+
+ }
+
+ private Map<String, Object> createParameterMap(String type, Object defaultVal, String name, String description) {
+ Map<String, Object> firstParam = new HashMap<String, Object>();
+ Map<String, Object> valuesMap = new HashMap<String, Object>();
+
+ valuesMap.put(ToscaTagNamesEnum.TYPE.getElementName(), type);
+ valuesMap.put(ToscaTagNamesEnum.DESCRIPTION.getElementName(), description);
+ valuesMap.put(ToscaTagNamesEnum.DEFAULT_VALUE.getElementName(), defaultVal);
+
+ firstParam.put(name, valuesMap);
+ return firstParam;
+ }
+
+ private void assertParameter(HeatParameterDefinition parameterDefinition, String name, String type, String description, Object defaultVal) {
+ assertEquals(name, parameterDefinition.getName());
+ assertEquals(description, parameterDefinition.getDescription());
+ assertEquals(type, parameterDefinition.getType());
+ assertEquals(String.valueOf(defaultVal), parameterDefinition.getDefaultValue());
+ assertEquals(String.valueOf(defaultVal), parameterDefinition.getCurrentValue());
+ }
+
+ private void verifyListElement3(Object element) {
+ List<Object> listElement = (List<Object>) element;
+ assertTrue(listElement.size() == 2);
+
+ Map<String, String> innerElement = (Map<String, String>) listElement.get(0);
+ assertTrue(innerElement.size() == 1);
+ Entry<String, String> innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("testTag1"));
+ assertTrue(innerEntry.getValue().equals("1 MB"));
+
+ innerElement = (Map<String, String>) listElement.get(1);
+ assertTrue(innerElement.size() == 1);
+ innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("type"));
+ assertTrue(innerEntry.getValue().equals("stringVal2"));
+ }
+
+ private void verifyListElement2(Object element) {
+ List<Object> listElement = (List<Object>) element;
+ assertTrue(listElement.size() == 2);
+
+ Map<String, Object> innerElement = (Map<String, Object>) listElement.get(0);
+ assertTrue(innerElement.size() == 1);
+ Entry<String, Object> innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("testTag1"));
+ assertTrue(innerEntry.getValue().equals("1 MB"));
+
+ assertTrue(listElement.get(1) instanceof Map);
+ innerElement = (Map<String, Object>) listElement.get(1);
+ assertTrue(innerElement.size() == 1);
+ innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("listTestTag"));
+ assertTrue(innerEntry.getValue() instanceof List);
+ }
+
+ private void verifyListElement1(Object element) {
+ List<Object> listElement = (List<Object>) element;
+ assertTrue(listElement.size() == 3);
+
+ Map<String, String> innerElement = (Map<String, String>) listElement.get(0);
+ assertTrue(innerElement.size() == 1);
+ Entry<String, String> innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("listTestTag"));
+ assertTrue(innerEntry.getValue().equals("1 MB"));
+
+ innerElement = (Map<String, String>) listElement.get(1);
+ assertTrue(innerElement.size() == 1);
+ innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("listTestTag"));
+ assertTrue(innerEntry.getValue().equals("2 MB"));
+
+ innerElement = (Map<String, String>) listElement.get(2);
+ assertTrue(innerElement.size() == 1);
+ innerEntry = innerElement.entrySet().iterator().next();
+ assertTrue(innerEntry.getKey().equals("stringTestTag"));
+ assertTrue(innerEntry.getValue().equals("stringVal2"));
+ }
+
+ public static String loadFileNameToJsonString(String fileName) throws IOException {
+ String sourceDir = "src/test/resources/normativeTypes";
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir, fileName);
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String content = new String(fileContent);
+ return content;
+ }
+
+ private static Object loadJsonFromFile(String fileName) throws IOException {
+ String content = loadFileNameToJsonString(fileName);
+ Object load = new Yaml().load(content);
+ return load;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java
index ac4d37ef76..068f04aae2 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java
@@ -20,21 +20,14 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -46,7 +39,17 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
public class InputsBusinessLogicTest {
@@ -63,6 +66,9 @@ public class InputsBusinessLogicTest {
@Mock
private ToscaOperationFacade toscaOperationFacadeMock;
+ @Mock
+ private UserValidations userValidations;
+
@InjectMocks
private InputsBusinessLogic testInstance;
@@ -83,13 +89,13 @@ public class InputsBusinessLogicTest {
instanceInputMap.put(COMPONENT_INSTANCE_ID, Collections.singletonList(componentInstanceInput));
instanceInputMap.put("someInputId", Collections.singletonList(new ComponentInstanceInput()));
service.setComponentInstancesInputs(instanceInputMap);
-
- Mockito.when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User()));
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User()));
+ when(userAdminMock.getUser(USER_ID, false)).thenReturn(Either.left(new User()));
}
@Test
public void getComponentInstanceInputs_ComponentInstanceNotExist() throws Exception {
- Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service));
+ when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service));
Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, "nonExisting");
assertTrue(componentInstanceInputs.isRight());
Mockito.verify(componentsUtilsMock).getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
@@ -115,13 +121,13 @@ public class InputsBusinessLogicTest {
@Test
public void getComponentInstanceInputs() throws Exception {
- Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service));
+ when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service));
Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID);
assertEquals("inputId", componentInstanceInputs.left().value().get(0).getInputId());
}
private void getComponents_emptyInputs(Service service) {
- Mockito.when(toscaOperationFacadeMock.getToscaElement(Mockito.eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service));
+ when(toscaOperationFacadeMock.getToscaElement(eq(COMPONENT_ID), Mockito.any(ComponentParametersView.class))).thenReturn(Either.left(service));
Either<List<ComponentInstanceInput>, ResponseFormat> componentInstanceInputs = testInstance.getComponentInstanceInputs(USER_ID, COMPONENT_ID, COMPONENT_INSTANCE_ID);
assertEquals(Collections.emptyList(), componentInstanceInputs.left().value());
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java
index 8109e36be1..e726f608f5 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManagerTest.java
@@ -20,15 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -42,51 +34,54 @@ import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import fj.data.Either;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
-public class InterfaceLifecycleTypeImportManagerTest {
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
- @InjectMocks
- private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager();
- public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class);
- public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
- public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+public class InterfaceLifecycleTypeImportManagerTest {
- static Logger log = Mockito.spy(Logger.class);
+ @InjectMocks
+ private InterfaceLifecycleTypeImportManager importManager = new InterfaceLifecycleTypeImportManager();
+ public static final CommonImportManager commonImportManager = Mockito.mock(CommonImportManager.class);
+ public static final IInterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
+ public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
- @BeforeClass
- public static void beforeClass() throws IOException {
- InterfaceLifecycleTypeImportManager.setLog(log);
- when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() {
- public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]);
- return ans;
- }
+ @BeforeClass
+ public static void beforeClass() throws IOException {
+ when(interfaceLifecycleOperation.createInterfaceType(Mockito.any(InterfaceDefinition.class))).thenAnswer(new Answer<Either<InterfaceDefinition, StorageOperationStatus>>() {
+ public Either<InterfaceDefinition, StorageOperationStatus> answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ Either<InterfaceDefinition, StorageOperationStatus> ans = Either.left((InterfaceDefinition) args[0]);
+ return ans;
+ }
- });
- when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod();
- }
+ });
+ when(commonImportManager.createElementTypesFromYml(Mockito.anyString(), Mockito.any())).thenCallRealMethod();
+ }
- @Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- }
+ @Before
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
- @Test
- public void importLiecycleTest() throws IOException {
- String ymlContent = getYmlContent();
- Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent);
- assertTrue(createCapabilityTypes.isLeft());
+ @Test
+ public void importLiecycleTest() throws IOException {
+ String ymlContent = getYmlContent();
+ Either<List<InterfaceDefinition>, ResponseFormat> createCapabilityTypes = importManager.createLifecycleTypes(ymlContent);
+ assertTrue(createCapabilityTypes.isLeft());
- }
+ }
- private String getYmlContent() throws IOException {
- Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml");
- byte[] fileContent = Files.readAllBytes(filePath);
- String ymlContent = new String(fileContent);
- return ymlContent;
- }
+ private String getYmlContent() throws IOException {
+ Path filePath = Paths.get("src/test/resources/types/interfaceLifecycleTypes.yml");
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String ymlContent = new String(fileContent);
+ return ymlContent;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java
new file mode 100644
index 0000000000..9aca92010e
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogicTest.java
@@ -0,0 +1,493 @@
+package org.openecomp.sdc.be.components.impl;
+
+
+import fj.data.Either;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
+import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.PolicyTargetDTO;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PolicyBusinessLogicTest {
+
+ @InjectMocks
+ private PolicyBusinessLogic businessLogic;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ @Mock
+ private IGraphLockOperation graphLockOperation;
+ @Mock
+ private PolicyTypeOperation policyTypeOperation;
+ @Mock
+ private UserValidations userValidations;
+ @Mock
+ private TitanDao titanDao;
+ @Mock
+ private ApplicationDataTypeCache dataTypeCache;
+ @Mock
+ private PropertyOperation propertyOperation;
+
+ private final static String COMPONENT_ID = "componentId";
+ private final static String COMPONENT_NAME = "componentName";
+ private final static String POLICY_TYPE_NAME = "policyTypeName";
+ private final static String POLICY_ID = "policyId";
+ private final static String INVALID_POLICY_ID = "invalidPolicyId";
+ private final static String POLICY_NAME = "policyName";
+ private final static String OTHER_POLICY_NAME = "otherPolicyName";
+ private final static String USER_ID = "jh0003";
+ private final static String UNIQUE_ID_EXSISTS = "uniqueIdExists";
+ private final static String UNIQUE_ID_DOESNT_EXSISTS = "uniqueIdDoesntExists";
+ private final static String FAKE_TYPE = "fakeType";
+ private final static String COMPONENT_INSTANCE_TYPE = "component_Instances";
+ private final static String GROUP_TYPE = "GROUPS";
+
+
+
+
+ private final String CREATE_POLICY = "create Policy";
+
+ private final static User user = buildUser();
+ private final static PolicyDefinition policy = buildPolicy(POLICY_NAME);
+ private final static PolicyDefinition otherPolicy = buildPolicy(OTHER_POLICY_NAME);
+ private final static Resource resource = buildResource();
+ private final static PolicyTypeDefinition policyType = buildPolicyType();
+
+ private static Either<User, ResponseFormat> userSuccessEither;
+ private static Either<Component, StorageOperationStatus> componentSuccessEither;
+ private static Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeSuccessEither;
+ private static Either<PolicyDefinition, StorageOperationStatus> policySuccessEither;
+ private static ResponseFormat notFoundResponse;
+ private static ResponseFormat invalidContentResponse;
+ private static ResponseFormat nameExistsResponse;
+
+ @BeforeClass
+ public static void setup() {
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir));
+ createResponses();
+ new ConfigurationManager(new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir));
+ }
+
+ private static void createResponses() {
+ userSuccessEither = Either.left(user);
+ componentSuccessEither = Either.left(resource);
+ getPolicyTypeSuccessEither = Either.left(policyType);
+ policySuccessEither = Either.left(policy);
+ notFoundResponse = new ResponseFormat();
+ notFoundResponse.setStatus(404);
+ invalidContentResponse = new ResponseFormat();
+ invalidContentResponse.setStatus(400);
+ nameExistsResponse = new ResponseFormat();
+ nameExistsResponse.setStatus(409);
+ }
+
+ @Test
+ public void createPolicySuccessTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither);
+ when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(policySuccessEither);
+ stubUnlockAndCommit();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
+ assertTrue(response.isLeft());
+ }
+
+ @Test
+ public void createPolicyUserFailureTest(){
+ Either<User, ResponseFormat> userNotFoundResponse = Either.right(new ResponseFormat(404));
+ when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userNotFoundResponse);
+ stubRollback();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
+ assertNotFound(response);
+ }
+
+ private void assertNotFound(Either<PolicyDefinition, ResponseFormat> response) {
+ assertTrue(response.isRight() && response.right().value().getStatus().equals(404));
+ }
+
+ @Test
+ public void createPolicyComponentFailureTest(){
+ when(userValidations.validateUserExists(eq(USER_ID), eq(CREATE_POLICY), eq(false))).thenReturn(userSuccessEither);
+ Either<Component, StorageOperationStatus> componentNotFoundResponse = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND), eq(ComponentTypeEnum.RESOURCE))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse);
+ when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentNotFoundResponse);
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
+ assertNotFound(response);
+ }
+
+ @Test
+ public void createPolicyPolicyTypeFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeFailed = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeFailed);
+ when(componentsUtils.convertFromStorageResponse(eq(getPolicyTypeFailed.right().value()))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND))).thenReturn(notFoundResponse);
+ stubUnlockAndRollback();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
+ assertNotFound(response);
+ }
+
+ @Test
+ public void createPolicyComponentTypeFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ when(policyTypeOperation.getLatestPolicyTypeByType(eq(POLICY_TYPE_NAME))).thenReturn(getPolicyTypeSuccessEither);
+ Either<PolicyDefinition, StorageOperationStatus> addPolicyRes = Either.right(StorageOperationStatus.BAD_REQUEST);
+ when(toscaOperationFacade.associatePolicyToComponent(eq(COMPONENT_ID), any(PolicyDefinition.class), eq(0))).thenReturn(addPolicyRes);
+ when(componentsUtils.convertFromStorageResponse(eq(addPolicyRes.right().value()))).thenReturn(ActionStatus.INVALID_CONTENT);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_CONTENT))).thenReturn(invalidContentResponse);
+ stubUnlockAndRollback();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.createPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_TYPE_NAME, USER_ID, true);
+ assertTrue(response.isRight() && response.right().value().getStatus().equals(400));
+ }
+
+ @Test
+ public void updatePolicySuccessTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither);
+ stubUnlockAndCommit();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, otherPolicy, USER_ID, true);
+ assertTrue(response.isLeft());
+ }
+
+ @Test
+ public void updatePolicyNameFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NAME_ALREADY_EXIST), eq(POLICY_NAME))).thenReturn(nameExistsResponse);
+ stubUnlockAndRollback();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.updatePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, policy, USER_ID, true);
+ assertTrue(response.isRight() && response.right().value().getStatus().equals(409));
+ }
+
+ @Test
+ public void getPolicySuccessTest(){
+ stubValidationSuccess(CREATE_POLICY);
+ stubCommit();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID);
+ assertTrue(response.isLeft());
+ }
+
+ @Test
+ public void getPolicyFailureTest(){
+ stubValidationSuccess(CREATE_POLICY);
+ stubRollback();
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), eq(INVALID_POLICY_ID), eq(COMPONENT_ID))).thenReturn(notFoundResponse);
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.getPolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID);
+ assertTrue(response.isRight() && response.right().value().getStatus().equals(404));
+ }
+
+ @Test
+ public void deletePolicySuccessTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ stubCommit();
+ when(toscaOperationFacade.removePolicyFromComponent(eq(COMPONENT_ID),eq(POLICY_ID))).thenReturn(StorageOperationStatus.OK);
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, USER_ID, true);
+ assertTrue(response.isLeft());
+ }
+
+ @Test
+ public void deletePolicyFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ stubCommit();
+ stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER();
+ Either<PolicyDefinition, ResponseFormat> response = businessLogic.deletePolicy(ComponentTypeEnum.RESOURCE, COMPONENT_ID, INVALID_POLICY_ID, USER_ID, true);
+ assertNotFound(response);
+ }
+
+ private void stubComponentUtilsGetResponsePOLICY_NOT_FOUND_ON_CONTAINER() {
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER), anyString(), anyString())).thenReturn(new ResponseFormat(404));
+ }
+
+ @Test
+ public void updatePolicyPropertiesSuccessTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>()));
+ String prop1 = "Name";
+ String prop2 = "Type";
+ when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop1), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop1));
+ when(propertyOperation.validateAndUpdatePropertyValue(eq(null), eq(prop2), anyBoolean(), eq(null), anyMap())).thenReturn(Either.left(prop2));
+ when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), any(PolicyDefinition.class))).thenReturn(policySuccessEither);
+ stubUnlockAndCommit();
+ PropertyDataDefinition[] properties = getProperties(prop1, prop2);
+ policy.setProperties(Arrays.asList(properties));
+ Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, properties , USER_ID, true);
+ assertTrue(response.isLeft());
+ }
+
+ @Test
+ public void updatePolicyTargetsSuccessTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ stubGetToscaFullElementSuccess();
+ stubUpdatePolicyOfComponentSuccess();
+ stubGetToscaElementSuccess();
+ stubGetTargetType();
+
+ Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargets(), USER_ID);
+
+ Assert.assertTrue(result.isLeft());
+ PolicyDefinition policyResult = result.left().value();
+ Map<PolicyTargetType, List<String>> targets = getTargets();
+ assertThat(policyResult.getTargets().values()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(targets.get(PolicyTargetType.GROUPS), targets.get(PolicyTargetType.COMPONENT_INSTANCES));
+
+ }
+
+ private void stubGetTargetType() {
+ }
+
+ @Test
+ public void updatePolicyTargetsTargetIDFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ stubGetToscaFullElementSuccess();
+ stubGetToscaElementSuccess();
+ stubUpdatePolicyOfComponentSuccess();
+ stubComponentUtilsGetResponseTargetNotFound();
+ stubRollback();
+
+ Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeId(), USER_ID);
+
+ Assert.assertTrue(result.isRight());
+ ResponseFormat responseResult = result.right().value();
+ Assert.assertEquals(responseResult.getStatus().longValue(), 400L);
+
+ }
+
+ private void stubComponentUtilsGetResponseTargetNotFound() {
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST), (anyString()))).thenReturn(new ResponseFormat(400));
+ }
+
+ @Test
+ public void updatePolicyTargetsTypeFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ stubGetToscaFullElementSuccess();
+ stubGetToscaElementSuccess();
+ stubUpdatePolicyOfComponentSuccess();
+ stubComponentUtilsGetResponseTargetNotFound();
+ stubRollback();
+
+ Either<PolicyDefinition, ResponseFormat> result = businessLogic.updatePolicyTargets(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getTargetListFakeType(), USER_ID);
+
+ Assert.assertTrue(result.isRight());
+ ResponseFormat responseResult = result.right().value();
+ Assert.assertTrue(responseResult.getStatus().equals(400));
+
+ }
+
+ private void stubUpdatePolicyOfComponentSuccess() {
+ when(toscaOperationFacade.updatePolicyOfComponent(eq(COMPONENT_ID), eq(policy))).thenReturn(policySuccessEither);
+ }
+
+
+ @Test
+ public void updatePolicyPropertiesFailureTest(){
+ stubValidateAndLockSuccess(CREATE_POLICY);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.PROPERTY_NOT_FOUND))).thenReturn(notFoundResponse);
+ stubUnlockAndRollback();
+ policy.setProperties(null);
+ Either<List<PropertyDataDefinition>, ResponseFormat> response = businessLogic.updatePolicyProperties(ComponentTypeEnum.RESOURCE, COMPONENT_ID, POLICY_ID, getProperties("Name", "Type") , USER_ID, true);
+ assertTrue(response.isRight() && response.right().value().getStatus().equals(404));
+ }
+
+ private PropertyDataDefinition[] getProperties(String prop1, String prop2) {
+ PropertyDataDefinition property1 = new PropertyDataDefinition();
+ property1.setName(prop1);
+ property1.setValue(prop1);
+ PropertyDataDefinition property2 = new PropertyDataDefinition();
+ property2.setName(prop2);
+ property2.setValue(prop2);
+ PropertyDataDefinition[] properties = {property1, property2};
+ return properties;
+ }
+
+
+ private void stubUnlockAndRollback() {
+ when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
+ stubRollback();
+ }
+
+ private void stubCommit() {
+ when(titanDao.commit()).thenReturn(TitanOperationStatus.OK);
+ }
+
+ private void stubRollback() {
+ when(titanDao.rollback()).thenReturn(TitanOperationStatus.OK);
+ }
+
+ private void stubUnlockAndCommit() {
+ when(graphLockOperation.unlockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
+ stubCommit();
+ }
+
+ private void stubValidateAndLockSuccess(String methodName) {
+ stubValidationSuccess(methodName);
+ when(graphLockOperation.lockComponent(eq(COMPONENT_ID), any(NodeTypeEnum.class))).thenReturn(StorageOperationStatus.OK);
+ }
+
+ private void stubValidationSuccess(String methodName) {
+ when(userValidations.validateUserExists(eq(USER_ID), eq(methodName), eq(false))).thenReturn(userSuccessEither);
+ when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID), any(ComponentParametersView.class))).thenReturn(componentSuccessEither);
+ }
+
+ private void stubGetToscaFullElementSuccess() {
+ when(toscaOperationFacade.getToscaFullElement(eq(COMPONENT_ID))).thenReturn(buildElementEither());
+ }
+
+ private void stubGetToscaElementSuccess() {
+ when(toscaOperationFacade.getToscaElement(eq(COMPONENT_ID))).thenReturn(componentSuccessEither);
+ }
+
+ private Either<Component, StorageOperationStatus> buildElementEither() {
+ ResourceBuilder builder = new ResourceBuilder();
+ GroupDefinition groupDefinition = GroupDefinitionBuilder.create().setUniqueId(UNIQUE_ID_EXSISTS).build();
+ ComponentInstanceBuilder componentInstanceBuilder = new ComponentInstanceBuilder();
+ ComponentInstance componentInstance = componentInstanceBuilder.setUniqueId(UNIQUE_ID_EXSISTS).build();
+ return Either.left(builder.addGroups(groupDefinition).addComponentInstance(componentInstance).build());
+ }
+
+ private Map<PolicyTargetType, List<String>> getTargets() {
+ Map<PolicyTargetType, List<String>> targets = new HashMap<>();
+ targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_EXSISTS));
+ targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_EXSISTS));
+ return targets;
+ }
+
+
+
+ private static PolicyTypeDefinition buildPolicyType() {
+ PolicyTypeDefinition policyType = new PolicyTypeDefinition();
+ policyType.setType(POLICY_TYPE_NAME);
+ return policyType;
+ }
+
+ private static PolicyDefinition buildPolicy(String policyName) {
+ PolicyDefinition policy = new PolicyDefinition();
+ policy.setUniqueId(POLICY_ID);
+ policy.setPolicyTypeName(POLICY_TYPE_NAME);
+ policy.setComponentName(COMPONENT_NAME);
+ policy.setName(policyName);
+ return policy;
+ }
+
+ private static Resource buildResource() {
+ Resource resource = new Resource();
+ resource.setUniqueId(COMPONENT_ID);
+ resource.setName(COMPONENT_NAME);
+ resource.setCreatorUserId(USER_ID);
+ resource.setLastUpdaterUserId(USER_ID);
+ resource.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ resource.setIsDeleted(false);
+ resource.setResourceType(ResourceTypeEnum.VF);
+ resource.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue());
+ Map<String, PolicyDefinition> policies = new HashMap<>();
+ policies.put(POLICY_ID, policy);
+ resource.setPolicies(policies);
+ return resource;
+ }
+
+ private static User buildUser() {
+ User user = new User();
+ user.setUserId(USER_ID);
+ return user;
+ }
+ private List<PolicyTargetDTO> getTargetDTOList() {
+ PolicyTargetDTO target1 = new PolicyTargetDTO();
+ target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS));
+ target1.setType("GROUPS");
+
+ PolicyTargetDTO target2 = new PolicyTargetDTO();
+ target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS));
+ target2.setType("componentInstances");
+
+ return Arrays.asList(target1, target2);
+ }
+
+ private List<PolicyTargetDTO> getFakeIDTargetDTOList() {
+ PolicyTargetDTO target1 = new PolicyTargetDTO();
+ target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS));
+ target1.setType(GROUP_TYPE);
+
+ PolicyTargetDTO target2 = new PolicyTargetDTO();
+ target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS));
+ target2.setType(COMPONENT_INSTANCE_TYPE);
+
+ return Arrays.asList(target1, target2);
+ }
+ private List<PolicyTargetDTO> getFakeTypeTargetDTOList() {
+ PolicyTargetDTO target1 = new PolicyTargetDTO();
+ target1.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS));
+ target1.setType(FAKE_TYPE);
+
+ PolicyTargetDTO target2 = new PolicyTargetDTO();
+ target2.setUniqueIds(Collections.singletonList(UNIQUE_ID_EXSISTS));
+ target2.setType(FAKE_TYPE);
+
+ return Arrays.asList(target1, target2);
+ }
+
+ private Map<PolicyTargetType, List<String>> getTargetListFakeType() {
+ Map<PolicyTargetType, List<String>> targets = new HashMap<>();
+ targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS));
+ targets.put(PolicyTargetType.TYPE_DOES_NOT_EXIST, Collections.singletonList(UNIQUE_ID_EXSISTS));
+ return targets;
+ }
+
+ private Map<PolicyTargetType, List<String>> getTargetListFakeId() {
+ Map<PolicyTargetType, List<String>> targets = new HashMap<>();
+ targets.put(PolicyTargetType.COMPONENT_INSTANCES, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS));
+ targets.put(PolicyTargetType.GROUPS, Collections.singletonList(UNIQUE_ID_DOESNT_EXSISTS));
+ return targets;
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java
new file mode 100644
index 0000000000..ad3e6e8974
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyPropertiesBusinessLogicTest.java
@@ -0,0 +1,148 @@
+package org.openecomp.sdc.be.components.impl;
+
+import fj.data.Either;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import javax.ws.rs.core.Response;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PolicyPropertiesBusinessLogicTest {
+
+ private static final String POLICY_ID = "policy1";
+ private static final String RESOURCE_ID = "resourceId";
+ private static final String USER_ID = "userId";
+ public static final String NO_PROPS_POLICY = "policy2";
+ @InjectMocks
+ private PolicyBusinessLogic testInstance;
+
+ @Mock
+ private UserValidations userValidations;
+
+ @Mock
+ private TitanDao titanDao;
+
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Mock
+ private ComponentsUtils componentsUtils;
+
+ private ComponentParametersView componentFilter;
+ private Resource resource;
+ private PropertyDefinition prop1, prop2;
+
+ @Before
+ public void setUp() throws Exception {
+ componentFilter = new ComponentParametersView(true);
+ componentFilter.setIgnorePolicies(false);
+ componentFilter.setIgnoreUsers(false);
+
+ prop1 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build();
+ prop2 = new PropertyDataDefinitionBuilder().setUniqueId("prop1").build();
+
+ PolicyDefinition policy1 = PolicyDefinitionBuilder.create()
+ .setUniqueId(POLICY_ID)
+ .setProperties(prop1, prop2)
+ .build();
+
+ PolicyDefinition policy2 = PolicyDefinitionBuilder.create()
+ .setUniqueId(NO_PROPS_POLICY)
+ .build();
+ resource = new ResourceBuilder()
+ .setUniqueId(RESOURCE_ID)
+ .setLifeCycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)
+ .setLastUpdaterUserId(USER_ID)
+ .addPolicy(policy1)
+ .addPolicy(policy2)
+ .build();
+ }
+
+ @After
+ public void tearDown() {
+ verify(titanDao).commit();
+ }
+
+ @Test
+ public void getPolicyProperties_userIdIsNull() {
+ String userId = null;
+ ResponseFormat forbiddenResponse = new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode());
+ when(userValidations.validateUserExists(eq(userId), anyString(), eq(false))).thenReturn(Either.right(forbiddenResponse));
+ Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, null);
+ assertThat(policyProperties.right().value()).isSameAs(forbiddenResponse);
+ }
+
+ @Test
+ public void getPolicyProperties_componentNotFound() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User()));
+ ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class);
+ when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod();
+ ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode());
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), anyString())).thenReturn(notFoundResponse);
+ Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID);
+ assertThat(policyProperties.right().value()).isSameAs(notFoundResponse);
+ }
+
+ @Test
+ public void getPolicyProperties_policyNotExist() {
+ doPolicyValidations();
+ ResponseFormat notFoundResponse = new ResponseFormat(Response.Status.NOT_FOUND.getStatusCode());
+ when(componentsUtils.getResponseFormat(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, "nonExistingPolicy", RESOURCE_ID)).thenReturn(notFoundResponse);
+ Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, "nonExistingPolicy", USER_ID);
+ assertThat(policyProperties.right().value()).isEqualTo(notFoundResponse);
+ }
+
+ @Test
+ public void getPolicyProperties_noPropertiesOnPolicy() {
+ doPolicyValidations();
+ Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, NO_PROPS_POLICY, USER_ID);
+ assertThat(policyProperties.left().value()).isNull();
+ }
+
+ @Test
+ public void getPolicyProperties() {
+ doPolicyValidations();
+ Either<List<PropertyDataDefinition>, ResponseFormat> policyProperties = testInstance.getPolicyProperties(ComponentTypeEnum.RESOURCE, RESOURCE_ID, POLICY_ID, USER_ID);
+ assertThat(policyProperties.left().value())
+ .usingElementComparatorOnFields("uniqueId")
+ .containsExactly(prop1, prop2);
+ }
+
+ private void doPolicyValidations() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(new User()));
+ ArgumentCaptor<ComponentParametersView> filterCaptor = ArgumentCaptor.forClass(ComponentParametersView.class);
+ when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID), filterCaptor.capture())).thenReturn(Either.left(resource));
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java
new file mode 100644
index 0000000000..7dc12d96e6
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogicTest.java
@@ -0,0 +1,110 @@
+package org.openecomp.sdc.be.components.impl;
+
+import com.google.common.collect.ImmutableMap;
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.DummyConfigurationManager;
+import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+import static com.google.common.collect.Sets.newHashSet;
+import static java.util.Collections.emptyList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PolicyTypeBusinessLogicTest {
+
+ private static final String USER_ID = "userId";
+ private static final Set<String> EXCLUDED_POLICY_TYPES = newHashSet("type1", "type2");
+ private static final String COMPONENT_TYPE = "VF";
+
+ @InjectMocks
+ private PolicyTypeBusinessLogic testInstance;
+ @Mock
+ private TitanDao titanDao;
+ @Mock
+ private PolicyTypeOperation policyTypeOperation;
+ @Mock
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private UserValidations userValidations;
+
+ @Before
+ public void setUp() throws Exception {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.left(new User()));
+ when(componentsUtils.convertToResponseFormatOrNotFoundErrorToEmptyList(any(StorageOperationStatus.class))).thenCallRealMethod();
+ when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenReturn(ImmutableMap.of(COMPONENT_TYPE, EXCLUDED_POLICY_TYPES));
+ }
+
+ @BeforeClass
+ public static void beforeClass() {
+ new DummyConfigurationManager();
+ }
+
+ @Test
+ public void getAllPolicyTypes_userNotExist() {
+ ResponseFormat userNotExistResponse = new ResponseFormat();
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(true))).thenReturn(Either.right(userNotExistResponse));
+ Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes.right().value()).isSameAs(userNotExistResponse);
+ }
+
+ @Test
+ public void getAllPolicyTypes_whenExcludePolicyTypesSetIsNull_passNullExcludedTypesSet() {
+ when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()).thenCallRealMethod();
+ when(policyTypeOperation.getAllPolicyTypes(null)).thenReturn(Either.left(emptyList()));
+ Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes.left().value()).isEmpty();
+ }
+
+ @Test
+ public void getAllPolicyTypes() {
+ List<PolicyTypeDefinition> policyTypes = Arrays.asList(new PolicyTypeBuilder().setUniqueId("id1").build(),
+ new PolicyTypeBuilder().setUniqueId("id2").build(),
+ new PolicyTypeBuilder().setUniqueId("id3").build());
+ when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.left(policyTypes));
+ Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes.left().value()).isSameAs(policyTypes);
+ }
+
+ @Test
+ public void getAllPolicyTypes_noPolicyTypes() {
+ when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes.left().value()).isEmpty();
+ verify(titanDao).commit();
+ }
+
+ @Test
+ public void getAllPolicyTypes_err() {
+ when(policyTypeOperation.getAllPolicyTypes(EXCLUDED_POLICY_TYPES)).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
+ ResponseFormat errResponse = new ResponseFormat();
+ when(componentsUtils.getResponseFormat(StorageOperationStatus.GENERAL_ERROR)).thenReturn(errResponse);
+ Either<List<PolicyTypeDefinition>, ResponseFormat> allPolicyTypes = testInstance.getAllPolicyTypes(USER_ID, COMPONENT_TYPE);
+ assertThat(allPolicyTypes.right().value()).isSameAs(errResponse);
+ verify(titanDao).commit();
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
index f7724aaeff..8054baf15f 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
@@ -20,22 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.Ignore;
@@ -44,13 +29,13 @@ import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.ElementOperationMock;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
import org.openecomp.sdc.be.auditing.impl.AuditingLogFormatUtil;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
+import org.openecomp.sdc.be.components.validation.UserValidations;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
@@ -98,1635 +83,1738 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
public class ResourceBusinessLogicTest {
- private static Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class.getName());
- public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router";
- public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
- public static final String RESOURCE_SUBCATEGORY = "Router";
+ private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogicTest.class);
+ public static final String RESOURCE_CATEGORY = "Network Layer 2-3/Router";
+ public static final String RESOURCE_CATEGORY1 = "Network Layer 2-3";
+ public static final String RESOURCE_SUBCATEGORY = "Router";
- public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway";
- public static final String UPDATED_SUBCATEGORY = "Gateway";
+ public static final String UPDATED_CATEGORY = "Network Layer 2-3/Gateway";
+ public static final String UPDATED_SUBCATEGORY = "Gateway";
- public static final String RESOURCE_NAME = "My-Resource_Name with space";
+ public static final String RESOURCE_NAME = "My-Resource_Name with space";
private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
+ private static final String GENERIC_CR_NAME = "org.openecomp.resource.abstract.nodes.CR";
private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC";
private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
-
- final ServletContext servletContext = Mockito.mock(ServletContext.class);
- IAuditingManager iAuditingManager = null;
- IElementOperation mockElementDao;
- TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
- UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
- ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
- NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
- NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
- TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
- final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
- final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
- final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class);
- final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
- WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
- AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class);
- @InjectMocks
- ResourceBusinessLogic bl = new ResourceBusinessLogic();
- ResponseFormatManager responseManager = null;
- AuditingManager auditingManager = Mockito.mock(AuditingManager.class);
- GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
- User user = null;
- Resource resourceResponse = null;
- Resource genericVF = null;
- Resource genericVFC = null;
- Resource genericPNF = null;
- ComponentsUtils componentsUtils = new ComponentsUtils();
- ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic();
- CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
- Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
- private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
- CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
-
-
- public ResourceBusinessLogicTest() {
-
- }
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- Mockito.reset(propertyOperation);
-
- ExternalConfiguration.setAppName("catalog-be");
-
- // Init Configuration
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
- // Elements
- mockElementDao = new ElementOperationMock();
-
- // User data and management
- user = new User();
- user.setUserId("jh0003");
- user.setFirstName("Jimmi");
- user.setLastName("Hendrix");
- user.setRole(Role.ADMIN.name());
-
- Either<User, ActionStatus> eitherGetUser = Either.left(user);
- when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
-
- // Servlet Context attributes
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
- when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
-
- Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
- Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
- when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse);
-
- Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
- when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
-
- Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
- when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
- when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
- when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
-
- Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
- when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
-
- Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
- when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
- when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
- when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
-
- // createResource
- resourceResponse = createResourceObject(true);
- Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
- Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null);
- when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate);
- when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate);
- Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
- when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
-
- // BL object
- artifactManager.nodeTemplateOperation = nodeTemplateOperation;
- bl = new ResourceBusinessLogic();
- bl.setElementDao(mockElementDao);
- bl.setUserAdmin(mockUserAdmin);
- bl.setCapabilityTypeOperation(capabilityTypeOperation);
- componentsUtils.Init();
- componentsUtils.setAuditingManager(auditingManager);
- bl.setComponentsUtils(componentsUtils);
- bl.setLifecycleManager(lifecycleBl);
- bl.setGraphLockOperation(graphLockOperation);
- bl.setArtifactsManager(artifactManager);
- bl.setPropertyOperation(propertyOperation);
- bl.setTitanGenericDao(mockTitanDao);
- bl.setApplicationDataTypeCache(applicationDataTypeCache);
- bl.setCsarOperation(csarOperation);
- bl.setCacheManagerOperation(cacheManager);
- bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
- toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
- toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
- bl.setToscaOperationFacade(toscaOperationFacade);
- Resource resourceCsar = createResourceObjectCsar(true);
- setCanWorkOnResource(resourceCsar);
- Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
- when(toscaOperationFacade.getToscaElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
- responseManager = ResponseFormatManager.getInstance();
-
- }
-
- private Resource createResourceObject(boolean afterCreate) {
- Resource resource = new Resource();
- resource.setName(RESOURCE_NAME);
- resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<String>();
- tgs.add("test");
- tgs.add(resource.getName());
- resource.setTags(tgs);
- List<String> template = new ArrayList<String>();
- template.add("Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setContactId("ya5467");
- resource.setIcon("MyIcon");
-
- if (afterCreate) {
- resource.setName(resource.getName());
- resource.setVersion("0.1");
- resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion());
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
- return resource;
- }
-
- private Resource createResourceObjectCsar(boolean afterCreate) {
- Resource resource = new Resource();
- resource.setName(RESOURCE_NAME);
- resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<String>();
- tgs.add("test");
- tgs.add(resource.getName());
- resource.setTags(tgs);
- List<String> template = new ArrayList<String>();
- template.add("Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setResourceVendorModelNumber("");
- resource.setContactId("ya5467");
- resource.setIcon("MyIcon");
- resource.setCsarUUID("valid_vf.csar");
- resource.setCsarVersion("1");
-
- if (afterCreate) {
- resource.setName(resource.getName());
- resource.setVersion("0.1");
-
- resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion());
- resource.setCreatorUserId(user.getUserId());
- resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
- return resource;
- }
-
- private Resource setCanWorkOnResource(Resource resource) {
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- resource.setLastUpdaterUserId(user.getUserId());
- return resource;
- }
-
- @Test
- public void testHappyScenario() {
- Resource resource = createResourceObject(false);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
-
- if (createResponse.isRight()) {
- assertEquals(new Integer(200), createResponse.right().value().getStatus());
- }
- assertEquals(createResourceObject(true), createResponse.left().value());
- }
-
- @Test
- public void testUpdateHappyScenario() {
- Resource resource = createResourceObjectCsar(true);
- setCanWorkOnResource(resource);
-
- Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
- when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
- Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
- when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
-
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
- if (updateResponse.isRight()) {
- assertEquals(new Integer(200), updateResponse.right().value().getStatus());
- }
- assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId());
- }
-
- /* CREATE validations - start ***********************/
- // Resource name - start
-
- @Test
- public void testFailedResourceValidations() {
- testResourceNameExist();
- testResourceNameEmpty();
- // testResourceNameExceedsLimit();
- testResourceNameWrongFormat();
- testResourceDescExceedsLimitCreate();
- testResourceDescNotEnglish();
- testResourceDescriptionEmpty();
- testResourceDescriptionMissing();
- testResourceIconMissing();
- testResourceIconInvalid();
- testResourceIconExceedsLimit();
- testResourceTagNotExist();
- testResourceTagEmpty();
- testTagsExceedsLimitCreate();
- testTagsNoServiceName();
- testInvalidTag();
-
- testContactIdTooLong();
- testContactIdWrongFormatCreate();
- testResourceContactIdEmpty();
- testResourceContactIdMissing();
- testVendorNameExceedsLimit();
- testVendorNameWrongFormatCreate();
- testVendorReleaseWrongFormat();
- testVendorReleaseExceedsLimitCreate();
- testResourceVendorModelNumberExceedsLimit();
- testResourceVendorNameMissing();
- testResourceVendorReleaseMissing();
- testResourceCategoryExist();
- testResourceBadCategoryCreate();
- testHappyScenarioCostLicenseType();
- testCostWrongFormatCreate();
- testLicenseTypeWrongFormatCreate();
- testResourceTemplateNotExist();
- testResourceTemplateEmpty();
- testResourceTemplateInvalid();
- }
-
- private void testResourceNameExist() {
- String resourceName = "alreadyExists";
- Resource resourceExist = createResourceObject(false);
- resourceExist.setName(resourceName);
- resourceExist.getTags().add(resourceName);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
- }
-
- private void testResourceNameEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setName(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceNameExceedsLimit() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- // 51 chars, the limit is 50
- String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
- resourceExccedsNameLimit.setName(tooLongResourceName);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
- }
-
- private void testResourceNameWrongFormat() {
- Resource resource = createResourceObject(false);
- // contains :
- String nameWrongFormat = "ljg?fd";
- resource.setName(nameWrongFormat);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- // Resource name - end
- // Resource description - start
- private void testResourceDescExceedsLimitCreate() {
- Resource resourceExccedsDescLimit = createResourceObject(false);
- // 1025 chars, the limit is 1024
- String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
- + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
- + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
- + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
- + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
- + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
- + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
- + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
-
- resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
- }
-
- private void testResourceDescNotEnglish() {
- Resource notEnglish = createResourceObject(false);
- // Not english
- String notEnglishDesc = "\uC2B5";
- notEnglish.setDescription(notEnglishDesc);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceDescriptionEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setDescription("");
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceDescriptionMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setDescription(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
- }
- // Resource description - end
- // Resource icon start
-
- private void testResourceIconMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setIcon(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceIconInvalid() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setIcon("kjk3453^&");
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceIconExceedsLimit() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
- }
-
- // Resource icon end
- // Resource tags - start
- private void testResourceTagNotExist() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setTags(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
- }
-
- private void testResourceTagEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setTags(new ArrayList<String>());
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
- }
-
- private void testTagsExceedsLimitCreate() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
- String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
- String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
- String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
- String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
- String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
- String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
- String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
- String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
- String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
- String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
- String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
- String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
- String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
- String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
- String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
- String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
-
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- tagsList.add(tag2);
- tagsList.add(tag3);
- tagsList.add(tag4);
- tagsList.add(tag5);
- tagsList.add(tag6);
- tagsList.add(tag7);
- tagsList.add(tag8);
- tagsList.add(tag9);
- tagsList.add(tag10);
- tagsList.add(tag11);
- tagsList.add(tag12);
- tagsList.add(tag13);
- tagsList.add(tag14);
- tagsList.add(tag15);
- tagsList.add(tag16);
- tagsList.add(tag17);
- tagsList.add(tag18);
- tagsList.add(tag19);
- tagsList.add(tag20);
- tagsList.add(tag21);
- tagsList.add(resourceExccedsNameLimit.getName());
-
- resourceExccedsNameLimit.setTags(tagsList);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
-
- }
-
- private void testTagsSingleExceedsLimit() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
- String tag2 = resourceExccedsNameLimit.getName();
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- tagsList.add(tag2);
-
- resourceExccedsNameLimit.setTags(tagsList);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
-
- }
-
- private void testTagsNoServiceName() {
- Resource serviceExccedsNameLimit = createResourceObject(false);
- String tag1 = "afzs2qLBb";
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- serviceExccedsNameLimit.setTags(tagsList);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
-
- }
-
- private void testInvalidTag() {
- Resource serviceExccedsNameLimit = createResourceObject(false);
- String tag1 = "afzs2qLBb%#%";
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- serviceExccedsNameLimit.setTags(tagsList);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[] { "Resource", "tag" });
-
- }
-
- // Resource tags - stop
- // Resource contact start
-
- private void testContactIdTooLong() {
- Resource resourceContactId = createResourceObject(false);
- // 59 chars instead of 50
- String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
- resourceContactId.setContactId(contactIdTooLong);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testContactIdWrongFormatCreate() {
- Resource resourceContactId = createResourceObject(false);
- // 3 letters and 3 digits and special characters
- String contactIdFormatWrong = "yrt134!!!";
- resourceContactId.setContactId(contactIdFormatWrong);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceContactIdEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setContactId("");
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceContactIdMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setContactId(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testVendorNameExceedsLimit() {
- Resource resourceExccedsVendorNameLimit = createResourceObject(false);
- String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
- resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
- }
-
- private void testResourceVendorModelNumberExceedsLimit() {
- Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
- String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
- resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
- }
-
- private void testVendorNameWrongFormatCreate() {
- Resource resource = createResourceObject(false);
- // contains *
- String nameWrongFormat = "ljg*fd";
- resource.setVendorName(nameWrongFormat);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME);
- }
-
- private void testVendorReleaseWrongFormat() {
- Resource resource = createResourceObject(false);
- // contains >
- String nameWrongFormat = "1>2";
- resource.setVendorRelease(nameWrongFormat);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE);
-
- }
-
- private void testVendorReleaseExceedsLimitCreate() {
- Resource resourceExccedsNameLimit = createResourceObject(false);
- String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
- resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- }
-
- private void testResourceVendorNameMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setVendorName(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME);
- }
-
- private void testResourceVendorReleaseMissing() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setVendorRelease(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE);
- }
-
- // Resource vendor name/release stop
- // Category start
- private void testResourceCategoryExist() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setCategories(null);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- private void testResourceBadCategoryCreate() {
-
- Resource resourceExist = createResourceObject(false);
- resourceExist.setCategories(null);
- resourceExist.addCategory("koko", "koko");
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- // Category stop
- // Cost start
- private void testHappyScenarioCostLicenseType() {
- Resource createResourceObject = createResourceObject(false);
- Resource createResourceObjectAfterCreate = createResourceObject(true);
- // Adding cost and licenseType to basic mock
- Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
- when(toscaOperationFacade.createToscaComponent(Mockito.any(Resource.class))).thenReturn(eitherCreate);
-
- String cost = "123.456";
- String licenseType = "User";
- createResourceObject.setCost(cost);
- createResourceObject.setLicenseType(licenseType);
- Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
-
- if (createResponse.isRight()) {
- assertEquals(new Integer(200), createResponse.right().value().getStatus());
- }
- createResourceObjectAfterCreate.setCost(cost);
- createResourceObjectAfterCreate.setLicenseType(licenseType);
- assertEquals(createResourceObjectAfterCreate, createResponse.left().value());
- }
-
- private void testCostWrongFormatCreate() {
- Resource resourceCost = createResourceObject(false);
- // Comma instead of fullstop
- String cost = "12356,464";
- resourceCost.setCost(cost);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_CONTENT);
- }
-
- // Cost stop
- // License type start
- private void testLicenseTypeWrongFormatCreate() {
- Resource resourceLicenseType = createResourceObject(false);
- // lowcase
- String licenseType = "cpu";
- resourceLicenseType.setLicenseType(licenseType);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_CONTENT);
- }
-
- // License type stop
- // Derived from start
- private void testResourceTemplateNotExist() {
- Resource resourceExist = createResourceObject(false);
- List<String> list = null;
- resourceExist.setDerivedFrom(list);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
-
- private void testResourceTemplateEmpty() {
- Resource resourceExist = createResourceObject(false);
- resourceExist.setDerivedFrom(new ArrayList<String>());
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
-
- private void testResourceTemplateInvalid() {
- Resource resourceExist = createResourceObject(false);
- ArrayList<String> derivedFrom = new ArrayList<String>();
- derivedFrom.add("kuku");
- resourceExist.setDerivedFrom(derivedFrom);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- }
- // Derived from stop
-
- private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
- ResponseFormat actualResponse = createResponse.right().value();
- assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
- assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
- }
-
- // UPDATE tests - start
- // Resource name
- @Test
- public void testResourceNameWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- // contains *
- String nameWrongFormat = "ljg*fd";
- updatedResource.setName(nameWrongFormat);
-
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
-
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
-
- }
-
- @Test
- public void testResourceNameAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String name = "ljg";
- updatedResource.setName(name);
- resource.setVersion("1.0");
-
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
-
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
-
- }
-
- @Ignore
- public void testResourceNameExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // 51 chars, the limit is 50
- String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
- updatedResource.setName(tooLongResourceName);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
-
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
- }
-
- @Test
- public void testResourceNameAlreadyExist_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceName = "alreadyExists";
- updatedResource.setName(resourceName);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
- when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
- }
-
- //
-
- @Test
- public void testResourceDescExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // 1025 chars, the limit is 1024
- String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
- + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
- + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
- + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
- + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
- + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
- + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
- + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
- updatedResource.setDescription(tooLongResourceDesc);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
-
- }
-
- @Test
- public void testIconWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains .
- String icon = "icon.jpg";
- updatedResource.setIcon(icon);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
-
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
-
- }
-
- @Test
- public void testIconAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains
- String icon = "icon";
- updatedResource.setIcon(icon);
-
- resource.setVersion("1.0");
- ;
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
-
- }
-
- @Test
- public void testTagsExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
- String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
- String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
- String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
- String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
- String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
- String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
- String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
- String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
- String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
- String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
- String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
- String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
- String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
- String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
- String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
- String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
- String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
- String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
-
- List<String> tagsList = new ArrayList<String>();
- tagsList.add(tag1);
- tagsList.add(tag2);
- tagsList.add(tag3);
- tagsList.add(tag4);
- tagsList.add(tag5);
- tagsList.add(tag6);
- tagsList.add(tag7);
- tagsList.add(tag8);
- tagsList.add(tag9);
- tagsList.add(tag10);
- tagsList.add(tag11);
- tagsList.add(tag12);
- tagsList.add(tag13);
- tagsList.add(tag14);
- tagsList.add(tag15);
- tagsList.add(tag16);
- tagsList.add(tag17);
- tagsList.add(tag18);
- tagsList.add(tag19);
- tagsList.add(tag20);
- tagsList.add(tag21);
- tagsList.add(resource.getName());
-
- updatedResource.setTags(tagsList);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
- }
-
- @Test
- public void testVendorNameWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains *
- String nameWrongFormat = "ljg*fd";
- updatedResource.setVendorName(nameWrongFormat);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME);
-
- }
-
- @Test
- public void testVendorNameAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- // contains *
- String nameWrongFormat = "ljg*fd";
- updatedResource.setVendorName(nameWrongFormat);
- resource.setVersion("1.0");
- ;
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED);
-
- }
-
- @Test
- public void testVendorReleaseExceedsLimit_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- // 129 chars, the limit is 128
- String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
- updatedResource.setVendorRelease(tooLongVendorRelease);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
- assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
- }
-
- @Ignore
- public void testContactIdWrongFormat_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceId = resource.getUniqueId();
- // 3 letters and 3 digits
- String contactIdTooLong = "yrt134";
- updatedResource.setContactId(contactIdTooLong);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- @Test
- public void testResourceBadCategory_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceId = resource.getUniqueId();
- String badCategory = "ddfds";
- updatedResource.setCategories(null);
- updatedResource.addCategory(badCategory, "fikt");
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
- }
-
- @Test
- public void testResourceCategoryAfterCertify_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- String resourceId = resource.getUniqueId();
- updatedResource.setCategories(null);
- updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
- resource.setVersion("1.0");
- ;
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
- }
-
- // Derived from start
- @Test
- public void testResourceTemplateNotExist_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
- String resourceId = resource.getUniqueId();
-
- List<String> list = null;
- updatedResource.setDerivedFrom(list);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
-
- @Test
- public void testResourceTemplateEmpty_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- updatedResource.setDerivedFrom(new ArrayList<String>());
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
- }
-
- @Test
- public void testResourceTemplateInvalid_UPDATE() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- derivedFrom.add("kuku");
- updatedResource.setDerivedFrom(derivedFrom);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
- }
-
- @Test
- public void testResourceTemplateCertify_UPDATE_HAPPY() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
- when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending);
-
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>());
- when(propertyOperation.deleteAllPropertiesAssociatedToNode(Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode);
-
- resource.setVersion("1.0");
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- derivedFrom.add("tosca.nodes.Root");
- updatedResource.setDerivedFrom(derivedFrom);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
- when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
- assertTrue(createResponse.isLeft());
- }
-
- @Test
- public void testResourceTemplateCertify_UPDATE_SAD() {
- Resource resource = createResourceObject(true);
- Resource updatedResource = createResourceObject(true);
- String resourceId = resource.getUniqueId();
-
- // this is in order to prevent failing with 403 earlier
- Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
- when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
-
- Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
- when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString()))
- .thenReturn(isToscaNameExtending);
-
- resource.setVersion("1.0");
-
- ArrayList<String> derivedFrom = new ArrayList<String>();
- derivedFrom.add("tosca.nodes.Root");
- updatedResource.setDerivedFrom(derivedFrom);
- Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
- when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
- Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user,
- false);
- assertTrue(createResponse.isRight());
-
- assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
- }
- // Derived from stop
-
- @Test
- public void createOrUpdateResourceAlreadyCheckout() {
- Resource resourceExist = createResourceObject(false);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
-
- createResponse.left().value().setLastUpdaterUserId(user.getUserId());
- assertTrue(createResponse.isLeft());
-
- Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value());
- Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value());
- when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult);
- when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult);
-
- Resource resourceToUpdtae = createResourceObject(false);
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
- assertTrue(createOrUpdateResource.isLeft());
-
- Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class));
- Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
-
- }
-
- @Test
- public void createOrUpdateResourceCertified() {
- Resource resourceExist = createResourceObject(false);
-
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
-
- assertTrue(createResponse.isLeft());
- Resource certifiedResource = createResponse.left().value();
- certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- certifiedResource.setVersion("1.0");
-
-
- Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource);
- Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value());
- when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult);
- when(toscaOperationFacade.overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class))).thenReturn(getLatestResult);
-
- when(lifecycleBl.changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse);
-
- Resource resourceToUpdtae = createResourceObject(false);
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
- assertTrue(createOrUpdateResource.isLeft());
-
- Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class));
- Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
-
- }
-
- @Test
- public void createOrUpdateResourceNotExist() {
- Resource resourceToUpdtae = createResourceObject(false);
-
- Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult);
-
- Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult);
-
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
- assertTrue(createOrUpdateResource.isLeft());
-
- Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(Mockito.any(Resource.class), Mockito.any(Resource.class));
- Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), Mockito.eq(user), Mockito.eq(LifeCycleTransitionEnum.CHECKOUT), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
-
- }
-
- @Test
- public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
- Resource basic = createResourceObject(true);
-
- Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
- assertTrue(validatePropertiesDefaultValues.isLeft());
- }
-
- @Test
- public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
- Resource basic = createResourceObject(true);
- PropertyDefinition property = new PropertyDefinition();
- property.setName("myProperty");
- property.setType(ToscaPropertyType.INTEGER.getType());
- property.setDefaultValue("1");
- List<PropertyDefinition> properties = new ArrayList<>();
- properties.add(property);
- basic.setProperties(properties);
- when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true);
- when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
- Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
- assertTrue(validatePropertiesDefaultValues.isLeft());
- }
- @Test
- public void testValidatePropertiesDefaultValues_FailedWithProperties() {
- Resource basic = createResourceObject(true);
- PropertyDefinition property = new PropertyDefinition();
- property.setName("myProperty");
- property.setType(ToscaPropertyType.INTEGER.getType());
- property.setDefaultValue("1.5");
- List<PropertyDefinition> properties = new ArrayList<>();
- properties.add(property);
- basic.setProperties(properties);
+ final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ IElementOperation mockElementDao;
+ TitanDao mockTitanDao = Mockito.mock(TitanDao.class);
+ UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
+ ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
+ NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
+ TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
+ final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
+ final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
+ final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class);
+ final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class);
+ WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ UserValidations userValidations = Mockito.mock(UserValidations.class);
+ WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
+ AuditingLogFormatUtil auditingLogFormatter = Mockito.mock(AuditingLogFormatUtil.class);
+ @InjectMocks
+ ResourceBusinessLogic bl = new ResourceBusinessLogic();
+ ResponseFormatManager responseManager = null;
+ GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
+ User user = null;
+ Resource resourceResponse = null;
+ Resource genericVF = null;
+ Resource genericCR = null;
+ Resource genericVFC = null;
+ Resource genericPNF = null;
+ ComponentsUtils componentsUtils;
+ ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic();
+ CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
+ Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
+ private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
+ CacheMangerOperation cacheManager = Mockito.mock(CacheMangerOperation.class);
+
+
+ public ResourceBusinessLogicTest() {
+
+ }
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ Mockito.reset(propertyOperation);
+
+ ExternalConfiguration.setAppName("catalog-be");
+
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+
+ // Elements
+ mockElementDao = new ElementOperationMock();
+
+ // User data and management
+ user = new User();
+ user.setUserId("jh0003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+
+ Either<User, ActionStatus> eitherGetUser = Either.left(user);
+ when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
+ when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(Either.left(user));
+ // Servlet Context attributes
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
+ when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
+
+ Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
+ Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true);
+ when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse);
+
+ Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
+ when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist);
+
+ Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
+ when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount);
+ /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
+ when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
+ when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/
+
+ Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
+ when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
+
+ Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false);
+ when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
+ when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
+ when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
+
+ // createResource
+ resourceResponse = createResourceObject(true);
+ Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
+ Either<Integer, StorageOperationStatus> eitherValidate = Either.left(null);
+ when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
+ when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate);
+ Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
+ when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
+
+ // BL object
+ artifactManager.setNodeTemplateOperation(nodeTemplateOperation);
+ bl = new ResourceBusinessLogic();
+ bl.setElementDao(mockElementDao);
+ bl.setUserAdmin(mockUserAdmin);
+ bl.setCapabilityTypeOperation(capabilityTypeOperation);
+ bl.setComponentsUtils(componentsUtils);
+ bl.setLifecycleManager(lifecycleBl);
+ bl.setGraphLockOperation(graphLockOperation);
+ bl.setArtifactsManager(artifactManager);
+ bl.setPropertyOperation(propertyOperation);
+ bl.setTitanGenericDao(mockTitanDao);
+ bl.setApplicationDataTypeCache(applicationDataTypeCache);
+ bl.setCsarOperation(csarOperation);
+ bl.setCacheManagerOperation(cacheManager);
+ bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
+ toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation);
+ toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ bl.setUserValidations(userValidations);
+ Resource resourceCsar = createResourceObjectCsar(true);
+ setCanWorkOnResource(resourceCsar);
+ Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar);
+ when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes);
+ responseManager = ResponseFormatManager.getInstance();
+
+ }
+
+ private Resource createResourceObject(boolean afterCreate) {
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<String>();
+ template.add("Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setContactId("ya5467");
+ resource.setIcon("MyIcon");
+
+ if (afterCreate) {
+ resource.setName(resource.getName());
+ resource.setVersion("0.1");
+ resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion());
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+ return resource;
+ }
+
+ private Resource createResourceObjectCsar(boolean afterCreate) {
+ Resource resource = new Resource();
+ resource.setName(RESOURCE_NAME);
+ resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY);
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add("test");
+ tgs.add(resource.getName());
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<String>();
+ template.add("Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setResourceVendorModelNumber("");
+ resource.setContactId("ya5467");
+ resource.setIcon("MyIcon");
+ resource.setCsarUUID("valid_vf.csar");
+ resource.setCsarVersion("1");
+
+ if (afterCreate) {
+ resource.setName(resource.getName());
+ resource.setVersion("0.1");
+
+ resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion());
+ resource.setCreatorUserId(user.getUserId());
+ resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+ return resource;
+ }
+
+ private Resource setCanWorkOnResource(Resource resource) {
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ resource.setLastUpdaterUserId(user.getUserId());
+ return resource;
+ }
+
+ @Test
+ public void testHappyScenario() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createResourceObject(false);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+
+ if (createResponse.isRight()) {
+ assertEquals(new Integer(200), createResponse.right().value().getStatus());
+ }
+ assertEquals(createResourceObject(true), createResponse.left().value());
+ }
+
+ @Test
+ public void testUpdateHappyScenario() {
+ Resource resource = createResourceObjectCsar(true);
+ setCanWorkOnResource(resource);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = Either.left(resource);
+ when(toscaOperationFacade.getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, resource.getCsarUUID(), resource.getSystemName())).thenReturn(resourceLinkedToCsarRes);
+ Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
+ when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
+
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> updateResponse = bl.validateAndUpdateResourceFromCsar(resource, user, null, null, resource.getUniqueId());
+ if (updateResponse.isRight()) {
+ assertEquals(new Integer(200), updateResponse.right().value().getStatus());
+ }
+ assertEquals(resource.getUniqueId(), updateResponse.left().value().getUniqueId());
+ }
+
+ /* CREATE validations - start ***********************/
+ // Resource name - start
+
+ @Test
+ public void testFailedResourceValidations() {
+ testResourceNameExist();
+ testResourceNameEmpty();
+ // testResourceNameExceedsLimit();
+ testResourceNameWrongFormat();
+ testResourceDescExceedsLimitCreate();
+ testResourceDescNotEnglish();
+ testResourceDescriptionEmpty();
+ testResourceDescriptionMissing();
+ testResourceIconMissing();
+ testResourceIconInvalid();
+ testResourceIconExceedsLimit();
+ testResourceTagNotExist();
+ testResourceTagEmpty();
+ testTagsExceedsLimitCreate();
+ testTagsNoServiceName();
+ testInvalidTag();
+
+ testContactIdTooLong();
+ testContactIdWrongFormatCreate();
+ testResourceContactIdEmpty();
+ testResourceContactIdMissing();
+ testVendorNameExceedsLimit();
+ testVendorNameWrongFormatCreate();
+ testVendorReleaseWrongFormat();
+ testVendorReleaseExceedsLimitCreate();
+ testResourceVendorModelNumberExceedsLimit();
+ testResourceVendorNameMissing();
+ testResourceVendorReleaseMissing();
+ testResourceCategoryExist();
+ testResourceBadCategoryCreate();
+ testHappyScenarioCostLicenseType();
+ testCostWrongFormatCreate();
+ testLicenseTypeWrongFormatCreate();
+ testResourceTemplateNotExist();
+ testResourceTemplateEmpty();
+ testResourceTemplateInvalid();
+ }
+
+ private void testResourceNameExist() {
+ String resourceName = "alreadyExists";
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setName(resourceName);
+ resourceExist.getTags().add(resourceName);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
+ }
+
+ private void testResourceNameEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setName(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertResponse(createResponse, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceNameExceedsLimit() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ // 51 chars, the limit is 50
+ String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
+ resourceExccedsNameLimit.setName(tooLongResourceName);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
+ }
+
+ private void testResourceNameWrongFormat() {
+ Resource resource = createResourceObject(false);
+ // contains :
+ String nameWrongFormat = "ljg?fd";
+ resource.setName(nameWrongFormat);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ // Resource name - end
+ // Resource description - start
+ private void testResourceDescExceedsLimitCreate() {
+ Resource resourceExccedsDescLimit = createResourceObject(false);
+ // 1025 chars, the limit is 1024
+ String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
+ + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
+ + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
+ + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
+ + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
+ + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
+ + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
+ + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
+
+ resourceExccedsDescLimit.setDescription(tooLongResourceDesc);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsDescLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+ }
+
+ private void testResourceDescNotEnglish() {
+ Resource notEnglish = createResourceObject(false);
+ // Not english
+ String notEnglishDesc = "\uC2B5";
+ notEnglish.setDescription(notEnglishDesc);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(notEnglish, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceDescriptionEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDescription("");
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceDescriptionMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDescription(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue());
+ }
+ // Resource description - end
+ // Resource icon start
+
+ private void testResourceIconMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceIconInvalid() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon("kjk3453^&");
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceIconExceedsLimit() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
+ }
+
+ // Resource icon end
+ // Resource tags - start
+ private void testResourceTagNotExist() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setTags(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+
+ private void testResourceTagEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setTags(new ArrayList<String>());
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_TAGS);
+ }
+
+ private void testTagsExceedsLimitCreate() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
+ String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
+ String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
+ String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
+ String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
+ String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
+ String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
+ String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
+ String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
+ String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
+ String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
+ String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
+ String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
+ String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
+ String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
+ String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
+ String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
+
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+ tagsList.add(tag3);
+ tagsList.add(tag4);
+ tagsList.add(tag5);
+ tagsList.add(tag6);
+ tagsList.add(tag7);
+ tagsList.add(tag8);
+ tagsList.add(tag9);
+ tagsList.add(tag10);
+ tagsList.add(tag11);
+ tagsList.add(tag12);
+ tagsList.add(tag13);
+ tagsList.add(tag14);
+ tagsList.add(tag15);
+ tagsList.add(tag16);
+ tagsList.add(tag17);
+ tagsList.add(tag18);
+ tagsList.add(tag19);
+ tagsList.add(tag20);
+ tagsList.add(tag21);
+ tagsList.add(resourceExccedsNameLimit.getName());
+
+ resourceExccedsNameLimit.setTags(tagsList);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
+
+ }
+
+ private void testTagsSingleExceedsLimit() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb5X6tZhiunkcEwiFX1qRQY8YZl3y3Du5M5xeQY5Nq9afcFHDZ9HaURw43gH27nAUWM36bMbMylwTFSzzNV8NO4v4ripe6Q15Vc2nPOFI";
+ String tag2 = resourceExccedsNameLimit.getName();
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+
+ resourceExccedsNameLimit.setTags(tagsList);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT, "" + ValidationUtils.TAG_MAX_LENGTH);
+
+ }
+
+ private void testTagsNoServiceName() {
+ Resource serviceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb";
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
+
+ }
+
+ private void testInvalidTag() {
+ Resource serviceExccedsNameLimit = createResourceObject(false);
+ String tag1 = "afzs2qLBb%#%";
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ serviceExccedsNameLimit.setTags(tagsList);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(serviceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_FIELD_FORMAT, new String[]{"Resource", "tag"});
+
+ }
+
+ // Resource tags - stop
+ // Resource contact start
+
+ private void testContactIdTooLong() {
+ Resource resourceContactId = createResourceObject(false);
+ // 59 chars instead of 50
+ String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
+ resourceContactId.setContactId(contactIdTooLong);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testContactIdWrongFormatCreate() {
+ Resource resourceContactId = createResourceObject(false);
+ // 3 letters and 3 digits and special characters
+ String contactIdFormatWrong = "yrt134!!!";
+ resourceContactId.setContactId(contactIdFormatWrong);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceContactId, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceContactIdEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setContactId("");
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceContactIdMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setContactId(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testVendorNameExceedsLimit() {
+ Resource resourceExccedsVendorNameLimit = createResourceObject(false);
+ String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ }
+
+ private void testResourceVendorModelNumberExceedsLimit() {
+ Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
+ String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ }
+
+ private void testVendorNameWrongFormatCreate() {
+ Resource resource = createResourceObject(false);
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ resource.setVendorName(nameWrongFormat);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME);
+ }
+
+ private void testVendorReleaseWrongFormat() {
+ Resource resource = createResourceObject(false);
+ // contains >
+ String nameWrongFormat = "1>2";
+ resource.setVendorRelease(nameWrongFormat);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_VENDOR_RELEASE);
+
+ }
+
+ private void testVendorReleaseExceedsLimitCreate() {
+ Resource resourceExccedsNameLimit = createResourceObject(false);
+ String tooLongVendorRelease = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsNameLimit.setVendorRelease(tooLongVendorRelease);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+
+ private void testResourceVendorNameMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setVendorName(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.MISSING_VENDOR_NAME);
+ }
+
+ private void testResourceVendorReleaseMissing() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setVendorRelease(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.MISSING_VENDOR_RELEASE);
+ }
+
+ // Resource vendor name/release stop
+ // Category start
+ private void testResourceCategoryExist() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setCategories(null);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ private void testResourceBadCategoryCreate() {
+
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setCategories(null);
+ resourceExist.addCategory("koko", "koko");
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ // Category stop
+ // Cost start
+ private void testHappyScenarioCostLicenseType() {
+ Resource createResourceObject = createResourceObject(false);
+ Resource createResourceObjectAfterCreate = createResourceObject(true);
+ // Adding cost and licenseType to basic mock
+ Either<Resource, StorageOperationStatus> eitherCreate = Either.left(createResourceObjectAfterCreate);
+ when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate);
+
+ String cost = "123.456";
+ String licenseType = "User";
+ createResourceObject.setCost(cost);
+ createResourceObject.setLicenseType(licenseType);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(createResourceObject, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+
+ if (createResponse.isRight()) {
+ assertEquals(new Integer(200), createResponse.right().value().getStatus());
+ }
+ createResourceObjectAfterCreate.setCost(cost);
+ createResourceObjectAfterCreate.setLicenseType(licenseType);
+ assertEquals(createResourceObjectAfterCreate, createResponse.left().value());
+ }
+
+ private void testCostWrongFormatCreate() {
+ Resource resourceCost = createResourceObject(false);
+ // Comma instead of fullstop
+ String cost = "12356,464";
+ resourceCost.setCost(cost);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceCost, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_CONTENT);
+ }
+
+ // Cost stop
+ // License type start
+ private void testLicenseTypeWrongFormatCreate() {
+ Resource resourceLicenseType = createResourceObject(false);
+ // lowcase
+ String licenseType = "cpu";
+ resourceLicenseType.setLicenseType(licenseType);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceLicenseType, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_CONTENT);
+ }
+
+ // License type stop
+ // Derived from start
+ private void testResourceTemplateNotExist() {
+ Resource resourceExist = createResourceObject(false);
+ List<String> list = null;
+ resourceExist.setDerivedFrom(list);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+
+ private void testResourceTemplateEmpty() {
+ Resource resourceExist = createResourceObject(false);
+ resourceExist.setDerivedFrom(new ArrayList<String>());
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+
+ private void testResourceTemplateInvalid() {
+ Resource resourceExist = createResourceObject(false);
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("kuku");
+ resourceExist.setDerivedFrom(derivedFrom);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ }
+ // Derived from stop
+
+ private void assertResponse(Either<Resource, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ ResponseFormat actualResponse = createResponse.right().value();
+ assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
+ assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
+ }
+
+ // UPDATE tests - start
+ // Resource name
+ @Test
+ public void testResourceNameWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ updatedResource.setName(nameWrongFormat);
+
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue());
+
+ }
+
+ @Test
+ public void testResourceNameAfterCertify_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ // when(resourceOperation.getResource_tx(resource.getUniqueId(),false)).thenReturn(eitherUpdate);
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String name = "ljg";
+ updatedResource.setName(name);
+ resource.setVersion("1.0");
+
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
+
+ }
+
+ @Ignore
+ public void testResourceNameExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // 51 chars, the limit is 50
+ String tooLongResourceName = "zCRCAWjqte0DtgcAAMmcJcXeNubeX1p1vOZNTShAHOYNAHvV3iK";
+ updatedResource.setName(tooLongResourceName);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
+ }
+
+ @Test
+ public void testResourceNameAlreadyExist_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceName = "alreadyExists";
+ updatedResource.setName(resourceName);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resourceName);
+ }
+
+ //
+
+ @Test
+ public void testResourceDescExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // 1025 chars, the limit is 1024
+ String tooLongResourceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
+ + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
+ + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
+ + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
+ + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
+ + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
+ + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
+ + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
+ updatedResource.setDescription(tooLongResourceDesc);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.RESOURCE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+
+ }
+
+ @Test
+ public void testIconWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains .
+ String icon = "icon.jpg";
+ updatedResource.setIcon(icon);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.RESOURCE.getValue());
+
+ }
+
+ @Test
+ public void testIconAfterCertify_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains
+ String icon = "icon";
+ updatedResource.setIcon(icon);
+
+ resource.setVersion("1.0");
+ ;
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
+
+ }
+
+ @Test
+ public void testTagsExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String tag1 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjQ";
+ String tag2 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjW";
+ String tag3 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjE";
+ String tag4 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjb";
+ String tag5 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjr";
+ String tag6 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag7 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag8 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjd";
+ String tag9 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjf";
+ String tag10 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjg";
+ String tag11 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjh";
+ String tag12 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjj";
+ String tag13 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjk";
+ String tag14 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjs";
+ String tag15 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjz";
+ String tag16 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBjx";
+ String tag17 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj2";
+ String tag18 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj3";
+ String tag19 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj4";
+ String tag20 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj5";
+ String tag21 = "I63llMSEF12FntTwpMt64JhopkjQZzv5KS7mBoRku42PYLrBj0";
+
+ List<String> tagsList = new ArrayList<String>();
+ tagsList.add(tag1);
+ tagsList.add(tag2);
+ tagsList.add(tag3);
+ tagsList.add(tag4);
+ tagsList.add(tag5);
+ tagsList.add(tag6);
+ tagsList.add(tag7);
+ tagsList.add(tag8);
+ tagsList.add(tag9);
+ tagsList.add(tag10);
+ tagsList.add(tag11);
+ tagsList.add(tag12);
+ tagsList.add(tag13);
+ tagsList.add(tag14);
+ tagsList.add(tag15);
+ tagsList.add(tag16);
+ tagsList.add(tag17);
+ tagsList.add(tag18);
+ tagsList.add(tag19);
+ tagsList.add(tag20);
+ tagsList.add(tag21);
+ tagsList.add(resource.getName());
+
+ updatedResource.setTags(tagsList);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
+ }
+
+ @Test
+ public void testVendorNameWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ updatedResource.setVendorName(nameWrongFormat);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME);
+
+ }
+
+ @Test
+ public void testVendorNameWrongFormat() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ // contains *
+ String nameWrongFormat = "ljg*fd";
+ updatedResource.setVendorName(nameWrongFormat);
+ resource.setVersion("1.0");
+ ;
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.INVALID_VENDOR_NAME);
+
+ }
+
+ @Test
+ public void testVendorReleaseExceedsLimit_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ // 129 chars, the limit is 128
+ String tooLongVendorRelease = "h1KSyJh9EspI8SPwAGu4VETfqWejeanuB1PCJBxJmJncYnrW0lnsEFFVRIukRJkwlOVnZCy8p38tjhANeZq3BGMHIawWR6ICl8Wi9mikRYALWgvJug00JrlQ0iPVKPLxy";
+ updatedResource.setVendorRelease(tooLongVendorRelease);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resource.getUniqueId(), updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ }
+
+ @Ignore
+ public void testContactIdWrongFormat_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceId = resource.getUniqueId();
+ // 3 letters and 3 digits
+ String contactIdTooLong = "yrt134";
+ updatedResource.setContactId(contactIdTooLong);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void testResourceBadCategory_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceId = resource.getUniqueId();
+ String badCategory = "ddfds";
+ updatedResource.setCategories(null);
+ updatedResource.addCategory(badCategory, "fikt");
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ }
+
+ @Test
+ public void testResourceCategoryAfterCertify_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ String resourceId = resource.getUniqueId();
+ updatedResource.setCategories(null);
+ updatedResource.addCategory(RESOURCE_CATEGORY1, UPDATED_SUBCATEGORY);
+ resource.setVersion("1.0");
+ ;
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
+ }
+
+ // Derived from start
+ @Test
+ public void testResourceTemplateNotExist_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+ String resourceId = resource.getUniqueId();
+
+ List<String> list = null;
+ updatedResource.setDerivedFrom(list);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+
+ @Test
+ public void testResourceTemplateEmpty_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ updatedResource.setDerivedFrom(new ArrayList<String>());
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+ }
+
+ @Test
+ public void testResourceTemplateInvalid_UPDATE() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("kuku");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+ }
+
+ @Test
+ public void testResourceTemplateCertify_UPDATE_HAPPY() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(true);
+ when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString())).thenReturn(isToscaNameExtending);
+
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = Either.left(new HashMap<>());
+ when(propertyOperation.deleteAllPropertiesAssociatedToNode(any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(findPropertiesOfNode);
+
+ resource.setVersion("1.0");
+
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(updatedResource);
+ when(toscaOperationFacade.updateToscaElement(updatedResource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user, false);
+ assertTrue(createResponse.isLeft());
+ }
+
+ @Test
+ public void testResourceTemplateCertify_UPDATE_SAD() {
+ Resource resource = createResourceObject(true);
+ Resource updatedResource = createResourceObject(true);
+ String resourceId = resource.getUniqueId();
+
+ // this is in order to prevent failing with 403 earlier
+ Either<Component, StorageOperationStatus> eitherUpdate = Either.left(setCanWorkOnResource(resource));
+ when(toscaOperationFacade.getToscaElement(resource.getUniqueId())).thenReturn(eitherUpdate);
+
+ Either<Boolean, StorageOperationStatus> isToscaNameExtending = Either.left(false);
+ when(toscaOperationFacade.validateToscaResourceNameExtends(Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(isToscaNameExtending);
+
+ resource.setVersion("1.0");
+
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ updatedResource.setDerivedFrom(derivedFrom);
+ Either<Resource, StorageOperationStatus> dataModelResponse = Either.left(resource);
+ when(toscaOperationFacade.updateToscaElement(resource)).thenReturn(dataModelResponse);
+ Either<Resource, ResponseFormat> createResponse = bl.updateResourceMetadata(resourceId, updatedResource, null, user,
+ false);
+ assertTrue(createResponse.isRight());
+
+ assertResponse(createResponse, ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+ }
+ // Derived from stop
+
+ @Test
+ public void createOrUpdateResourceAlreadyCheckout() {
+ Resource resourceExist = createResourceObject(false);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+
+ createResponse.left().value().setLastUpdaterUserId(user.getUserId());
+ assertTrue(createResponse.isLeft());
+
+ Either<Resource, StorageOperationStatus> getLatestResult = Either.left(createResponse.left().value());
+ Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value());
+ when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult);
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult);
+
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertTrue(createOrUpdateResource.isLeft());
+
+ Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+
+ }
+
+ @Test
+ public void createOrUpdateResourceCertified() {
+ Resource resourceExist = createResourceObject(false);
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExist, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+
+ assertTrue(createResponse.isLeft());
+ Resource certifiedResource = createResponse.left().value();
+ certifiedResource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ certifiedResource.setVersion("1.0");
+
+
+ Either<Resource, StorageOperationStatus> getLatestResult = Either.left(certifiedResource);
+ Either<Component, StorageOperationStatus> getCompLatestResult = Either.left(createResponse.left().value());
+ when(toscaOperationFacade.getLatestByName(resourceExist.getName())).thenReturn(getCompLatestResult);
+ when(toscaOperationFacade.overrideComponent(any(Resource.class), any(Resource.class))).thenReturn(getLatestResult);
+
+ when(lifecycleBl.changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(createResponse);
+
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertTrue(createOrUpdateResource.isLeft());
+
+ Mockito.verify(toscaOperationFacade, Mockito.times(1)).overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, Mockito.times(1)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+
+ }
+
+ @Test
+ public void createOrUpdateResourceNotExist() {
+ Resource resourceToUpdtae = createResourceObject(false);
+
+ Either<Component, StorageOperationStatus> getLatestResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getLatestByName(resourceToUpdtae.getName())).thenReturn(getLatestResult);
+
+ Either<Component, StorageOperationStatus> getLatestToscaNameResult = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getLatestByToscaResourceName(resourceToUpdtae.getToscaResourceName())).thenReturn(getLatestToscaNameResult);
+
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResource = bl.createOrUpdateResourceByImport(resourceToUpdtae, user, false, false, false, null, null, false);
+ assertTrue(createOrUpdateResource.isLeft());
+
+ Mockito.verify(toscaOperationFacade, Mockito.times(0)).overrideComponent(any(Resource.class), any(Resource.class));
+ Mockito.verify(lifecycleBl, Mockito.times(0)).changeState(Mockito.anyString(), eq(user), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), Mockito.anyBoolean(), Mockito.anyBoolean());
+
+ }
+
+ @Test
+ public void testValidatePropertiesDefaultValues_SuccessfullWithoutProperties() {
+ Resource basic = createResourceObject(true);
+
+ Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
+ assertTrue(validatePropertiesDefaultValues.isLeft());
+ }
+
+ @Test
+ public void testValidatePropertiesDefaultValues_SuccessfullWithProperties() {
+ Resource basic = createResourceObject(true);
+ PropertyDefinition property = new PropertyDefinition();
+ property.setName("myProperty");
+ property.setType(ToscaPropertyType.INTEGER.getType());
+ property.setDefaultValue("1");
+ List<PropertyDefinition> properties = new ArrayList<>();
+ properties.add(property);
+ basic.setProperties(properties);
+ when(propertyOperation.isPropertyTypeValid(property)).thenReturn(true);
+ when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(true);
+ Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
+ assertTrue(validatePropertiesDefaultValues.isLeft());
+ }
+
+ @Test
+ public void testValidatePropertiesDefaultValues_FailedWithProperties() {
+ Resource basic = createResourceObject(true);
+ PropertyDefinition property = new PropertyDefinition();
+ property.setName("myProperty");
+ property.setType(ToscaPropertyType.INTEGER.getType());
+ property.setDefaultValue("1.5");
+ List<PropertyDefinition> properties = new ArrayList<>();
+ properties.add(property);
+ basic.setProperties(properties);
- when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
- Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
- assertTrue(validatePropertiesDefaultValues.isRight());
- }
-
-// @Test
-// public void testDeleteMarkedResourcesNoResources() {
-// List<GraphVertex> ids = new ArrayList<>();
-// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids);
-// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
+ when(propertyOperation.isPropertyDefaultValueValid(property, emptyDataTypes)).thenReturn(false);
+ Either<Boolean, ResponseFormat> validatePropertiesDefaultValues = bl.validatePropertiesDefaultValues(basic);
+ assertTrue(validatePropertiesDefaultValues.isRight());
+ }
+
+// @Test
+// public void testDeleteMarkedResourcesNoResources() {
+// List<GraphVertex> ids = new ArrayList<>();
+// Either<List<GraphVertex>, StorageOperationStatus> eitherNoResources = Either.left(ids);
+// when(topologyTemplateOperation.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
+//
+// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
+// assertTrue(deleteMarkedResources.isLeft());
+// assertTrue(deleteMarkedResources.left().value().isEmpty());
//
-// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
-// assertTrue(deleteMarkedResources.isLeft());
-// assertTrue(deleteMarkedResources.left().value().isEmpty());
+// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
//
-// Mockito.verify(artifactManager, Mockito.times(0)).deleteAllComponentArtifactsIfNotOnGraph(Mockito.anyList());
+// }
//
-// }
+// @Test
+// public void testDeleteMarkedResources() {
+// List<String> ids = new ArrayList<String>();
+// String resourceInUse = "123";
+// ids.add(resourceInUse);
+// String resourceFree = "456";
+// ids.add(resourceFree);
+// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
+// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
//
-// @Test
-// public void testDeleteMarkedResources() {
-// List<String> ids = new ArrayList<String>();
-// String resourceInUse = "123";
-// ids.add(resourceInUse);
-// String resourceFree = "456";
-// ids.add(resourceFree);
-// Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
-// when(toscaOperationFacade.getAllComponentsMarkedForDeletion()).thenReturn(eitherNoResources);
+// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
+// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
//
-// Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
-// Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
+// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
+// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
+// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse);
//
-// List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
-// Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
-// when(toscaOperationFacade.getComponentArtifactsForDelete(resourceFree, NodeTypeEnum.Resource, true)).thenReturn(getArtifactsResponse);
+// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
+// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
//
-// when(toscaOperationFacade.isComponentInUse(resourceFree)).thenReturn(resourceFreeResponse);
-// when(toscaOperationFacade.isComponentInUse(resourceInUse)).thenReturn(resourceInUseResponse);
+// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
+// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
//
-// Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
-// when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
+// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK);
+// List<String> deletedComponents = new ArrayList<>();
+// deletedComponents.add(resourceFree);
+// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
//
-// when(artifactManager.deleteAllComponentArtifactsIfNotOnGraph(artifacts)).thenReturn(StorageOperationStatus.OK);
-// List<String> deletedComponents = new ArrayList<>();
-// deletedComponents.add(resourceFree);
-// when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.RESOURCE)).thenReturn(Either.left(deletedComponents));
-//
-// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
-// assertTrue(deleteMarkedResources.isLeft());
-// List<String> resourceIdList = deleteMarkedResources.left().value();
-// assertFalse(resourceIdList.isEmpty());
-// assertTrue(resourceIdList.contains(resourceFree));
-// assertFalse(resourceIdList.contains(resourceInUse));
+// Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
+// assertTrue(deleteMarkedResources.isLeft());
+// List<String> resourceIdList = deleteMarkedResources.left().value();
+// assertFalse(resourceIdList.isEmpty());
+// assertTrue(resourceIdList.contains(resourceFree));
+// assertFalse(resourceIdList.contains(resourceInUse));
//
-// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts);
-// }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testFindVfCsarArtifactsToHandle() {
-
- Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
- String methodName = "findVfCsarArtifactsToHandle";
- Resource resource = new Resource();
- String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
- String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
- String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
-
- String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
- String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
- String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
-
- byte[] oldPayloadData = "oldPayloadData".getBytes();
- byte[] newPayloadData = "newPayloadData".getBytes();
- Map<String, ArtifactDefinition> deploymentArtifacts =new HashMap<>();
-
- ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
- deploymentArtifactToUpdate.setMandatory(false);
- deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
- deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
- deploymentArtifactToUpdate.setPayload(oldPayloadData);
- deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
- deploymentArtifactToDelete.setMandatory(false);
- deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
- deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
- deploymentArtifactToDelete.setPayload(oldPayloadData);
- deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
-
- deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate);
- deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete);
- deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
-
- Map<String, ArtifactDefinition> artifacts = new HashMap<>();
-
- ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
- artifactToUpdate.setMandatory(false);
- artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
- artifactToUpdate.setArtifactType("SNMP_POLL");
- artifactToUpdate.setPayload(oldPayloadData);
- artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition artifactToDelete = new ArtifactDefinition();
- artifactToDelete.setMandatory(false);
- artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
- artifactToDelete.setArtifactType("SNMP_TRAP");
- artifactToDelete.setPayload(oldPayloadData);
- artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
-
- ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
-
- artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()),artifactToUpdate);
- artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()),artifactToDelete);
- artifacts.put("ignore",artifactToIgnore);
-
- resource.setDeploymentArtifacts(deploymentArtifacts);
- resource.setArtifacts(artifacts);
-
- List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
- NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null,
- ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
- newPayloadData, deploymentArtifactToUpdate.getArtifactName());
-
- NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
- ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
- newPayloadData, artifactToUpdate.getArtifactName());
-
- NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null,
- ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName);
-
- NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null,
- ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT,
- newPayloadData, artifactInfoToCreateFileName);
-
- artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
- artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
- artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
- artifactPathAndNameList.add(informationalArtifactInfoToCreate);
-
- Object[] argObjects = {resource, artifactPathAndNameList, user};
- Class[] argClasses = {Resource.class, List.class, User.class};
- try {
- Method method = targetClass.getDeclaredMethod(methodName, argClasses);
- method.setAccessible(true);
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes =
- (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects);
- assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
- EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value();
- assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2);
- assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Update).size()==2);
- assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.Create).size()==2);
-
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void testVFGeneratedInputs() {
-
- Resource resource = createVF();
- List<InputDefinition> inputs = resource.getInputs();
- assertTrue(8 == inputs.size());
- for(InputDefinition input : inputs){
- assertNotNull(input.getOwnerId());
- }
- assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName()));
- assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion()));
- }
-
- @Test
- public void testVFUpdateGenericInputsToLatestOnCheckout() {
-
- //create a VF that is derived from generic version 1.0
- Resource resource = createVF();
- // create a new generic version without properties
- genericVF.setVersion("2.0");
- genericVF.setProperties(null);
- String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
- List<InputDefinition> currentInputs = resource.getInputs();
- //verify previous inputs ownerId fields exist - user may not delete generated inputs
- assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size());
- Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
- //verify success
- assertTrue(upgradeToLatestGeneric.isLeft());
- //verify update required and valid
- assertTrue(upgradeToLatestGeneric.left().value());
- //verify version was upgraded
- assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion));
- //verify inputs were not deleted
- assertTrue(8 == resource.getInputs().size());
- //verify inputs ownerId fields were removed - user may delete/edit inputs
- assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size());
- }
-
-
- @Test
- public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
-
- //create a VF that is derived from generic version 1.0
- Resource resource = createVF();
-
- //add an input to the VF
- PropertyDefinition newProp = new PropertyDefinition();
- newProp.setType("integer");
- newProp.setName("newProp");
- resource.getInputs().add(new InputDefinition(newProp));
-
- //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type
- genericVF.setVersion("2.0");
- newProp.setType("string");
- genericVF.setProperties(new ArrayList<PropertyDefinition>());
- genericVF.getProperties().add(newProp);
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod();
- String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
- assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size());
- Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
- //verify success
- assertTrue(upgradeToLatestGeneric.isLeft());
- //verify update is invalid an void
- assertFalse(upgradeToLatestGeneric.left().value());
- //verify version was not upgraded
- assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion));
- //verify inputs were not removed
- assertTrue(9 == resource.getInputs().size());
- //verify user defined input exists
- assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size());
- assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer"));
- }
-
- @Test
- public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
-
- Resource resource = createPNF();
- List<InputDefinition> inputs = resource.getInputs();
- assertTrue(8 == inputs.size());
- for(InputDefinition input : inputs){
- assertNotNull(input.getOwnerId());
- }
- assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName()));
- assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion()));
- assertTrue(0 == resource.getArtifacts().size());
- }
-
-
- private Resource createVF() {
-
- genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
- when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF));
- Resource resource = createResourceObject(true);
- resource.setDerivedFrom(null);
- resource.setResourceType(ResourceTypeEnum.VF);
- when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
- when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod();
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isLeft());
- return createResponse.left().value();
- }
-
- private Resource createPNF() {
-
- genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
- when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF));
- Resource resource = createResourceObject(true);
- resource.setDerivedFrom(null);
- resource.setResourceType(ResourceTypeEnum.PNF);
- when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
- when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF));
- when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
- when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod();
- Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
- assertTrue(createResponse.isLeft());
- return createResponse.left().value();
- }
-
-
-
+// Mockito.verify(artifactManager, Mockito.times(1)).deleteAllComponentArtifactsIfNotOnGraph(artifacts);
+// }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testFindVfCsarArtifactsToHandle() {
+
+ Class<ResourceBusinessLogic> targetClass = ResourceBusinessLogic.class;
+ String methodName = "findVfCsarArtifactsToHandle";
+ Resource resource = new Resource();
+ String deploymentArtifactToUpdateFileName = "deploymentArtifactToUpdate.yaml";
+ String deploymentArtifactToDeleteFileName = "deploymentArtifactToDelete.yaml";
+ String deploymentArtifactToCreateFileName = "deploymentArtifactToCreate.yaml";
+
+ String artifactInfoToUpdateFileName = "infoArtifactToUpdate.yaml";
+ String artifactInfoToDeleteFileName = "infoArtifactToDelete.yaml";
+ String artifactInfoToNotDeleteFileName = "infoArtifactNotToDelete.yaml";
+ String artifactInfoToCreateFileName = "infoArtifactToCreate.yaml";
+
+ byte[] oldPayloadData = "oldPayloadData".getBytes();
+ byte[] newPayloadData = "newPayloadData".getBytes();
+ Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
+
+ ArtifactDefinition deploymentArtifactToUpdate = new ArtifactDefinition();
+ deploymentArtifactToUpdate.setMandatory(false);
+ deploymentArtifactToUpdate.setArtifactName(deploymentArtifactToUpdateFileName);
+ deploymentArtifactToUpdate.setArtifactType("SNMP_POLL");
+ deploymentArtifactToUpdate.setPayload(oldPayloadData);
+ deploymentArtifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+
+ ArtifactDefinition deploymentArtifactToDelete = new ArtifactDefinition();
+ deploymentArtifactToDelete.setMandatory(false);
+ deploymentArtifactToDelete.setArtifactName(deploymentArtifactToDeleteFileName);
+ deploymentArtifactToDelete.setArtifactType("SNMP_TRAP");
+ deploymentArtifactToDelete.setPayload(oldPayloadData);
+ deploymentArtifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+
+ ArtifactDefinition deploymentArtifactToIgnore = new ArtifactDefinition();
+
+ deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToUpdate.getArtifactName()), deploymentArtifactToUpdate);
+ deploymentArtifacts.put(ValidationUtils.normalizeArtifactLabel(deploymentArtifactToDelete.getArtifactName()), deploymentArtifactToDelete);
+ deploymentArtifacts.put("ignore", deploymentArtifactToIgnore);
+
+ Map<String, ArtifactDefinition> artifacts = new HashMap<>();
+
+ ArtifactDefinition artifactToUpdate = new ArtifactDefinition();
+ artifactToUpdate.setMandatory(false);
+ artifactToUpdate.setArtifactName(artifactInfoToUpdateFileName);
+ artifactToUpdate.setArtifactType("SNMP_POLL");
+ artifactToUpdate.setPayload(oldPayloadData);
+ artifactToUpdate.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+
+ ArtifactDefinition artifactToDelete = new ArtifactDefinition();
+ artifactToDelete.setMandatory(false);
+ artifactToDelete.setArtifactName(artifactInfoToDeleteFileName);
+ artifactToDelete.setArtifactType("SNMP_TRAP");
+ artifactToDelete.setPayload(oldPayloadData);
+ artifactToDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+ artifactToDelete.setIsFromCsar(true);
+
+ ArtifactDefinition artifactToNotDelete = new ArtifactDefinition();
+ artifactToNotDelete.setMandatory(false);
+ artifactToNotDelete.setArtifactName(artifactInfoToNotDeleteFileName);
+ artifactToNotDelete.setArtifactType("SNMP_TRAP");
+ artifactToNotDelete.setPayload(oldPayloadData);
+ artifactToNotDelete.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(oldPayloadData));
+ artifactToNotDelete.setIsFromCsar(false);
+
+ ArtifactDefinition artifactToIgnore = new ArtifactDefinition();
+
+ artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToUpdate.getArtifactName()), artifactToUpdate);
+ artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToDelete.getArtifactName()), artifactToDelete);
+ artifacts.put(ValidationUtils.normalizeArtifactLabel(artifactToNotDelete.getArtifactName()), artifactToNotDelete);
+ artifacts.put("ignore", artifactToIgnore);
+
+ resource.setDeploymentArtifacts(deploymentArtifacts);
+ resource.setArtifacts(artifacts);
+
+ List<NonMetaArtifactInfo> artifactPathAndNameList = new ArrayList<>();
+ NonMetaArtifactInfo deploymentArtifactInfoToUpdate = new NonMetaArtifactInfo(deploymentArtifactToUpdate.getArtifactName(), null,
+ ArtifactTypeEnum.findType(deploymentArtifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
+ newPayloadData, deploymentArtifactToUpdate.getArtifactName(), false);
+
+ NonMetaArtifactInfo informationalArtifactInfoToUpdate = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
+ ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
+ newPayloadData, artifactToUpdate.getArtifactName(), false);
+
+ NonMetaArtifactInfo informationalArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
+ ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.INFORMATIONAL,
+ newPayloadData, artifactToUpdate.getArtifactName(), true);
+
+ NonMetaArtifactInfo deploymentArtifactInfoToUpdateFromCsar = new NonMetaArtifactInfo(artifactToUpdate.getArtifactName(), null,
+ ArtifactTypeEnum.findType(artifactToUpdate.getArtifactType()), ArtifactGroupTypeEnum.DEPLOYMENT,
+ newPayloadData, artifactToUpdate.getArtifactName(), true);
+
+ NonMetaArtifactInfo deploymentArtifactInfoToCreate = new NonMetaArtifactInfo(deploymentArtifactToCreateFileName, null,
+ ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.DEPLOYMENT, newPayloadData, deploymentArtifactToCreateFileName, false);
+
+ NonMetaArtifactInfo informationalArtifactInfoToCreate = new NonMetaArtifactInfo(artifactInfoToCreateFileName, null,
+ ArtifactTypeEnum.OTHER, ArtifactGroupTypeEnum.INFORMATIONAL,
+ newPayloadData, artifactInfoToCreateFileName, false);
+
+ artifactPathAndNameList.add(deploymentArtifactInfoToUpdate);
+ artifactPathAndNameList.add(informationalArtifactInfoToUpdate);
+ artifactPathAndNameList.add(deploymentArtifactInfoToCreate);
+ artifactPathAndNameList.add(informationalArtifactInfoToCreate);
+ artifactPathAndNameList.add(informationalArtifactInfoToUpdateFromCsar);
+ artifactPathAndNameList.add(deploymentArtifactInfoToUpdateFromCsar);
+
+ Object[] argObjects = {resource, artifactPathAndNameList, user};
+ Class[] argClasses = {Resource.class, List.class, User.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes =
+ (Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat>) method.invoke(bl, argObjects);
+ assertTrue(findVfCsarArtifactsToHandleRes.isLeft());
+ EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> foundVfArtifacts = findVfCsarArtifactsToHandleRes.left().value();
+ assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.CREATE).size() == 4);
+ assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.UPDATE).size() == 4);
+ assertTrue(foundVfArtifacts.get(ArtifactOperationEnum.DELETE).size() == 1);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testVFGeneratedInputs() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createVF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertTrue(8 == inputs.size());
+ for (InputDefinition input : inputs) {
+ assertNotNull(input.getOwnerId());
+ }
+ assertTrue(resource.getDerivedFromGenericType().equals(genericVF.getToscaResourceName()));
+ assertTrue(resource.getDerivedFromGenericVersion().equals(genericVF.getVersion()));
+ }
+
+ @Test
+ public void testCRGeneratedInputs() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createCR();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertTrue(5 == inputs.size());
+ for (InputDefinition input : inputs) {
+ assertNotNull(input.getOwnerId());
+ }
+ assertTrue(resource.getDerivedFromGenericType().equals(genericCR.getToscaResourceName()));
+ assertTrue(resource.getDerivedFromGenericVersion().equals(genericCR.getVersion()));
+ }
+
+ @Test
+ public void testVFUpdateGenericInputsToLatestOnCheckout() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ //create a VF that is derived from generic version 1.0
+ Resource resource = createVF();
+ // create a new generic version without properties
+ genericVF.setVersion("2.0");
+ genericVF.setProperties(null);
+ String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
+ List<InputDefinition> currentInputs = resource.getInputs();
+ //verify previous inputs ownerId fields exist - user may not delete generated inputs
+ assertTrue(8 == currentInputs.stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size());
+ Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
+ //verify success
+ assertTrue(upgradeToLatestGeneric.isLeft());
+ //verify update required and valid
+ assertTrue(upgradeToLatestGeneric.left().value());
+ //verify version was upgraded
+ assertFalse(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion));
+ //verify inputs were not deleted
+ assertTrue(8 == resource.getInputs().size());
+ //verify inputs ownerId fields were removed - user may delete/edit inputs
+ assertTrue(8 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size());
+ }
+
+
+ @Test
+ public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
+
+ //create a VF that is derived from generic version 1.0
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createVF();
+
+ //add an input to the VF
+ PropertyDefinition newProp = new PropertyDefinition();
+ newProp.setType("integer");
+ newProp.setName("newProp");
+ resource.getInputs().add(new InputDefinition(newProp));
+
+ //create a new generic version with a new property which has the same name as a user defined input on the VF with a different type
+ genericVF.setVersion("2.0");
+ newProp.setType("string");
+ genericVF.setProperties(new ArrayList<PropertyDefinition>());
+ genericVF.getProperties().add(newProp);
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), genericVF.getUniqueId())).thenCallRealMethod();
+ String currentDerivedFromVersion = resource.getDerivedFromGenericVersion();
+ assertTrue(8 == resource.getInputs().stream().filter(p -> null != p.getOwnerId()).collect(Collectors.toList()).size());
+ Either<Boolean, ResponseFormat> upgradeToLatestGeneric = bl.shouldUpgradeToLatestGeneric(resource);
+ //verify success
+ assertTrue(upgradeToLatestGeneric.isLeft());
+ //verify update is invalid an void
+ assertFalse(upgradeToLatestGeneric.left().value());
+ //verify version was not upgraded
+ assertTrue(resource.getDerivedFromGenericVersion().equals(currentDerivedFromVersion));
+ //verify inputs were not removed
+ assertTrue(9 == resource.getInputs().size());
+ //verify user defined input exists
+ assertTrue(1 == resource.getInputs().stream().filter(p -> null == p.getOwnerId()).collect(Collectors.toList()).size());
+ assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer"));
+ }
+
+ @Test
+ public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
+ validateUserRoles(Role.ADMIN, Role.DESIGNER);
+ Resource resource = createPNF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertTrue(3 == inputs.size());
+ for (InputDefinition input : inputs) {
+ assertNotNull(input.getOwnerId());
+ }
+ assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName()));
+ assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion()));
+ assertTrue(0 == resource.getArtifacts().size());
+ }
+
+
+ private Resource createVF() {
+
+ genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_VF_NAME)).thenReturn(Either.left(genericVF));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.VF);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericVF));
+ when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericVF)).thenCallRealMethod();
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericVF.getProperties(), resource.getUniqueId())).thenCallRealMethod();
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isLeft());
+ return createResponse.left().value();
+ }
+
+
+ private Resource createCR() {
+
+ genericCR = setupGenericTypeMock(GENERIC_CR_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_CR_NAME)).thenReturn(Either.left(genericCR));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.CR);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericCR));
+ when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericCR)).thenCallRealMethod();
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericCR.getProperties(), resource.getUniqueId())).thenCallRealMethod();
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isLeft());
+ return createResponse.left().value();
+ }
+
+ private Resource createPNF() {
+
+ genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.PNF);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ when(genericTypeBusinessLogic.fetchDerivedFromGenericType(resource)).thenReturn(Either.left(genericPNF));
+ when(genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericPNF)).thenCallRealMethod();
+ when(genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericPNF.getProperties(), resource.getUniqueId())).thenCallRealMethod();
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isLeft());
+ return createResponse.left().value();
+ }
+
+
+ private Map<String, String> getGenericPropertiesByToscaName(String toscaName) {
+ HashMap<String, String> PNFProps = new HashMap<String, String>() {{
+ put("nf_function", "string");
+ put("nf_role", "string");
+ put("nf_type", "string");
+ }};
+
+ HashMap<String, String> CRProps = new HashMap<String, String>() {{
+ putAll(PNFProps);
+ put("nf_naming_code", "string");
+ put("nf_naming", "org.openecomp.datatypes.Naming");
+ }};
+
+ HashMap<String, String> VFProps = new HashMap<String, String>() {{
+ putAll(CRProps);
+ put("availability_zone_max_count", "integer");
+ put("min_instances", "integer");
+ put("max_instances", "integer");
+ }};
+
+ if (toscaName.contains("PNF")) return PNFProps;
+ if (toscaName.contains("CR")) return CRProps;
+ if (toscaName.contains("VF")) return VFProps;
+
+ return new HashMap<>();
+ }
+
+
private Resource setupGenericTypeMock(String toscaName) {
-
- Resource genericType = createResourceObject(true);
- genericType.setVersion("1.0");
- genericType.setToscaResourceName(toscaName);
- String[] propNames = {"nf_function", "nf_role", "nf_naming_code", "nf_type", "nf_naming", "availability_zone_max_count", "min_instances", "max_instances"};
- String[] propTypes = {"string", "string", "string", "string", "org.openecomp.datatypes.Naming", "integer", "integer", "integer"};
- List<PropertyDefinition> genericProps = new ArrayList<>();
- for(int i = 0; i < 8; ++i){
- PropertyDefinition prop = new PropertyDefinition();
- prop.setName(propNames[i]);
- prop.setType(propTypes[i]);
- genericProps.add(prop);
- }
- genericType.setProperties(genericProps);
- return genericType;
- }
-
-
-
+
+ Resource genericType = createResourceObject(true);
+ genericType.setVersion("1.0");
+ genericType.setToscaResourceName(toscaName);
+ List<PropertyDefinition> genericProps = new ArrayList<>();
+ Map<String, String> genericPropsMap = getGenericPropertiesByToscaName(toscaName);
+ genericPropsMap.forEach((name, type) -> {
+ PropertyDefinition prop = new PropertyDefinition();
+ prop.setName(name);
+ prop.setType(type);
+ genericProps.add(prop);
+ });
+
+ genericType.setProperties(genericProps);
+ return genericType;
+ }
+
+ private void validateUserRoles(Role... roles) {
+ List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
+ when(userValidations.validateUserRole(user, listOfRoles)).thenReturn(Either.left(true));
+ }
+
+
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java
index 581adb28df..3abf711b91 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java
@@ -20,16 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -53,6 +44,7 @@ import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ConfigurationSource;
@@ -61,252 +53,259 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
public class ResourceInstanceBusinessLogicTest {
- private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId";
- private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload";
- private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams";
- private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId";
- private static final String SERVICE_ID = "MyServiceId";
- private static final String HEAT_LABEL = "myHeat";
- private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env";
- private static final String USER_ID = "jh0003";
- private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis();
-
- static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null);
-
- @InjectMocks
- static ServiceComponentInstanceBusinessLogic bl = new ServiceComponentInstanceBusinessLogic();
-
- public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class);
- public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class);
-// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
- public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
- public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
- public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
-
- static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
- static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
-
- // @BeforeClass
- public static void setup() {
-
- Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
- Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME);
-
- ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true);
- Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>();
- artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact);
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts);
- Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact);
-
- ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false);
- Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>();
- artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload);
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload);
- Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload);
-
- ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false);
- Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>();
- artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams);
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams);
- Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams);
-
- Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL));
- Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder);
-
- Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class));
-
- Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false));
- Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact);
-
- Either<User, ActionStatus> eitherUser = Either.left(adminUser);
- Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser);
-
- Object lightService = new Service();
- Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService);
-// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService);
-
- Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class),
- Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class));
-
- Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false));
-
- Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class),
- Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither);
-
- Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>());
- Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft);
-
- bl.setToscaOperationFacade(toscaOperationFacade);
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status);
- Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status);
- Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status);
-
- }
-
- @Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
-// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager);
- setup();
- }
-
- @Test
- public void testAddResourceInstanceArtifacts() throws Exception {
- ComponentInstance resourceInstance = new ComponentInstance();
- resourceInstance.setName(RESOURCE_INSTANCE_ID);
- resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS);
- resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
- Service service = new Service();
- service.setUniqueId(SERVICE_ID);
-
- Map<String, String> existingEnvVersions = new HashMap<>();
- Resource originResource = new Resource();
- originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD);
- Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions);
- assertTrue(addArtifactsRes.isLeft());
-
- Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
-// assertTrue(deploymentArtifacts.size() == 2);
-
- ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase());
- assertNotNull(heatDefinition);
-// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition);
+ private static final String RESOURCE_ID_WITH_HEAT_PARAMS = "MyResourceId";
+ private static final String RESOURCE_ID_NO_PAYLOAD = "NoHeatPayload";
+ private static final String RESOURCE_ID_NO_HEAT_PARAMS = "NoHeatParams";
+ private static final String RESOURCE_INSTANCE_ID = "MyResourceInstanceId";
+ private static final String SERVICE_ID = "MyServiceId";
+ private static final String HEAT_LABEL = "myHeat";
+ private static final String HEAT_ENV_LABEL = HEAT_LABEL + "Env";
+ private static final String USER_ID = "jh0003";
+ private static final long ARTIFACT_CREATION_TIME = System.currentTimeMillis();
+
+ static User adminUser = new User("John", "Doh", USER_ID, "", "ADMIN", null);
+
+ @InjectMocks
+ static ComponentInstanceBusinessLogic bl = new ComponentInstanceBusinessLogic();
+
+ public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class);
+ public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class);
+// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
+ public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+ public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
+ public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+
+ static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
+ static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+
+ // @BeforeClass
+ public static void setup() {
+
+ Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
+ Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(ArtifactsBusinessLogic.HEAT_ENV_NAME);
+
+ ArtifactDefinition heatArtifact = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true);
+ Map<String, ArtifactDefinition> artifacts = new HashMap<String, ArtifactDefinition>();
+ artifacts.put(HEAT_LABEL.toLowerCase(), heatArtifact);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifact = Either.left(artifacts);
+ Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_WITH_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifact);
+
+ ArtifactDefinition heatArtifactNoPayload = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_PAYLOAD, HEAT_LABEL, ARTIFACT_CREATION_TIME, true, false);
+ Map<String, ArtifactDefinition> artifactsNoPayload = new HashMap<String, ArtifactDefinition>();
+ artifactsNoPayload.put(HEAT_LABEL.toLowerCase(), heatArtifactNoPayload);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoPayload = Either.left(artifactsNoPayload);
+ Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_PAYLOAD, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoPayload);
+
+ ArtifactDefinition heatArtifactNoParams = getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false);
+ Map<String, ArtifactDefinition> artifactsNoParams = new HashMap<String, ArtifactDefinition>();
+ artifactsNoParams.put(HEAT_LABEL.toLowerCase(), heatArtifactNoParams);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> eitherGetResourceArtifactNoParams = Either.left(artifactsNoParams);
+ Mockito.when(artifactBusinessLogic.getArtifacts(RESOURCE_ID_NO_HEAT_PARAMS, NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(eitherGetResourceArtifactNoParams);
+
+ Either<ArtifactDefinition, ResponseFormat> eitherPlaceHolder = Either.left(getArtifactPlaceHolder(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL));
+ Mockito.when(artifactBusinessLogic.createArtifactPlaceHolderInfo(RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL.toLowerCase(), placeHolderData, USER_ID, ArtifactGroupTypeEnum.DEPLOYMENT, false)).thenReturn(eitherPlaceHolder);
+
+ Mockito.when(artifactBusinessLogic.createArtifactAuditingFields(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString())).thenReturn(new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class));
+
+ Either<ArtifactDefinition, StorageOperationStatus> eitherArtifact = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false));
+ Mockito.when(artifactBusinessLogic.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(eitherArtifact);
+
+ Either<User, ActionStatus> eitherUser = Either.left(adminUser);
+ Mockito.when(userAdminManager.getUser(USER_ID, false)).thenReturn(eitherUser);
+
+ Object lightService = new Service();
+ Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService);
+
+ Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.any(AuditingActionEnum.class),
+ Mockito.any(ComponentTypeEnum.class), Mockito.any(ResourceAuditData.class));
+
+ Either<ArtifactDefinition, ResponseFormat> heatEnvEither = Either.left(getHeatArtifactDefinition(USER_ID, RESOURCE_INSTANCE_ID, HEAT_ENV_LABEL, ARTIFACT_CREATION_TIME, true, false));
+
+ Mockito.when(artifactBusinessLogic.createHeatEnvPlaceHolder(Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString(), Mockito.any(User.class),
+ Mockito.any(Component.class), Mockito.anyObject())).thenReturn(heatEnvEither);
+
+ Either<List<GroupInstance>, StorageOperationStatus> groupInstanceEitherLeft = Either.left(new ArrayList<GroupInstance>());
+ Mockito.when(groupInstanceOperation.getAllGroupInstances(Mockito.anyString(), Mockito.any(NodeTypeEnum.class))).thenReturn(groupInstanceEitherLeft);
+
+ bl.setToscaOperationFacade(toscaOperationFacade);
+
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status);
+ Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any())).thenReturn(status);
+ Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(), Mockito.any(Map.class))).thenReturn(status);
+
+ }
+
+ @Before
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager);
+ setup();
+ }
+
+ @Test
+ public void testAddResourceInstanceArtifacts() throws Exception {
+ ComponentInstance resourceInstance = new ComponentInstance();
+ resourceInstance.setName(RESOURCE_INSTANCE_ID);
+ resourceInstance.setComponentUid(RESOURCE_ID_WITH_HEAT_PARAMS);
+ resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
+ Service service = new Service();
+ service.setUniqueId(SERVICE_ID);
+
+ Map<String, String> existingEnvVersions = new HashMap<>();
+ Resource originResource = new Resource();
+ originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD);
+ Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions);
+ assertTrue(addArtifactsRes.isLeft());
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
+ assertNotNull(deploymentArtifacts);
+// assertTrue(deploymentArtifacts.size() == 2);
+
+ ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase());
+ assertNotNull(heatDefinition);
+// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_WITH_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, true), heatDefinition);
//
-// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase());
-// assertNotNull(heatEnvDefinition);
+// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase());
+// assertNotNull(heatEnvDefinition);
//
-// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters();
-// assertNotNull(heatParameters);
+// List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters();
+// assertNotNull(heatParameters);
//
-// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters();
-// assertNotNull(heatEnvParameters);
+// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters();
+// assertNotNull(heatEnvParameters);
//
-// assertEquals(heatParameters.size(), heatEnvParameters.size());
+// assertEquals(heatParameters.size(), heatEnvParameters.size());
//
-// int index = 0;
-// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) {
-// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index);
-// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId());
-// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType());
-// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName());
-// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription());
-// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue());
-// // current of heat parameter should be the default for heat env
-// // parameter
-// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue());
+// int index = 0;
+// for (HeatParameterDefinition heatEnvParameter : heatEnvParameters) {
+// HeatParameterDefinition heatParameterDefinition = heatParameters.get(index);
+// assertEquals(heatEnvParameter.getUniqueId(), heatParameterDefinition.getUniqueId());
+// assertEquals(heatEnvParameter.getType(), heatParameterDefinition.getType());
+// assertEquals(heatEnvParameter.getName(), heatParameterDefinition.getName());
+// assertEquals(heatEnvParameter.getDescription(), heatParameterDefinition.getDescription());
+// assertEquals(heatEnvParameter.getCurrentValue(), heatParameterDefinition.getCurrentValue());
+// // current of heat parameter should be the default for heat env
+// // parameter
+// assertEquals(heatEnvParameter.getDefaultValue(), heatParameterDefinition.getCurrentValue());
//
-// index++;
-// }
- }
-
- @Test
- public void testAddResourceInstanceArtifactsNoParams() throws Exception {
- ComponentInstance resourceInstance = new ComponentInstance();
- resourceInstance.setName(RESOURCE_INSTANCE_ID);
- resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS);
- resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
- Service service = new Service();
- service.setUniqueId(SERVICE_ID);
- Map<String, String> existingEnvVersions = new HashMap<>();
- Resource originResource = new Resource();
- originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD);
- Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions);
- assertTrue(addArtifactsRes.isLeft());
-
- Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
-// assertTrue(deploymentArtifacts.size() == 2);
-
- ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase());
- assertNotNull(heatDefinition);
-// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition);
-
-// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase());
-// assertNotNull(heatEnvDefinition);
-
- List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters();
- assertNull(heatParameters);
-
-// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters();
-// assertNull(heatEnvParameters);
-
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception {
- ComponentInstance resourceInstance = new ComponentInstance();
- resourceInstance.setName(RESOURCE_INSTANCE_ID);
- resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD);
- resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
- Service service = new Service();
- service.setUniqueId(SERVICE_ID);
- Map<String, String> existingEnvVersions = new HashMap<>();
- Resource originResource = new Resource();
- originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD);
-
- Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions);
- assertTrue(addArtifactsRes.isLeft());
-
- Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
- assertNotNull(deploymentArtifacts);
- assertTrue(deploymentArtifacts.size() == 0);
-
- Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString());
- }
-
- private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) {
- ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
- artifactInfo.setArtifactName(artifactName + ".yml");
- artifactInfo.setArtifactType("HEAT");
- artifactInfo.setDescription("hdkfhskdfgh");
- artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
-
- artifactInfo.setUserIdCreator(userId);
- String fullName = "Jim H";
- artifactInfo.setUpdaterFullName(fullName);
- // long time = System.currentTimeMillis();
- artifactInfo.setCreatorFullName(fullName);
- artifactInfo.setCreationDate(time);
- artifactInfo.setLastUpdateDate(time);
- artifactInfo.setUserIdLastUpdater(userId);
- artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase());
- artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()));
-
- if (!placeholderOnly) {
- artifactInfo.setEsId(artifactInfo.getUniqueId());
- artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz");
-
- if (withHeatParams) {
- List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
- HeatParameterDefinition heatParam = new HeatParameterDefinition();
- heatParam.setCurrentValue("11");
- heatParam.setDefaultValue("22");
- heatParam.setDescription("desc");
- heatParam.setName("myParam");
- heatParam.setType("number");
- heatParams.add(heatParam);
- artifactInfo.setListHeatParameters(heatParams);
- }
- }
-
- return artifactInfo;
- }
-
- private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) {
- ArtifactDefinition artifact = new ArtifactDefinition();
-
- artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase()));
- artifact.setArtifactLabel(logicalName.toLowerCase());
-
- return artifact;
- }
+// index++;
+// }
+ }
+
+ @Test
+ public void testAddResourceInstanceArtifactsNoParams() throws Exception {
+ ComponentInstance resourceInstance = new ComponentInstance();
+ resourceInstance.setName(RESOURCE_INSTANCE_ID);
+ resourceInstance.setComponentUid(RESOURCE_ID_NO_HEAT_PARAMS);
+ resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
+ Service service = new Service();
+ service.setUniqueId(SERVICE_ID);
+ Map<String, String> existingEnvVersions = new HashMap<>();
+ Resource originResource = new Resource();
+ originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD);
+ Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions);
+ assertTrue(addArtifactsRes.isLeft());
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
+ assertNotNull(deploymentArtifacts);
+// assertTrue(deploymentArtifacts.size() == 2);
+
+ ArtifactDefinition heatDefinition = deploymentArtifacts.get(HEAT_LABEL.toLowerCase());
+ assertNotNull(heatDefinition);
+// assertEquals(getHeatArtifactDefinition(USER_ID, RESOURCE_ID_NO_HEAT_PARAMS, HEAT_LABEL, ARTIFACT_CREATION_TIME, false, false), heatDefinition);
+
+// ArtifactDefinition heatEnvDefinition = deploymentArtifacts.get(HEAT_ENV_LABEL.toLowerCase());
+// assertNotNull(heatEnvDefinition);
+
+ List<HeatParameterDefinition> heatParameters = heatDefinition.getListHeatParameters();
+ assertNull(heatParameters);
+
+// List<HeatParameterDefinition> heatEnvParameters = heatEnvDefinition.getListHeatParameters();
+// assertNull(heatEnvParameters);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testAddResourceInstanceArtifactsNoArtifacts() throws Exception {
+ ComponentInstance resourceInstance = new ComponentInstance();
+ resourceInstance.setName(RESOURCE_INSTANCE_ID);
+ resourceInstance.setComponentUid(RESOURCE_ID_NO_PAYLOAD);
+ resourceInstance.setUniqueId(RESOURCE_INSTANCE_ID);
+ Service service = new Service();
+ service.setUniqueId(SERVICE_ID);
+ Map<String, String> existingEnvVersions = new HashMap<>();
+ Resource originResource = new Resource();
+ originResource.setUniqueId(RESOURCE_ID_NO_PAYLOAD);
+
+ Either<ActionStatus, ResponseFormat> addArtifactsRes = bl.addComponentInstanceArtifacts(service, resourceInstance, originResource, adminUser, existingEnvVersions);
+ assertTrue(addArtifactsRes.isLeft());
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceInstance.getDeploymentArtifacts();
+ assertNotNull(deploymentArtifacts);
+ assertTrue(deploymentArtifacts.size() == 0);
+
+ Mockito.verify(artifactBusinessLogic, Mockito.times(0)).addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString());
+ }
+
+ private static ArtifactDefinition getHeatArtifactDefinition(String userId, String resourceId, String artifactName, long time, boolean placeholderOnly, boolean withHeatParams) {
+ ArtifactDefinition artifactInfo = new ArtifactDefinition();
+
+ artifactInfo.setArtifactName(artifactName + ".yml");
+ artifactInfo.setArtifactType("HEAT");
+ artifactInfo.setDescription("hdkfhskdfgh");
+ artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
+
+ artifactInfo.setUserIdCreator(userId);
+ String fullName = "Jim H";
+ artifactInfo.setUpdaterFullName(fullName);
+ // long time = System.currentTimeMillis();
+ artifactInfo.setCreatorFullName(fullName);
+ artifactInfo.setCreationDate(time);
+ artifactInfo.setLastUpdateDate(time);
+ artifactInfo.setUserIdLastUpdater(userId);
+ artifactInfo.setArtifactLabel(HEAT_LABEL.toLowerCase());
+ artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()));
+
+ if (!placeholderOnly) {
+ artifactInfo.setEsId(artifactInfo.getUniqueId());
+ artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz");
+
+ if (withHeatParams) {
+ List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
+ HeatParameterDefinition heatParam = new HeatParameterDefinition();
+ heatParam.setCurrentValue("11");
+ heatParam.setDefaultValue("22");
+ heatParam.setDescription("desc");
+ heatParam.setName("myParam");
+ heatParam.setType("number");
+ heatParams.add(heatParam);
+ artifactInfo.setListHeatParameters(heatParams);
+ }
+ }
+
+ return artifactInfo;
+ }
+
+ private static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) {
+ ArtifactDefinition artifact = new ArtifactDefinition();
+
+ artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase()));
+ artifact.setArtifactLabel(logicalName.toLowerCase());
+
+ return artifact;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java
index 309689af45..5f4dfdc6f7 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogicTest.java
@@ -1,12 +1,6 @@
package org.openecomp.sdc.be.components.impl.generic;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-import java.util.List;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -20,7 +14,12 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class GenericTypeBusinessLogicTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java
new file mode 100644
index 0000000000..6b1b37e5bc
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtilsTest.java
@@ -0,0 +1,258 @@
+package org.openecomp.sdc.be.components.impl.utils;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.Test;
+import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
+import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+
+public class PolicyTypeImportUtilsTest {
+
+ private static final String UNIQUE_ID_EXSISTS = "uniqueId";
+
+ @Test
+ public void isPolicyTypesEquals_whenBothTypesAreNull_returnTrue() {
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, null)).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenOneTypeIsNull_returnFalse() {
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(new PolicyTypeDefinition(), null)).isFalse();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(null, new PolicyTypeDefinition())).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenTypesIsSameObject_returnTrue() {
+ PolicyTypeDefinition policyType = new PolicyTypeDefinition();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(policyType, policyType)).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_allFieldsEquals_returnTrue() {
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(createPolicyTypeWithAllFields(), createPolicyTypeWithAllFields())).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenTypesAreDifferentInANonCompareFields_returnTrue() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setOwnerId("ownerIdNew");
+ type2.setModificationTime(System.currentTimeMillis());
+ type2.setCreationTime(System.currentTimeMillis());
+ type2.setUniqueId("uniqueIdNew");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenTypeIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setType("newType");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenDescriptionIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setDescription("newDescription");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenTargetsAreDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setTargets(new ArrayList<>());
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenDerivedFromIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setDerivedFrom("newDerivedFrom");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenVersionIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setVersion("2.0");
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypesEquals_whenMetadataIsDifferent_returnFalse() {
+ PolicyTypeDefinition type1 = createPolicyTypeWithAllFields();
+ PolicyTypeDefinition type2 = createPolicyTypeWithAllFields();
+ type2.setMetadata(ImmutableMap.of("newKey", "newVal"));
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesListNotOfSameSize_returnFalse() {
+ PolicyTypeDefinition noProperties = new PolicyTypeDefinition();
+ PolicyTypeDefinition emptyProperties = new PolicyTypeBuilder().setProperties(Collections.emptyList()).build();
+ PolicyTypeDefinition oneProp = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build();
+ PolicyTypeDefinition twoProps = new PolicyTypeBuilder().setProperties(Arrays.asList(createPropertyDefinitionWithAllFields("prop1"),
+ createPropertyDefinitionWithAllFields("prop2")))
+ .build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(noProperties, oneProp)).isFalse();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(emptyProperties, oneProp)).isFalse();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(twoProps, oneProp)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesSamePropertiesList_returnTrue() {
+ List<PropertyDefinition> propList = Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"));
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(propList).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(propList).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesListFieldsEquals_returnTrue() {
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesListDifferentInANonComparedFields_returnTrue() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1DiffNonComparedFields = createPropertyDefinitionWithAllFields("prop1");
+ prop1DiffNonComparedFields.setOwnerId("newOwner");
+ prop1DiffNonComparedFields.setValue("newVal");
+ prop1DiffNonComparedFields.setConstraints(null);
+ prop1DiffNonComparedFields.setUniqueId("newId");
+ prop1DiffNonComparedFields.setHidden(true);
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffNonComparedFields)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isTrue();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesNotOfSameName_returnFalse() {
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop1"))).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(createPropertyDefinitionWithAllFields("prop2"))).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesNotOFSameType_returnFalse() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1TypeInteger = createPropertyDefinitionWithAllFields("prop1");
+ prop1TypeInteger.setType("integer");
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1TypeInteger)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesNotOfSameDefaultVal_returnFalse() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1DiffDefault = createPropertyDefinitionWithAllFields("prop1");
+ prop1DiffDefault.setDefaultValue("newDefVal");
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDefault)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesNotOfSameSchema_returnFalse() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1DiffSchema = createPropertyDefinitionWithAllFields("prop1");
+ prop1DiffSchema.setSchema(null);
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffSchema)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesIsPasswordFieldNotSame_returnFalse() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1DiffIsPassword = createPropertyDefinitionWithAllFields("prop1");
+ prop1DiffIsPassword.setPassword(!prop1.isPassword());
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsPassword)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesIsRequiredFieldNotSame_returnFalse() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1DiffIsRequired = createPropertyDefinitionWithAllFields("prop1");
+ prop1DiffIsRequired.setRequired(!prop1.isRequired());
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffIsRequired)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ @Test
+ public void isPolicyTypeEquals_whenPropertiesNotSameDescription_returnFalse() {
+ PropertyDefinition prop1 = createPropertyDefinitionWithAllFields("prop1");
+ PropertyDefinition prop1DiffDescription = createPropertyDefinitionWithAllFields("prop1");
+ prop1DiffDescription.setDescription("newDescription");
+
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1)).build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setProperties(Collections.singletonList(prop1DiffDescription)).build();
+ assertThat(PolicyTypeImportUtils.isPolicyTypesEquals(type1, type2)).isFalse();
+ }
+
+ private PolicyTypeDefinition createPolicyTypeWithAllFields() {
+ return new PolicyTypeBuilder()
+ .setType("type1")
+ .setDerivedFrom("derivedFrom")
+ .setVersion("1.0")
+ .setDescription("description")
+ .setUniqueId("id1")
+ .setHighestVersion(true)
+ .setModificationTime(System.currentTimeMillis())
+ .setCreationTime(System.currentTimeMillis())
+ .setTargets(getTargets())
+ .setOwner("owner")
+ .setMetadata(ImmutableMap.of("key1", "val1", "key2", "val2"))
+ .build();
+ }
+
+ private PropertyDefinition createPropertyDefinitionWithAllFields(String name) {
+ return new PropertyDataDefinitionBuilder()
+ .setConstraints(Arrays.asList(new GreaterThanConstraint("abc"), new MinLengthConstraint(5)))
+ .setUniqueId("uid")
+ .setDefaultValue("val1")
+ .setType("string")
+ .setValue("val1")
+ .setName(name)
+ .setSchemaType("string")
+ .setOwnerId("owner")
+ .setStatus("status")
+ .setDescription("description")
+ .setIsPassword(false)
+ .setIsRequired(false)
+ .build();
+ }
+
+ private List<String> getTargets() {
+
+ return Collections.singletonList(UNIQUE_ID_EXSISTS);
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java
new file mode 100644
index 0000000000..0dac6ecb2b
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/utils/TestGenerationUtils.java
@@ -0,0 +1,20 @@
+package org.openecomp.sdc.be.components.impl.utils;
+
+import org.mockito.Mockito;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+
+public class TestGenerationUtils {
+
+ public static ComponentsUtils getComponentsUtils() {
+ ExternalConfiguration.setAppName("catalog-be");
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ return new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java
new file mode 100644
index 0000000000..fe6071239e
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/GroupMembersUpdateOperationTest.java
@@ -0,0 +1,152 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
+import org.openecomp.sdc.be.components.utils.GroupDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Stream;
+
+import static java.util.Collections.emptyMap;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class GroupMembersUpdateOperationTest {
+
+ private static final String CONTAINER_ID = "containerId";
+ private static final String INSTANCE_ID_PRE_CHANGE = "inst2";
+ private static final String INSTANCE_ID_POST_CHANGE = "newInst2";
+ @InjectMocks
+ private GroupMembersUpdateOperation testInstance;
+ @Mock
+ private GroupsOperation groupsOperation;
+ @Mock
+ private ComponentsUtils componentsUtils;
+
+ @Captor
+ private ArgumentCaptor<List<GroupDataDefinition>> updatedGroupsCaptor;
+ private GroupDefinition group1, group2, group3;
+ private Resource container;
+ private ComponentInstance prevInst2Version, currInst2Version;
+ private static final ComponentInstance DONT_CARE = new ComponentInstance();
+
+ @Before
+ public void setUp() throws Exception {
+ group1 = createGroupWithMembers("group1", "inst1", INSTANCE_ID_PRE_CHANGE);
+ group2 = createGroupWithMembers("group2", "inst1", "inst2", "inst3");
+ group3 = createGroupWithMembers("group3", "inst1", "inst3");
+ container = new ResourceBuilder()
+ .addGroups(group1)
+ .addGroups(group2)
+ .setUniqueId(CONTAINER_ID)
+ .setComponentType(ComponentTypeEnum.RESOURCE)
+ .build();
+ prevInst2Version = new ComponentInstanceBuilder()
+ .setId(INSTANCE_ID_PRE_CHANGE)
+ .build();
+ currInst2Version = new ComponentInstanceBuilder()
+ .setId(INSTANCE_ID_POST_CHANGE)
+ .build();
+ }
+
+ @Test
+ public void whenNoGroupsOnContainer_returnOk() {
+ ActionStatus actionStatus = testInstance.onChangeVersion(new Resource(), DONT_CARE, DONT_CARE);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void whenEmptyListOfGroups_returnOk() {
+ Resource resource = new Resource();
+ resource.setGroups(new ArrayList<>());
+ ActionStatus actionStatus = testInstance.onChangeVersion(resource, DONT_CARE, DONT_CARE);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void whenGroupsHasNoMembers_returnOk() {
+ GroupDefinition group1 = new GroupDefinition();
+ group1.setMembers(emptyMap());
+ GroupDefinition group2 = new GroupDefinition();
+ group2.setMembers(emptyMap());
+ Resource container = new ResourceBuilder()
+ .addGroups(group1)
+ .addGroups(group2)
+ .build();
+ ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("inst1").build();
+ ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void whenPrevInstanceIsNotAMemberOfAnyGroup_returnOk() {
+ ComponentInstance prevInstance = new ComponentInstanceBuilder().setId("nonMemberInst").build();
+ ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInstance, DONT_CARE);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+ @Test
+ public void whenGroupHasPrevInstanceAsMember_replaceWithNewInstanceId_updateReplacedGroups() {
+ verifyAllGroupsHasPrevInstancesAsMembers();
+ when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.left(null));
+ ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verifyGroupWithPrevInstanceMemberWereReplaced();
+ assertThat(updatedGroupsCaptor.getValue())
+ .containsExactlyInAnyOrder(group1, group2);
+ }
+
+ @Test
+ public void whenFailingToUpdateGroups_propagateError() {
+ when(groupsOperation.updateGroups(eq(container), updatedGroupsCaptor.capture())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, ComponentTypeEnum.RESOURCE)).thenCallRealMethod();
+ ActionStatus actionStatus = testInstance.onChangeVersion(container, prevInst2Version, currInst2Version);
+ assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ private void verifyGroupWithPrevInstanceMemberWereReplaced() {
+ assertGroupMembersIds(group1, "inst1", INSTANCE_ID_POST_CHANGE);
+ assertGroupMembersIds(group2, "inst1", INSTANCE_ID_POST_CHANGE, "inst3");
+ assertGroupMembersIds(group3, "inst1", "inst3");
+ }
+
+ private void verifyAllGroupsHasPrevInstancesAsMembers() {
+ assertGroupMembersIds(group1, "inst1", INSTANCE_ID_PRE_CHANGE);
+ assertGroupMembersIds(group2, "inst1", INSTANCE_ID_PRE_CHANGE, "inst3");
+ assertGroupMembersIds(group3, "inst1", "inst3");
+ }
+
+ private void assertGroupMembersIds(GroupDefinition group, String ... expectedMembersIds) {
+ assertThat(group.getMembers())
+ .containsValues(expectedMembersIds);
+ }
+
+ private GroupDefinition createGroupWithMembers(String groupId, String ... membersIds) {
+ GroupDefinitionBuilder groupDefinitionBuilder = GroupDefinitionBuilder.create();
+ Stream.of(membersIds).forEach(memberId -> groupDefinitionBuilder.addMember(memberId + "name", memberId));
+ groupDefinitionBuilder.setUniqueId(groupId);
+ return groupDefinitionBuilder.build();
+ }
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java
new file mode 100644
index 0000000000..0da59d1157
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PolicyTargetsUpdateOperationTest.java
@@ -0,0 +1,127 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
+import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+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 java.util.List;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.components.impl.utils.TestGenerationUtils.getComponentsUtils;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PolicyTargetsUpdateOperationTest {
+
+ private static final String CONTAINER_ID = "containerId";
+
+ private PolicyTargetsUpdateOperation policyTargetsUpdateOperation;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Captor
+ private ArgumentCaptor<List<PolicyDefinition>> updatedPoliciesCaptor;
+ private PolicyDefinition policy1, policy2, policy3;
+ private Resource container;
+
+ @Before
+ public void setUp() throws Exception {
+ policy1 = createPolicyWithCmptInstAsTargets("policy1", "inst1", "inst2");
+ policy2 = createPolicyWithCmptInstAsTargets("policy2", "inst1", "inst2", "inst3");
+ policy3 = createPolicyWithCmptInstAsTargets("policy3", "inst1", "inst3");
+ container = new ResourceBuilder()
+ .addPolicy(policy1)
+ .addPolicy(policy2)
+ .addPolicy(policy3)
+ .setUniqueId(CONTAINER_ID)
+ .build();
+ policyTargetsUpdateOperation = new PolicyTargetsUpdateOperation(toscaOperationFacade, getComponentsUtils());
+ }
+
+ @Test
+ public void whenNoPolicies_returnActionOk() {
+ Component container = new Resource();
+ ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build();
+ ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build();
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion);
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void whenNoCmptInstancePolicies_returnOk() {
+ PolicyDefinition policy = PolicyDefinitionBuilder.create().addGroupTarget("someGroup").build();
+ Component container = new ResourceBuilder().addPolicy(policy).build();
+ ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build();
+ ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build();
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion);
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void whenNoPoliciesWithPrevInstanceAsTarget_returnActionOk() {
+ ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("prevVersion").build();
+ ComponentInstance newVersion = new ComponentInstanceBuilder().setId("newVersion").build();
+ ActionStatus operationStatus = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion);
+ assertThat(operationStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void replacePrevCmptInstanceIdWithNewInstanceIdAndUpdatePolicies() {
+ ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build();
+ ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build();
+ when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), updatedPoliciesCaptor.capture())).thenReturn(StorageOperationStatus.OK);
+ ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion);
+ assertThat(updatePoliciesRes).isEqualTo(ActionStatus.OK);
+ List<PolicyDefinition> updatedPolicies = updatedPoliciesCaptor.getValue();
+ verifyUpdatedPolicies(updatedPolicies, policy1, policy2);//policy3 does not have "inst2" as target, no update needed
+ verifyUpdatedPolicyTargets(policy1, "inst1", "inst2New");
+ verifyUpdatedPolicyTargets(policy2, "inst1", "inst2New", "inst3");
+ }
+
+ @Test
+ public void whenUpdateOfPoliciesFails_propagateTheFailure() {
+ ComponentInstance prevVersion = new ComponentInstanceBuilder().setId("inst2").build();
+ ComponentInstance newVersion = new ComponentInstanceBuilder().setId("inst2New").build();
+ when(toscaOperationFacade.updatePoliciesOfComponent(eq(CONTAINER_ID), anyList())).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ ActionStatus updatePoliciesRes = policyTargetsUpdateOperation.onChangeVersion(container, prevVersion, newVersion);
+ assertThat(updatePoliciesRes).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
+ private void verifyUpdatedPolicyTargets(PolicyDefinition updatedPolicy, String ... expectedCmptInstanceTargetIds) {
+ assertThat(updatedPolicy.resolveComponentInstanceTargets())
+ .containsExactlyInAnyOrder(expectedCmptInstanceTargetIds);
+ }
+
+ private void verifyUpdatedPolicies(List<PolicyDefinition> updatedPolicies, PolicyDefinition ... expectedUpdatedPolicies) {
+ assertThat(updatedPolicies)
+ .usingElementComparatorOnFields("targets")
+ .containsExactlyInAnyOrder(expectedUpdatedPolicies);
+ }
+
+ private PolicyDefinition createPolicyWithCmptInstAsTargets(String uniqueId, String ... instId) {
+ PolicyDefinitionBuilder policyDefinitionBuilder = PolicyDefinitionBuilder.create();
+ Stream.of(instId).forEach(policyDefinitionBuilder::addComponentInstanceTarget);
+ return policyDefinitionBuilder.setUniqueId(uniqueId).build();
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java
new file mode 100644
index 0000000000..ef239f9a2b
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/version/PostChangeVersionOperationOrchestratorTest.java
@@ -0,0 +1,80 @@
+package org.openecomp.sdc.be.components.impl.version;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PostChangeVersionOperationOrchestratorTest {
+
+ private PostChangeVersionOperationOrchestrator testInstance;
+ @Mock
+ private PostChangeVersionOperation postChangeVersionOperation1;
+ @Mock
+ private PostChangeVersionOperation postChangeVersionOperation2;
+ @Mock
+ private PostChangeVersionOperation postChangeVersionOperation3;
+
+ @Before
+ public void setUp() throws Exception {
+ testInstance = new PostChangeVersionOperationOrchestrator(asList(postChangeVersionOperation1, postChangeVersionOperation2, postChangeVersionOperation3));
+ }
+
+ @Test
+ public void whenFirstPostOperationFails_doNotRunFollowingOperations() {
+ ComponentInstance newVersion = new ComponentInstance();
+ ComponentInstance prevVersion = new ComponentInstance();
+ Resource container = new Resource();
+ when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ verifyZeroInteractions(postChangeVersionOperation2, postChangeVersionOperation3);
+ }
+
+ @Test
+ public void whenAnyPostOperationFails_doNotRunFollowingOperations() {
+ ComponentInstance newVersion = new ComponentInstance();
+ ComponentInstance prevVersion = new ComponentInstance();
+ Resource container = new Resource();
+ when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK);
+ when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ verifyZeroInteractions(postChangeVersionOperation3);
+ }
+
+ @Test
+ public void whenLastPostOperationFails_returnTheFailureResult() {
+ ComponentInstance newVersion = new ComponentInstance();
+ ComponentInstance prevVersion = new ComponentInstance();
+ Resource container = new Resource();
+ when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK);
+ when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK);
+ when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void whenAllOperationsSucceeds_returnOk() {
+ ComponentInstance newVersion = new ComponentInstance();
+ ComponentInstance prevVersion = new ComponentInstance();
+ Resource container = new Resource();
+ when(postChangeVersionOperation1.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK);
+ when(postChangeVersionOperation2.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK);
+ when(postChangeVersionOperation3.onChangeVersion(container, prevVersion, newVersion)).thenReturn(ActionStatus.OK);
+ ActionStatus actionStatus = testInstance.doPostChangeVersionOperations(container, prevVersion, newVersion);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ }
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java
index 31c795478a..cfb5bb59e0 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransitionTest.java
@@ -20,14 +20,11 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
@@ -35,139 +32,138 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
public class CertificationChangeTransitionTest extends LifecycleTestBase {
- private CertificationChangeTransition certifyTransitionObj = null;
- private CertificationChangeTransition certificationCancelObj = null;
- private CertificationChangeTransition certificationFailObj = null;
-
- private ComponentsUtils componentsUtils = new ComponentsUtils();
- private User owner = null;
-
- Resource resource;
-
- @SuppressWarnings("unchecked")
- @Before
- public void setup() {
-
- super.setup();
- componentsUtils.Init();
- // checkout transition object
- certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
- certifyTransitionObj.setConfigurationManager(configurationManager);
- certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation);
-
- certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
- certificationCancelObj.setConfigurationManager(configurationManager);
- certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation);
-
- certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
- certificationFailObj.setConfigurationManager(configurationManager);
- certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation);
-
- owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null);
-
- resource = createResourceObject();
- }
-
- @Test
- public void testVFCMTStateValidation(){
- Resource resource = createResourceVFCMTObject();
-
- User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null);
-
- Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(validateBeforeTransition.isLeft(), true);
- }
-
- @Test
- public void testStateValidationSuccess() {
-
- Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(changeStateResult.isLeft(), true);
-
- }
-
- @Test
- public void testStateValidationFail() {
-
- // checkout
- Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
- assertValidationStateErrorResponse(validateBeforeTransition);
-
- // checkin
- validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertValidationStateErrorResponse(validateBeforeTransition);
-
- // rfc
- validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertValidationStateErrorResponse(validateBeforeTransition);
-
- // certified
- validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
- assertValidationStateErrorResponse(validateBeforeTransition);
-
- }
-
- @Test
- public void testRolesFail() {
- Either<Resource, ResponseFormat> changeStateResult;
-
- resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
- modifier.setRole(Role.DESIGNER.name());
- Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
-
- Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION);
-
- modifier.setRole(Role.TESTER.name());
- validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testRolesSuccess() {
-
- resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
-
- Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(true, validateBeforeTransition.isLeft());
-
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
- modifier.setRole(Role.ADMIN.name());
- validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(true, validateBeforeTransition.isLeft());
-
- }
-
- private void assertValidationStateErrorResponse(Either<Boolean, ResponseFormat> validateBeforeTransition) {
- assertEquals(validateBeforeTransition.isRight(), true);
- ResponseFormat error = validateBeforeTransition.right().value();
- Either<Resource, ResponseFormat> changeStateResult = Either.right(error);
- assertEquals(changeStateResult.isRight(), true);
-
- assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
- }
+ private CertificationChangeTransition certifyTransitionObj = null;
+ private CertificationChangeTransition certificationCancelObj = null;
+ private CertificationChangeTransition certificationFailObj = null;
+
+ private User owner = null;
+
+ Resource resource;
+
+ @SuppressWarnings("unchecked")
+ @Before
+ public void setup() {
+
+ super.setup();
+ // checkout transition object
+ certifyTransitionObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ certifyTransitionObj.setConfigurationManager(configurationManager);
+ certifyTransitionObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+
+ certificationCancelObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ certificationCancelObj.setConfigurationManager(configurationManager);
+ certificationCancelObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+
+ certificationFailObj = new CertificationChangeTransition(LifeCycleTransitionEnum.CERTIFY, componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ certificationFailObj.setConfigurationManager(configurationManager);
+ certificationFailObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+
+ owner = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null);
+
+ resource = createResourceObject();
+ }
+
+ @Test
+ public void testVFCMTStateValidation(){
+ Resource resource = createResourceVFCMTObject();
+
+ User user = new User("cs0008", "Carlos", "Santana", "cs@sdc.com", "DESIGNER", null);
+
+ Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(validateBeforeTransition.isLeft(), true);
+ }
+
+ @Test
+ public void testStateValidationSuccess() {
+
+ Either<Boolean, ResponseFormat> changeStateResult = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(changeStateResult.isLeft(), true);
+
+ }
+
+ @Test
+ public void testStateValidationFail() {
+
+ // checkout
+ Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ assertValidationStateErrorResponse(validateBeforeTransition);
+
+ // checkin
+ validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ assertValidationStateErrorResponse(validateBeforeTransition);
+
+ // rfc
+ validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ assertValidationStateErrorResponse(validateBeforeTransition);
+
+ // certified
+ validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
+ assertValidationStateErrorResponse(validateBeforeTransition);
+
+ }
+
+ @Test
+ public void testRolesFail() {
+ Either<Resource, ResponseFormat> changeStateResult;
+
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+ modifier.setRole(Role.DESIGNER.name());
+ Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+
+ Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION);
+
+ modifier.setRole(Role.TESTER.name());
+ validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testRolesSuccess() {
+
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ Either<User, ResponseFormat> ownerResponse = certifyTransitionObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+
+ Either<Boolean, ResponseFormat> validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, owner, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(true, validateBeforeTransition.isLeft());
+
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+ modifier.setRole(Role.ADMIN.name());
+ validateBeforeTransition = certifyTransitionObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(true, validateBeforeTransition.isLeft());
+
+ }
+
+ private void assertValidationStateErrorResponse(Either<Boolean, ResponseFormat> validateBeforeTransition) {
+ assertEquals(validateBeforeTransition.isRight(), true);
+ ResponseFormat error = validateBeforeTransition.right().value();
+ Either<Resource, ResponseFormat> changeStateResult = Either.right(error);
+ assertEquals(changeStateResult.isRight(), true);
+
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_NOT_READY_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java
index 5530d4c0f5..f9fb9c83c1 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.List;
-
+import fj.data.Either;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -38,7 +32,6 @@ import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionAr
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -55,215 +48,219 @@ import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.Silent.class)
public class CertificationRequestTest extends LifecycleTestBase {
- private ComponentsUtils componentsUtils = new ComponentsUtils();
- @Mock
- private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
- @Mock
- private ServiceBusinessLogic serviceBusinessLogic;
- @Mock
- private CapabilityOperation capabilityOperation;
- @Mock
- private ToscaExportHandler toscaExportUtils;
-
- private CertificationRequestTransition rfcObj;
-
-
- @Before
- public void setup() {
- super.setup();
- rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
- // checkout transition object
-// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation);
- // checkoutObj.setAuditingManager(iAuditingManager);
- rfcObj.setConfigurationManager(configurationManager);
- componentsUtils.Init();
-
-// Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation);
-// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either);
- }
-
- @Test
- public void testVFCMTStateValidation(){
- Either<? extends Component, ResponseFormat> changeStateResult;
- Resource resource = createResourceVFCMTObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
-
- User user = new User();
- user.setUserId("cs0008");
- user.setFirstName("Carlos");
- user.setLastName("Santana");
- user.setRole(Role.TESTER.name());
-
- changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false);
- assertEquals(changeStateResult.isLeft(), true);
- }
-
- @Test
- public void testCheckoutStateValidation() {
- Either<? extends Component, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- // changeStateResult = rfcObj.changeStateOperation(resource, user,
- // owner, false);
- changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false);
- assertEquals(changeStateResult.isLeft(), true);
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- // changeStateResult = rfcObj.changeStateOperation(resource, user,
- // owner, false);
- changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false);
- assertEquals(changeStateResult.isLeft(), true);
- }
-
- @Test
- public void testAlreadyRfc() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testCertificationInProgress() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testAlreadyCertified() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() {
- Resource resource = new Resource();
- Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
- assertTrue(validateAllResourceInstanceCertified.isLeft());
- }
-
- @Test
- public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() {
- Resource resource = new Resource();
- List<ComponentInstance> riList = new ArrayList<ComponentInstance>();
- ComponentInstance ri = new ComponentInstance();
- ri.setComponentVersion("2.0");
- riList.add(ri);
- resource.setComponentInstances(riList);
-
- Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
- assertTrue(validateAllResourceInstanceCertified.isLeft());
- }
-
- @Test
- public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() {
- Resource resource = createVFWithRI("0.3");
-
- simulateCertifiedVersionExistForRI();
-
- Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
-
- assertTrue(validateAllResourceInstanceCertified.isRight());
- ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value();
- assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN);
- assertTrue(responseFormat.getMessageId().equals("SVC4559"));
-
- }
-
- @Test
- public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() {
- Resource resource = createVFWithRI("1.3");
-
- simulateCertifiedVersionExistForRI();
-
- Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
-
- assertTrue(validateAllResourceInstanceCertified.isRight());
- ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value();
- assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN);
- assertTrue(responseFormat.getMessageId().equals("SVC4559"));
-
- }
-
- @Test
- public void testDeploymentArtifactRestriction() {
- Either<? extends Component, ResponseFormat> changeStateResult;
- Service service = createServiceObject(false);
- service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
- Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
-
- Either<Service, ResponseFormat> result = Either.left(service);
- Either<ToscaElement, StorageOperationStatus> reqCertRes = Either.left(ModelConverter.convertToToscaElement(service));
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition()));
- when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false)).thenReturn(result);
- when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false)).thenReturn(result);
- when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts);
- when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes);
- changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, false);
- assertEquals(changeStateResult.isLeft(), true);
- }
-
- private void simulateCertifiedVersionExistForRI() {
- Component dummyResource = new Resource();
- Either<Component, StorageOperationStatus> result = Either.left(dummyResource);
- Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource));
- Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.class))).thenReturn(result);
- }
-
- private Resource createVFWithRI(String riVersion) {
- Resource resource = new Resource();
- List<ComponentInstance> riList = new ArrayList<ComponentInstance>();
- ComponentInstance ri = new ComponentInstance();
-
- ri.setComponentVersion(riVersion);
- ri.setComponentUid("someUniqueId");
- riList.add(ri);
- resource.setComponentInstances(riList);
- return resource;
- }
+ @Mock
+ private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
+ @Mock
+ private ServiceBusinessLogic serviceBusinessLogic;
+ @Mock
+ private CapabilityOperation capabilityOperation;
+ @Mock
+ private ToscaExportHandler toscaExportUtils;
+
+ private CertificationRequestTransition rfcObj;
+
+
+ @Before
+ public void setup() {
+ super.setup();
+ rfcObj = new CertificationRequestTransition(componentsUtils, toscaElementLifecycleOperation, serviceDistributionArtifactsBuilder, serviceBusinessLogic, capabilityOperation, toscaExportUtils, toscaOperationFacade, titanDao);
+ // checkout transition object
+// rfcObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+ // checkoutObj.setAuditingManager(iAuditingManager);
+ rfcObj.setConfigurationManager(configurationManager);
+
+// Either<ToscaRepresentation, ToscaError> either = Either.left(toscaRepresentation);
+// when(toscaExportUtils.exportComponent(Mockito.any())).thenReturn(either);
+
+ }
+
+ @Test
+ public void testVFCMTStateValidation(){
+ Either<? extends Component, ResponseFormat> changeStateResult;
+ Resource resource = createResourceVFCMTObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+
+ User user = new User();
+ user.setUserId("cs0008");
+ user.setFirstName("Carlos");
+ user.setLastName("Santana");
+ user.setRole(Role.TESTER.name());
+
+ changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false);
+ assertEquals(changeStateResult.isLeft(), true);
+ }
+
+ @Test
+ public void testCheckoutStateValidation() {
+ Either<? extends Component, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ // changeStateResult = rfcObj.changeStateOperation(resource, user,
+ // owner, false);
+ changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false);
+ assertEquals(changeStateResult.isLeft(), true);
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // changeStateResult = rfcObj.changeStateOperation(resource, user,
+ // owner, false);
+ changeStateResult = rfcObj.changeState(ComponentTypeEnum.RESOURCE, resource, serviceBusinessLogic, user, owner, false, false);
+ assertEquals(changeStateResult.isLeft(), true);
+ }
+
+ @Test
+ public void testAlreadyRfc() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testCertificationInProgress() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testAlreadyCertified() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ Either<Boolean, ResponseFormat> validateBeforeTransition = rfcObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CERTIFIED, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testValidateAllResourceInstanceCertified_SuccessWithoutRI() {
+ Resource resource = new Resource();
+ Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
+ assertTrue(validateAllResourceInstanceCertified.isLeft());
+ }
+
+ @Test
+ public void testValidateAllResourceInstanceCertified_SuccessWithCertifiedResources() {
+ Resource resource = new Resource();
+ List<ComponentInstance> riList = new ArrayList<ComponentInstance>();
+ ComponentInstance ri = new ComponentInstance();
+ ri.setComponentVersion("2.0");
+ riList.add(ri);
+ resource.setComponentInstances(riList);
+
+ Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
+ assertTrue(validateAllResourceInstanceCertified.isLeft());
+ }
+
+ @Test
+ public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMinorVersion() {
+ Resource resource = createVFWithRI("0.3");
+
+ simulateCertifiedVersionExistForRI();
+
+ Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
+
+ assertTrue(validateAllResourceInstanceCertified.isRight());
+ ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value();
+ assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN);
+ assertTrue(responseFormat.getMessageId().equals("SVC4559"));
+
+ }
+
+ @Test
+ public void testValidateAllResourceInstanceCertified_FailWithUnCertifiedResourcesMajorVersion() {
+ Resource resource = createVFWithRI("1.3");
+
+ simulateCertifiedVersionExistForRI();
+
+ Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified = rfcObj.validateAllResourceInstanceCertified(resource);
+
+ assertTrue(validateAllResourceInstanceCertified.isRight());
+ ResponseFormat responseFormat = validateAllResourceInstanceCertified.right().value();
+ assertTrue(responseFormat.getStatus() == HttpStatus.SC_FORBIDDEN);
+ assertTrue(responseFormat.getMessageId().equals("SVC4559"));
+
+ }
+
+ @Test
+ public void testDeploymentArtifactRestriction() {
+ Either<? extends Component, ResponseFormat> changeStateResult;
+ Service service = createServiceObject();
+ service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ Either<User, ResponseFormat> ownerResponse = rfcObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+
+ Either<Service, ResponseFormat> result = Either.left(service);
+ Either<ToscaElement, StorageOperationStatus> reqCertRes = Either.left(ModelConverter.convertToToscaElement(service));
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultArtifacts = Either.left(Either.left(new ArtifactDefinition()));
+ when(serviceBusinessLogic.generateHeatEnvArtifacts(service, owner, false, true)).thenReturn(result);
+ when(serviceBusinessLogic.generateVfModuleArtifacts(service, owner, false, true)).thenReturn(result);
+ when(serviceBusinessLogic.populateToscaArtifacts(service, owner, true, false, false)).thenReturn(resultArtifacts);
+ when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(reqCertRes);
+ changeStateResult = rfcObj.changeState(ComponentTypeEnum.SERVICE, service, serviceBusinessLogic, user, owner, false, true);
+ assertEquals(changeStateResult.isLeft(), true);
+ }
+
+ private void simulateCertifiedVersionExistForRI() {
+ Component dummyResource = new Resource();
+ Either<Component, StorageOperationStatus> result = Either.left(dummyResource);
+ Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.left(dummyResource));
+ Mockito.when(toscaOperationFacade.findLastCertifiedToscaElementByUUID(Mockito.any(Component.class))).thenReturn(result);
+ }
+
+ private Resource createVFWithRI(String riVersion) {
+ Resource resource = new Resource();
+ List<ComponentInstance> riList = new ArrayList<ComponentInstance>();
+ ComponentInstance ri = new ComponentInstance();
+
+ ri.setComponentVersion(riVersion);
+ ri.setComponentUid("someUniqueId");
+ riList.add(ri);
+ resource.setComponentInstances(riList);
+ return resource;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java
index 21111ef59e..e60998b177 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckinTest.java
@@ -20,14 +20,11 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
@@ -35,135 +32,133 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
public class CheckinTest extends LifecycleTestBase {
- private CheckinTransition checkinObj = null;
- private ComponentsUtils componentsUtils = new ComponentsUtils();
-
- @Before
- public void setup() {
-
- super.setup();
-
- // checkout transition object
- checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
- checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation);
- checkinObj.setConfigurationManager(configurationManager);
- componentsUtils.Init();
- }
-
- @Test
- public void testSimpleCheckin() {
- Either<Boolean, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(changeStateResult.isLeft(), true);
-
- }
-
- @Test
- public void testSimpleServiceCheckin() {
- Either<Boolean, ResponseFormat> changeStateResult;
- Service service = createServiceObject(false);
-
- service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(changeStateResult.isLeft(), true);
-
- }
-
- @Test
- public void testCheckinTwiceValidation() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(owner.isLeft());
- // changeStateResult = checkinObj.changeStateOperation(resource, user,
- // owner.left().value());
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
-
- assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testServiceCheckinTwiceValidation() {
- Either<Service, ResponseFormat> changeStateResult;
- Service service = createServiceObject(false);
-
- service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
- assertTrue(owner.isLeft());
-
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
-
- assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testCheckoutByAnotherUserValidation() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
- modifier.setRole(Role.DESIGNER.name());
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- // changeStateResult = checkinObj.changeStateOperation(resource,
- // modifier, owner);
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
-
- assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testServiceCheckoutByAnotherUserValidation() {
- Either<Service, ResponseFormat> changeStateResult;
- Service service = createServiceObject(false);
-
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
- modifier.setRole(Role.DESIGNER.name());
-
- service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
-
- assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
+ private CheckinTransition checkinObj = null;
+
+ @Before
+ public void setup() {
+
+ super.setup();
+ // checkout transition object
+ checkinObj = new CheckinTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ checkinObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+ checkinObj.setConfigurationManager(configurationManager);
+ }
+
+ @Test
+ public void testSimpleCheckin() {
+ Either<Boolean, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ changeStateResult = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ assertEquals(changeStateResult.isLeft(), true);
+
+ }
+
+ @Test
+ public void testSimpleServiceCheckin() {
+ Either<Boolean, ResponseFormat> changeStateResult;
+ Service service = createServiceObject();
+
+ service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ changeStateResult = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ assertEquals(changeStateResult.isLeft(), true);
+
+ }
+
+ @Test
+ public void testCheckinTwiceValidation() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(owner.isLeft());
+ // changeStateResult = checkinObj.changeStateOperation(resource, user,
+ // owner.left().value());
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testServiceCheckinTwiceValidation() {
+ Either<Service, ResponseFormat> changeStateResult;
+ Service service = createServiceObject();
+
+ service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Either<User, ResponseFormat> owner = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
+ assertTrue(owner.isLeft());
+
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.SERVICE, user, owner.left().value(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+
+ assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, service.getName(), ComponentTypeEnum.SERVICE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testCheckoutByAnotherUserValidation() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+ modifier.setRole(Role.DESIGNER.name());
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ // changeStateResult = checkinObj.changeStateOperation(resource,
+ // modifier, owner);
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
+
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testServiceCheckoutByAnotherUserValidation() {
+ Either<Service, ResponseFormat> changeStateResult;
+ Service service = createServiceObject();
+
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+ modifier.setRole(Role.DESIGNER.name());
+
+ service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ Either<User, ResponseFormat> ownerResponse = checkinObj.getComponentOwner(service, ComponentTypeEnum.SERVICE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkinObj.validateBeforeTransition(service, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
+
+ assertServiceResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, service.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java
index 1e3f6f6ce8..0826e5d40c 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTest.java
@@ -20,16 +20,13 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
@@ -37,153 +34,151 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
public class CheckoutTest extends LifecycleTestBase {
- private CheckoutTransition checkoutObj = null;
- private ComponentsUtils componentsUtils = new ComponentsUtils();
- @InjectMocks
- ResourceBusinessLogic bl = new ResourceBusinessLogic();
-
- @Before
- public void setup() {
-
- super.setup();
-
- // checkout transition object
- checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
- checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation);
- checkoutObj.setConfigurationManager(configurationManager);
- componentsUtils.Init();
- bl.setToscaOperationFacade(toscaOperationFacade);
- bl.setComponentsUtils(componentsUtils);
-
- }
-
- @Test
- public void testCheckoutStateValidation() {
- Either<? extends Component, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false);
- assertEquals(changeStateResult.isLeft(), true);
-
- resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false);
- assertEquals(changeStateResult.isLeft(), true);
-
- }
-
- @Test
- public void testAlreadyCheckout() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
-
- assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testCertificationInProgress() {
- Either<? extends Component, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false);
-
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
-
- assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testReadyForCertification() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
-
- // if modifier = owner
- Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- // changeStateResult = checkoutObj.changeStateOperation(resource, user,
- // owner);
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(validateBeforeTransition.isLeft(), true);
-
- // else
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
-
- // admin
- modifier.setRole(Role.ADMIN.name());
- // changeStateResult = checkoutObj.changeStateOperation(resource, user,
- // owner);
- validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(validateBeforeTransition.isLeft(), true);
-
- // designer
- modifier.setRole(Role.TESTER.name());
- validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
-
- assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
-
- }
-
- @Test
- public void testRoles() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
-
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
-
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
- modifier.setRole(Role.DESIGNER.name());
- Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- // changeStateResult = checkoutObj.changeStateOperation(resource,
- // modifier, owner);
- Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(validateBeforeTransition.isLeft(), true);
-
- modifier.setRole(Role.TESTER.name());
- // changeStateResult = checkoutObj.changeStateOperation(resource,
- // modifier, owner);
- validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION);
-
- }
+ private CheckoutTransition checkoutObj = null;
+ @InjectMocks
+ ResourceBusinessLogic bl = new ResourceBusinessLogic();
+
+ @Before
+ public void setup() {
+
+ super.setup();
+ // checkout transition object
+ checkoutObj = new CheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ checkoutObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+ checkoutObj.setConfigurationManager(configurationManager);
+ bl.setToscaOperationFacade(toscaOperationFacade);
+ bl.setComponentsUtils(componentsUtils);
+
+ }
+
+ @Test
+ public void testCheckoutStateValidation() {
+ Either<? extends Component, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false);
+ assertEquals(changeStateResult.isLeft(), true);
+
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false);
+ assertEquals(changeStateResult.isLeft(), true);
+
+ }
+
+ @Test
+ public void testAlreadyCheckout() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+
+ assertEquals(changeStateResult.isRight(), true);
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testCertificationInProgress() {
+ Either<? extends Component, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ changeStateResult = checkoutObj.changeState(ComponentTypeEnum.RESOURCE, resource, bl, user, owner, false, false);
+
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
+
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testReadyForCertification() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+
+ // if modifier = owner
+ Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ // changeStateResult = checkoutObj.changeStateOperation(resource, user,
+ // owner);
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ assertEquals(validateBeforeTransition.isLeft(), true);
+
+ // else
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+
+ // admin
+ modifier.setRole(Role.ADMIN.name());
+ // changeStateResult = checkoutObj.changeStateOperation(resource, user,
+ // owner);
+ validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ assertEquals(validateBeforeTransition.isLeft(), true);
+
+ // designer
+ modifier.setRole(Role.TESTER.name());
+ validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+
+ assertEquals(changeStateResult.isRight(), true);
+ assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+
+ }
+
+ @Test
+ public void testRoles() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
+
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+ modifier.setRole(Role.DESIGNER.name());
+ Either<User, ResponseFormat> ownerResponse = checkoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ // changeStateResult = checkoutObj.changeStateOperation(resource,
+ // modifier, owner);
+ Either<Boolean, ResponseFormat> validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ assertEquals(validateBeforeTransition.isLeft(), true);
+
+ modifier.setRole(Role.TESTER.name());
+ // changeStateResult = checkoutObj.changeStateOperation(resource,
+ // modifier, owner);
+ validateBeforeTransition = checkoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertResponse(changeStateResult, ActionStatus.RESTRICTED_OPERATION);
+
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java
index bc131ff39a..941af0d728 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java
@@ -20,20 +20,13 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.junit.BeforeClass;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import org.openecomp.sdc.AuditingMockManager;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -41,6 +34,7 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -67,173 +61,185 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.mockito.Mockito.when;
public class LifecycleTestBase {
- private static Logger log = LoggerFactory.getLogger(LifecycleTestBase.class.getName());
- @InjectMocks
- protected final ServletContext servletContext = Mockito.mock(ServletContext.class);
- protected IAuditingManager iAuditingManager = null;
- protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
- protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
- protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class);
- protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);;
- protected User user = null;
- protected Resource resourceResponse;
- protected Service serviceResponse;
- protected static ConfigurationManager configurationManager = null;
- protected ResponseFormatManager responseManager = null;
- protected TitanDao titanDao = Mockito.mock(TitanDao.class);
- protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
-
- @BeforeClass
- public static void setupClass() {
- ExternalConfiguration.setAppName("catalog-be");
-
- // Init Configuration
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- configurationManager = new ConfigurationManager(configurationSource);
- }
-
- public void setup() {
-
- // Auditing
- iAuditingManager = new AuditingMockManager("lll");
-
- // User data and management
- user = new User();
- user.setUserId("jh003");
- user.setFirstName("Jimmi");
- user.setLastName("Hendrix");
- user.setRole(Role.ADMIN.name());
-
- Either<User, ActionStatus> eitherGetUser = Either.left(user);
- when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser);
-
- // Servlet Context attributes
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
- when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation);
- when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager);
-
- // Resource Operation mock methods
- // getCount
-
- // createResource
- resourceResponse = createResourceObject();
- Either<ToscaElement, StorageOperationStatus> eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse));
- when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class)))
- .thenAnswer(createAnswer(eitherComponent));
-
- when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class)))
- .thenAnswer(createAnswer(eitherComponent));
-
- when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class)))
- .thenAnswer(createAnswer(eitherComponent));
-
- Either<User, StorageOperationStatus> getOwnerResult = Either.left(user);
- when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult);
-
- Either<Component, StorageOperationStatus> eitherlatestDerived = Either.right(StorageOperationStatus.OK);
- when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived);
-
- responseManager = ResponseFormatManager.getInstance();
-
- }
-
- public static <T> Answer<T> createAnswer(final T value) {
- Answer<T> dummy = new Answer<T>() {
- @Override
- public T answer(InvocationOnMock invocation) throws Throwable {
- return value;
- }
-
- };
- return dummy;
- }
-
- protected Resource createResourceObject() {
- Resource resource = new Resource();
- resource.setName("MyResourceName");
- resource.setUniqueId("uid");
- resource.addCategory("VoIP", "INfra");
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<String>();
- tgs.add("test");
- resource.setTags(tgs);
- List<String> template = new ArrayList<String>();
- template.add("Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setContactId("yavivi");
- resource.setIcon("MyIcon.jpg");
- resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
-
- return resource;
- }
-
- protected Resource createResourceVFCMTObject() {
- ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition();
- rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT);
- ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ;
-
- Resource resource = new Resource(cMetadataDataDefinition);
- resource.setUniqueId("rid");
- resource.setName("MyResourceVFCMTName");
- resource.addCategory("VoIP", "INfra");
- resource.setDescription("My short description");
- List<String> tgs = new ArrayList<String>();
- tgs.add("test1");
- resource.setTags(tgs);
- List<String> template = new ArrayList<String>();
- template.add("Root");
- resource.setDerivedFrom(template);
- resource.setVendorName("Motorola");
- resource.setVendorRelease("1.0.0");
- resource.setContactId("yavivi");
- resource.setIcon("MyIcon.jpg");
- resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
-
- return resource;
- }
-
- protected Service createServiceObject(boolean b) {
- Service service = new Service();
- service.setName("MyServiceName");
- service.setUniqueId("sid");
- service.addCategory("VoIP", null);
- service.setDescription("My short description");
- List<String> tgs = new ArrayList<String>();
- tgs.add("test");
- service.setTags(tgs);
- List<String> template = new ArrayList<String>();
- template.add("Root");
- service.setContactId("aa0001");
- service.setIcon("MyIcon.jpg");
-
- return service;
- }
-
- protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
- ResponseFormat actualResponse = createResponse.right().value();
- }
-
- protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
- ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
- ResponseFormat actualResponse = createResponse.right().value();
- }
-
- protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) {
- ArtifactDefinition artifact = new ArtifactDefinition();
-
- artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase()));
- artifact.setArtifactLabel(logicalName.toLowerCase());
-
- return artifact;
- }
+ private static final Logger log = LoggerFactory.getLogger(LifecycleTestBase.class);
+ @InjectMocks
+ protected final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ protected UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
+ protected WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ protected WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
+ protected ToscaElementLifecycleOperation toscaElementLifecycleOperation = Mockito.mock(ToscaElementLifecycleOperation.class);
+ protected ArtifactsBusinessLogic artifactsManager = Mockito.mock(ArtifactsBusinessLogic.class);;
+ protected User user = null;
+ protected Resource resourceResponse;
+ protected Service serviceResponse;
+ protected static ConfigurationManager configurationManager = null;
+ protected ResponseFormatManager responseManager = null;
+ protected TitanDao titanDao = Mockito.mock(TitanDao.class);
+ protected ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
+ protected static ComponentsUtils componentsUtils;
+
+ @BeforeClass
+ public static void setupClass() {
+ ExternalConfiguration.setAppName("catalog-be");
+
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ }
+
+ public void setup() {
+
+// ExternalConfiguration.setAppName("catalog-be");
+//
+// // init Configuration
+// String appConfigDir = "src/test/resources/config/catalog-be";
+// ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+// configurationManager = new ConfigurationManager(configurationSource);
+
+
+ // User data and management
+ user = new User();
+ user.setUserId("jh003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+
+ Either<User, ActionStatus> eitherGetUser = Either.left(user);
+ when(mockUserAdmin.getUser("jh003", false)).thenReturn(eitherGetUser);
+
+ // Servlet Context attributes
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
+ when(webAppContext.getBean(ToscaElementLifecycleOperation.class)).thenReturn(toscaElementLifecycleOperation);
+ when(webAppContext.getBean(ArtifactsBusinessLogic.class)).thenReturn(artifactsManager);
+
+ // Resource Operation mock methods
+ // getCount
+
+ // createResource
+ resourceResponse = createResourceObject();
+ Either<ToscaElement, StorageOperationStatus> eitherComponent = Either.left(ModelConverter.convertToToscaElement(resourceResponse));
+ when(toscaElementLifecycleOperation.checkoutToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class)))
+ .thenAnswer(createAnswer(eitherComponent));
+
+ when(toscaElementLifecycleOperation.checkinToscaELement(Mockito.any(LifecycleStateEnum.class), Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class)))
+ .thenAnswer(createAnswer(eitherComponent));
+
+ when(toscaElementLifecycleOperation.requestCertificationToscaElement(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class)))
+ .thenAnswer(createAnswer(eitherComponent));
+
+ Either<User, StorageOperationStatus> getOwnerResult = Either.left(user);
+ when(toscaElementLifecycleOperation.getToscaElementOwner(Mockito.anyString())).thenReturn(getOwnerResult);
+
+ Either<Component, StorageOperationStatus> eitherlatestDerived = Either.right(StorageOperationStatus.OK);
+ when(toscaOperationFacade.shouldUpgradeToLatestDerived(Mockito.any(Resource.class))).thenReturn(eitherlatestDerived);
+
+ responseManager = ResponseFormatManager.getInstance();
+
+ }
+
+ public static <T> Answer<T> createAnswer(final T value) {
+ Answer<T> dummy = new Answer<T>() {
+ @Override
+ public T answer(InvocationOnMock invocation) throws Throwable {
+ return value;
+ }
+
+ };
+ return dummy;
+ }
+
+ protected Resource createResourceObject() {
+ Resource resource = new Resource();
+ resource.setUniqueId("uid");
+ resource.setName("MyResourceName");
+ resource.setUniqueId("uid");
+ resource.addCategory("VoIP", "INfra");
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add("test");
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<String>();
+ template.add("Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setContactId("yavivi");
+ resource.setIcon("MyIcon.jpg");
+ resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
+
+ return resource;
+ }
+
+ protected Resource createResourceVFCMTObject() {
+ ResourceMetadataDataDefinition rMetadataDataDefinition = new ResourceMetadataDataDefinition();
+ rMetadataDataDefinition.setResourceType(ResourceTypeEnum.VFCMT);
+ ComponentMetadataDefinition cMetadataDataDefinition = new ComponentMetadataDefinition(rMetadataDataDefinition) ;
+
+ Resource resource = new Resource(cMetadataDataDefinition);
+ resource.setUniqueId("rid");
+ resource.setName("MyResourceVFCMTName");
+ resource.addCategory("VoIP", "INfra");
+ resource.setDescription("My short description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add("test1");
+ resource.setTags(tgs);
+ List<String> template = new ArrayList<String>();
+ template.add("Root");
+ resource.setDerivedFrom(template);
+ resource.setVendorName("Motorola");
+ resource.setVendorRelease("1.0.0");
+ resource.setContactId("yavivi");
+ resource.setIcon("MyIcon.jpg");
+ resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
+
+ return resource;
+ }
+
+ protected Service createServiceObject() {
+ Service service = new Service();
+ service.setName("MyServiceName");
+ service.setUniqueId("sid");
+ service.addCategory("VoIP", null);
+ service.setDescription("My short description");
+ List<String> tgs = new ArrayList<String>();
+ tgs.add("test");
+ service.setTags(tgs);
+ List<String> template = new ArrayList<String>();
+ template.add("Root");
+ service.setContactId("aa0001");
+ service.setIcon("MyIcon.jpg");
+
+ return service;
+ }
+
+ protected void assertResponse(Either<? extends Component, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ ResponseFormat actualResponse = createResponse.right().value();
+ }
+
+ protected void assertServiceResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
+ ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
+ ResponseFormat actualResponse = createResponse.right().value();
+ }
+
+ protected static ArtifactDefinition getArtifactPlaceHolder(String resourceId, String logicalName) {
+ ArtifactDefinition artifact = new ArtifactDefinition();
+
+ artifact.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, logicalName.toLowerCase()));
+ artifact.setArtifactLabel(logicalName.toLowerCase());
+
+ return artifact;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java
index 11913ad31a..d5d665809d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTest.java
@@ -20,105 +20,100 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
public class UndoCheckoutTest extends LifecycleTestBase {
- private UndoCheckoutTransition undoCheckoutObj = null;
- private ComponentsUtils componentsUtils = new ComponentsUtils();
-
- @Before
- public void setup() {
+ private UndoCheckoutTransition undoCheckoutObj = null;
- super.setup();
+ @Before
+ public void setup() {
- // checkout transition object
- undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
- undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation);
- undoCheckoutObj.setConfigurationManager(configurationManager);
- componentsUtils.Init();
+ super.setup();
+ // checkout transition object
+ undoCheckoutObj = new UndoCheckoutTransition(componentsUtils, toscaElementLifecycleOperation, toscaOperationFacade, titanDao);
+ undoCheckoutObj.setLifeCycleOperation(toscaElementLifecycleOperation);
+ undoCheckoutObj.setConfigurationManager(configurationManager);
- }
+ }
- @Test
- public void testResourceNotCheckedOutValidation() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
+ @Test
+ public void testResourceNotCheckedOutValidation() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
+ Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
+ assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
- resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
- resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
+ resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.CERTIFIED);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
- resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
+ resource.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, user, owner, LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
- }
+ }
- @Test
- public void testDifferentResourceOwnerValidation() {
- Either<Resource, ResponseFormat> changeStateResult;
- Resource resource = createResourceObject();
+ @Test
+ public void testDifferentResourceOwnerValidation() {
+ Either<Resource, ResponseFormat> changeStateResult;
+ Resource resource = createResourceObject();
- resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- User modifier = new User();
- modifier.setUserId("modifier");
- modifier.setFirstName("Albert");
- modifier.setLastName("Einstein");
- modifier.setRole(Role.DESIGNER.name());
+ resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ User modifier = new User();
+ modifier.setUserId("modifier");
+ modifier.setFirstName("Albert");
+ modifier.setLastName("Einstein");
+ modifier.setRole(Role.DESIGNER.name());
- Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
- assertTrue(ownerResponse.isLeft());
- User owner = ownerResponse.left().value();
- Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(validateBeforeTransition.isRight(), true);
- changeStateResult = Either.right(validateBeforeTransition.right().value());
- assertEquals(changeStateResult.isRight(), true);
+ Either<User, ResponseFormat> ownerResponse = undoCheckoutObj.getComponentOwner(resource, ComponentTypeEnum.RESOURCE);
+ assertTrue(ownerResponse.isLeft());
+ User owner = ownerResponse.left().value();
+ Either<Boolean, ResponseFormat> validateBeforeTransition = undoCheckoutObj.validateBeforeTransition(resource, ComponentTypeEnum.RESOURCE, modifier, owner, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ assertEquals(validateBeforeTransition.isRight(), true);
+ changeStateResult = Either.right(validateBeforeTransition.right().value());
+ assertEquals(changeStateResult.isRight(), true);
- assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
- }
+ assertResponse(changeStateResult, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, resource.getName(), ComponentTypeEnum.RESOURCE.name().toLowerCase(), user.getFirstName(), user.getLastName(), user.getUserId());
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java
index ab2e865ae0..89b82b91d2 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogicTest.java
@@ -1,14 +1,7 @@
package org.openecomp.sdc.be.components.merge;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
+import com.google.common.collect.Sets;
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -24,9 +17,14 @@ 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 com.google.common.collect.Sets;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
-import fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
public class GlobalInputsFilteringBusinessLogicTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java
index a00b0b8e8a..ec741b4953 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/GlobalTypesMergeBusinessLogicTest.java
@@ -1,13 +1,6 @@
package org.openecomp.sdc.be.components.merge;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs;
-
-import java.util.Arrays;
-import java.util.List;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -18,7 +11,13 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.Resource;
-import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.components.utils.ObjectGenerator.buildResourceWithInputs;
public class GlobalTypesMergeBusinessLogicTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java
index 773b068cd7..d50f4859db 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/RelationsComparatorTest.java
@@ -1,10 +1,5 @@
package org.openecomp.sdc.be.components.merge;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
@@ -14,14 +9,23 @@ import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
+import java.util.Arrays;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class RelationsComparatorTest {
public static final String INSTANCE1 = "instance1";
public static final String INSTANCE2 = "instance2";
RelationsComparator testInstance;
- private RequirementCapabilityRelDef relation1, relation2, relation3, relation4;
- private ComponentInstance componentInstance1, componentInstance2;
+ private RequirementCapabilityRelDef relation1;
+ private RequirementCapabilityRelDef relation2;
+ private RequirementCapabilityRelDef relation3;
+ private RequirementCapabilityRelDef relation4;
+ private ComponentInstance componentInstance1;
+ private ComponentInstance componentInstance2;
@Before
public void setUp() {
@@ -59,21 +63,21 @@ public class RelationsComparatorTest {
@Test
public void isRelationsChanged_notSameType() throws Exception {
RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1);
- relation2DifType.getSingleRelationship().getRelation().getRelationship().setType("someDiffType");
+ relation2DifType.resolveSingleRelationship().getRelation().getRelationship().setType("someDiffType");
isRelationsChangedTest(relation2DifType);
}
@Test
public void isRelationsChanged_notSameCapability() throws Exception {
RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1);
- relation2DifType.getSingleRelationship().getRelation().setCapabilityUid("someDiffUid");
+ relation2DifType.resolveSingleRelationship().getRelation().setCapabilityUid("someDiffUid");
isRelationsChangedTest(relation2DifType);
}
@Test
public void isRelationsChanged_notSameReqName() throws Exception {
RequirementCapabilityRelDef relation2DifType = buildRelation("2", INSTANCE1);
- relation2DifType.getSingleRelationship().getRelation().setRequirement("someDiffReq");
+ relation2DifType.resolveSingleRelationship().getRelation().setRequirement("someDiffReq");
isRelationsChangedTest(relation2DifType);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java
index 3b1ed52550..298a4454b3 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/TopologyComparatorTest.java
@@ -1,10 +1,6 @@
package org.openecomp.sdc.be.components.merge;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -20,7 +16,10 @@ 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 fj.data.Either;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class TopologyComparatorTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java
new file mode 100644
index 0000000000..be9f426c2c
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolverTest.java
@@ -0,0 +1,113 @@
+package org.openecomp.sdc.be.components.merge.capability;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
+import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+
+import java.util.Map;
+
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyMap;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class SimpleCapabilityResolverTest {
+
+ public static final String NEW_OWNER_ID1 = "owner1";
+ public static final String NEW_OWNER_ID2 = "owner2";
+ public static final String OLD_OWNER_ID1 = "oldOwner1";
+ private static final String OLD_OWNER_ID2 = "oldOwner2";
+ public static final String OLD_OWNER_ID3 = "oldOwner3";
+ @InjectMocks
+ private SimpleCapabilityResolver testInstance;
+ @Mock
+ private MergeInstanceUtils MergeInstanceUtils;
+
+ private CapabilityDefinition capName1Owner1Type1;
+ private CapabilityDefinition capName1Owner1Type2;
+ private CapabilityDefinition capName1Owner2Type1;
+ private CapabilityDefinition capName2Owner1Type2;
+
+ private CapabilityDefinition prevCapName1Owner1Type1;
+ private CapabilityDefinition prevCapName1Owner1Type2;
+ private CapabilityDefinition prevCapName1Owner2Type1;
+ private CapabilityDefinition prevCapName2Owner1Type2;
+ private CapabilityDefinition prevCapName1Owner3Type1;
+ private CapabilityDefinition prevCapName3Owner1Type1;
+ private CapabilityDefinition prevCapName1Owner1Type3;
+ CapabilityDefinition[] prevCapabilities;
+ private ComponentInstance oldInstance;
+ private ComponentInstance currInstance;
+
+
+ @Before
+ public void setUp() {
+ capName1Owner1Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type1").build();
+ prevCapName1Owner1Type1 = new CapabilityDefinition(capName1Owner1Type1);
+ prevCapName1Owner1Type1.setOwnerId(OLD_OWNER_ID1);
+
+ capName1Owner1Type2 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID1).setType("type2").build();
+ prevCapName1Owner1Type2 = new CapabilityDefinition(capName1Owner1Type2);
+ prevCapName1Owner1Type2.setOwnerId(OLD_OWNER_ID1);
+
+ capName1Owner2Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(NEW_OWNER_ID2).setType("type1").build();
+ prevCapName1Owner2Type1 = new CapabilityDefinition(capName1Owner2Type1);
+ prevCapName1Owner2Type1.setOwnerId(OLD_OWNER_ID2);
+
+ capName2Owner1Type2 = new CapabilityDefinitionBuilder().setName("name2").setOwnerId(NEW_OWNER_ID1).setType("type2").build();
+ prevCapName2Owner1Type2 = new CapabilityDefinition(capName2Owner1Type2);
+ prevCapName2Owner1Type2.setOwnerId(OLD_OWNER_ID1);
+
+ //prev capabilities that are not mapped to any new capability
+ prevCapName1Owner3Type1 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID3).setType("type1").build();
+ prevCapName3Owner1Type1 = new CapabilityDefinitionBuilder().setName("name3").setOwnerId(OLD_OWNER_ID1).setType("type1").build();
+ prevCapName1Owner1Type3 = new CapabilityDefinitionBuilder().setName("name1").setOwnerId(OLD_OWNER_ID1).setType("type3").build();
+
+ currInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(capName1Owner1Type1, capName1Owner1Type2, capName1Owner2Type1, capName2Owner1Type2).build();
+ prevCapabilities = new CapabilityDefinition[]{prevCapName1Owner1Type1, prevCapName1Owner1Type2, prevCapName1Owner2Type1, prevCapName2Owner1Type2, prevCapName1Owner3Type1, prevCapName3Owner1Type1, prevCapName1Owner1Type3};
+ oldInstance = new ComponentInstanceBuilder().setId("inst1").addCapabilities(prevCapabilities).build();
+ }
+
+ @Test
+ public void resolvePrevCapIdToNewCapability_resolveByTypeNameAndNewOwnerId() {
+ when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2));
+ Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance);
+ assertThat(oldToNewMap).hasSize(4);
+ assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1);
+ assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2);
+ assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1);
+ assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2);
+ }
+
+ @Test
+ public void resolvePrevCapIdToNewCapability_noMatchingNewOwnerIds() {
+ when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance)).thenReturn(emptyMap());
+ Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapIdToNewCapability(oldInstance, currInstance);
+ assertThat(oldToNewMap).isEmpty();
+ }
+
+ @Test
+ public void mapOldToNewInstanceCapabilitiesOwnerIds() {
+ Resource container = new ResourceBuilder().addComponentInstance(currInstance).build();
+ Resource prevInstanceOrigNode = new Resource();
+ when(MergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, "inst1", asList(OLD_OWNER_ID1, OLD_OWNER_ID2, OLD_OWNER_ID3))).thenReturn(ImmutableMap.of(OLD_OWNER_ID1, NEW_OWNER_ID1, OLD_OWNER_ID2, NEW_OWNER_ID2));
+ Map<CapabilityDefinition, CapabilityDefinition> oldToNewMap = testInstance.resolvePrevCapToNewCapability(container, prevInstanceOrigNode, "inst1", asList(prevCapabilities));
+ assertThat(oldToNewMap).hasSize(4);
+ assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type1, capName1Owner1Type1);
+ assertThat(oldToNewMap).containsEntry(prevCapName1Owner1Type2, capName1Owner1Type2);
+ assertThat(oldToNewMap).containsEntry(prevCapName1Owner2Type1, capName1Owner2Type1);
+ assertThat(oldToNewMap).containsEntry(prevCapName2Owner1Type2, capName2Owner1Type2);
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java
index bcdd08e95b..c75a6ccd5d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogicTest.java
@@ -1,12 +1,5 @@
package org.openecomp.sdc.be.components.merge.heat;
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.stream.Stream;
-
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.components.utils.ArtifactBuilder;
@@ -15,6 +8,13 @@ import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+
public class HeatEnvArtifactsMergeBusinessLogicTest {
private HeatEnvArtifactsMergeBusinessLogic testInstance;
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java
index 26b6782918..30801b0a4a 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBLTest.java
@@ -1,14 +1,6 @@
package org.openecomp.sdc.be.components.merge.input;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.ListUtils;
import org.junit.Before;
import org.junit.Test;
@@ -22,7 +14,14 @@ import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class ComponentInputsMergeBLTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java
index b0124e4e44..98fceab7a8 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogicTest.java
@@ -1,26 +1,24 @@
package org.openecomp.sdc.be.components.merge.input;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.Resource;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
public class InputsValuesMergingBusinessLogicTest {
public static final String INPUT_DEFUALT_TYPE = "string";
@@ -133,54 +131,4 @@ public class InputsValuesMergingBusinessLogicTest {
inputDef.setOwnerId("owner");
return inputDef;
}
-
- private void addInstanceProperty(Resource resource, ComponentInstanceProperty prop, String instanceId) {
- addInstancePropDefinition(resource.getComponentInstancesProperties(), prop, instanceId);
- }
-
- private void addInstanceInput(Resource resource, ComponentInstanceInput prop, String instanceId) {
- addInstancePropDefinition(resource.getComponentInstancesInputs(), prop, instanceId);
- }
-
- private <T extends PropertyDataDefinition> void addInstancePropDefinition(Map<String, List<T>> propsDefinitions, T propDef, String instanceId) {
- propsDefinitions.computeIfAbsent(instanceId, id -> new ArrayList<>()).add(propDef);
- }
-
- private Resource createResourceWithInputs(String ... inputsIds) {
- Resource resource = new Resource();
- List<InputDefinition> inputs = new ArrayList<>();
- for (String inputId : inputsIds) {
- InputDefinition inputDefinition = new InputDefinition();
- inputDefinition.setOwnerId("cs0008");
- inputDefinition.setUniqueId(inputId);
- inputs.add(inputDefinition);
- }
- resource.setInputs(inputs);
- return resource;
- }
-
-
- private ComponentInstanceProperty createGetInputComponentProperty(String ... declaredToInputId) {
- ComponentInstanceProperty prevDeclaredProperty = new ComponentInstanceProperty();
- for (String inputId : declaredToInputId) {
- addGetInputValueOnProp(inputId, prevDeclaredProperty);
- }
-
- return prevDeclaredProperty;
- }
-
- private void addGetInputValueOnProp(String declaredToInputId, PropertyDataDefinition declaredProperty) {
- GetInputValueDataDefinition getInputDef = new GetInputValueDataDefinition();
- getInputDef.setInputId(declaredToInputId);
- if (declaredProperty.getGetInputValues() == null) {
- declaredProperty.setGetInputValues(new ArrayList<>());
- }
- declaredProperty.getGetInputValues().add(getInputDef);
- }
-
- private ComponentInstanceInput createGetInputComponentInstanceInput(String declaredToInputId) {
- ComponentInstanceInput prevDeclaredProp = new ComponentInstanceInput();
- addGetInputValueOnProp(declaredToInputId, prevDeclaredProp);
- return prevDeclaredProp;
- }
} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java
index be16bc3621..df3e0ddb68 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMergeTest.java
@@ -1,10 +1,5 @@
package org.openecomp.sdc.be.components.merge.instance;
-import static junit.framework.TestCase.assertEquals;
-
-import java.util.HashMap;
-import java.util.Map;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -14,6 +9,11 @@ import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Resource;
+import java.util.HashMap;
+import java.util.Map;
+
+import static groovy.util.GroovyTestCase.assertEquals;
+
public class ComponentInstanceArtifactsMergeTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java
new file mode 100644
index 0000000000..4fbb1ab5d7
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabiliteisPropertiesMergeTest.java
@@ -0,0 +1,70 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+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.exception.ResponseFormat;
+
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ComponentInstanceCapabiliteisPropertiesMergeTest {
+
+ @InjectMocks
+ private ComponentInstanceCapabiliteisPropertiesMerge testInstance;
+
+ @Mock
+ private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL;
+
+ @Mock
+ private ComponentsUtils componentsUtils;
+
+ private DataForMergeHolder mergeHolder;
+
+ private Resource origInstanceNode;
+ private List<CapabilityDefinition> origInstanceCapabilities;
+
+ @Before
+ public void setUp() throws Exception {
+ origInstanceNode = new Resource();
+ origInstanceCapabilities = Collections.emptyList();
+ mergeHolder = new DataForMergeHolder();
+ mergeHolder.setOrigInstanceNode(origInstanceNode);
+ mergeHolder.setOrigInstanceCapabilities(origInstanceCapabilities);
+ }
+
+ @Test
+ public void mergeDataAfterCreate() {
+ Service currentComponent = new Service();
+ when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities))
+ .thenReturn(ActionStatus.OK);
+ Either<Component, ResponseFormat> mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId");
+ assertTrue(mergeResult.isLeft());
+ }
+
+ @Test
+ public void mergeDataAfterCreate_error() {
+ Service currentComponent = new Service();
+ when(capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(currentComponent, origInstanceNode, "instId", origInstanceCapabilities))
+ .thenReturn(ActionStatus.GENERAL_ERROR);
+ when(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)).thenReturn(new ResponseFormat());
+ Either<Component, ResponseFormat> mergeResult = testInstance.mergeDataAfterCreate(new User(), mergeHolder, currentComponent, "instId");
+ assertTrue(mergeResult.isRight());
+ }
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java
new file mode 100644
index 0000000000..d73459c1b1
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesMergeBLTest.java
@@ -0,0 +1,275 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import com.google.common.collect.ImmutableMap;
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.components.merge.capability.SimpleCapabilityResolver;
+import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
+import org.openecomp.sdc.be.components.utils.CapabilityDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
+import org.openecomp.sdc.be.components.utils.ComponentInstancePropertyBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static java.util.Collections.emptyMap;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ComponentInstanceCapabilitiesMergeBLTest {
+
+ private static final String INSTANCE1 = "inst1";
+ private static final String INSTANCE2 = "inst2";
+
+ private ComponentCapabilitiesPropertiesMergeBL testInstance;
+ private ComponentsUtils componentsUtils;
+ @Mock
+ private SimpleCapabilityResolver capabilityResolver;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ @Mock
+ private DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic;
+ @Captor
+ private ArgumentCaptor<List<ComponentInstanceProperty>> prevCapPropertiesCaptor;
+ @Captor
+ private ArgumentCaptor<List<ComponentInstanceProperty>> currCapPropertiesCaptor;
+ @Captor
+ private ArgumentCaptor<ComponentParametersView> getCurrResourceFilterCapture;
+
+ private CapabilityDefinition oldCap;
+ private CapabilityDefinition oldCap2;
+ private CapabilityDefinition newCap;
+ private CapabilityDefinition newCap2;
+
+ private ComponentParametersView getCapabilitiesPropsFilter;
+
+ protected static ConfigurationManager configurationManager = null;
+
+ @Before
+ public void setUp() throws Exception {
+ oldCap = new CapabilityDefinitionBuilder()
+ .setOwnerId(INSTANCE1)
+ .setOwnerName(INSTANCE1)
+ .setId("cap1")
+ .setType("type1")
+ .setName("cap1")
+ .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build())
+ .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build())
+ .build();
+
+ oldCap2 = new CapabilityDefinitionBuilder()
+ .setOwnerId(INSTANCE2)
+ .setOwnerName(INSTANCE2)
+ .setId("cap2")
+ .setType("type1")
+ .setName("cap2")
+ .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build())
+ .build();
+
+ newCap = new CapabilityDefinitionBuilder()
+ .setOwnerId(INSTANCE1)
+ .setOwnerName(INSTANCE1)
+ .setId("cap1")
+ .setType("type1")
+ .setName("cap1")
+ .addProperty(new ComponentInstancePropertyBuilder().setName("prop1").build())
+ .build();
+
+ newCap2 = new CapabilityDefinitionBuilder()
+ .setOwnerId(INSTANCE2)
+ .setOwnerName(INSTANCE2)
+ .setId("cap2")
+ .setType("type1")
+ .setName("cap2")
+ .addProperty(new ComponentInstancePropertyBuilder().setName("prop2").build())
+ .addProperty(new ComponentInstancePropertyBuilder().setName("prop3").build())
+ .build();
+
+ getCapabilitiesPropsFilter = new ComponentParametersView();
+ getCapabilitiesPropsFilter.disableAll();
+ getCapabilitiesPropsFilter.setIgnoreComponentInstances(false);
+ getCapabilitiesPropsFilter.setIgnoreCapabilities(false);
+ getCapabilitiesPropsFilter.setIgnoreCapabiltyProperties(false);
+
+ ExternalConfiguration.setAppName("catalog-be");
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
+ testInstance = new ComponentCapabilitiesPropertiesMergeBL(dataDefinitionsValuesMergingBusinessLogic, toscaOperationFacade, componentsUtils, capabilityResolver);
+ }
+
+ @Test
+ public void mergeCapabilityProperties_singleCapability() {
+ ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build();
+ ComponentInstance newInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build();
+ Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build();
+ Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build();
+ when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), getCurrResourceFilterCapture.capture())).thenReturn(Either.left(newResource));
+ when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(ImmutableMap.of(oldCap, newCap));
+ when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK);
+
+ ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource);
+
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture());
+ assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2");
+ assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1");
+ assertThat(getCurrResourceFilterCapture.getValue()).isEqualToComparingFieldByField(getCapabilitiesPropsFilter);
+ }
+
+ @Test
+ public void mergeCapabilityProperties_failToGetResourceWithPropsCapabilities() {
+ Resource currResource = new ResourceBuilder().setUniqueId("rid").build();
+ when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
+ ActionStatus actionStatus = testInstance.mergeComponents(new Resource(), currResource);
+ assertThat(actionStatus).isEqualTo(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ @Test
+ public void mergeCapabilityProperties_multipleCapabilitiesToMerge() {
+ ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build();
+ ComponentInstance prevInst2 = new ComponentInstanceBuilder().addCapability(oldCap2).setName(oldCap2.getOwnerName()).build();
+
+ ComponentInstance currInst1 = new ComponentInstanceBuilder().addCapability(newCap).setName(newCap.getOwnerName()).build();
+ ComponentInstance currInst2 = new ComponentInstanceBuilder().addCapability(newCap2).setName(newCap2.getOwnerName()).build();
+
+ Resource currResource = new ResourceBuilder().addComponentInstance(currInst1).addComponentInstance(currInst2).build();
+ Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).addComponentInstance(prevInst2).build();
+ when(toscaOperationFacade.getToscaElement(eq(currResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(currResource));
+ when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, currInst1)).thenReturn(ImmutableMap.of(oldCap, newCap));
+ when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst2, currInst2)).thenReturn(ImmutableMap.of(oldCap2, newCap2));
+ when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(currResource)).thenReturn(StorageOperationStatus.OK);
+ ActionStatus actionStatus = testInstance.mergeComponents(prevResource, currResource);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList());
+ }
+
+ @Test
+ public void mergeCapabilityProperties_noNewCapabilitiesResolved() {
+ ComponentInstance prevInst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build();
+ ComponentInstance newInst1 = new ComponentInstanceBuilder().setName(oldCap.getOwnerName()).build();
+ Resource prevResource = new ResourceBuilder().addComponentInstance(prevInst1).build();
+ Resource newResource = new ResourceBuilder().addComponentInstance(newInst1).build();
+ when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource));
+ when(capabilityResolver.resolvePrevCapIdToNewCapability(prevInst1, newInst1)).thenReturn(emptyMap());
+ when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.OK);
+ ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic);
+ }
+
+ @Test
+ public void mergeCapabilityProperties_noPrevCapabilitiesToMerge() {
+ Resource newResource = new Resource();
+ Resource prevResource = new Resource();
+ when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource));
+ verifyNoMoreInteractions(toscaOperationFacade);
+ ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic);
+ }
+
+ @Test
+ public void mergeCapabilityProperties_failedToUpdateComponent() {
+ ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(oldCap).setName(oldCap.getOwnerName()).build();
+ Resource newResource = new Resource();
+ Resource prevResource = new ResourceBuilder().addComponentInstance(inst1).build();
+ when(toscaOperationFacade.getToscaElement(eq(newResource.getUniqueId()), any(ComponentParametersView.class))).thenReturn(Either.left(newResource));
+ when(toscaOperationFacade.updateComponentCalculatedCapabilitiesProperties(newResource)).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.mergeComponents(prevResource, newResource);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
+ ////////////////////////////
+ @Test
+ public void mergeInstanceCapabilityProperties_singleCap() {
+ List<CapabilityDefinition> previousInstanceCapabilities = Collections.singletonList(oldCap);
+ ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).setId(newCap.getOwnerId()).build();
+ Resource container = new ResourceBuilder().addComponentInstance(inst1).build();
+ Resource origInstanceNode = new Resource();
+ when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, newCap.getOwnerId())).thenReturn(StorageOperationStatus.OK);
+ when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap));
+ ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verify(dataDefinitionsValuesMergingBusinessLogic).mergeInstanceDataDefinitions(prevCapPropertiesCaptor.capture(), currCapPropertiesCaptor.capture());
+
+ assertThat(prevCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1", "prop2");
+ assertThat(currCapPropertiesCaptor.getValue()).extracting("name").containsExactly("prop1");
+ }
+
+ @Test
+ public void mergeInstanceCapabilityProperties() {
+ List<CapabilityDefinition> previousInstanceCapabilities = Arrays.asList(oldCap, oldCap2);
+ ComponentInstance inst1 = new ComponentInstanceBuilder().addCapability(newCap).addCapability(newCap2).setId(newCap.getOwnerId()).build();
+ Resource container = new ResourceBuilder().addComponentInstance(inst1).build();
+ Resource origInstanceNode = new Resource();
+ when(capabilityResolver.resolvePrevCapToNewCapability(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities)).thenReturn(ImmutableMap.of(oldCap, newCap, oldCap2, newCap2));
+ when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK);
+ ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, origInstanceNode, INSTANCE1, previousInstanceCapabilities);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verify(dataDefinitionsValuesMergingBusinessLogic, times(2)).mergeInstanceDataDefinitions(anyList(), anyList());
+ }
+
+ @Test
+ public void mergeInstanceCapabilityProperties_emptyCapabilitiesList() {
+ ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(new Resource(), new Resource(), "instanceId", Collections.emptyList());
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(toscaOperationFacade, dataDefinitionsValuesMergingBusinessLogic, capabilityResolver);
+ }
+
+ @Test
+ public void mergeInstanceCapabilityProperties_failedToUpdateComponent() {
+ Resource container = new Resource();
+ Resource resource = new Resource();
+ List<CapabilityDefinition> capList = singletonList(oldCap);
+ when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, capList)).thenReturn(ImmutableMap.of(oldCap, newCap));
+ when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, capList);
+ assertThat(actionStatus).isEqualTo(ActionStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void mergeInstanceCapabilityProperties_noNewCapabilitiesFound() {
+ Resource container = new Resource();
+ Resource resource = new Resource();
+ List<CapabilityDefinition> prevCapabilities = singletonList(oldCap);
+ when(capabilityResolver.resolvePrevCapToNewCapability(container, resource, INSTANCE1, prevCapabilities)).thenReturn(emptyMap());
+ when(toscaOperationFacade.updateComponentInstanceCapabilityProperties(container, INSTANCE1)).thenReturn(StorageOperationStatus.OK);
+ ActionStatus actionStatus = testInstance.mergeComponentInstanceCapabilities(container, resource, INSTANCE1, prevCapabilities);
+ assertThat(actionStatus).isEqualTo(ActionStatus.OK);
+ verifyZeroInteractions(dataDefinitionsValuesMergingBusinessLogic);
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java
index 2101ea49ab..115825733e 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMergeTest.java
@@ -1,13 +1,6 @@
package org.openecomp.sdc.be.components.merge.instance;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -26,7 +19,13 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.mockito.Mockito.when;
public class ComponentInstanceHeatEnvMergeTest {
@@ -67,7 +66,7 @@ public class ComponentInstanceHeatEnvMergeTest {
for (ArtifactDefinition mergedArtifact : mergedArtifacts) {
Map<String, Object> json = new HashMap<>();
when(artifactsBusinessLogicMock.buildJsonForUpdateArtifact(mergedArtifact, ArtifactGroupTypeEnum.DEPLOYMENT, null)).thenReturn(json);
- ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.Update);
+ ArtifactsBusinessLogic.ArtifactOperationInfo artifactUpdateOperation = artifactsBusinessLogicMock.new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE);
when(artifactsBusinessLogicMock.updateResourceInstanceArtifactNoContent(Mockito.eq(instanceId), Mockito.eq(resource),
Mockito.eq(USER), Mockito.eq(json),
Mockito.refEq(artifactUpdateOperation),
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java
index bc3efe423d..630a43ef2d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogicTest.java
@@ -1,13 +1,6 @@
package org.openecomp.sdc.be.components.merge.instance;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@@ -29,7 +22,13 @@ 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 fj.data.Either;
+import java.util.Arrays;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
public class ComponentInstanceMergeDataBusinessLogicTest {
@@ -112,4 +111,6 @@ public class ComponentInstanceMergeDataBusinessLogicTest {
assertFalse(value.isIgnoreArtifacts());
}
+
+
} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java
index cb3d506bfc..d946206f23 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMergeTest.java
@@ -1,16 +1,6 @@
package org.openecomp.sdc.be.components.merge.instance;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyList;
-import static org.mockito.ArgumentMatchers.anyListOf;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-import java.util.List;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@@ -19,8 +9,6 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL;
import org.openecomp.sdc.be.components.utils.ObjectGenerator;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -37,7 +25,16 @@ 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 fj.data.Either;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyListOf;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
public class ComponentInstancePropsAndInputsMergeTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java
new file mode 100644
index 0000000000..08c8456064
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeTest.java
@@ -0,0 +1,378 @@
+package org.openecomp.sdc.be.components.merge.instance;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
+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.CapabilityRequirementRelationship;
+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.RelationshipInfo;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ComponentInstanceRelationMergeTest {
+ private ComponentInstanceRelationMerge compInstanceRelationMerge;
+ @Mock
+ private DataForMergeHolder dataHolder;
+ private Component containerComponent;
+ private Component updatedContainerComponent;
+ private ComponentInstance currentResourceInstance;
+
+ private RequirementCapabilityRelDef requirementDef1;
+ private RequirementCapabilityRelDef requirementDef2;
+ private RequirementCapabilityRelDef capabilityDef1;
+ private RequirementCapabilityRelDef capabilityDef2;
+
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Mock
+ private User user;
+
+ @Captor
+ ArgumentCaptor<VfRelationsMergeInfo> argumentCaptor;
+
+
+ @Before
+ public void startUp() {
+ compInstanceRelationMerge = new ComponentInstanceRelationMerge();
+ compInstanceRelationMerge.setToscaOperationFacade(toscaOperationFacade);
+
+ MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils();
+ mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade);
+ compInstanceRelationMerge.setMergeInstanceUtils(mergeInstanceUtils);
+
+ containerComponent = new Service();
+ List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>();
+
+ requirementDef1 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF2.VFI_1", "SRV1.VF1.VFC_1.VFCI_1", "Requirement1");
+ resourceInstancesRelations.add(requirementDef1);
+ requirementDef2 = createRequirementDef("SRV1.VF1.VFI_1", "SRV1.VF3.VFI_1", "SRV1.VF1.VFC_2.VFCI_2", "Requirement2");
+ resourceInstancesRelations.add(requirementDef2);
+
+
+ capabilityDef1 = createCapabilityDef("SRV1.VF4.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_3.VFCI_3", "Capability3");
+ resourceInstancesRelations.add(capabilityDef1);
+ capabilityDef2 = createCapabilityDef("SRV1.VF5.VFI_1", "SRV1.VF1.VFI_1", "SRV1.VF1.VFC_4.VFCI_1", "Capability4");
+ resourceInstancesRelations.add(capabilityDef2);
+
+ containerComponent.setComponentInstancesRelations(resourceInstancesRelations );
+
+ currentResourceInstance = new ComponentInstance();
+ currentResourceInstance.setUniqueId("SRV1.VF1.VFI_1");
+ currentResourceInstance.setComponentUid("SRV1.VF1");
+ currentResourceInstance.setIsProxy(false);
+
+ updatedContainerComponent = new Service();
+ updatedContainerComponent.setUniqueId("123123123123123123");
+ }
+
+ @Test
+ public void testSaveDataBeforeMerge() {
+ Resource vf = new Resource();
+
+ List<ComponentInstance> vfcInstances = new ArrayList<>();
+ vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true));
+ vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true));
+ vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false));
+ vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true));
+ vf.setComponentInstances(vfcInstances);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
+ vf.setResourceType(ResourceTypeEnum.VF);
+
+ compInstanceRelationMerge.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, vf);
+
+ verify(dataHolder).setVfRelationsInfo(argumentCaptor.capture());
+ VfRelationsMergeInfo relationsMergeInfo = argumentCaptor.getValue();
+ List<RelationMergeInfo> fromRelationsMergeInfo = relationsMergeInfo.getFromRelationsInfo();
+ List<RelationMergeInfo> toRelationsMergeInfo = relationsMergeInfo.getToRelationsInfo();
+
+ assertNotNull("Expected not null list of relations merge info", fromRelationsMergeInfo);
+ assertNotNull("Expected not null list of relations merge info", toRelationsMergeInfo);
+
+ assertEquals("Expected 2 elements", 2, fromRelationsMergeInfo.size());
+ assertEquals("Expected 1 elements", 1, toRelationsMergeInfo.size());
+ }
+
+ @Test
+ public void testMergeDataAfterCreate_NoSavedData() {
+ compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2");
+
+ verify(dataHolder).getVfRelationsMergeInfo();
+ List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations();
+ assertNull("Expected no relations", relations);
+ }
+
+ @Test
+ public void testMergeDataAfterCreate() {
+ Resource vf = new Resource();
+
+ List<ComponentInstance> vfcInstances = new ArrayList<>();
+ vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_1", "SRV1.VF1.VFC_1", true));
+ vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true));
+ vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false));
+ vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_1", "SRV1.VF1.VFC_4", true));
+ vf.setComponentInstances(vfcInstances);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
+ vf.setResourceType(ResourceTypeEnum.VF);
+
+ Either<Component, StorageOperationStatus> eitherVF = Either.left(vf);
+ when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF);
+
+
+ List<RelationMergeInfo> fromRelationsMergeInfo = new ArrayList<>();
+ List<RelationMergeInfo> toRelationsMergeInfo = new ArrayList<>();
+
+ RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1);
+ fromRelationsMergeInfo.add(relationMergeInfo1);
+ RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2);
+ toRelationsMergeInfo.add(relationMergeInfo2);
+
+ VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo);
+
+ when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo);
+
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2"));
+ componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1"));
+ componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1"));
+ componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1"));
+ componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1"));
+ updatedContainerComponent.setComponentInstances(componentInstances);
+
+ List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>();
+ updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations);
+
+ when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK);
+
+ compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2");
+
+ verify(dataHolder).getVfRelationsMergeInfo();
+ verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList());
+
+ List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations();
+ assertEquals("Expected 2 relations", 2, relations.size());
+
+
+ RequirementCapabilityRelDef capabilityRelDef = relations.get(0);
+ assertEquals("SRV1.VF1.VFC_4.VFCI_1", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId());
+ assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode());
+ assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode());
+
+ RequirementCapabilityRelDef requirementRelDef = relations.get(1);
+ assertEquals("SRV1.VF1.VFC_1.VFCI_1", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId());
+ assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode());
+ assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode());
+ }
+
+
+
+ @Test
+ public void testMergeDataAfterCreate_OwnerChanged() {
+ Resource vf = new Resource();
+
+ List<ComponentInstance> vfcInstances = new ArrayList<>();
+ vfcInstances.add(createVfci("vfc_A", "SRV1.VF1.VFC_1.VFCI_2", "SRV1.VF1.VFC_1", true));
+ vfcInstances.add(createVfci("vfc_B", "SRV1.VF1.VFC_2.VFCI_2", "SRV1.VF1.VFC_2", true));
+ vfcInstances.add(createVfci("vfc_C", "SRV1.VF1.VFC_3.VFCI_3", "SRV1.VF1.VFC_3", false));
+ vfcInstances.add(createVfci("vfc_D", "SRV1.VF1.VFC_4.VFCI_2", "SRV1.VF1.VFC_4", true));
+ vf.setComponentInstances(vfcInstances);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
+ vf.setResourceType(ResourceTypeEnum.VF);
+
+ Either<Component, StorageOperationStatus> eitherVF = Either.left(vf);
+ when(toscaOperationFacade.getToscaElement("SRV1.VF1")).thenReturn(eitherVF);
+
+
+ List<RelationMergeInfo> fromRelationsMergeInfo = new ArrayList<>();
+ List<RelationMergeInfo> toRelationsMergeInfo = new ArrayList<>();
+
+ RelationMergeInfo relationMergeInfo1 = new RelationMergeInfo("CapabilityType1", "capabilityA", "vfc_A", requirementDef1);
+ fromRelationsMergeInfo.add(relationMergeInfo1);
+ RelationMergeInfo relationMergeInfo2 = new RelationMergeInfo("CapabilityType4", "capabilityD", "vfc_D", capabilityDef2);
+ toRelationsMergeInfo.add(relationMergeInfo2);
+
+ VfRelationsMergeInfo relationsMergeInfo = new VfRelationsMergeInfo(fromRelationsMergeInfo, toRelationsMergeInfo);
+
+ when(dataHolder.getVfRelationsMergeInfo()).thenReturn(relationsMergeInfo);
+
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ componentInstances.add(createVfi("SRV1.VF1", "SRV1.VF1.VFI_2"));
+ componentInstances.add(createVfi("SRV1.VF2", "SRV1.VF2.VFI_1"));
+ componentInstances.add(createVfi("SRV1.VF3", "SRV1.VF3.VFI_1"));
+ componentInstances.add(createVfi("SRV1.VF4", "SRV1.VF4.VFI_1"));
+ componentInstances.add(createVfi("SRV1.VF5", "SRV1.VF5.VFI_1"));
+ updatedContainerComponent.setComponentInstances(componentInstances);
+
+ List<RequirementCapabilityRelDef> resourceInstancesRelations = new ArrayList<>();
+ updatedContainerComponent.setComponentInstancesRelations(resourceInstancesRelations);
+
+ when(toscaOperationFacade.associateResourceInstances(Mockito.anyString(), Mockito.anyList())).thenReturn(StorageOperationStatus.OK);
+
+ compInstanceRelationMerge.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, "SRV1.VF1.VFI_2");
+
+ verify(dataHolder).getVfRelationsMergeInfo();
+ verify(toscaOperationFacade).associateResourceInstances(Mockito.anyString(), Mockito.anyList());
+
+ List<RequirementCapabilityRelDef> relations = updatedContainerComponent.getComponentInstancesRelations();
+ assertEquals("Expected 2 relations", 2, relations.size());
+
+
+ RequirementCapabilityRelDef capabilityRelDef = relations.get(0);
+ assertEquals("SRV1.VF1.VFC_4.VFCI_2", capabilityRelDef.resolveSingleRelationship().getRelation().getCapabilityOwnerId());
+ assertEquals("SRV1.VF5.VFI_1", capabilityRelDef.getFromNode());
+ assertEquals("SRV1.VF1.VFI_2", capabilityRelDef.getToNode());
+
+ RequirementCapabilityRelDef requirementRelDef = relations.get(1);
+ assertEquals("SRV1.VF1.VFC_1.VFCI_2", requirementRelDef.resolveSingleRelationship().getRelation().getRequirementOwnerId());
+ assertEquals("SRV1.VF1.VFI_2", requirementRelDef.getFromNode());
+ assertEquals("SRV1.VF2.VFI_1", requirementRelDef.getToNode());
+ }
+
+
+ /**
+ * @param vfId
+ * @param vfiUniqueId
+ * @return
+ */
+ private ComponentInstance createVfi(String vfId, String vfiUniqueId) {
+ ComponentInstance vfi = new ComponentInstance();
+ vfi.setUniqueId(vfiUniqueId);
+ vfi.setComponentUid(vfId);
+
+ Resource vf = new Resource();
+ vf.setUniqueId(vfId);
+ return vfi;
+ }
+
+ private ComponentInstance createVfci(String name, String uniqueId, String componentUid, boolean foundVfc) {
+ ComponentInstance compInst = new ComponentInstance();
+ compInst.setName(name);
+ compInst.setUniqueId(uniqueId);
+ compInst.setComponentUid(componentUid);
+
+ if(foundVfc) {
+ createVfc(componentUid);
+ }
+ else {
+ failLoadVfc(componentUid);
+ }
+ return compInst;
+ }
+
+ private void failLoadVfc(String uid) {
+ Either<Component, StorageOperationStatus> eitherVFC = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC);
+ }
+
+ private Component createVfc(String uid) {
+ Resource vfc = new Resource();
+ vfc.setUniqueId(uid);
+
+ Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
+ Map<String, List<RequirementDefinition>> requirements = new HashMap<>();;
+ IntStream.range(0, 5).forEach(i -> {
+
+ List<CapabilityDefinition> capList = new LinkedList<>();
+ capList.add(null);
+ CapabilityDefinition capDef = new CapabilityDefinition();
+ capDef.setName("CapabilityName" + i);
+ capDef.setUniqueId("Capability" + i);
+ capDef.setType("CapabilityType" + i);
+ capList.add(capDef);
+ capabilities.put("Key" + i, capList);
+
+ List<RequirementDefinition> reqList = new LinkedList<>();
+ reqList.add(null);
+ RequirementDefinition reqDef = new RequirementDefinition();
+ reqDef.setName("RequirementName" + i);
+ reqDef.setUniqueId("Requirement" + i);
+ reqDef.setCapability("CapabilityType" + i);
+ reqList.add(reqDef);
+ requirements.put("Key" + i, reqList);
+
+ });
+ vfc.setCapabilities(capabilities );
+ vfc.setRequirements(requirements);
+
+ Either<Component, StorageOperationStatus> eitherVFC = Either.left(vfc);
+ when(toscaOperationFacade.getToscaElement(uid)).thenReturn(eitherVFC);
+
+ return vfc;
+ }
+
+ private RequirementCapabilityRelDef createRequirementCapabilityDef(String fromNode, String toNode) {
+ RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef();
+
+ reqCapDef.setFromNode(fromNode);
+ reqCapDef.setToNode(toNode);
+
+ List<CapabilityRequirementRelationship> relationships = new ArrayList<>();
+ CapabilityRequirementRelationship capabilityRequirementRelationship = new CapabilityRequirementRelationship();
+ relationships.add(capabilityRequirementRelationship);
+ reqCapDef.setRelationships(relationships);
+
+ return reqCapDef;
+ }
+
+ private RequirementCapabilityRelDef createRequirementDef(String fromNode, String toNode, String ownerId, String requirementUid) {
+ RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode);
+ CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship();
+
+ RelationshipInfo relationshipInfo = new RelationshipInfo();
+ relationshipInfo.setRequirementOwnerId(ownerId);
+ relationshipInfo.setRequirementUid(requirementUid);
+ relationshipInfo.setRelationships(new RelationshipImpl());
+ capabilityRequirementRelationship.setRelation(relationshipInfo );
+
+
+
+ return reqCapDef;
+ }
+
+ private RequirementCapabilityRelDef createCapabilityDef(String fromNode, String toNode, String ownerId, String capabilityUid) {
+ RequirementCapabilityRelDef reqCapDef = createRequirementCapabilityDef(fromNode, toNode);
+ CapabilityRequirementRelationship capabilityRequirementRelationship = reqCapDef.resolveSingleRelationship();
+
+ RelationshipInfo relationshipInfo = new RelationshipInfo();
+ relationshipInfo.setCapabilityOwnerId(ownerId);
+ relationshipInfo.setCapabilityUid(capabilityUid);
+ relationshipInfo.setRelationships(new RelationshipImpl());
+ capabilityRequirementRelationship.setRelation(relationshipInfo );
+
+ return reqCapDef;
+ }
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java
new file mode 100644
index 0000000000..65ab3ec121
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/path/ComponentInstanceForwardingPathMergeTest.java
@@ -0,0 +1,101 @@
+package org.openecomp.sdc.be.components.merge.path;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceForwardingPathMerge;
+import org.openecomp.sdc.be.components.path.BaseForwardingPathVersionChangeTest;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.common.api.UserRoleEnum;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.Set;
+
+import static groovy.util.GroovyTestCase.assertEquals;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.TestCase.assertTrue;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.when;
+
+public class ComponentInstanceForwardingPathMergeTest extends BaseForwardingPathVersionChangeTest {
+
+ @InjectMocks
+ private ComponentInstanceForwardingPathMerge testInstance;
+
+ @Mock
+ private ServiceBusinessLogic serviceBusinessLogic;
+
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ private User user;
+
+ @Before
+ public void setUpData() {
+ MockitoAnnotations.initMocks(this);
+ user = new User();
+ user.setUserId("44");
+ user.setRole(UserRoleEnum.ADMIN.getName());
+ }
+
+ @Test
+ public void testIgnoreMergeSinceItIsNotService() {
+
+ testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC);
+ assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId());
+ Either<Component, ResponseFormat> componentResponseFormatEither = testInstance
+ .mergeDataAfterCreate(user, dataHolder, newNodeAC, "3344");
+ assertNotNull(componentResponseFormatEither);
+ assertTrue(componentResponseFormatEither.isLeft());
+ assertEquals(newNodeAC, componentResponseFormatEither.left().value());
+ }
+
+ @Test
+ public void mergeShouldDelete() {
+ Set<String> forwardingPathNamesToDeleteOnComponentInstanceDeletion = new ForwardingPathUtils()
+ .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeACI.getUniqueId());
+ nodeACI.getCapabilities().clear();
+ newNodeAC.getCapabilities().clear();
+ when(serviceBusinessLogic.deleteForwardingPaths(any(), any(), any(), anyBoolean()))
+ .thenReturn(Either.left(forwardingPathNamesToDeleteOnComponentInstanceDeletion));
+ when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC));
+
+ // Change internal ci, just like change version do
+ service.getComponentInstances().remove(nodeACI);
+ service.getComponentInstances().add(newNodeACI);
+
+ testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC);
+ assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId());
+ Either<Component, ResponseFormat> componentResponseFormatEither = testInstance
+ .mergeDataAfterCreate(user, dataHolder, service, newNodeA);
+ assertNotNull(componentResponseFormatEither);
+ assertTrue(componentResponseFormatEither.isLeft());
+ assertEquals(0, ((Service) componentResponseFormatEither.left().value()).getForwardingPaths().size());
+ }
+
+ @Test
+ public void mergeShouldUpdate() {
+ when(serviceBusinessLogic.updateForwardingPath(any(), any(), any(), anyBoolean()))
+ .thenReturn(Either.left(service));
+ when(toscaOperationFacade.getToscaFullElement(any())).thenReturn(Either.left(newNodeAC));
+ testInstance.saveDataBeforeMerge(dataHolder, service, nodeACI, newNodeAC);
+ assertEquals(nodeACI.getUniqueId(), dataHolder.getOrigComponentInstId());
+
+ // Change internal ci, just like change version do
+ service.getComponentInstances().remove(nodeACI);
+ service.getComponentInstances().add(newNodeACI);
+
+ Either<Component, ResponseFormat> componentResponseFormatEither = testInstance
+ .mergeDataAfterCreate(user, dataHolder, service, newNodeA);
+ assertNotNull(componentResponseFormatEither);
+ assertTrue(componentResponseFormatEither.isLeft());
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java
index 0a858c9a29..bbb2dd6895 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstanceInputsMergeBLTest.java
@@ -1,18 +1,12 @@
package org.openecomp.sdc.be.components.merge.property;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-import java.util.Collections;
-import java.util.List;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceInputsMergeBL;
import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -23,7 +17,13 @@ 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 fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
public class ComponentInstanceInputsMergeBLTest {
@@ -41,7 +41,8 @@ public class ComponentInstanceInputsMergeBLTest {
@Mock
private ComponentsUtils componentsUtils;
- private Resource oldResource, newResource;
+ private Resource oldResource;
+ private Resource newResource;
@Before
public void setUp() throws Exception {
@@ -71,22 +72,22 @@ public class ComponentInstanceInputsMergeBLTest {
@Test
public void mergeInstancesInputs() throws Exception {
when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.left(Collections.emptyMap()));
- ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource);
+ ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource);
assertEquals(actionStatus, ActionStatus.OK);
verifyMergeBLCalled(oldResource, newResource);
}
@Test
- public void mergeInstancesInputs_failure() throws Exception {
+ public void mergeInstancesInputs_failure() {
when(toscaOperationFacade.updateComponentInstanceInputsToComponent(newResource.getComponentInstancesInputs(), newResource.getUniqueId())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR);
verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic);
- ActionStatus actionStatus = testInstance.mergeComponentInstancesInputs(oldResource, newResource);
+ ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource);
assertEquals(ActionStatus.GENERAL_ERROR, actionStatus);
}
@Test
- public void mergeInstanceProps() throws Exception {
+ public void mergeInstanceProps() {
List<ComponentInstanceInput> newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1);
List<ComponentInstanceInput> oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1);
when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs))
@@ -97,7 +98,7 @@ public class ComponentInstanceInputsMergeBLTest {
}
@Test
- public void mergeInstanceProps_failure() throws Exception {
+ public void mergeInstanceProps_failure() {
List<ComponentInstanceInput> newInstanceInputs = newResource.safeGetComponentInstanceInput(INSTANCE1);
List<ComponentInstanceInput> oldInstInputs = oldResource.safeGetComponentInstanceInput(INSTANCE1);
when(toscaOperationFacade.updateComponentInstanceInputs(newResource, INSTANCE1, newInstanceInputs))
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java
index 7948ab8a3d..6013009106 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/ComponentInstancePropertiesMergeBLTest.java
@@ -1,18 +1,12 @@
package org.openecomp.sdc.be.components.merge.property;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-import java.util.Collections;
-import java.util.List;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.merge.instance.ComponentInstancePropertiesMergeBL;
import org.openecomp.sdc.be.components.utils.ResourceBuilder;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -21,7 +15,13 @@ 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 fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
public class ComponentInstancePropertiesMergeBLTest {
@@ -40,7 +40,8 @@ public class ComponentInstancePropertiesMergeBLTest {
@Mock
private ComponentsUtils componentsUtils;
- private Resource oldResource, newResource;
+ private Resource oldResource;
+ private Resource newResource;
@Before
public void setUp() throws Exception {
@@ -64,7 +65,7 @@ public class ComponentInstancePropertiesMergeBLTest {
public void mergeInstancesPropsAndInputs_mergeInstanceProps() throws Exception {
when(toscaOperationFacade.updateComponentInstancePropsToComponent(newResource.getComponentInstancesProperties(), newResource.getUniqueId()))
.thenReturn(Either.left(Collections.emptyMap()));
- ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource);
+ ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource);
assertEquals(actionStatus, ActionStatus.OK);
verifyMergeBLCalled(oldResource, newResource);
}
@@ -75,7 +76,7 @@ public class ComponentInstancePropertiesMergeBLTest {
.thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR)).thenReturn(ActionStatus.GENERAL_ERROR);
verifyNoMoreInteractions(toscaOperationFacade, propertyValuesMergingBusinessLogic);
- ActionStatus actionStatus = testInstance.mergeComponentInstancesProperties(oldResource, newResource);
+ ActionStatus actionStatus = testInstance.mergeComponents(oldResource, newResource);
assertEquals(ActionStatus.GENERAL_ERROR, actionStatus);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java
index 8669a781b4..3b079d30d5 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogicTest.java
@@ -1,21 +1,22 @@
package org.openecomp.sdc.be.components.merge.property;
-import static org.mockito.Mockito.verify;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionAbstractBuilder;
import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.mockito.Mockito.verify;
+
public class DataDefinitionsValuesMergingBusinessLogicTest {
private static final String DEFAULT_PROP_TYPE = "string";
@@ -110,9 +111,10 @@ public class DataDefinitionsValuesMergingBusinessLogicTest {
}
private PropertyDataDefinition createGetInputPropertyDataDefinition(String name, String ... inputsNames) {
- PropertyDataDefinitionBuilder propertyBuilder = new PropertyDataDefinitionBuilder()
+ PropertyDataDefinitionAbstractBuilder propertyBuilder = new PropertyDataDefinitionBuilder()
.setName(name)
.setType(DEFAULT_PROP_TYPE);
+
for (String inputName : inputsNames) {
propertyBuilder.addGetInputValue(inputName);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java
index 6faee487f4..5c23ec0e8c 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogicTest.java
@@ -1,17 +1,6 @@
package org.openecomp.sdc.be.components.merge.property;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
@@ -25,7 +14,17 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import fj.data.Either;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class PropertyDataValueMergeBusinessLogicTest {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java
index 8e7949f108..0590c7e500 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java
@@ -1,82 +1,63 @@
package org.openecomp.sdc.be.components.merge.resource;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-import java.util.Collections;
-
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.openecomp.sdc.be.components.merge.input.ComponentInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstanceInputsMergeBL;
-import org.openecomp.sdc.be.components.merge.property.ComponentInstancePropertiesMergeBL;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand;
import org.openecomp.sdc.be.components.utils.ObjectGenerator;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.model.Resource;
+import java.util.Arrays;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
public class ResourceDataMergeBusinessLogicTest {
@InjectMocks
private ResourceDataMergeBusinessLogic testInstance;
@Mock
- private ComponentInstanceInputsMergeBL instanceInputsValueMergeBLMock;
+ private ComponentsMergeCommand commandA;
@Mock
- private ComponentInstancePropertiesMergeBL instancePropertiesValueMergeBLMock;
+ private ComponentsMergeCommand commandB;
@Mock
- private ComponentInputsMergeBL inputsValueMergeBLMock;
+ private ComponentsMergeCommand commandC;
@Before
public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
+ testInstance = new ResourceDataMergeBusinessLogic(Arrays.asList(commandA, commandB, commandC));
}
@Test
- public void mergeResourceInputs_allMergeClassesAreCalled() throws Exception {
+ public void mergeResources_allMergeClassesAreCalled() {
Resource oldResource = ObjectGenerator.buildBasicResource();
Resource newResource = ObjectGenerator.buildBasicResource();
- when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK);
- when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK);
- when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.OK);
+ when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK);
+ when(commandB.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK);
+ when(commandC.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK);
ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource);
assertEquals(ActionStatus.OK, actionStatus);
}
@Test
- public void mergeResourceInputs_failToMergeProperties_dontCallOtherMergeMethods() throws Exception {
+ public void mergeResources_mergeCommandFailed_dontCallOtherMergeMethods() {
Resource oldResource = ObjectGenerator.buildBasicResource();
Resource newResource = ObjectGenerator.buildBasicResource();
- when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR);
+ when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR);
ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource);
assertEquals(ActionStatus.GENERAL_ERROR, actionStatus);
- verifyZeroInteractions(instanceInputsValueMergeBLMock, inputsValueMergeBLMock);
+ verify(commandA).description();
+ verifyZeroInteractions(commandB, commandC);
}
- @Test
- public void mergeResourceInputs_failToMergeInstanceInputs_dontCallOtherMergeMethods() throws Exception {
- Resource oldResource = ObjectGenerator.buildBasicResource();
- Resource newResource = ObjectGenerator.buildBasicResource();
- when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK);
- when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR);
- ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource);
- assertEquals(ActionStatus.GENERAL_ERROR, actionStatus);
- verifyZeroInteractions(inputsValueMergeBLMock);
- }
-
- @Test
- public void mergeResourceInputs_failedToMergeInputs() throws Exception {
- Resource oldResource = ObjectGenerator.buildBasicResource();
- Resource newResource = ObjectGenerator.buildBasicResource();
- when(instancePropertiesValueMergeBLMock.mergeComponentInstancesProperties(oldResource, newResource)).thenReturn(ActionStatus.OK);
- when(instanceInputsValueMergeBLMock.mergeComponentInstancesInputs(oldResource, newResource)).thenReturn(ActionStatus.OK);
- when(inputsValueMergeBLMock.mergeAndRedeclareComponentInputs(oldResource, newResource, Collections.emptyList())).thenReturn(ActionStatus.GENERAL_ERROR);
- ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource);
- assertEquals(ActionStatus.GENERAL_ERROR, actionStatus);
- }
} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java
new file mode 100644
index 0000000000..3131c4987c
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtilsTest.java
@@ -0,0 +1,328 @@
+package org.openecomp.sdc.be.components.merge.utils;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+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.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class MergeInstanceUtilsTest {
+ private MergeInstanceUtils mergeInstanceUtils = new MergeInstanceUtils();
+
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Before
+ public void startUp() {
+ mergeInstanceUtils.setToscaOperationFacade(toscaOperationFacade);
+ }
+
+ @Test
+ public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent() {
+ Component container = new Service();
+
+ Resource vfOld = new Resource();
+ vfOld.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfOld.setResourceType(ResourceTypeEnum.VF);
+
+ ComponentInstance vfci1 = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false);
+ createVfc(vfci1);
+ List<ComponentInstance> vfciList = Arrays.asList(vfci1);
+ vfOld.setComponentInstances(vfciList);
+
+ ComponentInstance vfi1 = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false);
+ container.setComponentInstances(Arrays.asList(vfi1));
+
+ Resource vfNew = new Resource();
+ vfNew.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfNew.setResourceType(ResourceTypeEnum.VF);
+
+ List<ComponentInstance> vfciList2 = Arrays.asList(vfci1);
+ vfNew.setComponentInstances(vfciList2);
+
+ Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfNew);
+ when(toscaOperationFacade.getToscaElement(vfi1.getComponentUid())).thenReturn(eitherComponent);
+
+
+ Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, vfOld, "SRV1.VF2.VFI_1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1"));
+ assertEquals("SRV1.VF1.VFI_1.VFC1.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1"));
+ }
+
+ @Test
+ public void testMapOldToNewCapabilitiesOwnerIdsComponentComponent_Proxy() {
+ Resource container = new Resource();
+ container.setComponentType(ComponentTypeEnum.RESOURCE);
+ container.setResourceType(ResourceTypeEnum.VF);
+
+
+ Component serviceOld = new Service();
+ serviceOld.setComponentType(ComponentTypeEnum.SERVICE);
+
+ Resource vfOld = new Resource();
+ vfOld.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfOld.setResourceType(ResourceTypeEnum.VF);
+
+ ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false);
+ createVfc(vfciOld);
+ List<ComponentInstance> vfciList = Arrays.asList(vfciOld);
+ vfOld.setComponentInstances(vfciList);
+
+ ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false);
+ serviceOld.setComponentInstances(Arrays.asList(vfiOld));
+ Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfOld);
+ when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent);
+
+ Component serviceNew = new Service();
+ serviceNew.setComponentType(ComponentTypeEnum.SERVICE);
+
+ Resource vfNew = new Resource();
+ vfNew.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfNew.setResourceType(ResourceTypeEnum.VF);
+
+ ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false);
+ createVfc(vfciNew);
+ List<ComponentInstance> vfciList2 = Arrays.asList(vfciNew);
+ vfNew.setComponentInstances(vfciList2);
+
+ ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false);
+ serviceNew.setComponentInstances(Arrays.asList(vfiNew));
+ Either<Component, StorageOperationStatus> eitherComponent3 = Either.left(vfNew);
+ when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3);
+
+ ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true);
+ proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW");
+ Resource proxyVfcNew = new Resource();
+ proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE);
+ proxyVfcNew.setResourceType(ResourceTypeEnum.VFC);
+
+ Either<Component, StorageOperationStatus> eitherComponent4 = Either.left(serviceNew);
+ when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4);
+
+ container.setComponentInstances(Arrays.asList(proxyVfciNew));
+
+ Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, serviceOld, "SRV1.PROXY_VFC_NEW.VFCI1", Arrays.asList("SRV1.VF1.VFI_1.VFC1.VFCI_1"));
+
+ assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1"));
+ }
+
+ @Test
+ public void testMapOldToNewCapabilitiesOwnerIdsComponentInstanceComponentInstance() {
+ ComponentInstance oldInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false);
+ createVfc(oldInstance);
+
+ ComponentInstance newInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC2.VFCI_1" ,"SRV1.VF1.VFI_1.VFC2", false);
+ createVfc(newInstance);
+
+ Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, newInstance);
+ assertEquals("SRV1.VF1.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1"));
+ }
+
+ @Test
+ public void testMapOldToNewCapabilitiesOwnerIdsComponentInstComponentInst_Proxy() {
+
+ Component serviceOld = new Service();
+ serviceOld.setComponentType(ComponentTypeEnum.SERVICE);
+
+ Resource vfOld = new Resource();
+ vfOld.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfOld.setResourceType(ResourceTypeEnum.VF);
+
+ ComponentInstance vfciOld = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false);
+ createVfc(vfciOld);
+ List<ComponentInstance> vfciList = Arrays.asList(vfciOld);
+ vfOld.setComponentInstances(vfciList);
+
+ ComponentInstance vfiOld = createComponentInstance("SRV1.VF1.VFI_1" ,"SRV1.VF1", false);
+ serviceOld.setComponentInstances(Arrays.asList(vfiOld));
+ Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfOld);
+ when(toscaOperationFacade.getToscaElement(vfiOld.getComponentUid())).thenReturn(eitherComponent);
+
+ ComponentInstance proxyVfciOld = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true);
+ proxyVfciOld.setSourceModelUid("SRV_PROXY");
+ Resource proxyVfcOld = new Resource();
+ proxyVfcOld.setComponentType(ComponentTypeEnum.RESOURCE);
+ proxyVfcOld.setResourceType(ResourceTypeEnum.VFC);
+
+ Either<Component, StorageOperationStatus> eitherComponent2 = Either.left(serviceOld);
+ when(toscaOperationFacade.getToscaElement(proxyVfciOld.getSourceModelUid())).thenReturn(eitherComponent2);
+
+
+ Component serviceNew = new Service();
+ serviceNew.setComponentType(ComponentTypeEnum.SERVICE);
+
+ Resource vfNew = new Resource();
+ vfNew.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfNew.setResourceType(ResourceTypeEnum.VF);
+
+ ComponentInstance vfciNew = createComponentInstance("SRV1.VF2.VFI_1.VFC2.VFCI_1" ,"SRV1.VF2.VFI_1.VFC2", false);
+ createVfc(vfciNew);
+ List<ComponentInstance> vfciList2 = Arrays.asList(vfciNew);
+ vfNew.setComponentInstances(vfciList2);
+
+ ComponentInstance vfiNew = createComponentInstance("SRV1.VF2.VFI_1" ,"SRV1.VF2", false);
+ serviceNew.setComponentInstances(Arrays.asList(vfiNew));
+ Either<Component, StorageOperationStatus> eitherComponent3 = Either.left(vfNew);
+ when(toscaOperationFacade.getToscaElement(vfiNew.getComponentUid())).thenReturn(eitherComponent3);
+
+ ComponentInstance proxyVfciNew = createComponentInstance("SRV1.PROXY_VFC_NEW.VFCI1", "SRV1.PROXY_VFC_NEW", true);
+ proxyVfciNew.setSourceModelUid("SRV_PROXY_NEW");
+ Resource proxyVfcNew = new Resource();
+ proxyVfcNew.setComponentType(ComponentTypeEnum.RESOURCE);
+ proxyVfcNew.setResourceType(ResourceTypeEnum.VFC);
+
+ Either<Component, StorageOperationStatus> eitherComponent4 = Either.left(serviceNew);
+ when(toscaOperationFacade.getToscaElement(proxyVfciNew.getSourceModelUid())).thenReturn(eitherComponent4);
+
+ Map<String, String> mapResult = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(proxyVfciOld, proxyVfciNew);
+ assertEquals("SRV1.VF2.VFI_1.VFC2.VFCI_1", mapResult.get("SRV1.VF1.VFI_1.VFC1.VFCI_1"));
+ }
+
+
+ @Test
+ public void testConvertToVfciNameMap() {
+ ComponentInstance componentInstance1 = new ComponentInstance();
+ componentInstance1.setName("ComponentInstance1");
+
+ ComponentInstance componentInstance2 = new ComponentInstance();
+ componentInstance2.setName("ComponentInstance2");
+
+ List<ComponentInstance> componentInstances = Arrays.asList(componentInstance1, componentInstance2);
+ Map<String, ComponentInstance> mapResult = mergeInstanceUtils.convertToVfciNameMap(componentInstances);
+
+ assertEquals(2, mapResult.size());
+ assertEquals(componentInstance1, mapResult.get("ComponentInstance1"));
+ assertEquals(componentInstance2, mapResult.get("ComponentInstance2"));
+ }
+
+ @Test
+ public void testGetVfcInstances_NullComponentInstance() {
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null);
+
+ assertTrue(vfcInstances.isEmpty());
+ }
+
+ @Test
+ public void testGetVfcInstances_ComponentInstanceFailedLoadComponent() {
+ ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false);
+
+ Either<Component, StorageOperationStatus> eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent);
+
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance);
+
+ assertTrue(vfcInstances.isEmpty());
+ }
+
+ @Test
+ public void testGetVfcInstances_ComponentInstanceFailedLoadActualComponent() {
+ ComponentInstance componentInstance = createComponentInstance("SRV1.PROXY_VFC.VFCI1", "SRV1.PROXY_VFC", true);
+ componentInstance.setSourceModelUid("SRV_PROXY");
+
+ Either<Component, StorageOperationStatus> eitherComponent = Either.right(StorageOperationStatus.NOT_FOUND);
+ when(toscaOperationFacade.getToscaElement(componentInstance.getSourceModelUid())).thenReturn(eitherComponent);
+
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance);
+
+ assertTrue(vfcInstances.isEmpty());
+ }
+
+
+ @Test
+ public void testGetVfcInstancesAtomicComponentInstance() {
+ ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false);
+
+ createVfc(componentInstance);
+
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance);
+
+ assertEquals(1, vfcInstances.size());
+ assertEquals(componentInstance, vfcInstances.get(0));
+ }
+
+
+ @Test
+ public void testGetVfcInstancesNonAtomicComponentInstance() {
+ ComponentInstance componentInstance = createComponentInstance("SRV1.VF1.VFI_1", "SRV1.VF1", false);
+
+ Resource vf = new Resource();
+ Either<Component, StorageOperationStatus> eitherComponent = Either.left(vf);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
+ vf.setResourceType(ResourceTypeEnum.VF);
+
+ ComponentInstance vfci = createComponentInstance("SRV1.VF1.VFI_1.VFC1.VFCI_1" ,"SRV1.VF1.VFI_1.VFC1", false);
+ createVfc(vfci);
+ List<ComponentInstance> vfciList = Arrays.asList(vfci);
+
+ vf.setComponentInstances(vfciList);
+ when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent);
+
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(componentInstance);
+
+ assertEquals(vfciList, vfcInstances);
+ }
+
+ @Test
+ public void testGetVfcInstances_ComponentNullI_nstanceComponent() {
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null, new Resource());
+
+ assertTrue(vfcInstances.isEmpty());
+ }
+
+ @Test
+ public void testGetVfcInstances_ComponentInstance_NullComponent() {
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(new ComponentInstance(), null);
+
+ assertTrue(vfcInstances.isEmpty());
+ }
+
+ @Test
+ public void testGetVfcInstances_NullComponentInstance_NullComponent() {
+ List<ComponentInstance> vfcInstances = mergeInstanceUtils.getVfcInstances(null, null);
+
+ assertTrue(vfcInstances.isEmpty());
+ }
+
+
+ /**
+ * @param uniqueId
+ * @param componentUid
+ * @param isProxy
+ * @return
+ */
+ private ComponentInstance createComponentInstance(String uniqueId, String componentUid, boolean isProxy) {
+ ComponentInstance componentInstance = new ComponentInstance();
+ componentInstance.setUniqueId(uniqueId);
+ componentInstance.setComponentUid(componentUid);
+ componentInstance.setIsProxy(isProxy);
+ return componentInstance;
+ }
+
+ /**
+ * @param componentInstance
+ */
+ private void createVfc(ComponentInstance componentInstance) {
+ Resource vfc = new Resource();
+ Either<Component, StorageOperationStatus> eitherComponent = Either.left(vfc);
+ vfc.setComponentType(ComponentTypeEnum.RESOURCE);
+ vfc.setResourceType(ResourceTypeEnum.VFC);
+ when(toscaOperationFacade.getToscaElement(componentInstance.getComponentUid())).thenReturn(eitherComponent);
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java
new file mode 100644
index 0000000000..44f87bb352
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathTest.java
@@ -0,0 +1,208 @@
+package org.openecomp.sdc.be.components.path;
+
+import com.google.common.collect.Lists;
+import fj.data.Either;
+import org.junit.Before;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.components.path.beans.TitanGraphTestSetup;
+import org.openecomp.sdc.be.components.path.utils.GraphTestUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+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.impl.UniqueIdBuilder;
+import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class BaseForwardingPathTest extends BeConfDependentTest implements ForwardingPathTestUtils {
+
+ protected User user;
+ protected ForwardingPathDataDefinition forwardingPathDataDefinition;
+
+ @Autowired
+ protected TitanGraphClient titanGraphClient;
+
+ @Autowired
+ protected CapabiltyRequirementConvertor capabiltyRequirementConvertor;
+
+ @Autowired
+ protected ToscaOperationFacade toscaOperationFacade;
+
+ @Autowired
+ protected ServiceBusinessLogic bl;
+
+ @Autowired
+ protected IElementOperation elementDao;
+
+ @Autowired
+ protected ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
+ @javax.annotation.Resource
+ protected TitanDao titanDao;
+
+ @Before
+ public void initTitan() {
+ TitanGraphTestSetup.createGraph(titanGraphClient.getGraph().left().value());
+ categoryDefinition = new CategoryDefinition();
+ categoryDefinition.setName(CATEGORY_NAME);
+ }
+
+ @Before
+ public void initUser() {
+ // User data and management
+ user = new User();
+ user.setUserId("jh0003");
+ user.setFirstName("Jimmi");
+ user.setLastName("Hendrix");
+ user.setRole(Role.ADMIN.name());
+ }
+
+
+ protected CategoryDefinition categoryDefinition;
+ protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
+ protected static final String CATEGORY_NAME = "cat_name";
+ protected static final String FORWARDING_PATH_ID = "forwarding_pathId";
+ protected static final String HTTP_PROTOCOL = "http";
+
+
+ protected Resource setupGenericServiceMock() {
+ Resource genericService = new Resource();
+ genericService.setVersion("1.0");
+ genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
+ return genericService;
+ }
+
+ protected void initGraph() {
+ Map<GraphPropertyEnum, Object> props = new HashMap<>();
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, "org.openecomp.resource.abstract.nodes.service");
+
+ GraphTestUtils.createServiceVertex(titanDao, props);
+
+ GraphVertex resourceVertex = GraphTestUtils.createResourceVertex(titanDao, props, ResourceTypeEnum.PNF);
+ resourceVertex.setJsonMetadataField(JsonPresentationFields.VERSION, "0.1");
+ Either<GraphVertex, TitanOperationStatus> vertexTitanOperationStatusEither = titanDao.updateVertex(resourceVertex);
+ assertTrue(vertexTitanOperationStatusEither.isLeft());
+ }
+
+ protected Service createTestService() {
+ createCategory();
+ createServiceCategory(CATEGORY_NAME);
+ initGraph();
+ Service service = new Service();
+ service.setName("ForwardingPathTestingService");
+ service.setDescription("Just a comment.");
+ service.setTags(Lists.newArrayList(service.getName(), service.getComponentType().getValue() + service.getName() + "2"));
+ service.setContactId("as123y");
+ service.setIcon("MyIcon");
+ service.setProjectCode("414155");
+ ArrayList<CategoryDefinition> categories = new ArrayList<>();
+ CategoryDefinition cd = new CategoryDefinition();
+ cd.setName(CATEGORY_NAME);
+ cd.setNormalizedName("abcde");
+ categories.add(cd);
+ service.setCategories(categories);
+ service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ return service;
+ }
+
+ protected void createCategory() {
+ Either<CategoryDefinition, ActionStatus> category = elementDao.createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory);
+ assertTrue("Failed to create category", category.isLeft());
+ }
+
+ protected void createServiceCategory(String categoryName) {
+ GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY);
+ Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>();
+ String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY);
+ cat.setUniqueId(catId);
+ metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId);
+ metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName());
+ metadataProperties.put(GraphPropertyEnum.NAME, categoryName);
+ metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
+ cat.setMetadataProperties(metadataProperties);
+ cat.updateMetadataJsonWithCurrentMetadataProperties();
+
+ Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat);
+
+ assertTrue(catRes.isLeft());
+ }
+
+ protected Service initForwardPath() {
+ ForwardingPathDataDefinition forwardingPathDataDefinition = createMockPath();
+ Service service = new Service();
+ service.setUniqueId(FORWARDING_PATH_ID);
+ assertEquals(null, service.addForwardingPath(forwardingPathDataDefinition));
+ return service;
+ }
+
+ protected ForwardingPathDataDefinition createMockPath() {
+ if (forwardingPathDataDefinition != null) {
+ return forwardingPathDataDefinition;
+ }
+ forwardingPathDataDefinition = new ForwardingPathDataDefinition("Yoyo");
+ forwardingPathDataDefinition.setUniqueId(java.util.UUID.randomUUID().toString());
+ forwardingPathDataDefinition.setDestinationPortNumber("414155");
+ forwardingPathDataDefinition.setProtocol(HTTP_PROTOCOL);
+ org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition> forwardingPathElementDataDefinitionListDataDefinition = new org.openecomp.sdc.be.datatypes.elements.ListDataDefinition<>();
+ forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("fromNode", "toNode", "333", "444", "2222", "5555"));
+ forwardingPathElementDataDefinitionListDataDefinition.add(new ForwardingPathElementDataDefinition("toNode", "toNode2", "4444", "44444", "4", "44"));
+ forwardingPathDataDefinition.setPathElements(forwardingPathElementDataDefinitionListDataDefinition);
+ return forwardingPathDataDefinition;
+ }
+
+ protected Service createService() {
+ Either<Service, ResponseFormat> serviceCreateResult = bl.createService(createTestService(), user);
+ assertTrue("Failed to create service", serviceCreateResult.isLeft());
+ Service service = serviceCreateResult.left().value();
+// ComponentInstance componentInstance = new ComponentInstance();
+// componentInstance.setName("Test1");
+// componentInstance.setNormalizedName("Test1");
+// componentInstance.setUniqueId("Test1");
+// componentInstance.setInputValueCounter(1);
+// componentInstance.setAttributeValueCounter(1);
+// componentInstance.setIcon("network");
+// componentInstance.setComponentVersion("1.0");
+// componentInstance.setIsProxy(true);
+// componentInstance.setComponentUid(service.getUniqueId());
+// componentInstance.setPropertyValueCounter(1);
+// componentInstance.setPosX("333");
+// componentInstance.setPosY("333");
+// componentInstance.setOriginType(OriginTypeEnum.VF);
+//
+// Either<ComponentInstance, ResponseFormat> instanceResult = serviceComponentInstanceBusinessLogic.createComponentInstance("services", service.getUniqueId(), user.getUserId(), componentInstance);
+// assertTrue("Failed to create instance", instanceResult.isLeft());
+ return service;
+ }
+}
+
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java
new file mode 100644
index 0000000000..0e56680728
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/BaseForwardingPathVersionChangeTest.java
@@ -0,0 +1,104 @@
+package org.openecomp.sdc.be.components.path;
+
+import com.google.common.collect.Lists;
+import org.junit.Before;
+import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+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.Resource;
+import org.openecomp.sdc.be.model.Service;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public abstract class BaseForwardingPathVersionChangeTest {
+ protected Service service;
+ protected ComponentInstance nodeACI;
+ protected ComponentInstance newNodeACI;
+ protected Component newNodeAC;
+ protected Component newNodeWithoutCapability;
+ protected DataForMergeHolder dataHolder;
+ protected static final String nodeA = "nodeA";
+ protected static final String NODE_A_FORWARDER_CAPABILITY = "nodeA_FORWARDER_CAPABILITY";
+ protected static final String nodeB = "nodeB";
+ protected static final String newNodeA = "newNodeA";
+ protected static final String fpName = "fpName";
+ protected static final String FPId = "1122";
+
+
+ @Before
+ public void initService() {
+ service = new Service();
+ ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName);
+ String protocol = "protocol";
+ forwardingPath.setProtocol(protocol);
+ forwardingPath.setDestinationPortNumber("DestinationPortNumber");
+ ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition
+ = new ListDataDefinition<>();
+
+ forwardingPathElementListDataDefinition.add(
+ new ForwardingPathElementDataDefinition(nodeA, nodeB, NODE_A_FORWARDER_CAPABILITY, "nodeBcpType" , "nodeDcpName",
+ "nodeBcpName"));
+ forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>();
+ forwardingPaths.put(FPId, forwardingPath);
+ service.setForwardingPaths(forwardingPaths);
+ nodeACI = new ComponentInstance();
+ initComponentInstance(nodeACI, nodeA);
+ newNodeACI = new ComponentInstance();
+ initComponentInstance(newNodeACI, newNodeA);
+ newNodeAC = new Resource();
+ newNodeWithoutCapability=new Resource();
+ initComponent(newNodeAC, newNodeA);
+ service.setComponentInstances(Lists.newArrayList(newNodeACI));
+ initComponentWithoutForwarder(newNodeWithoutCapability,"newNodeC");
+ service.setComponentInstances(Lists.newArrayList(nodeACI));
+
+ dataHolder = new DataForMergeHolder();
+ dataHolder.setOrigComponentInstId(nodeA);
+ }
+
+ private void initComponent(Component component, String uniqueId) {
+ component.setUniqueId(uniqueId);
+ HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilites();
+ component.setCapabilities(capabilities);
+ }
+
+ private void initComponentWithoutForwarder(Component component, String uniqueId) {
+ component.setUniqueId(uniqueId);
+ HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilitesWithoutForwarder();
+ component.setCapabilities(capabilities);
+ }
+
+ private HashMap<String, List<CapabilityDefinition>> initCapabilites() {
+ HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
+ CapabilityDefinition forwarder = new CapabilityDefinition();
+ forwarder.setType(ForwardingPathUtils.FORWARDER_CAPABILITY);
+ forwarder.setUniqueId(NODE_A_FORWARDER_CAPABILITY);
+ capabilities.put("bla bla", Arrays.asList(forwarder));
+ return capabilities;
+ }
+
+ private HashMap<String, List<CapabilityDefinition>> initCapabilitesWithoutForwarder() {
+ HashMap<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
+ CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
+ capabilityDefinition.setType("tosca.capabilities.Node");
+ capabilityDefinition.setUniqueId("tosca capability");
+ capabilities.put("bla bla", Arrays.asList(capabilityDefinition));
+ return capabilities;
+ }
+
+ private void initComponentInstance(ComponentInstance component, String uniqueId) {
+ component.setUniqueId(uniqueId);
+ HashMap<String, List<CapabilityDefinition>> capabilities = initCapabilites();
+ component.setCapabilities(capabilities);
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java
new file mode 100644
index 0000000000..03bbc31aef
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathBussinessLogicTest.java
@@ -0,0 +1,107 @@
+
+package org.openecomp.sdc.be.components.path;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import fj.data.Either;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
+import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = "/paths/path-context.xml")
+public class ForwardingPathBussinessLogicTest extends BaseForwardingPathTest {
+
+
+ @Test
+ public void shouldFailToUpdateForwardingPathSincePathDoesNotExist() {
+ Service service = initForwardPath();
+ Either<Service, ResponseFormat> serviceResponseFormatEither = bl.updateForwardingPath(FORWARDING_PATH_ID, service, user, true);
+ assertEquals(true, serviceResponseFormatEither.isRight());
+ }
+
+ @Test
+ public void shouldFailToDeleteForwardingPathSincePathDoesNotExist() {
+ Service service = initForwardPath();
+ Either<Set<String>, ResponseFormat> serviceResponseFormatEither = bl.deleteForwardingPaths("delete_forward_test", Sets.newHashSet(FORWARDING_PATH_ID), user, true);
+ assertEquals(true, serviceResponseFormatEither.isRight());
+ }
+
+ @Test
+ public void shouldSucceedCreateAndDeleteForwardingPath() {
+ Service createdService = createService();
+ Service service = initForwardPath();
+ assertNotNull(service);
+ Either<Service, ResponseFormat> serviceResponseFormatEither = bl.createForwardingPath(createdService.getUniqueId(), service, user, true);
+ assertEquals(true, serviceResponseFormatEither.isLeft());
+ Map<String, ForwardingPathDataDefinition> forwardingPathsMap = serviceResponseFormatEither.left().value().getForwardingPaths();
+ Set<String> pathIds = forwardingPathsMap.keySet();
+ assertEquals(1, pathIds.size());
+ String toscaResourceName = forwardingPathsMap.values().iterator().next().getToscaResourceName();
+
+ // should return the created path
+ Either<UiComponentDataTransfer, ResponseFormat> uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
+ assertEquals(true, uiResaponse.isLeft());
+ UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value();
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = uiServiceDataTransfer.getForwardingPaths();
+ assertTrue(forwardingPaths.keySet().equals(pathIds));
+ Map<String, ForwardingPathDataDefinition> updatedForwardingPaths = new HashMap<>(forwardingPaths);
+ String newProtocol = "https";
+ ForwardingPathDataDefinition forwardingPathDataDefinition = updatedForwardingPaths.values().stream().findAny().get();
+ assertEquals(forwardingPathDataDefinition.getProtocol(), HTTP_PROTOCOL);
+ assertEquals(toscaResourceName, forwardingPathDataDefinition.getToscaResourceName());
+ ForwardingPathDataDefinition forwardingPathDataDefinitionUpdate = updatedForwardingPaths.values().iterator().next();
+ // updated values
+ forwardingPathDataDefinitionUpdate.setProtocol(newProtocol);
+ forwardingPathDataDefinitionUpdate.setPathElements(new ListDataDefinition<>());
+
+ // should update value
+ service.getForwardingPaths().clear();
+ service.getForwardingPaths().put(forwardingPathDataDefinitionUpdate.getUniqueId(), forwardingPathDataDefinitionUpdate);
+ serviceResponseFormatEither = bl.updateForwardingPath(createdService.getUniqueId(), service, user, true);
+ assertTrue(serviceResponseFormatEither.isLeft());
+
+ // make sure changes were applied
+ uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
+ assertEquals(true, uiResaponse.isLeft());
+ uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value();
+ Map<String, ForwardingPathDataDefinition> forwardingPathsUpdated = uiServiceDataTransfer.getForwardingPaths();
+ ForwardingPathDataDefinition updatedData = forwardingPathsUpdated.values().iterator().next();
+ assertEquals(newProtocol, updatedData.getProtocol());
+ assertTrue(updatedData.getPathElements().isEmpty());
+
+ Service createdData = serviceResponseFormatEither.left().value();
+ Set<String> paths = createdData.getForwardingPaths().keySet();
+ Either<Set<String>, ResponseFormat> setResponseFormatEither = bl.deleteForwardingPaths(createdService.getUniqueId(), paths, user, true);
+ assertEquals(true, setResponseFormatEither.isLeft());
+
+ // nothing to return now
+ uiResaponse = bl.getComponentDataFilteredByParams(createdService.getUniqueId(), user, Lists.newArrayList(ComponentFieldsEnum.COMPONENT_INSTANCES.getValue(),ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
+ assertEquals(true, uiResaponse.isLeft());
+ uiServiceDataTransfer = (UiServiceDataTransfer) uiResaponse.left().value();
+ forwardingPaths = uiServiceDataTransfer.getForwardingPaths();
+ assertTrue(forwardingPaths == null || forwardingPaths.isEmpty());
+
+ }
+
+
+
+
+}
+
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java
new file mode 100644
index 0000000000..5af94d7938
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathChangeVersionTest.java
@@ -0,0 +1,60 @@
+package org.openecomp.sdc.be.components.path;
+
+import org.javatuples.Pair;
+import org.junit.Test;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+public class ForwardingPathChangeVersionTest extends BaseForwardingPathVersionChangeTest {
+
+
+ @Test
+ public void updateForwardingPath() {
+ Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils()
+ .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA);
+ Map<String, ForwardingPathDataDefinition> updated = pair.getValue0();
+ assertNotNull(updated);
+ assertEquals(1, updated.size());
+ assertEquals(newNodeA, updated.values().iterator().next().getPathElements().getListToscaDataDefinition().get(0).getFromNode());
+ Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1();
+ assertNotNull(deleted);
+ assertEquals(0, deleted.size());
+ }
+
+ @Test
+ public void deleteForwardingPath(){
+ newNodeAC.setCapabilities(new HashMap<>());
+ Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils()
+ .updateForwardingPathOnVersionChange(service,dataHolder,newNodeAC, newNodeA);
+ Map<String, ForwardingPathDataDefinition> updated = pair.getValue0();
+ assertNotNull(updated);
+ assertEquals(0, updated.size());
+
+ Map<String, ForwardingPathDataDefinition> deleted = pair.getValue1();
+ assertNotNull(deleted);
+ assertEquals(1, deleted.size());
+ assertEquals(FPId, deleted.keySet().stream().findAny().get());
+ }
+
+ @Test
+ public void fetchPathsToBeDeletedZeroPaths(){
+ Set<String> data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service,
+ dataHolder,newNodeAC);
+ assertEquals(0,data.size());
+ }
+
+ @Test
+ public void fetchPathsToBeDeleted(){
+ Set<String> data=new ForwardingPathUtils().getForwardingPathsToBeDeletedOnVersionChange(service,
+ dataHolder,newNodeWithoutCapability);
+ assertEquals(1,data.size());
+ }
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java
new file mode 100644
index 0000000000..e5de493cb1
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathDeleteCITest.java
@@ -0,0 +1,74 @@
+package org.openecomp.sdc.be.components.path;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+import org.openecomp.sdc.be.model.Service;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class ForwardingPathDeleteCITest {
+
+ private Service service;
+ private static final String nodeA = "nodeA";
+ private static final String nodeB = "nodeB";
+ private static final String fpName = "fpName";
+
+ @Before
+ public void initService() {
+ service = new Service();
+ ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(fpName);
+ String protocol = "protocol";
+ forwardingPath.setProtocol(protocol);
+ forwardingPath.setDestinationPortNumber("DestinationPortNumber");
+ ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition
+ = new ListDataDefinition<>();
+
+ forwardingPathElementListDataDefinition.add(
+ new ForwardingPathElementDataDefinition(nodeA, nodeB, "nodeAcpType", "nodeBcpType", "nodeDcpName",
+ "nodeBcpName"));
+ forwardingPathElementListDataDefinition.add(
+ new ForwardingPathElementDataDefinition(nodeB, "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName",
+ "nodeBcpName"));
+ forwardingPathElementListDataDefinition.add(
+ new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName",
+ "nodeBcpName"));
+ forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = new HashMap<>();
+ forwardingPaths.put("NEW", forwardingPath);
+ service.setForwardingPaths(forwardingPaths);
+ }
+
+
+ @Test
+ public void getListToDelete() {
+
+ Set<String> forwardingPathNamesToDeleteOnComponenetInstanceDeletion = new ForwardingPathUtils()
+ .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeA);
+ assertEquals(1, forwardingPathNamesToDeleteOnComponenetInstanceDeletion.size());
+ assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName));
+
+ Set<String> forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils()
+ .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, nodeB);
+ assertNotNull(forwardingPathNamesToDeleteOnCIDelete);
+ assertEquals(1, forwardingPathNamesToDeleteOnCIDelete.size());
+ assertTrue(forwardingPathNamesToDeleteOnComponenetInstanceDeletion.contains(fpName));
+
+ forwardingPathNamesToDeleteOnCIDelete = new ForwardingPathUtils()
+ .findForwardingPathNamesToDeleteOnComponentInstanceDeletion(service, "Does not exist");
+ assertNotNull(forwardingPathNamesToDeleteOnCIDelete);
+ assertEquals(0, forwardingPathNamesToDeleteOnCIDelete.size());
+ assertFalse(forwardingPathNamesToDeleteOnCIDelete.contains(fpName));
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java
new file mode 100644
index 0000000000..9ab9ffd788
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathTestUtils.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.be.components.path;
+
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+
+public interface ForwardingPathTestUtils {
+
+ default ForwardingPathDataDefinition createPath(String pathName, String protocol, String ports, String uniqueId){
+ ForwardingPathDataDefinition forwardingPath = new ForwardingPathDataDefinition(pathName);
+ forwardingPath.setProtocol(protocol);
+ forwardingPath.setDestinationPortNumber(ports);
+ forwardingPath.setUniqueId(uniqueId);
+ ListDataDefinition<ForwardingPathElementDataDefinition> forwardingPathElementListDataDefinition = new ListDataDefinition<>();
+ String nodeA = "nodeA";
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition(nodeA, "nodeB", "nodeAcpType", "nodeBcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeB", "nodeC", "nodeBcpType", "nodeCcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPathElementListDataDefinition.add(new ForwardingPathElementDataDefinition("nodeC", "nodeD", "nodeCcpType", "nodeDcpType", "nodeDcpName", "nodeBcpName"));
+ forwardingPath.setPathElements(forwardingPathElementListDataDefinition);
+
+ return forwardingPath;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java
new file mode 100644
index 0000000000..e7100a4a7e
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathToscaUtilTest.java
@@ -0,0 +1,186 @@
+package org.openecomp.sdc.be.components.path;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
+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.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
+import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
+import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+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 static org.junit.Assert.assertEquals;
+import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDER;
+import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME;
+import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PORTS_RANGE;
+import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.PROTOCOL;
+import static org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil.addForwardingPaths;
+
+/**
+ * @author KATYR, ORENK
+ * @since November 19, 2017
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = "/paths/path-context.xml")
+public class ForwardingPathToscaUtilTest extends BaseForwardingPathTest {
+
+ private static final String NODE_NAME_1 = "nodeA-name";
+ private static final String NODE_NAME_2 = "nodeB-name";
+ private static final String PATH_1_PROTOCOL = "protocol-path1";
+ private static final String PATH_1_DESC = "path1-desc";
+ private static final String PATH_1_PORTS = "8585";
+ private static final String PATH_1_NAME = "pathName1";
+ private Service service;
+ private Map<String, Component> originComponents = new HashMap<>();
+ private static final String NODE_ID_1 = "nodeA-id";
+ private static final String NODE_ID_2 = "nodeB-id";
+ private static final String FORWARDING_PATH_TOSCA_TYPE = "org.openecomp.nodes.ForwardingPath";
+
+
+ @Before
+ public void setUpForwardingPath() {
+ service = initForwardPath();
+ List<ComponentInstance> componentInstances = new ArrayList<>();
+ componentInstances.add(generateComponentInstance(NODE_NAME_1, NODE_ID_1));
+ componentInstances.add(generateComponentInstance(NODE_NAME_2, NODE_ID_2));
+ service.setComponentInstances(componentInstances);
+ }
+
+ private ComponentInstance generateComponentInstance(String name, String uuid) {
+ ComponentInstance componentInstance = new ComponentInstance();
+ componentInstance.setName(name);
+ componentInstance.setUniqueId(uuid);
+ componentInstance.setComponentUid(uuid);
+ Map<String, List<CapabilityDefinition>> capabiltiesMap = new HashMap<>();
+ CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
+ capabilityDefinition.setMinOccurrences(Integer.toString(1));
+ capabilityDefinition.setMaxOccurrences(Integer.toString(100));
+ capabilityDefinition.setType(ForwardingPathToscaUtil.FORWARDS_TO_TOSCA_NAME);
+ capabilityDefinition.setName(name);
+ capabilityDefinition.setUniqueId(name);
+ capabilityDefinition.setPath(Arrays.asList("Just", "something", "to", "read"));
+ capabiltiesMap.put(capabilityDefinition.getName(),
+ Collections.singletonList(capabilityDefinition));
+ componentInstance.setCapabilities(capabiltiesMap);
+ Resource resource = new Resource();
+ resource.setToscaResourceName("test");
+ originComponents.put(uuid, resource);
+ return componentInstance;
+ }
+
+
+ @Test
+ public void singleElementPath() {
+ createPathSingleElement();
+ Map<String, ToscaNodeTemplate> nodeTemplatesRes = new HashMap<>();
+
+ Map<String, ToscaNodeTemplate> expectedNodeTemplatesRes = new HashMap<>();
+ ToscaNodeTemplate pathEntry = new ToscaNodeTemplate();
+ pathEntry.setType(FORWARDING_PATH_TOSCA_TYPE);
+ Map<String, Object> expectedProps = new HashMap<>();
+ expectedProps.put(PORTS_RANGE, Collections.singletonList(PATH_1_PORTS));
+ expectedProps.put(PROTOCOL, PATH_1_PROTOCOL);
+ pathEntry.setProperties(expectedProps);
+ List<Map<String, ToscaTemplateRequirement>> requirements = new ArrayList<>();
+ ToscaTemplateRequirement firstEntryReq = new ToscaTemplateRequirement();
+ ToscaTemplateRequirement secondEntryReq = new ToscaTemplateRequirement();
+
+ firstEntryReq.setCapability("null." + NODE_NAME_1);
+ secondEntryReq.setCapability("null." + NODE_NAME_2);
+
+ firstEntryReq.setNode(NODE_NAME_1);
+ secondEntryReq.setNode(NODE_NAME_2);
+
+ firstEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME);
+ secondEntryReq.setRelationship(FORWARDS_TO_TOSCA_NAME);
+
+ Map<String, ToscaTemplateRequirement> entryMap1 = new HashMap<>();
+ Map<String, ToscaTemplateRequirement> entryMap2 = new HashMap<>();
+
+ entryMap1.put(FORWARDER, firstEntryReq);
+ entryMap2.put(FORWARDER, secondEntryReq);
+
+ requirements.add(entryMap1);
+ requirements.add(entryMap2);
+
+ pathEntry.setRequirements(requirements);
+ expectedNodeTemplatesRes.put(PATH_1_NAME, pathEntry);
+ addForwardingPaths(service, nodeTemplatesRes, capabiltyRequirementConvertor, originComponents,
+ toscaOperationFacade);
+
+ assertEquals(2, nodeTemplatesRes.get(PATH_1_NAME).getRequirements().size());
+ compareToscaPathEntry(expectedNodeTemplatesRes, nodeTemplatesRes);
+ }
+
+ private void compareToscaPathEntry(Map<String, ToscaNodeTemplate> expectedNodeTemplatesRes,
+ Map<String, ToscaNodeTemplate> nodeTemplatesRes) {
+ final ToscaNodeTemplate expectedTemplate = expectedNodeTemplatesRes.get(PATH_1_NAME);
+ final ToscaNodeTemplate actualTemplate = nodeTemplatesRes.get(PATH_1_NAME);
+ assertEquals(expectedTemplate.getProperties(), actualTemplate.getProperties());
+ final int size = expectedTemplate.getRequirements().size();
+ assertEquals(size,
+ actualTemplate.getRequirements().size());
+ for (int i = 0; i < size; i++) {
+ compareToscaRequirement(expectedTemplate, actualTemplate, i);
+ }
+ }
+
+ private void compareToscaRequirement(ToscaNodeTemplate expectedTemplate,
+ ToscaNodeTemplate actualTemplate,
+ int i) {
+ final ToscaTemplateRequirement actualRequirement =
+ actualTemplate.getRequirements().get(i).get(FORWARDER);
+ final ToscaTemplateRequirement expectedToscaRequirement = expectedTemplate
+ .getRequirements()
+ .get(i).get(FORWARDER);
+ assertEquals(actualRequirement.getCapability(), expectedToscaRequirement.getCapability());
+ assertEquals(actualRequirement.getNode(), expectedToscaRequirement.getNode());
+ }
+
+ private void createPathSingleElement() {
+ ForwardingPathElementDataDefinition element1 = initElement(NODE_ID_1, NODE_ID_2, NODE_NAME_1,
+ NODE_NAME_2);
+
+ ListDataDefinition<ForwardingPathElementDataDefinition> list = new ListDataDefinition<>();
+ list.add(element1);
+
+
+ ForwardingPathDataDefinition path = new ForwardingPathDataDefinition();
+ path.setDescription(PATH_1_DESC);
+ path.setProtocol(PATH_1_PROTOCOL);
+ path.setDestinationPortNumber(PATH_1_PORTS);
+ path.setToscaResourceName(FORWARDING_PATH_TOSCA_TYPE);
+ path.setPathElements(list);
+ path.setName(PATH_1_NAME);
+
+ Map<String, ForwardingPathDataDefinition> paths = new HashMap<>();
+ paths.put(PATH_1_NAME, path);
+
+ service.setForwardingPaths(paths);
+ }
+
+ private ForwardingPathElementDataDefinition initElement(String fromId, String toId, String
+ fromCP, String toCP) {
+ ForwardingPathElementDataDefinition element = new ForwardingPathElementDataDefinition();
+ element.setFromCP(fromCP);
+ element.setFromNode(fromId);
+ element.setToCP(toCP);
+ element.setToNode(toId);
+ return element;
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java
new file mode 100644
index 0000000000..fd9e25f475
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/ForwardingPathValidatorTest.java
@@ -0,0 +1,151 @@
+package org.openecomp.sdc.be.components.path;
+
+
+import com.google.common.collect.Sets;
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.Collection;
+import java.util.Set;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+public class ForwardingPathValidatorTest implements ForwardingPathTestUtils {
+
+ ResponseFormatManager mock;
+
+ private Service service = (Service) getToscaFullElement().left().value();
+
+
+ @Mock
+ ToscaOperationFacade toscaOperationFacade;
+ @InjectMocks
+ ForwardingPathValidationUtilTest test = new ForwardingPathValidationUtilTest();
+
+ private static final String SERVICE_ID = "serviceid1";
+
+
+
+
+ @Before
+ public void init() {
+ MockitoAnnotations.initMocks(this);
+ mock = Mockito.mock(ResponseFormatManager.class);
+ when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class))).thenReturn(Either.left(service));
+ when(mock.getResponseFormat(any())).thenReturn(new ResponseFormat());
+ when(mock.getResponseFormat(any(), any())).thenReturn(new ResponseFormat());
+ when(mock.getResponseFormat(any(), any(), any())).thenReturn(new ResponseFormat());
+
+ }
+
+ @Test
+ public void testValidForwardingPathName(){
+
+ Collection<ForwardingPathDataDefinition> paths = createData("pathName", "http", "8285", "pathName");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false);
+ assertTrue(booleanResponseFormatEither.isLeft());
+ }
+
+ @Test
+ public void testEmptyForwardingPathName(){
+ Collection<ForwardingPathDataDefinition> paths = createData("", "protocol", "8285", "name1");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test
+ .validateForwardingPaths(paths, SERVICE_ID, false);
+ assertTrue(booleanResponseFormatEither.isRight());
+ }
+
+ @Test
+ public void testLongForwardingPathName(){
+ String pathName = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" +
+ "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" +
+ "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: ";
+ Collection<ForwardingPathDataDefinition> paths = createData(pathName,
+ "http", "port", "name1");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test
+ .validateForwardingPaths(paths, SERVICE_ID, false);
+ assertTrue(booleanResponseFormatEither.isRight());
+
+ }
+
+ @Test
+ public void testUniqueForwardingPathNameUpdateName(){
+
+ Collection<ForwardingPathDataDefinition> paths = createData("pathName4", "httpfd", "82df85", "name1");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true);
+ assertTrue(booleanResponseFormatEither.isLeft());
+
+ }
+
+ @Test
+ public void testUniqueForwardingPathNameUpdatePort(){
+
+ Collection<ForwardingPathDataDefinition> paths = createData("pathName3", "httpfd", "82df85", "name1");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, true);
+ assertTrue(booleanResponseFormatEither.isLeft());
+
+ }
+
+ @Test
+ public void testLongForwardingPathPortNumber(){
+ String port = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" +
+ "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" +
+ "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: ";
+ Collection<ForwardingPathDataDefinition> paths = createData("pathName",
+ "http", port, "name1");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false);
+ assertTrue(booleanResponseFormatEither.isRight());
+
+ }
+
+ @Test
+ public void testLongForwardingPathProtocol(){
+ String protocol = "Failed to execute goal on project catalog-be: Could not resolve dependencies for project \n" +
+ "org.openecomp.sdc:catalog-be:war:1.1.0-SNAPSHOT: Failed to collect dependencies at \n" +
+ "org.openecomp.sdc.common:openecomp-sdc-artifact-generator-api:jar:1802.0.1.167: ";
+ Collection<ForwardingPathDataDefinition> paths = createData("pathName",
+ protocol, "port", "name1");
+ Either<Boolean, ResponseFormat> booleanResponseFormatEither = test.validateForwardingPaths(paths, SERVICE_ID, false);
+ assertTrue(booleanResponseFormatEither.isRight());
+
+ }
+
+ private Set<ForwardingPathDataDefinition> createData(String pathName, String protocol, String ports, String uniqueId) {
+
+ return Sets.newHashSet(createPath(pathName, protocol, ports, uniqueId));
+ }
+
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement() {
+
+ return Either.left((T) setUpServiceMcok());
+ }
+
+ private Service setUpServiceMcok(){
+ Service service = new Service();
+ service.addForwardingPath(createPath("pathName3", "http", "8285", "name1"));
+ return service;
+ }
+
+ private class ForwardingPathValidationUtilTest extends ForwardingPathValidator {
+
+ protected ResponseFormatManager getResponseFormatManager() {
+ return mock;
+ }
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java
new file mode 100644
index 0000000000..290ba07883
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ArtifactCassandraDaoMock.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+
+@Component("artifact-cassandra-dao")
+public class ArtifactCassandraDaoMock extends ArtifactCassandraDao {
+ @PostConstruct
+ @Override
+ public void init() {
+
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java
new file mode 100644
index 0000000000..c4885e1f07
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/AuditCassandraDaoMock.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+
+@Component("audit-cassandra-dao")
+public class AuditCassandraDaoMock extends AuditCassandraDao{
+
+ @PostConstruct
+ public void init() {
+
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java
new file mode 100644
index 0000000000..0d4b2f1e7e
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/CassandraClientMock.java
@@ -0,0 +1,21 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.MappingManager;
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.springframework.stereotype.Component;
+
+@Component("cassandra-client")
+public class CassandraClientMock extends CassandraClient{
+ public CassandraClientMock() {
+
+ }
+
+ @Override
+ public Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> connect(String keyspace) {
+ return null;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java
new file mode 100644
index 0000000000..6a9731e86d
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ComponentCassandraDaoMock.java
@@ -0,0 +1,68 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.ComponentCacheAccessor;
+import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao;
+import org.openecomp.sdc.be.resources.data.ComponentCacheData;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+@Component("component-cassandra-dao")
+public class ComponentCassandraDaoMock extends ComponentCassandraDao {
+
+ public static Integer DEFAULT_FETCH_SIZE = 500;
+ private ComponentCacheAccessor componentCacheAccessor;
+
+ public ComponentCassandraDaoMock() {
+ super();
+ }
+
+ @PostConstruct
+ public void init() {
+
+ }
+
+ public Either<List<ComponentCacheData>, ActionStatus> getComponents(List<String> ids) {
+
+ return null;
+ }
+
+ public Either<List<ComponentCacheData>, ActionStatus> getAllComponentIdTimeAndType() {
+ return null;
+ }
+
+
+ public Either<ComponentCacheData, ActionStatus> getComponent(String id) {
+
+ return null;
+ }
+
+ public CassandraOperationStatus saveComponent(ComponentCacheData componentCacheData) {
+ return null;
+ }
+
+
+ public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+ return null;
+ }
+
+
+ public Either<ImmutablePair<List<ComponentCacheData>, Set<String>>, ActionStatus> getComponents(
+ Map<String, Long> idToTimestampMap) {
+
+ return null;
+ }
+
+ public CassandraOperationStatus deleteComponent(String id) {
+ return null;
+ }
+
+ }
+
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java
new file mode 100644
index 0000000000..748ae56bd7
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/DistributionEngineMock.java
@@ -0,0 +1,61 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
+import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+
+public class DistributionEngineMock implements IDistributionEngine {
+ @Override
+ public boolean isActive() {
+ return false;
+ }
+
+ @Override
+ public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envName, String userId, String modifierName) {
+ return null;
+ }
+
+ @Override
+ public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, String userId, String modifierName) {
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus isEnvironmentAvailable(String envName) {
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus isEnvironmentAvailable() {
+ return null;
+ }
+
+ @Override
+ public void disableEnvironment(String envName) {
+
+ }
+
+ @Override
+ public StorageOperationStatus isReadyForDistribution(Service service, String envName) {
+ return null;
+ }
+
+ @Override
+ public INotificationData buildServiceForDistribution(Service service, String distributionId, String workloadContext) {
+ return null;
+ }
+
+ @Override
+ public StorageOperationStatus verifyServiceHasDeploymentArtifacts(Service service) {
+ return null;
+ }
+
+ @Override
+ public OperationalEnvironmentEntry getEnvironmentById(String opEnvId) {
+ return null;
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java
new file mode 100644
index 0000000000..2d7b1ad287
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/EnvironmentCassandraDaoMock.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+
+@Component("operational-environment-dao")
+public class EnvironmentCassandraDaoMock extends OperationalEnvironmentDao {
+ @PostConstruct
+ @Override
+ public void init() {
+
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java
new file mode 100644
index 0000000000..09e1a72b44
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathToscaOperationFacade.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.impl.ForwardingPathUtils;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+@org.springframework.stereotype.Component("tosca-operation-facade")
+public class ForwardingPathToscaOperationFacade extends ToscaOperationFacade {
+ protected static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
+ @Override
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
+
+ return Either.left(setupGenericServiceMock());
+ }
+
+ protected Resource setupGenericServiceMock(){
+ Resource genericService = new Resource();
+ genericService.setVersion("1.0");
+ genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
+ return genericService;
+ }
+
+ @Override
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
+ if(resourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || resourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){
+ Resource component = new Resource();
+ component.setToscaResourceName(GENERIC_SERVICE_NAME);
+ return Either.left((T)component);
+ }
+ return super.getLatestByName(resourceName);
+ }
+
+ @Override
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
+ if(toscaResourceName.equals(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME) || toscaResourceName.equals(ForwardingPathUtils.FORWARDER_CAPABILITY)){
+ Resource component = new Resource();
+ component.setToscaResourceName(GENERIC_SERVICE_NAME);
+ return Either.left((T)component);
+ }
+ return super.getLatestByToscaResourceName(toscaResourceName);
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java
new file mode 100644
index 0000000000..1aa3ab8102
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/ForwardingPathValidatorMock.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.components.path.ForwardingPathValidator;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import java.util.Collection;
+
+public class ForwardingPathValidatorMock extends ForwardingPathValidator {
+ @Override
+ public Either<Boolean, ResponseFormat> validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths, String serviceId,
+ boolean isUpdate) {
+ return Either.left(Boolean.TRUE);
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java
new file mode 100644
index 0000000000..4e3923d2ea
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/InMemoryTitanGraphClient.java
@@ -0,0 +1,218 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+
+import com.thinkaurelius.titan.core.InvalidElementException;
+import com.thinkaurelius.titan.core.InvalidIDException;
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.QueryException;
+import com.thinkaurelius.titan.core.SchemaViolationException;
+import com.thinkaurelius.titan.core.TitanConfigurationException;
+import com.thinkaurelius.titan.core.TitanFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
+import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
+import com.thinkaurelius.titan.core.schema.TitanManagement;
+import com.thinkaurelius.titan.core.util.TitanCleanup;
+import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException;
+import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException;
+import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException;
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.dao.TitanClientStrategy;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+@Component("titan-client")
+public class InMemoryTitanGraphClient extends TitanGraphClient {
+
+
+ private static final Logger logger = LoggerFactory.getLogger(InMemoryTitanGraphClient.class);
+
+ private static final String OK = "GOOD";
+
+ public InMemoryTitanGraphClient() {
+ }
+
+
+ private TitanGraph graph;
+ TitanClientStrategy titanClientStrategy;
+
+ public InMemoryTitanGraphClient(TitanClientStrategy titanClientStrategy) {
+ super();
+ this.titanClientStrategy = titanClientStrategy;
+ logger.info("** TitanGraphClient created");
+ }
+
+ @PostConstruct
+ public TitanOperationStatus createGraph() {
+
+ logger.info("** createGraph started **");
+ graph = TitanFactory.build().set("storage.backend", "inmemory").open();
+ createTitanSchema();
+
+ logger.info("** in memory graph created");
+ return TitanOperationStatus.OK;
+
+ }
+
+
+ public void cleanupGraph() {
+ if (graph != null) {
+ // graph.shutdown();
+ graph.close();
+ TitanCleanup.clear(graph);
+ }
+ }
+
+ public TitanOperationStatus createGraph(String titanCfgFile) {
+ logger.info("** open graph with {} started", titanCfgFile);
+ try {
+ logger.info("openGraph : try to load file {}", titanCfgFile);
+ graph = TitanFactory.open(titanCfgFile);
+ if (graph.isClosed()) {
+ logger.error("titan graph was not initialized");
+ return TitanOperationStatus.NOT_CREATED;
+ }
+
+ } catch (Exception e) {
+ this.graph = null;
+ logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile, e);
+ return TitanOperationStatus.NOT_CONNECTED;
+ }
+
+ logger.info("** Titan graph created ");
+
+ return TitanOperationStatus.OK;
+ }
+
+
+ public Either<TitanGraph, TitanOperationStatus> getGraph() {
+ if (graph != null) {
+ return Either.left(graph);
+ } else {
+ return Either.right(TitanOperationStatus.NOT_CREATED);
+ }
+ }
+
+ public TitanOperationStatus commit() {
+ if (graph != null) {
+ try {
+ graph.tx().commit();
+ return TitanOperationStatus.OK;
+ } catch (Exception e) {
+ return handleTitanException(e);
+ }
+ } else {
+ return TitanOperationStatus.NOT_CREATED;
+ }
+ }
+
+ public TitanOperationStatus rollback() {
+ if (graph != null) {
+ try {
+ // graph.rollback();
+ graph.tx().rollback();
+ return TitanOperationStatus.OK;
+ } catch (Exception e) {
+ return handleTitanException(e);
+ }
+ } else {
+ return TitanOperationStatus.NOT_CREATED;
+ }
+ }
+
+ public static TitanOperationStatus handleTitanException(Exception e) {
+ if (e instanceof TitanConfigurationException) {
+ return TitanOperationStatus.TITAN_CONFIGURATION;
+ }
+ if (e instanceof SchemaViolationException) {
+ return TitanOperationStatus.TITAN_SCHEMA_VIOLATION;
+ }
+ if (e instanceof PermanentLockingException) {
+ return TitanOperationStatus.TITAN_SCHEMA_VIOLATION;
+ }
+ if (e instanceof IDPoolExhaustedException) {
+ return TitanOperationStatus.GENERAL_ERROR;
+ }
+ if (e instanceof InvalidElementException) {
+ return TitanOperationStatus.INVALID_ELEMENT;
+ }
+ if (e instanceof InvalidIDException) {
+ return TitanOperationStatus.INVALID_ID;
+ }
+ if (e instanceof QueryException) {
+ return TitanOperationStatus.INVALID_QUERY;
+ }
+ if (e instanceof ResourceUnavailableException) {
+ return TitanOperationStatus.RESOURCE_UNAVAILABLE;
+ }
+ if (e instanceof IllegalArgumentException) {
+ // TODO check the error message??
+ return TitanOperationStatus.ILLEGAL_ARGUMENT;
+ }
+
+ return TitanOperationStatus.GENERAL_ERROR;
+ }
+
+ public boolean getHealth() {
+ return true;
+ }
+
+ private boolean isGraphOpen() {
+ return true;
+ }
+
+
+ private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck";
+
+
+ private void createTitanSchema() {
+
+ TitanManagement graphMgt = graph.openManagement();
+ TitanGraphIndex index = null;
+ for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
+ PropertyKey propKey = null;
+ if (!graphMgt.containsPropertyKey(prop.getProperty())) {
+ Class<?> clazz = prop.getClazz();
+ if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) {
+ propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
+ }
+ } else {
+ propKey = graphMgt.getPropertyKey(prop.getProperty());
+ }
+ if (prop.isIndexed()) {
+ if (!graphMgt.containsGraphIndex(prop.getProperty())) {
+ if (prop.isUnique()) {
+ index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex();
+
+ graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures
+ // only
+ // one
+ // name
+ // per
+ // vertex
+ graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures
+ // name
+ // uniqueness
+ // in
+ // the
+ // graph
+
+ } else {
+ graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex();
+ }
+ }
+ }
+ }
+ graphMgt.commit();
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java
new file mode 100644
index 0000000000..4e0105f067
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/SdcSchemaFilesCassandraDaoMock.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+
+@Component("sdc-schema-files-cassandra-dao")
+public class SdcSchemaFilesCassandraDaoMock extends SdcSchemaFilesCassandraDao {
+
+ @PostConstruct
+ @Override
+ public void init() {
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java
new file mode 100644
index 0000000000..7a7eff879a
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/beans/TitanGraphTestSetup.java
@@ -0,0 +1,166 @@
+package org.openecomp.sdc.be.components.path.beans;
+
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
+import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
+import com.thinkaurelius.titan.core.schema.TitanManagement;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.be.dao.graph.datatype.ActionEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.resources.data.UserData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+public class TitanGraphTestSetup {
+
+
+ private static final Logger logger = LoggerFactory.getLogger(TitanGraphTestSetup.class);
+
+ private static TitanGraph graph;
+
+ public static boolean createGraph( TitanGraph graph) {
+ TitanGraphTestSetup.graph = graph;
+ createIndexesAndDefaults();
+
+ logger.info("** Titan graph created ");
+
+ return true;
+ }
+
+ private static boolean isVertexExist(Map<String, Object> properties) {
+ TitanGraphQuery query = graph.query();
+
+ if (properties != null && !properties.isEmpty()) {
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ query = query.has(entry.getKey(), entry.getValue());
+ }
+ }
+ Iterable<Vertex> vertecies = query.vertices();
+ java.util.Iterator<Vertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ return true;
+ }
+ return false;
+ }
+
+ private static void createDefaultAdminUser() {
+ createUser(getDefaultUserAdmin());
+ graph.tx().commit();
+
+ }
+
+ private static void createUser(UserData user) {
+ Map<String, Object> checkedProperties = new HashMap<>();
+ checkedProperties.put(GraphPropertiesDictionary.USERID.getProperty(), user.getUserId());
+ checkedProperties.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
+ Map<String, Object> properties = null;
+ if (!isVertexExist(checkedProperties)) {
+ Vertex vertex = graph.addVertex();
+ vertex.property(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName());
+ properties = user.toGraphMap();
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ private static UserData getDefaultUserAdmin() {
+ UserData userData = new UserData();
+ userData.setAction(ActionEnum.Create);
+ userData.setElementType(GraphElementTypeEnum.Node);
+ userData.setUserId("jh0003");
+ userData.setEmail("admin@sdc.com");
+ userData.setFirstName("Jimmy");
+ userData.setLastName("Hendrix");
+ userData.setRole("ADMIN");
+ userData.setStatus(UserStatusEnum.ACTIVE.name());
+ userData.setLastLoginTime(0L);
+ return userData;
+ }
+
+
+ private static void createVertexIndixes() {
+ logger.info("** createVertexIndixes started");
+
+ TitanManagement graphMgt = graph.openManagement();
+ TitanGraphIndex index = null;
+ for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
+ PropertyKey propKey = null;
+ if (!graphMgt.containsPropertyKey(prop.getProperty())) {
+ Class<?> clazz = prop.getClazz();
+ if (!ArrayList.class.getName().equals(clazz.getName()) && !HashMap.class.getName().equals(clazz.getName())) {
+ propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
+ }
+ } else {
+ propKey = graphMgt.getPropertyKey(prop.getProperty());
+ }
+ if (prop.isIndexed()) {
+ if (!graphMgt.containsGraphIndex(prop.getProperty())) {
+ if (prop.isUnique()) {
+ index = graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).unique().buildCompositeIndex();
+
+ graphMgt.setConsistency(propKey, ConsistencyModifier.LOCK); // Ensures
+ // only
+ // one
+ // name
+ // per
+ // vertex
+ graphMgt.setConsistency(index, ConsistencyModifier.LOCK); // Ensures
+ // name
+ // uniqueness
+ // in
+ // the
+ // graph
+
+ } else {
+ graphMgt.buildIndex(prop.getProperty(), Vertex.class).addKey(propKey).buildCompositeIndex();
+ }
+ }
+ }
+ }
+ graphMgt.commit();
+ logger.info("** createVertexIndixes ended");
+
+ }
+
+ private static void createEdgeIndixes() {
+ logger.info("** createEdgeIndixes started");
+ TitanManagement graphMgt = graph.openManagement();
+ for (GraphEdgePropertiesDictionary prop : GraphEdgePropertiesDictionary.values()) {
+ if (!graphMgt.containsGraphIndex(prop.getProperty())) {
+ PropertyKey propKey = graphMgt.makePropertyKey(prop.getProperty()).dataType(prop.getClazz()).make();
+ graphMgt.buildIndex(prop.getProperty(), Edge.class).addKey(propKey).buildCompositeIndex();
+
+ }
+ }
+ graphMgt.commit();
+ logger.info("** createEdgeIndixes ended");
+ }
+
+ private static void createIndexesAndDefaults() {
+ createVertexIndixes();
+ createEdgeIndixes();
+ createDefaultAdminUser();
+ createRootCatalogVertex();
+ }
+ private static void createRootCatalogVertex(){
+ Vertex vertex = graph.addVertex();
+ vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty(), IdBuilderUtils.generateUniqueId());
+ vertex.property(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName());
+ graph.tx().commit();
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.java
new file mode 100644
index 0000000000..79a1dab517
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/path/utils/GraphTestUtils.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.be.components.path.utils;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.io.IoCore;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.UUID;
+
+public final class GraphTestUtils {
+
+ public static GraphVertex createResourceVertex(TitanDao titanDao, Map<GraphPropertyEnum,Object> metadataProps, ResourceTypeEnum type) {
+ GraphVertex vertex = new GraphVertex();
+ if (type == ResourceTypeEnum.VF) {
+ vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ } else {
+ vertex.setLabel(VertexTypeEnum.NODE_TYPE);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE);
+ }
+ String uuid = UUID.randomUUID().toString();
+ vertex.setUniqueId(uuid);
+
+ vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name());
+ vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false);
+ for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) {
+ vertex.addMetadataProperty(prop.getKey(), prop.getValue());
+ }
+ titanDao.createVertex(vertex);
+ titanDao.commit();
+ return vertex;
+ }
+
+ public static GraphVertex createServiceVertex(TitanDao titanDao, Map<GraphPropertyEnum, Object> metadataProps){
+ GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ String uuid = UUID.randomUUID().toString();
+
+ vertex.setUniqueId(uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) {
+ vertex.addMetadataProperty(prop.getKey(), prop.getValue());
+ }
+ titanDao.createVertex(vertex);
+ titanDao.commit();
+ return vertex;
+ }
+
+ public static void clearGraph(TitanDao titanDao) {
+ Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph();
+ TitanGraph graph = graphResult.left().value();
+
+ Iterable<TitanVertex> vertices = graph.query().vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ while (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ vertex.remove();
+ }
+ }
+ titanDao.commit();
+ }
+
+ public static String exportGraphMl(TitanGraph graph, String outputDirectory) {
+ String result = null;
+ String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
+ try {
+ try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
+ graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
+ }
+ result = outputFile;
+ graph.tx().commit();
+ } catch (Exception e) {
+ graph.tx().rollback();
+ e.printStackTrace();
+ }
+ return result;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java
new file mode 100644
index 0000000000..9bd04d6da3
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeceleratorTest.java
@@ -0,0 +1,238 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.utils.ComponentInstanceBuilder;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.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.operations.impl.UniqueIdBuilder;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+
+@RunWith(MockitoJUnitRunner.class)
+public class ComponentInstancePropertyDeceleratorTest extends PropertyDeceleratorTestBase {
+
+ private static final String INSTANCE_ID = "inst1";
+ private static final String RESOURCE_ID = "resource1";
+
+ @InjectMocks
+ private ComponentInstancePropertyDecelerator testInstance;
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+ @Captor
+ private ArgumentCaptor<Map<String, List<ComponentInstanceProperty>>> instancePropertiesCaptor;
+ private Resource resource;
+
+ @Override
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ resource = createResourceWithInstance();
+ }
+
+ @Test
+ public void declarePropertiesAsInputs_componentInstanceNotExist() {
+ Component cmpt = new Resource();
+ Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(cmpt, "someCmptInstId", Collections.emptyList());
+ assertThat(createdInputs.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ verifyZeroInteractions(toscaOperationFacade);
+ }
+
+ @Test
+ public void declarePropertiesAsInputs_singleNonComplexProperty() {
+ List<PropertyDataDefinition> properties = Collections.singletonList(prop1);
+ List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties);
+ when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap()));
+ Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare);
+ List<InputDefinition> inputs = createdInputs.left().value();
+ List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID);
+ verifyCreatedInputs(properties, capturedInstanceProperties, inputs);
+ verifyUpdatedProperties(properties, capturedInstanceProperties, inputs);
+ }
+
+ @Test
+ public void declarePropertiesAsInputs_multipleNonComplexProperty() {
+ List<PropertyDataDefinition> properties = Arrays.asList(prop1, prop2);
+ List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties);
+ when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap()));
+ Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare);
+
+ List<InputDefinition> inputs = createdInputs.left().value();
+ List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID);
+ verifyCreatedInputs(properties, capturedInstanceProperties, inputs);
+ verifyUpdatedProperties(properties, capturedInstanceProperties, inputs);
+ }
+
+ @Test
+ public void declarePropertiesAsInputs_singleComplexProperty() {
+ PropertyDefinition innerProp1 = new PropertyDataDefinitionBuilder()
+ .setName(INNER_PROP1)
+ .setValue("true")
+ .setType("boolean")
+ .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming")
+ .build();
+ PropertyDefinition innerProp2 = new PropertyDataDefinitionBuilder()
+ .setName(INNER_PROP2)
+ .setValue("abc")
+ .setType("string")
+ .setUniqueId(complexProperty.getType() + ".datatype.ecomp_generated_naming")
+ .build();
+ List<ComponentInstancePropInput> propsToDeclare = createComplexPropInputList(innerProp1, innerProp2);
+ when(toscaOperationFacade.addComponentInstancePropertiesToComponent(eq(resource), instancePropertiesCaptor.capture(), eq("inst1"))).thenReturn(Either.left(Collections.emptyMap()));
+ Either<List<InputDefinition>, StorageOperationStatus> createdInputs = testInstance.declarePropertiesAsInputs(resource, "inst1", propsToDeclare);
+
+ List<InputDefinition> inputs = createdInputs.left().value();
+ List<ComponentInstanceProperty> capturedInstanceProperties = instancePropertiesCaptor.getValue().get(INSTANCE_ID);
+
+ verifyCreatedInputsFromComplexProperty(propsToDeclare, capturedInstanceProperties, inputs);
+ verifyUpdatedComplexProperty(capturedInstanceProperties, inputs);
+ }
+
+ private void verifyUpdatedProperties(List<PropertyDataDefinition> properties, List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) {
+ assertThat(capturedInstanceProperties).hasSize(properties.size());
+ Map<String, ComponentInstanceProperty> updatedPropertiesByName = MapUtil.toMap(capturedInstanceProperties, ComponentInstanceProperty::getName);
+ properties.forEach(prop -> verifyUpdatedInstanceProperty(prop, updatedPropertiesByName.get(prop.getName()), inputs));
+ }
+
+ private void verifyUpdatedComplexProperty(List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) {
+ assertThat(capturedInstanceProperties).hasSize(1);
+ verifyUpdatedInstanceComplexProperty(capturedInstanceProperties.get(0), inputs);
+ }
+
+ private void verifyCreatedInputs(List<PropertyDataDefinition> originalPropsToDeclare, List<ComponentInstanceProperty> capturedUpdatedProperties, List<InputDefinition> inputs) {
+ assertThat(inputs).hasSize(originalPropsToDeclare.size());
+ Map<String, InputDefinition> propertyIdToCreatedInput = MapUtil.toMap(inputs, InputDefinition::getPropertyId);
+ originalPropsToDeclare.forEach(propToDeclare -> verifyCreatedInput(propToDeclare, propertyIdToCreatedInput.get(propToDeclare.getUniqueId())));
+ capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId())));
+ }
+
+ private void verifyCreatedInputsFromComplexProperty(List<ComponentInstancePropInput> propsToDeclare, List<ComponentInstanceProperty> capturedInstanceProperties, List<InputDefinition> inputs) {
+ assertThat(inputs).hasSize(propsToDeclare.size());
+ Map<String, InputDefinition> inputsByName = MapUtil.toMap(inputs, InputDefinition::getName);
+ propsToDeclare.forEach(propToDeclare -> verifyCreatedInputFromComplexProperty(propToDeclare, inputsByName));
+ Map<String, List<InputDefinition>> propertyIdToCreatedInput = MapUtil.groupListBy(inputs, InputDefinition::getPropertyId);
+ capturedInstanceProperties.forEach(updatedProperty -> verifyInputPropertiesListFromComplexProperty(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId())));
+ }
+
+ private void verifyInputPropertiesListFromComplexProperty(ComponentInstanceProperty updatedProperty, List<InputDefinition> inputs) {
+ inputs.forEach(input -> verifyInputPropertiesList(updatedProperty, input));
+ }
+
+ private void verifyCreatedInputFromComplexProperty(ComponentInstancePropInput parentProperty, Map<String, InputDefinition> inputsByName) {
+ PropertyDefinition innerProperty = parentProperty.getInput();
+ String expectedInputName = generateExpectedInputName(parentProperty, innerProperty);
+ InputDefinition input = inputsByName.get(expectedInputName);
+ assertThat(input.getType()).isEqualTo(innerProperty.getType());
+ assertThat(input.getValue()).isEqualTo(innerProperty.getValue());
+// assertThat(input.getDefaultValue()).isEqualTo(innerProperty.getValue());//bug
+ assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName()));
+ assertThat(input.getPropertyId()).isEqualTo(parentProperty.getUniqueId());
+ assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID);
+
+ }
+
+ private void verifyInputPropertiesList(ComponentInstanceProperty updatedProperty, InputDefinition input) {
+ assertThat(input.getProperties()).hasSize(1);
+ assertThat(updatedProperty).isEqualTo(input.getProperties().get(0));
+ }
+
+
+ private List<ComponentInstancePropInput> createComplexPropInputList(PropertyDefinition ... innerProperties) {
+ return Stream.of(innerProperties).map(this::createComplexPropInput).collect(Collectors.toList());
+ }
+
+ private ComponentInstancePropInput createComplexPropInput(PropertyDefinition innerProp) {
+ ComponentInstancePropInput componentInstancePropInput = new ComponentInstancePropInput(new ComponentInstanceProperty(complexProperty));
+ componentInstancePropInput.setInput(innerProp);
+ componentInstancePropInput.setPropertiesName(complexProperty.getName() + "#" + innerProp.getName());
+ return componentInstancePropInput;
+ }
+
+ private void verifyUpdatedInstanceProperty(PropertyDataDefinition originalProperty, ComponentInstanceProperty updatedProperty, List<InputDefinition> inputs) {
+ assertThat(updatedProperty.getValue()).isEqualTo(generateGetInputValue(generateExpectedInputName(originalProperty)));
+ assertThat(updatedProperty.isGetInputProperty()).isTrue();
+ assertThat(updatedProperty.getName()).isEqualTo(originalProperty.getName());
+ List<GetInputValueDataDefinition> getInputValues = updatedProperty.getGetInputValues();
+ verifyGetInputValues(getInputValues, inputs);
+ }
+
+ private void verifyUpdatedInstanceComplexProperty(ComponentInstanceProperty updatedComplexProperty, List<InputDefinition> inputs) {
+ assertThat(updatedComplexProperty.getValue()).isEqualTo(generateComplexGetInputValue(inputs));
+ assertThat(updatedComplexProperty.isGetInputProperty()).isTrue();
+ assertThat(updatedComplexProperty.getName()).isEqualTo(complexProperty.getName());
+ List<GetInputValueDataDefinition> getInputValues = updatedComplexProperty.getGetInputValues();
+ verifyGetInputValues(getInputValues, inputs);
+ }
+
+ private void verifyGetInputValues(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs) {
+ Map<String, InputDefinition> inputsByName = MapUtil.toMap(inputs, InputDefinition::getName);
+ getInputValues.forEach(getInputVal -> {
+ InputDefinition input = inputsByName.get(getInputVal.getInputName());
+ assertThat(input.getUniqueId()).isEqualTo(getInputVal.getInputId());
+ });
+ }
+
+ private String generateComplexGetInputValue(List<InputDefinition> createdInputs) {
+ return String.format("{\"%s\":%s,\"%s\":%s}", INNER_PROP1, generateGetInputValue(createdInputs.get(0).getName()), INNER_PROP2, generateGetInputValue(createdInputs.get(1).getName()));
+ }
+
+ private String generateExpectedInputName(PropertyDataDefinition prop) {
+ return INSTANCE_ID + "_" + prop.getName();
+ }
+
+ private String generateExpectedInputName(PropertyDefinition parentProp, PropertyDefinition innerProperty) {
+ return INSTANCE_ID + "_" + parentProp.getName()+ "_" + innerProperty.getName();
+ }
+
+ private void verifyCreatedInput(PropertyDataDefinition property, InputDefinition input) {
+ assertThat(input.getType()).isEqualTo(property.getType());
+ assertThat(input.getName()).isEqualTo(generateExpectedInputName(property));
+ assertThat(input.getValue()).isEqualTo(property.getValue());
+ assertThat(input.getDefaultValue()).isEqualTo(property.getValue());
+ assertThat(input.getUniqueId()).isEqualTo(UniqueIdBuilder.buildPropertyUniqueId(RESOURCE_ID, input.getName()));
+ assertThat(input.getPropertyId()).isEqualTo(property.getUniqueId());
+ assertThat(input.getInstanceUniqueId()).isEqualTo(INSTANCE_ID);
+ }
+
+ private Resource createResourceWithInstance() {
+ ComponentInstance inst1 = new ComponentInstanceBuilder()
+ .setId(INSTANCE_ID)
+ .setNormalizedName(INSTANCE_ID)
+ .build();
+
+ return new ResourceBuilder()
+ .setUniqueId(RESOURCE_ID)
+ .addComponentInstance(inst1)
+ .build();
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java
new file mode 100644
index 0000000000..cd454d5a84
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeceleratorTest.java
@@ -0,0 +1,172 @@
+package org.openecomp.sdc.be.components.property;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.jsontitan.operations.PolicyOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+
+@RunWith(MockitoJUnitRunner.class)
+//note that testing for most of the common logic is under the ComponentInstancePropertyDeceleratorTest
+public class PolicyPropertyDeceleratorTest extends PropertyDeceleratorTestBase{
+
+ private static final String POLICY_ID = "policyId";
+ private static final String RESOURCE_ID = "resourceId";
+ private static final String INPUT_ID = "inputId";
+ @InjectMocks
+ private PolicyPropertyDecelerator policyPropertyDecelerator;
+ @Mock
+ private PolicyOperation policyOperation;
+ @Mock
+ private PropertyOperation propertyOperation;
+ @Captor
+ private ArgumentCaptor<List<PropertyDataDefinition>> updatedPropsCapture;
+ private Resource resource;
+ private InputDefinition input;
+
+ @Override
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ resource = createResourceWithPolicy();
+ input = new InputDefinition();
+ input.setUniqueId(INPUT_ID);
+ input.setName(INPUT_ID);
+ input.setValue("value");
+ }
+
+ @Test
+ public void testDeclarePropertiesAsInputs_policyNotExist() {
+ Either<List<InputDefinition>, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, "nonExistingPolicy", Collections.emptyList());
+ assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ verifyZeroInteractions(policyOperation);
+ }
+
+ @Test
+ public void testDeclarePropertiesAsInputs_failedToUpdateProperties() {
+ when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ Either<List<InputDefinition>, StorageOperationStatus> declareResult = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, Collections.emptyList());
+ assertThat(declareResult.right().value()).isEqualTo(StorageOperationStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void testDeclarePropertiesAsInputs() {
+ List<PropertyDataDefinition> properties = Arrays.asList(prop1, prop2);
+ List<ComponentInstancePropInput> propsToDeclare = createInstancePropInputList(properties);
+ when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK);
+ Either<List<InputDefinition>, StorageOperationStatus> createdInputs = policyPropertyDecelerator.declarePropertiesAsInputs(resource, POLICY_ID, propsToDeclare);
+ List<InputDefinition> inputs = createdInputs.left().value();
+ assertThat(inputs).hasSize(2);
+ verifyInputPropertiesList(inputs, updatedPropsCapture.getValue());
+ //creation of inputs values is part of the DefaultPropertyDecelerator and is tested in the ComponentInstancePropertyDeceleratorTest class
+ }
+
+ @Test
+ public void testUnDeclareProperties_whenComponentHasNoPolicies_returnOk() {
+ Resource resource = new Resource();
+ StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input);
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ verifyZeroInteractions(policyOperation);
+ }
+
+ @Test
+ public void testUnDeclareProperties_whenNoPropertiesFromPolicyMatchInputId_returnOk() {
+ StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(createResourceWithPolicy(), input);
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ verifyZeroInteractions(policyOperation);
+ }
+
+ @Test
+ public void whenFailingToUpdateDeclaredProperties_returnErrorStatus() {
+ Resource resource = createResourceWithPolicies(POLICY_ID);
+ PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID);
+ PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID);
+ policyDefinition.setProperties(Collections.singletonList(getInputPropForInput));
+ when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue()));
+ when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input);
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void testUnDeclareProperties_propertiesUpdatedCorrectly() {
+ Resource resource = createResourceWithPolicies(POLICY_ID, "policyId2");
+ PolicyDefinition policyDefinition = resource.getPolicies().get(POLICY_ID);
+ PropertyDataDefinition getInputPropForInput = buildGetInputProperty(INPUT_ID);
+ PropertyDataDefinition someOtherProperty = new PropertyDataDefinitionBuilder().build();
+ policyDefinition.setProperties(Arrays.asList(getInputPropForInput, someOtherProperty));
+
+ when(propertyOperation.findDefaultValueFromSecondPosition(Collections.emptyList(), getInputPropForInput.getUniqueId(), getInputPropForInput.getDefaultValue())).thenReturn(Either.left(getInputPropForInput.getDefaultValue()));
+ when(policyOperation.updatePolicyProperties(eq(resource), eq(POLICY_ID), updatedPropsCapture.capture())).thenReturn(StorageOperationStatus.OK);
+ StorageOperationStatus storageOperationStatus = policyPropertyDecelerator.unDeclarePropertiesAsInputs(resource, input);
+
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ List<PropertyDataDefinition> updatedProperties = updatedPropsCapture.getValue();
+ assertThat(updatedProperties).hasSize(1);
+ PropertyDataDefinition updatedProperty = updatedProperties.get(0);
+ assertThat(updatedProperty.isGetInputProperty()).isFalse();
+ assertThat(updatedProperty.getValue()).isEmpty();
+ assertThat(updatedProperty.getDefaultValue()).isEqualTo(getInputPropForInput.getDefaultValue());
+ assertThat(updatedProperty.getUniqueId()).isEqualTo(getInputPropForInput.getUniqueId());
+ }
+
+ private Resource createResourceWithPolicy() {
+ return createResourceWithPolicies(POLICY_ID);
+ }
+
+ private Resource createResourceWithPolicies(String ... policies) {
+ List<PolicyDefinition> policiesDef = Stream.of(policies)
+ .map(this::buildPolicy)
+ .collect(Collectors.toList());
+
+ return new ResourceBuilder()
+ .setUniqueId(RESOURCE_ID)
+ .setPolicies(policiesDef)
+ .build();
+ }
+
+ private PolicyDefinition buildPolicy(String policyId) {
+ return PolicyDefinitionBuilder.create()
+ .setUniqueId(policyId)
+ .setName(policyId)
+ .build();
+ }
+
+ private PropertyDataDefinition buildGetInputProperty(String inputId) {
+ return new PropertyDataDefinitionBuilder()
+ .addGetInputValue(inputId)
+ .setUniqueId(POLICY_ID + "_" + inputId)
+ .setDefaultValue("defaultValue")
+ .setValue(generateGetInputValue(inputId))
+ .build();
+ }
+
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java
new file mode 100644
index 0000000000..0c761a948d
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/property/PropertyDeceleratorTestBase.java
@@ -0,0 +1,69 @@
+package org.openecomp.sdc.be.components.property;
+
+import org.junit.Before;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.ComponentInstancePropInput;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.openecomp.sdc.common.api.Constants.GET_INPUT;
+
+public class PropertyDeceleratorTestBase {
+
+ static final String INNER_PROP1 = "ecomp_generated_naming";
+ static final String INNER_PROP2 = "naming_policy";
+ PropertyDataDefinition prop1, prop2, complexProperty;
+
+ @Before
+ public void setUp() throws Exception {
+ prop1 = new PropertyDataDefinitionBuilder()
+ .setUniqueId("prop1")
+ .setType("string")
+ .setName("prop1")
+ .setValue("value1")
+ .build();
+
+ prop2 = new PropertyDataDefinitionBuilder()
+ .setUniqueId("prop2")
+ .setType("string")
+ .setSchemaType("string")
+ .setName("prop2")
+ .setValue("[\"a\", \"b\"]")
+ .build();
+
+ complexProperty = new PropertyDataDefinitionBuilder()
+ .setUniqueId("prop3")
+ .setType("org.openecomp.type1")
+ .setName("prop3")
+ .setValue("{\"ecomp_generated_naming\":true\",\"naming_policy\":\"abc\"}")
+ .build();
+
+ }
+
+ List<ComponentInstancePropInput> createInstancePropInputList(List<PropertyDataDefinition> properties) {
+ return properties.stream().map(prop -> new ComponentInstancePropInput(new ComponentInstanceProperty(prop)))
+ .collect(Collectors.toList());
+ }
+
+ void verifyInputPropertiesList(List<InputDefinition> createdInputs, List<PropertyDataDefinition> capturedUpdatedProperties) {
+ Map<String, InputDefinition> propertyIdToCreatedInput = MapUtil.toMap(createdInputs, InputDefinition::getPropertyId);
+ capturedUpdatedProperties.forEach(updatedProperty -> verifyInputPropertiesList(updatedProperty, propertyIdToCreatedInput.get(updatedProperty.getUniqueId())));
+ }
+
+ String generateGetInputValue(String value) {
+ return String.format("{\"%s\":\"%s\"}", GET_INPUT, value);
+ }
+
+ private void verifyInputPropertiesList(PropertyDataDefinition updatedProperty, InputDefinition input) {
+ assertThat(input.getProperties()).hasSize(1);
+ assertThat(new ComponentInstanceProperty(updatedProperty)).isEqualTo(input.getProperties().get(0));
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java
new file mode 100644
index 0000000000..56aef5d923
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManagerTest.java
@@ -0,0 +1,138 @@
+package org.openecomp.sdc.be.components.scheduledtasks;
+
+import fj.data.Either;
+import org.apache.commons.lang.math.NumberUtils;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
+import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine;
+import org.openecomp.sdc.be.components.scheduledtasks.RecoveryThreadManager.FixEnvironmentTask;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class RecoveryThreadManagerTest extends BeConfDependentTest {
+
+ @InjectMocks
+ RecoveryThreadManager recoveryThreadManager = new RecoveryThreadManager();
+
+ private OperationalEnvironmentDao operationalEnvironmentDao = mock(OperationalEnvironmentDao.class);
+ private EnvironmentsEngine environmentsEngine = mock(EnvironmentsEngine.class);
+ private ScheduledExecutorService scheduledService = mock(ScheduledExecutorService.class);
+
+ @Before
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ reset(operationalEnvironmentDao, environmentsEngine, scheduledService);
+ recoveryThreadManager.init();
+ }
+
+ @Test
+ public void testInit() {
+ verify(scheduledService, Mockito.times(1)).scheduleAtFixedRate(recoveryThreadManager.task,
+ NumberUtils.LONG_ZERO, 180L, TimeUnit.SECONDS);
+
+ }
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testTaskNoRecords() {
+ FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task;
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> emptyList = Either.left(Arrays.asList());
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(emptyList);
+ fixEnvironmentTask.run();
+ verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testTaskCassandraCrash() {
+ FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task;
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherResult = Either.right(CassandraOperationStatus.GENERAL_ERROR);
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(eitherResult);
+ fixEnvironmentTask.run();
+ verify(environmentsEngine, Mockito.times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testTaskMultipleFailedRecords() {
+ FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task;
+ OperationalEnvironmentEntry mockEntry = Mockito.mock(OperationalEnvironmentEntry.class);
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> nonEmptyList = Either.left(Arrays.asList(mockEntry, mockEntry, mockEntry));
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> emptyList = Either.left(Arrays.asList());
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(nonEmptyList);
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(emptyList);
+ fixEnvironmentTask.run();
+ verify(environmentsEngine, Mockito.times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testTaskStaleRecords() {
+ FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task;
+ OperationalEnvironmentEntry mockFailedEntryFirst = Mockito.mock(OperationalEnvironmentEntry.class);
+ OperationalEnvironmentEntry mockFailedEntrySecond = Mockito.mock(OperationalEnvironmentEntry.class);
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> failedRecordsList = Either.left(Arrays.asList(mockFailedEntryFirst, mockFailedEntrySecond));
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(failedRecordsList);
+
+ OperationalEnvironmentEntry mockInProgressNonStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class);
+ OperationalEnvironmentEntry mockInProgressStaleEntry = Mockito.mock(OperationalEnvironmentEntry.class);
+ doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 /2)).when(mockInProgressNonStaleEntry).getLastModified();
+ doReturn(new Date(System.currentTimeMillis() - recoveryThreadManager.allowedTimeBeforeStaleSec * 1000 * 2)).when(mockInProgressStaleEntry).getLastModified();
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> inProgressList = Either.left(Arrays.asList(mockInProgressNonStaleEntry, mockInProgressStaleEntry));
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(inProgressList);
+ fixEnvironmentTask.run();
+
+ verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntryFirst));
+ verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockFailedEntrySecond));
+ verify(environmentsEngine).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressStaleEntry));
+ verify(environmentsEngine, times(0)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.eq(mockInProgressNonStaleEntry));
+
+ verify(environmentsEngine, times(3)).buildOpEnv(Mockito.any(Wrapper.class), Mockito.any(OperationalEnvironmentEntry.class));
+
+ }
+
+
+
+ @Test
+ public void testUnconnectedRecords() {
+ FixEnvironmentTask fixEnvironmentTask = recoveryThreadManager.task;
+ OperationalEnvironmentEntry mockCompleteConnected = Mockito.mock(OperationalEnvironmentEntry.class);
+ OperationalEnvironmentEntry mockCompleteUnconnected = Mockito.mock(OperationalEnvironmentEntry.class);
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> completeRecordsList = Either.left(Arrays.asList(mockCompleteConnected, mockCompleteUnconnected));
+ when(environmentsEngine.isInMap(mockCompleteConnected)).thenReturn(true);
+ when(environmentsEngine.isInMap(mockCompleteUnconnected)).thenReturn(false);
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED)).thenReturn(completeRecordsList);
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED)).thenReturn(Either.left(Arrays.asList()));
+ when(operationalEnvironmentDao.getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS)).thenReturn(Either.left(Arrays.asList()));
+ fixEnvironmentTask.run();
+
+ verify(environmentsEngine).createUebTopicsForEnvironment(mockCompleteUnconnected);
+ verify(environmentsEngine, times(0)).createUebTopicsForEnvironment(mockCompleteConnected);
+ verify(environmentsEngine).addToMap(mockCompleteUnconnected);
+ verify(environmentsEngine, times(0)).addToMap(mockCompleteConnected);
+ verify(environmentsEngine, times(1)).createUebTopicsForEnvironment(Mockito.any(OperationalEnvironmentEntry.class));
+
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java
index 55a119e078..32e3f9c10a 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ArtifactBuilder.java
@@ -1,10 +1,10 @@
package org.openecomp.sdc.be.components.utils;
-import java.util.ArrayList;
-
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import java.util.ArrayList;
+
public class ArtifactBuilder {
private ArtifactDefinition artifactDefinition;
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java
new file mode 100644
index 0000000000..4c137551dc
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/CapabilityDefinitionBuilder.java
@@ -0,0 +1,51 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+
+import java.util.ArrayList;
+
+public class CapabilityDefinitionBuilder {
+
+ private CapabilityDefinition capabilityDefinition;
+
+ public CapabilityDefinitionBuilder() {
+ capabilityDefinition = new CapabilityDefinition();
+ capabilityDefinition.setProperties(new ArrayList<>());
+ }
+
+ public CapabilityDefinitionBuilder addProperty(ComponentInstanceProperty property) {
+ capabilityDefinition.getProperties().add(property);
+ return this;
+ }
+
+ public CapabilityDefinitionBuilder setOwnerId(String ownerId) {
+ capabilityDefinition.setOwnerId(ownerId);
+ return this;
+ }
+
+ public CapabilityDefinitionBuilder setOwnerName(String ownerName) {
+ capabilityDefinition.setOwnerName(ownerName);
+ return this;
+ }
+
+ public CapabilityDefinitionBuilder setType(String type) {
+ capabilityDefinition.setType(type);
+ return this;
+ }
+
+ public CapabilityDefinitionBuilder setId(String ownerId) {
+ capabilityDefinition.setUniqueId(ownerId);
+ return this;
+ }
+
+ public CapabilityDefinitionBuilder setName(String name) {
+ capabilityDefinition.setName(name);
+ return this;
+ }
+
+
+ public CapabilityDefinition build() {
+ return capabilityDefinition;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java
new file mode 100644
index 0000000000..490140dac0
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentBuilder.java
@@ -0,0 +1,155 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+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.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.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public abstract class ComponentBuilder<T extends Component, B extends ComponentBuilder<T, B>> {
+
+ private T component;
+
+ protected abstract T component();
+
+ protected abstract ComponentBuilder<T, B> self();
+
+ public ComponentBuilder() {
+ this.component = component();
+ }
+
+ public ComponentBuilder(T component) {
+ this.component = component;
+ }
+
+ public ComponentBuilder<T, B> setUniqueId(String id) {
+ component.setUniqueId(id);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setLifeCycleState(LifecycleStateEnum lifeCycleState) {
+ component.setLifecycleState(lifeCycleState);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setLastUpdaterUserId(String lastUpdater) {
+ component.setLastUpdaterUserId(lastUpdater);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setInvariantUUid(String invariantUUid) {
+ component.setInvariantUUID(invariantUUid);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setName(String name) {
+ component.setName(name);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setComponentType(ComponentTypeEnum type) {
+ component.setComponentType(type);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setSystemName(String systemName) {
+ component.setSystemName(systemName);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addComponentInstance(ComponentInstance componentInstance) {
+ if (component.getComponentInstances() == null) {
+ component.setComponentInstances(new ArrayList<>());
+ }
+ component.getComponentInstances().add(componentInstance);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addInput(InputDefinition input) {
+ if (component.getInputs() == null) {
+ component.setInputs(new ArrayList<>());
+ }
+ component.getInputs().add(input);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addInput(String inputName) {
+ InputDefinition inputDefinition = new InputDefinition();
+ inputDefinition.setName(inputName);
+ inputDefinition.setUniqueId(inputName);
+ this.addInput(inputDefinition);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addInstanceProperty(String instanceId, ComponentInstanceProperty prop) {
+ if (component.getComponentInstancesProperties() == null) {
+ component.setComponentInstancesProperties(new HashMap<>());
+ }
+ component.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addInstanceProperty(String instanceId, String propName) {
+ ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty();
+ componentInstanceProperty.setName(propName);
+ this.addInstanceProperty(instanceId, componentInstanceProperty);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addInstanceInput(String instanceId, ComponentInstanceInput prop) {
+ if (component.getComponentInstancesInputs() == null) {
+ component.setComponentInstancesInputs(new HashMap<>());
+ }
+ component.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addInstanceInput(String instanceId, String propName) {
+ ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput();
+ componentInstanceInput.setName(propName);
+ this.addInstanceInput(instanceId, componentInstanceInput);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) {
+ if (component.getComponentInstancesRelations() == null) {
+ component.setComponentInstancesRelations(new ArrayList<>());
+ }
+ component.getComponentInstancesRelations().add(requirementCapabilityRelDef);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> addPolicy(PolicyDefinition policyDefinition) {
+ if (component.getPolicies() == null) {
+ component.setPolicies(new HashMap<>());
+ }
+ component.getPolicies().put(policyDefinition.getUniqueId(), policyDefinition);
+ return self();
+ }
+ public ComponentBuilder<T, B> addGroups(GroupDefinition groupDefinition){
+ if(component.getGroups() == null){
+ component.setGroups(new ArrayList<>());
+ }
+ component.getGroups().add(groupDefinition);
+ return self();
+ }
+
+ public ComponentBuilder<T, B> setPolicies(List<PolicyDefinition> policies) {
+ component.setPolicies(MapUtil.toMap(policies, PolicyDefinition::getUniqueId));
+ return self();
+ }
+
+ public T build() {
+ return component;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java
index a99f08c20d..f461806010 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstanceBuilder.java
@@ -1,17 +1,25 @@
package org.openecomp.sdc.be.components.utils;
-import java.util.HashMap;
-import java.util.Map;
-
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.ComponentInstance;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.stream.Stream;
+
public class ComponentInstanceBuilder {
private ComponentInstance componentInstance;
public ComponentInstanceBuilder() {
componentInstance = new ComponentInstance();
+ componentInstance.setCapabilities(new HashMap<>());
+ componentInstance.setDeploymentArtifacts(new HashMap<>());
+ }
+
+ public ComponentInstanceBuilder(ComponentInstance componentInstance) {
+ this.componentInstance = componentInstance;
}
public ComponentInstanceBuilder setName(String name) {
@@ -19,6 +27,16 @@ public class ComponentInstanceBuilder {
return this;
}
+ public ComponentInstanceBuilder setNormalizedName(String name) {
+ componentInstance.setNormalizedName(name);
+ return this;
+ }
+
+ public ComponentInstanceBuilder setUniqueId(String uniqueId) {
+ componentInstance.setUniqueId(uniqueId);
+ return this;
+ }
+
public ComponentInstanceBuilder setComponentUid(String componentUid) {
componentInstance.setComponentUid(componentUid);
return this;
@@ -35,14 +53,20 @@ public class ComponentInstanceBuilder {
}
public ComponentInstanceBuilder addDeploymentArtifact(ArtifactDefinition artifactDefinition) {
- Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
- if (deploymentArtifacts == null) {
- componentInstance.setDeploymentArtifacts(new HashMap<>());
- }
componentInstance.getDeploymentArtifacts().put(artifactDefinition.getArtifactName(), artifactDefinition);
return this;
}
+ public ComponentInstanceBuilder addCapability(CapabilityDefinition capabilityDefinition) {
+ componentInstance.getCapabilities().computeIfAbsent(capabilityDefinition.getType(), key -> new ArrayList<>()).add(capabilityDefinition);
+ return this;
+ }
+
+ public ComponentInstanceBuilder addCapabilities(CapabilityDefinition ... capabilities) {
+ Stream.of(capabilities).forEach(this::addCapability);
+ return this;
+ }
+
public ComponentInstance build() {
return componentInstance;
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java
new file mode 100644
index 0000000000..d8cfa2cb23
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ComponentInstancePropertyBuilder.java
@@ -0,0 +1,22 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+
+public class ComponentInstancePropertyBuilder extends PropertyDataDefinitionAbstractBuilder<ComponentInstanceProperty, ComponentInstancePropertyBuilder> {
+
+ @Override
+ protected PropertyDataDefinitionAbstractBuilder<ComponentInstanceProperty, ComponentInstancePropertyBuilder> self() {
+ return this;
+ }
+
+ @Override
+ ComponentInstanceProperty propertyDefinition() {
+ return new ComponentInstanceProperty();
+ }
+
+ @Override
+ public ComponentInstanceProperty build() {
+ return propertyDefinition;
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java
new file mode 100644
index 0000000000..d7deaa423a
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupDefinitionBuilder.java
@@ -0,0 +1,38 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.model.GroupDefinition;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class GroupDefinitionBuilder {
+ private GroupDefinition groupDefinition;
+
+ private GroupDefinitionBuilder() {
+ this.groupDefinition = new GroupDefinition();
+ }
+
+ public static GroupDefinitionBuilder create() {
+ return new GroupDefinitionBuilder();
+ }
+
+ public GroupDefinitionBuilder setUniqueId(String uid) {
+ groupDefinition.setUniqueId(uid);
+ return this;
+ }
+
+ public GroupDefinition build() {
+ return groupDefinition;
+ }
+
+ public GroupDefinitionBuilder addMember(String memberName, String memberId) {
+ Map<String, String> members = groupDefinition.getMembers();
+ if (members == null) {
+ members = new HashMap<>();
+ groupDefinition.setMembers(members);
+ }
+ members.put(memberId, memberId);
+ return this;
+ }
+}
+
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java
new file mode 100644
index 0000000000..719967fd6b
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/GroupTypeBuilder.java
@@ -0,0 +1,43 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+
+public class GroupTypeBuilder {
+
+ private GroupTypeDefinition groupTypeDataDefinition;
+
+ public static GroupTypeBuilder create() {
+ return new GroupTypeBuilder();
+ }
+
+ private GroupTypeBuilder() {
+ this.groupTypeDataDefinition = new GroupTypeDefinition();
+ }
+
+ public GroupTypeBuilder setType(String type) {
+ groupTypeDataDefinition.setType(type);
+ return this;
+ }
+
+ public GroupTypeBuilder setUniqueId(String uid) {
+ groupTypeDataDefinition.setUniqueId(uid);
+ return this;
+ }
+
+ public GroupTypeBuilder setVersion(String version) {
+ groupTypeDataDefinition.setVersion(version);
+ return this;
+ }
+
+ public GroupTypeBuilder setDerivedFrom(String derivedFrom) {
+ groupTypeDataDefinition.setDerivedFrom(derivedFrom);
+ return this;
+ }
+
+ public GroupTypeDefinition build() {
+ return groupTypeDataDefinition;
+ }
+
+
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java
index 3a99d54ffa..249cf69112 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ObjectGenerator.java
@@ -1,11 +1,5 @@
package org.openecomp.sdc.be.components.utils;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
@@ -15,6 +9,12 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
public class ObjectGenerator {
public static Resource buildResourceWithInputs(String ... inputNames) {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java
new file mode 100644
index 0000000000..b6aa96e7d7
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/OperationalEnvironmentBuilder.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+
+import java.util.Set;
+
+public class OperationalEnvironmentBuilder {
+
+ private OperationalEnvironmentEntry operationalEnvironmentEntry;
+
+ public OperationalEnvironmentBuilder() {
+ operationalEnvironmentEntry = new OperationalEnvironmentEntry();
+ }
+
+ public OperationalEnvironmentBuilder setEnvId(String envId) {
+ operationalEnvironmentEntry.setEnvironmentId(envId);
+ return this;
+ }
+
+ public OperationalEnvironmentBuilder setDmaapUebAddress(Set<String> addresses) {
+ operationalEnvironmentEntry.setDmaapUebAddress(addresses);
+ return this;
+ }
+
+ public OperationalEnvironmentBuilder setStatus(EnvironmentStatusEnum status) {
+ operationalEnvironmentEntry.setStatus(status);
+ return this;
+ }
+
+ public OperationalEnvironmentEntry build() {
+ return operationalEnvironmentEntry;
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java
new file mode 100644
index 0000000000..f818c04ccd
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyDefinitionBuilder.java
@@ -0,0 +1,70 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class PolicyDefinitionBuilder {
+
+ private PolicyDefinition policyDefinition;
+
+ private PolicyDefinitionBuilder() {
+ this.policyDefinition = new PolicyDefinition();
+ }
+
+ public static PolicyDefinitionBuilder create() {
+ return new PolicyDefinitionBuilder();
+ }
+
+ public PolicyDefinitionBuilder setName(String name) {
+ policyDefinition.setName(name);
+ return this;
+ }
+
+ public PolicyDefinitionBuilder setUniqueId(String uid) {
+ policyDefinition.setUniqueId(uid);
+ return this;
+ }
+
+ public PolicyDefinitionBuilder setProperties(PropertyDataDefinition ... props) {
+ policyDefinition.setProperties(Arrays.asList(props));
+ return this;
+ }
+
+ public PolicyDefinitionBuilder setTargets(Map<PolicyTargetType, List<String>> targets ){
+ policyDefinition.setTargets(targets);
+ return this;
+ }
+
+ public PolicyDefinitionBuilder addComponentInstanceTarget(String instId) {
+ Map<PolicyTargetType, List<String>> targets = getTargets();
+ targets.computeIfAbsent(PolicyTargetType.COMPONENT_INSTANCES, k -> new ArrayList<>())
+ .add(instId);
+ return this;
+ }
+
+ public PolicyDefinitionBuilder addGroupTarget(String groupId) {
+ Map<PolicyTargetType, List<String>> targets = getTargets();
+ targets.computeIfAbsent(PolicyTargetType.GROUPS, k -> new ArrayList<>()).add(groupId);
+ return this;
+ }
+
+ public PolicyDefinition build() {
+ return policyDefinition;
+ }
+
+ private Map<PolicyTargetType, List<String>> getTargets() {
+ Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
+ if (targets == null) {
+ targets = new HashMap<>();
+ policyDefinition.setTargets(targets);
+ }
+ return targets;
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java
new file mode 100644
index 0000000000..8c2b54f27e
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PolicyTypeBuilder.java
@@ -0,0 +1,84 @@
+package org.openecomp.sdc.be.components.utils;
+
+
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+
+import java.util.List;
+import java.util.Map;
+
+public class PolicyTypeBuilder {
+
+ private PolicyTypeDefinition policyTypeDataDefinition;
+
+ public PolicyTypeBuilder() {
+ this.policyTypeDataDefinition = new PolicyTypeDefinition();
+ }
+
+ public PolicyTypeBuilder setType(String type) {
+ policyTypeDataDefinition.setType(type);
+ return this;
+ }
+
+ public PolicyTypeBuilder setUniqueId(String uid) {
+ policyTypeDataDefinition.setUniqueId(uid);
+ return this;
+ }
+
+ public PolicyTypeBuilder setDerivedFrom(String derivedFrom) {
+ policyTypeDataDefinition.setDerivedFrom(derivedFrom);
+ return this;
+ }
+
+ public PolicyTypeBuilder setVersion(String version) {
+ policyTypeDataDefinition.setVersion(version);
+ return this;
+ }
+
+ public PolicyTypeBuilder setDescription(String version) {
+ policyTypeDataDefinition.setDescription(version);
+ return this;
+ }
+
+ public PolicyTypeBuilder setTargets(List<String> targets) {
+ policyTypeDataDefinition.setTargets(targets);
+ return this;
+ }
+
+ public PolicyTypeBuilder setMetadata(Map<String, String> metadata) {
+ policyTypeDataDefinition.setMetadata(metadata);
+ return this;
+ }
+
+ public PolicyTypeBuilder setModificationTime(long modificationTime) {
+ policyTypeDataDefinition.setModificationTime(modificationTime);
+ return this;
+ }
+
+ public PolicyTypeBuilder setCreationTime(long creationTime) {
+ policyTypeDataDefinition.setModificationTime(creationTime);
+ return this;
+ }
+
+ public PolicyTypeBuilder setOwner(String owner) {
+ policyTypeDataDefinition.setOwnerId(owner);
+ return this;
+ }
+
+ public PolicyTypeBuilder setHighestVersion(boolean isHighestVersion) {
+ policyTypeDataDefinition.setHighestVersion(isHighestVersion);
+ return this;
+ }
+
+ public PolicyTypeBuilder setProperties(List<PropertyDefinition> properties) {
+ policyTypeDataDefinition.setProperties(properties);
+ return this;
+ }
+
+ public PolicyTypeDefinition build() {
+ return policyTypeDataDefinition;
+ }
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java
new file mode 100644
index 0000000000..9d5d71d67c
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionAbstractBuilder.java
@@ -0,0 +1,94 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+
+import java.util.ArrayList;
+
+public abstract class PropertyDataDefinitionAbstractBuilder<B extends PropertyDataDefinition, T extends PropertyDataDefinitionAbstractBuilder<B, T>> {
+
+ B propertyDefinition;
+
+ protected abstract PropertyDataDefinitionAbstractBuilder<B, T> self();
+
+ abstract B propertyDefinition();
+
+ PropertyDataDefinitionAbstractBuilder() {
+ propertyDefinition = propertyDefinition();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setUniqueId(String id) {
+ this.propertyDefinition.setUniqueId(id);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setName(String name) {
+ this.propertyDefinition.setName(name);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setValue(String value) {
+ this.propertyDefinition.setValue(value);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setDefaultValue(String value) {
+ this.propertyDefinition.setDefaultValue(value);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setType(String type) {
+ this.propertyDefinition.setType(type);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setOwnerId(String ownerId) {
+ this.propertyDefinition.setOwnerId(ownerId);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setSchemaType(String type) {
+ if (propertyDefinition.getSchema() == null) {
+ propertyDefinition.setSchema(new SchemaDefinition());
+ }
+ if (propertyDefinition.getSchema().getProperty() == null) {
+ propertyDefinition.getSchema().setProperty(new PropertyDataDefinition());
+ }
+ propertyDefinition.getSchema().getProperty().setType(type);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> addGetInputValue(String inputName) {
+ GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
+ getInputValueDataDefinition.setInputName(inputName);
+ getInputValueDataDefinition.setInputId(inputName);
+ if (propertyDefinition.getGetInputValues() == null) {
+ propertyDefinition.setGetInputValues(new ArrayList<>());
+ }
+ propertyDefinition.getGetInputValues().add(getInputValueDataDefinition);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setIsRequired(boolean required) {
+ this.propertyDefinition.setRequired(required);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setDescription(String description) {
+ this.propertyDefinition.setDescription(description);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setIsPassword(boolean isPassword) {
+ this.propertyDefinition.setRequired(isPassword);
+ return self();
+ }
+
+ public PropertyDataDefinitionAbstractBuilder<B, T> setStatus(String status) {
+ this.propertyDefinition.setStatus(status);
+ return self();
+ }
+
+ public abstract B build();
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java
index e7ed170414..85b2228933 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/PropertyDataDefinitionBuilder.java
@@ -1,68 +1,29 @@
package org.openecomp.sdc.be.components.utils;
-import java.util.ArrayList;
-
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
-public class PropertyDataDefinitionBuilder {
-
- private PropertyDefinition propertyDefinition;
-
- public PropertyDataDefinitionBuilder() {
- propertyDefinition = new PropertyDefinition();
- }
-
- public PropertyDataDefinitionBuilder setUniqueId(String id) {
- this.propertyDefinition.setUniqueId(id);
- return this;
- }
-
- public PropertyDataDefinitionBuilder setName(String name) {
- this.propertyDefinition.setName(name);
- return this;
- }
+import java.util.List;
- public PropertyDataDefinitionBuilder setValue(String value) {
- this.propertyDefinition.setValue(value);
- return this;
- }
+public class PropertyDataDefinitionBuilder extends PropertyDataDefinitionAbstractBuilder<PropertyDefinition, PropertyDataDefinitionBuilder> {
- public PropertyDataDefinitionBuilder setDefaultValue(String value) {
- this.propertyDefinition.setDefaultValue(value);
+ protected PropertyDataDefinitionBuilder self() {
return this;
}
- public PropertyDataDefinitionBuilder setType(String type) {
- this.propertyDefinition.setType(type);
- return this;
+ @Override
+ PropertyDefinition propertyDefinition() {
+ return new PropertyDefinition();
}
- public PropertyDataDefinitionBuilder setSchemaType(String type) {
- if (propertyDefinition.getSchema() == null) {
- propertyDefinition.setSchema(new SchemaDefinition());
- }
- if (propertyDefinition.getSchema().getProperty() == null) {
- propertyDefinition.getSchema().setProperty(new PropertyDataDefinition());
- }
- propertyDefinition.getSchema().getProperty().setType(type);
- return this;
+ @Override
+ public PropertyDefinition build() {
+ return propertyDefinition;
}
- public PropertyDataDefinitionBuilder addGetInputValue(String inputName) {
- GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
- getInputValueDataDefinition.setInputName(inputName);
- getInputValueDataDefinition.setInputId(inputName);
- if (propertyDefinition.getGetInputValues() == null) {
- propertyDefinition.setGetInputValues(new ArrayList<>());
- }
- propertyDefinition.getGetInputValues().add(getInputValueDataDefinition);
- return this;
+ public PropertyDataDefinitionBuilder setConstraints(List<PropertyConstraint> constraints) {
+ propertyDefinition.setConstraints(constraints);
+ return self();
}
- public PropertyDefinition build() {
- return propertyDefinition;
- }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java
index 8c457f153f..e0d35c6b6a 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/RelationsBuilder.java
@@ -1,12 +1,12 @@
package org.openecomp.sdc.be.components.utils;
-import java.util.Collections;
-
import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RelationshipInfo;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import java.util.Collections;
+
public class RelationsBuilder {
private RequirementCapabilityRelDef relation;
@@ -16,8 +16,8 @@ public class RelationsBuilder {
RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo();
RelationshipImpl relationship = new RelationshipImpl();
requirementAndRelationshipPair.setRelationships(relationship);
- CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
- capReqRel.setRelation(requirementAndRelationshipPair);
+ CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
+ capReqRel.setRelation(requirementAndRelationshipPair);
relation.setRelationships(Collections.singletonList(capReqRel));
}
@@ -27,17 +27,17 @@ public class RelationsBuilder {
}
public RelationsBuilder setRequirementName(String reqName) {
- relation.getSingleRelationship().getRelation().setRequirement(reqName);
+ relation.resolveSingleRelationship().getRelation().setRequirement(reqName);
return this;
}
public RelationsBuilder setRelationType(String type) {
- relation.getSingleRelationship().getRelation().getRelationship().setType(type);
+ relation.resolveSingleRelationship().getRelation().getRelationship().setType(type);
return this;
}
public RelationsBuilder setCapabilityUID(String uid) {
- relation.getSingleRelationship().getRelation().setCapabilityUid(uid);
+ relation.resolveSingleRelationship().getRelation().setCapabilityUid(uid);
return this;
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java
index 3d4a29da71..25468af3c9 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ResourceBuilder.java
@@ -1,79 +1,26 @@
package org.openecomp.sdc.be.components.utils;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-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.InputDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
-public class ResourceBuilder {
-
- private Resource resource;
-
- public ResourceBuilder() {
- this.resource = new Resource();
- }
-
- public ResourceBuilder(Resource resource) {
- this.resource = resource;
- }
-
- public ResourceBuilder setUniqueId(String id) {
- resource.setUniqueId(id);
- return this;
- }
-
- public ResourceBuilder setInvariantUUid(String invariantUUid) {
- resource.setInvariantUUID(invariantUUid);
- return this;
- }
-
- public ResourceBuilder setName(String name) {
- resource.setName(name);
- return this;
- }
-
- public ResourceBuilder setComponentType(ComponentTypeEnum type) {
- resource.setComponentType(type);
- return this;
- }
+import java.util.ArrayList;
- public ResourceBuilder setSystemName(String systemName) {
- resource.setSystemName(systemName);
- return this;
- }
+public class ResourceBuilder extends ComponentBuilder<Resource, ResourceBuilder> {
- public ResourceBuilder addComponentInstance(ComponentInstance componentInstance) {
- if (resource.getComponentInstances() == null) {
- resource.setComponentInstances(new ArrayList<>());
- }
- resource.getComponentInstances().add(componentInstance);
- return this;
- }
+ private Resource resource;
- public ResourceBuilder addInput(InputDefinition input) {
- if (resource.getInputs() == null) {
- resource.setInputs(new ArrayList<>());
- }
- resource.getInputs().add(input);
- return this;
+ @Override
+ protected Resource component() {
+ resource = new Resource();
+ return resource;
}
- public ResourceBuilder addInput(String inputName) {
- InputDefinition inputDefinition = new InputDefinition();
- inputDefinition.setName(inputName);
- inputDefinition.setUniqueId(inputName);
- this.addInput(inputDefinition);
+ @Override
+ protected ComponentBuilder<Resource, ResourceBuilder> self() {
return this;
}
- public ResourceBuilder addProperty(PropertyDefinition propertyDefinition) {
+ ResourceBuilder addProperty(PropertyDefinition propertyDefinition) {
if (resource.getProperties() == null) {
resource.setProperties(new ArrayList<>());
}
@@ -81,46 +28,14 @@ public class ResourceBuilder {
return this;
}
- public ResourceBuilder addInstanceProperty(String instanceId, ComponentInstanceProperty prop) {
- if (resource.getComponentInstancesProperties() == null) {
- resource.setComponentInstancesProperties(new HashMap<>());
- }
- resource.getComponentInstancesProperties().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop);
- return this;
- }
-
- public ResourceBuilder addInstanceProperty(String instanceId, String propName) {
- ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty();
- componentInstanceProperty.setName(propName);
- this.addInstanceProperty(instanceId, componentInstanceProperty);
- return this;
- }
- public ResourceBuilder addInstanceInput(String instanceId, ComponentInstanceInput prop) {
- if (resource.getComponentInstancesInputs() == null) {
- resource.setComponentInstancesInputs(new HashMap<>());
- }
- resource.getComponentInstancesInputs().computeIfAbsent(instanceId, key -> new ArrayList<>()).add(prop);
- return this;
- }
- public ResourceBuilder addInstanceInput(String instanceId, String propName) {
- ComponentInstanceInput componentInstanceInput = new ComponentInstanceInput();
- componentInstanceInput.setName(propName);
- this.addInstanceInput(instanceId, componentInstanceInput);
- return this;
+ public ResourceBuilder() {
+ super();
}
- public ResourceBuilder addRelationship(RequirementCapabilityRelDef requirementCapabilityRelDef) {
- if (resource.getComponentInstancesRelations() == null) {
- resource.setComponentInstancesRelations(new ArrayList<>());
- }
- resource.getComponentInstancesRelations().add(requirementCapabilityRelDef);
- return this;
+ public ResourceBuilder(Resource resource) {
+ super(resource);
}
-
- public Resource build() {
- return resource;
- }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java
new file mode 100644
index 0000000000..d85ad9bcc2
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/ServiceBuilder.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.openecomp.sdc.be.model.Service;
+
+public class ServiceBuilder extends ComponentBuilder<Service, ServiceBuilder> {
+
+ private Service service;
+
+ public ServiceBuilder(Service component) {
+ super(component);
+ }
+
+ public ServiceBuilder() {
+ super();
+ }
+
+ @Override
+ protected Service component() {
+ service = new Service();
+ return service;
+ }
+
+ @Override
+ protected ComponentBuilder<Service, ServiceBuilder> self() {
+ return this;
+ }
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java
new file mode 100644
index 0000000000..be19e8b795
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/UtilsTest.java
@@ -0,0 +1,53 @@
+package org.openecomp.sdc.be.components.utils;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class UtilsTest {
+
+ @Test
+ public void testThatEmptyListReturns0() {
+ List<String> existingResourceNames = new ArrayList<>();
+ int counter = Utils.getNextCounter(existingResourceNames);
+ assertThat(counter).isZero();
+ }
+
+ @Test
+ public void testListWithValidValue() {
+ List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0");
+ int counter = Utils.getNextCounter(existingResourceNames);
+ assertThat(counter).isEqualTo(1);
+ }
+
+ @Test
+ public void testListWithInvalidSingleValue() {
+ List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection");
+ int counter = Utils.getNextCounter(existingResourceNames);
+ assertThat(counter).isEqualTo(1);
+ }
+
+ @Test
+ public void testListWithValidValues() {
+ List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0",
+ "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10",
+ "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15",
+ "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..2");
+ int counter = Utils.getNextCounter(existingResourceNames);
+ assertThat(counter).isEqualTo(16);
+ }
+
+ @Test
+ public void testListWithInvalidValue() {
+ List<String> existingResourceNames = Arrays.asList("d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..0",
+ "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..10",
+ "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection..15",
+ "d7f886ce-7e32-4b1f-bfd8-f664b03fee09.ruti..NetworkCollection");
+ int counter = Utils.getNextCounter(existingResourceNames);
+ assertThat(counter).isEqualTo(16);
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java
new file mode 100644
index 0000000000..df48a538a5
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidationTest.java
@@ -0,0 +1,153 @@
+package org.openecomp.sdc.be.components.validation;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
+import org.openecomp.sdc.be.components.impl.ActivationRequestInformation;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceDistributionReqInfo;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+public class ServiceDistributionValidationTest {
+
+ private static final String USER_ID = "userId";
+ private static final String SERVICE_ID = "serviceId";
+ private static final String ENV_ID = "envId";
+
+ @InjectMocks
+ private ServiceDistributionValidation testInstance;
+
+ @Mock
+ private UserValidations userValidations;
+
+ @Mock
+ private ToscaOperationFacade toscaOperationFacade;
+
+ @Mock
+ private OperationalEnvironmentDao operationalEnvironmentDao;
+
+ @Mock
+ private IDistributionEngine distributionEngine;
+
+ @Mock
+ private ComponentsUtils componentsUtils;
+
+ private User user;
+ private Service service;
+ private OperationalEnvironmentEntry operationalEnvironmentEntry;
+ private ResponseFormat errResponse;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ user = new User();
+ user.setUserId(USER_ID);
+ errResponse = new ResponseFormat();
+ service = new Service();
+ service.setUniqueId(SERVICE_ID);
+ service.setLifecycleState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
+ operationalEnvironmentEntry = new OperationalEnvironmentEntry();
+ operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.COMPLETED);
+ }
+
+ @Test
+ public void validateActivateServiceRequest_userNotExist() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.right(errResponse));
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData"));
+ assertEquals(errResponse, activateServiceReq.right().value());
+ verifyZeroInteractions(toscaOperationFacade, operationalEnvironmentDao, componentsUtils);
+ }
+
+ @Test
+ public void validateActivateServiceRequest_ServiceNotExist() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR));
+ when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.GENERAL_ERROR, ComponentTypeEnum.SERVICE)).thenReturn(ActionStatus.GENERAL_ERROR);
+ when(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue())).thenReturn(errResponse);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData"));
+ assertEquals(errResponse, activateServiceReq.right().value());
+ verifyZeroInteractions(operationalEnvironmentDao);
+ }
+
+ @Test
+ public void validateActivateServiceRequest_ServiceLifeCycleStateNotReadyForDistribution() {
+ service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service));
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.INVALID_SERVICE_STATE))).thenReturn(errResponse);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData"));
+ assertEquals(errResponse, activateServiceReq.right().value());
+ verifyZeroInteractions(operationalEnvironmentDao);
+ }
+
+ @Test
+ public void validateActivateServiceRequest_operationalEnvNotExist() throws Exception {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service));
+ when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(null);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData"));
+ assertEquals(errResponse, activateServiceReq.right().value());
+ }
+
+ @Test
+ public void validateActivateServiceRequest_operationalEnvStatusNotComplete() {
+ operationalEnvironmentEntry.setStatus(EnvironmentStatusEnum.IN_PROGRESS);
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service));
+ when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.API_RESOURCE_NOT_FOUND), anyString())).thenReturn(errResponse);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("distributionData"));
+ assertEquals(errResponse, activateServiceReq.right().value());
+ }
+
+ @Test
+ public void validateActivateServiceRequest_couldNotParseDistributionData() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service));
+ when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo());
+ assertEquals(errResponse, activateServiceReq.right().value());
+ }
+
+ @Test
+ public void validateActivateServiceRequest_distributionDataHasNoWorkloadContext() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service));
+ when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.MISSING_BODY))).thenReturn(errResponse);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo(""));
+ assertEquals(errResponse, activateServiceReq.right().value());
+ }
+
+ @Test
+ public void validateActivateServiceRequest_requestValid() {
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), eq(false))).thenReturn(Either.left(user));
+ when(toscaOperationFacade.getLatestServiceByUuid(eq(SERVICE_ID))).thenReturn(Either.left(service));
+ when(distributionEngine.getEnvironmentById(ENV_ID)).thenReturn(operationalEnvironmentEntry);
+ Either<ActivationRequestInformation, ResponseFormat> activateServiceReq = testInstance.validateActivateServiceRequest(SERVICE_ID, ENV_ID, user, new ServiceDistributionReqInfo("context"));
+ assertEquals(service, activateServiceReq.left().value().getServiceToActivate());
+ assertEquals("context", activateServiceReq.left().value().getWorkloadContext());
+ }
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java
new file mode 100644
index 0000000000..0408d31606
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/config/SpringConfig.java
@@ -0,0 +1,7 @@
+package org.openecomp.sdc.be.config;
+
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class SpringConfig {
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java
new file mode 100644
index 0000000000..4f90a0a42f
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/UiComponentDataConverterTest.java
@@ -0,0 +1,74 @@
+package org.openecomp.sdc.be.datamodel;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.components.utils.PolicyDefinitionBuilder;
+import org.openecomp.sdc.be.components.utils.ResourceBuilder;
+import org.openecomp.sdc.be.components.utils.ServiceBuilder;
+import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
+
+import java.util.Collections;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class UiComponentDataConverterTest {
+
+ private PolicyDefinition policy1, policy2;
+
+ @Before
+ public void setUp() throws Exception {
+ policy1 = PolicyDefinitionBuilder.create()
+ .setName("policy1")
+ .setUniqueId("uid1")
+ .build();
+
+ policy2 = PolicyDefinitionBuilder.create()
+ .setName("policy2")
+ .setUniqueId("uid2")
+ .build();
+ }
+
+ @Test
+ public void getUiDataTransferFromResourceByParams_policies_noPoliciesForResource() {
+ UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromResourceByParams(new Resource(), Collections.singletonList("policies"));
+ assertThat(componentDTO.getPolicies()).isEmpty();
+ }
+
+ @Test
+ public void getUiDataTransferFromServiceByParams_policies_noPoliciesForResource() {
+ UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromServiceByParams(new Service(), Collections.singletonList("policies"));
+ assertThat(componentDTO.getPolicies()).isEmpty();
+ }
+
+ @Test
+ public void getUiDataTransferFromResourceByParams_policies() {
+ Resource resourceWithPolicies = buildResourceWithPolicies();
+ UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromResourceByParams(resourceWithPolicies, Collections.singletonList("policies"));
+ assertThat(componentDTO.getPolicies()).isEqualTo(resourceWithPolicies.resolvePoliciesList());
+ }
+
+ @Test
+ public void getUiDataTransferFromServiceByParams_policies() {
+ Service resourceWithPolicies = buildServiceWithPolicies();
+ UiComponentDataTransfer componentDTO = UiComponentDataConverter.getUiDataTransferFromServiceByParams(resourceWithPolicies, Collections.singletonList("policies"));
+ assertThat(componentDTO.getPolicies()).isEqualTo(resourceWithPolicies.resolvePoliciesList());
+ }
+
+ private Resource buildResourceWithPolicies() {
+ return new ResourceBuilder()
+ .addPolicy(policy1)
+ .addPolicy(policy2)
+ .build();
+ }
+
+ private Service buildServiceWithPolicies() {
+ return new ServiceBuilder()
+ .addPolicy(policy1)
+ .addPolicy(policy2)
+ .build();
+ }
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java
index 290a5f4d1d..a80999a25b 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogicTest.java
@@ -20,18 +20,13 @@
package org.openecomp.sdc.be.distribution;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import javax.ws.rs.core.Response;
-
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.openecomp.sdc.be.components.BaseConfDependentTest;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse;
import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler;
import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask;
@@ -43,148 +38,384 @@ import org.openecomp.sdc.be.distribution.api.client.TopicRegistrationResponse;
import org.openecomp.sdc.be.distribution.api.client.TopicUnregistrationResponse;
import org.openecomp.sdc.common.datastructure.Wrapper;
-public class DistributionBusinessLogicTest extends BaseConfDependentTest {
-
- @InjectMocks
- DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class);
-
- CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class);
- AuditHandler auditHandler = Mockito.mock(AuditHandler.class);
-
- @Test
- public void testHandleRegistrationHappyScenario() {
- CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
- Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse);
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
- RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv");
- distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler);
-
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER);
- Mockito.verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class));
-
- assertTrue(!responseWrapper.isEmpty());
- Response response = responseWrapper.getInnerElement();
- assertTrue(response.getStatus() == HttpStatus.SC_OK);
-
- TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity();
-
- String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName();
- assertEquals(expectedStatusTopicName, actualStatusTopicName);
-
- String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
- String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName();
- assertEquals(expectedNotificationTopicName, actualNotificationTopicName);
-
- }
-
- @Test
- public void testHandleRegistrationFailedScenario() {
- CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
- CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR, HttpStatus.SC_SERVICE_UNAVAILABLE);
- DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration();
- RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv");
- String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
-
- Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse);
- Mockito.when(cambriaHandler.registerToTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER))
- .thenReturn(errorResponse);
-
- Wrapper<Response> responseWrapper = new Wrapper<>();
+import javax.ws.rs.core.Response;
- distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler);
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;
+
+public class DistributionBusinessLogicTest extends BeConfDependentTest {
+
+ @InjectMocks
+ DistributionBusinessLogic distributionBusinessLogic = Mockito.spy(DistributionBusinessLogic.class);
+
+ CambriaHandler cambriaHandler = Mockito.mock(CambriaHandler.class);
+ AuditHandler auditHandler = Mockito.mock(AuditHandler.class);
+
+ CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.CONNNECTION_ERROR,
+ HttpStatus.SC_SERVICE_UNAVAILABLE);
+ CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+ DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration();
+
+ @Before
+ public void init() {
+ MockitoAnnotations.initMocks(this);
+ Mockito.reset(cambriaHandler);
+ }
+
+ @Test
+ public void testHandleRegistrationNoConsumeStatusTopic() {
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+
+ testHandleRegistrationBasic(registrationRequest, responseWrapper);
+
+ String expectedStatusTopicName = buildTopicName(
+ configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(),
+ registrationRequest.getDistrEnvName());
+ verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper,
+ registrationRequest, SubscriberTypeEnum.CONSUMER, expectedStatusTopicName);
+
+ }
+
+ @Test
+ public void testHandleRegistrationConsumeStatusTopic() {
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+
+ testHandleRegistrationBasic(registrationRequest, responseWrapper);
+
+ String expectedStatusTopicName = buildTopicName(
+ configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(),
+ registrationRequest.getDistrEnvName());
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper,
+ registrationRequest, SubscriberTypeEnum.CONSUMER, expectedStatusTopicName);
+ }
+ /**
+ * Registration Fails When registering as consumer to Notification With Consumer Status flag false.
+ */
+ @Test
+ public void testHandleRegistrationFailedScenario() {
+
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
+ String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
+
+ Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName)).thenReturn(errorResponse);
+ testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen);
+ //Registered
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName);
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName);
+ //Did Not Register
+ verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER,
+ expectedStatusTopicName);
+ //Unregistered Activated (rollback)
+ verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.PRODUCER, expectedStatusTopicName);
+
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedStatusTopicName);
+
+ }
+
+ /**
+ * Registration Fails When registering as consumer to Notification With Consumer Status flag true.
+ */
+ @Test
+ public void testHandleRegistrationFailedConsumeStatusTopic() {
+
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
+ String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
+
+ Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName)).thenReturn(errorResponse);
+ testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen);
+
+ //Registered
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName);
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName);
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER,
+ expectedStatusTopicName);
+ //Unregistered Activated (rollback)
+ verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.PRODUCER, expectedStatusTopicName);
+ verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedStatusTopicName);
+ //Unregistered Not Activated
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName);
+ }
+
+ /**
+ * Registration Fails When registering as consumer to status With Consumer Status flag true.
+ */
+ @Test
+ public void testHandleRegistrationFailedConsumeStatusTopic2() {
+
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
+ String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
+
+ //Failing on new registration
+ Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER,
+ expectedStatusTopicName)).thenReturn(errorResponse);
+ testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen);
+ //Registered
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName);
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER,
+ expectedStatusTopicName);
+ //Did Not Register
+ verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName);
+ //Unregistered Activated (rollback)
+ verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.PRODUCER, expectedStatusTopicName);
+ //Unregistered Not Activated
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedStatusTopicName);
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName);
+
+ }
+
+
+ /**
+ * Registration Fails When registering as PRODUCER to status With Consumer Status flag true.
+ */
+ @Test
+ public void testHandleRegistrationFailedConsumeStatusTopic3() {
+
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", true);
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ String expectedNotificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
+ String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
+
+ //Failing on new registration
+ Runnable failWhen = () -> when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName)).thenReturn(errorResponse);
+ testHandleRegistrationFailed(registrationRequest, responseWrapper, failWhen);
+ //Registered
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName);
+ //Did Not Register
+ verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ responseWrapper,registrationRequest, SubscriberTypeEnum.CONSUMER,
+ expectedStatusTopicName);
+ verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ responseWrapper, registrationRequest,SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName);
+ //Unregistered Not Activated
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.PRODUCER, expectedStatusTopicName);
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName);
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(config.getUebServers(),
+ config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
+ SubscriberTypeEnum.CONSUMER, expectedStatusTopicName);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testHandleUnRegistrationHappyScenario() {
+ CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+
+ Mockito.when(cambriaHandler.unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(),
+ Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString()))
+ .thenReturn(okResponse);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false);
+ distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler);
+
+ Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER),
+ Mockito.anyString());
+ Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER),
+ Mockito.anyString());
+ Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(
+ Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), Mockito.anyString());
+ Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(
+ Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), Mockito.anyString());
+
+ Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(),
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class),
+ Mockito.anyString());
+
+ assertTrue(!responseWrapper.isEmpty());
+ Response response = responseWrapper.getInnerElement();
+ assertTrue(response.getStatus() == HttpStatus.SC_OK);
+
+ TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity();
+
+ String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(
+ configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(),
+ registrationRequest.getDistrEnvName());
+ String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName();
+ assertEquals(expectedStatusTopicName, actualStatusTopicName);
+
+ String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(
+ configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(),
+ registrationRequest.getDistrEnvName());
+ String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName();
+ assertEquals(expectedNotificationTopicName, actualNotificationTopicName);
+
+ assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK);
+ assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK);
+
+ }
+
+ @Test
+ public void testHandleUnRegistrationFailedScenario() {
+ CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+ CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR,
+ HttpStatus.SC_INTERNAL_SERVER_ERROR);
+
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv", false);
+ DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration();
+ String expectedStatusTopicName = DistributionEngineInitTask
+ .buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
+ String expectedNotificationTopicName = DistributionEngineInitTask
+ .buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
+ Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName)).thenReturn(okResponse);
+ Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER,
+ expectedNotificationTopicName)).thenReturn(errorResponse);
+
+ distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler);
+
+ Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER),
+ Mockito.anyString());
+ Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(
+ Mockito.eq(responseWrapper), Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER),
+ Mockito.anyString());
+ Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(
+ Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.PRODUCER), Mockito.anyString());
+ Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(
+ Mockito.eq(registrationRequest), Mockito.eq(SubscriberTypeEnum.CONSUMER), Mockito.anyString());
+
+ assertTrue(!responseWrapper.isEmpty());
+ Response response = responseWrapper.getInnerElement();
+ assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR);
+
+ TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity();
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER);
- Mockito.verify(cambriaHandler, Mockito.times(1)).unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER);
+ String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName();
+ assertEquals(expectedStatusTopicName, actualStatusTopicName);
- assertTrue(!responseWrapper.isEmpty());
- Response response = responseWrapper.getInnerElement();
- assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName();
+ assertEquals(expectedNotificationTopicName, actualNotificationTopicName);
- }
+ assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(),
+ CambriaOperationStatus.AUTHENTICATION_ERROR);
+ assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK);
- @Test
- public void testHandleUnRegistrationHappyScenario() {
- CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+ }
- Mockito.when(cambriaHandler.unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class))).thenReturn(okResponse);
+ @SuppressWarnings("unchecked")
+ private void testHandleRegistrationBasic(RegistrationRequest registrationRequest,
+ Wrapper<Response> responseWrapper) {
+ CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
+ Mockito.when(cambriaHandler.registerToTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(),
+ Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString()))
+ .thenReturn(okResponse);
- Wrapper<Response> responseWrapper = new Wrapper<>();
- RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv");
- distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler);
+ String expectedStatusTopicName = buildTopicName(
+ configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(),
+ registrationRequest.getDistrEnvName());
+ String expectedNotificationTopicName = buildTopicName(
+ configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(),
+ registrationRequest.getDistrEnvName());
- Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER);
+ distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler);
- Mockito.verify(cambriaHandler, Mockito.times(2)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class));
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper,
+ registrationRequest, SubscriberTypeEnum.PRODUCER, expectedStatusTopicName);
+ verify(distributionBusinessLogic, Mockito.times(1)).registerDistributionClientToTopic(responseWrapper,
+ registrationRequest, SubscriberTypeEnum.CONSUMER, expectedNotificationTopicName);
- assertTrue(!responseWrapper.isEmpty());
- Response response = responseWrapper.getInnerElement();
- assertTrue(response.getStatus() == HttpStatus.SC_OK);
+ verify(cambriaHandler, Mockito.times(0)).unRegisterFromTopic(Mockito.anyCollection(), Mockito.anyString(),
+ Mockito.anyString(), Mockito.anyString(), Mockito.any(SubscriberTypeEnum.class), Mockito.anyString());
- TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity();
+ assertTrue(!responseWrapper.isEmpty());
+ Response response = responseWrapper.getInnerElement();
+ assertTrue(response.getStatus() == HttpStatus.SC_OK);
- String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName();
- assertEquals(expectedStatusTopicName, actualStatusTopicName);
+ TopicRegistrationResponse okTopicResponse = (TopicRegistrationResponse) response.getEntity();
- String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(configurationManager.getDistributionEngineConfiguration().getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
- String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName();
- assertEquals(expectedNotificationTopicName, actualNotificationTopicName);
+ String actualStatusTopicName = okTopicResponse.getDistrStatusTopicName();
+ assertEquals(expectedStatusTopicName, actualStatusTopicName);
- assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.OK);
- assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK);
+ String actualNotificationTopicName = okTopicResponse.getDistrNotificationTopicName();
+ assertEquals(expectedNotificationTopicName, actualNotificationTopicName);
+ }
- }
+ private void testHandleRegistrationFailed(RegistrationRequest registrationRequest,
+ Wrapper<Response> responseWrapper, Runnable failWhen) {
+ String expectedStatusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- @Test
- public void testHandleUnRegistrationFailedScenario() {
- CambriaErrorResponse okResponse = new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
- CambriaErrorResponse errorResponse = new CambriaErrorResponse(CambriaOperationStatus.AUTHENTICATION_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- Wrapper<Response> responseWrapper = new Wrapper<>();
- RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", "myEnv");
- DistributionEngineConfiguration config = configurationManager.getDistributionEngineConfiguration();
- String expectedStatusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
- String expectedNotificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
- Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedStatusTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER)).thenReturn(okResponse);
- Mockito.when(cambriaHandler.unRegisterFromTopic(config.getUebServers(), expectedNotificationTopicName, config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER))
- .thenReturn(errorResponse);
- distributionBusinessLogic.handleUnRegistration(responseWrapper, registrationRequest, auditHandler);
- Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(0)).registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER);
- Mockito.verify(distributionBusinessLogic, Mockito.times(1)).unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER);
- assertTrue(!responseWrapper.isEmpty());
- Response response = responseWrapper.getInnerElement();
- assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.CONSUMER,
+ expectedStatusTopicName)).thenReturn(okResponse);
- TopicUnregistrationResponse okTopicUnregisterResponse = (TopicUnregistrationResponse) response.getEntity();
+ when(cambriaHandler.registerToTopic(config.getUebServers(), config.getUebPublicKey(),
+ config.getUebSecretKey(), registrationRequest.getApiPublicKey(), SubscriberTypeEnum.PRODUCER,
+ expectedStatusTopicName)).thenReturn(okResponse);
- String actualStatusTopicName = okTopicUnregisterResponse.getDistrStatusTopicName();
- assertEquals(expectedStatusTopicName, actualStatusTopicName);
+ failWhen.run();
- String actualNotificationTopicName = okTopicUnregisterResponse.getDistrNotificationTopicName();
- assertEquals(expectedNotificationTopicName, actualNotificationTopicName);
+ distributionBusinessLogic.handleRegistration(responseWrapper, registrationRequest, auditHandler);
- assertEquals(okTopicUnregisterResponse.getNotificationUnregisterResult(), CambriaOperationStatus.AUTHENTICATION_ERROR);
- assertEquals(okTopicUnregisterResponse.getStatusUnregisterResult(), CambriaOperationStatus.OK);
+ assertTrue(!responseWrapper.isEmpty());
+ Response response = responseWrapper.getInnerElement();
+ assertTrue(response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR);
- }
- @Before
- public void init() {
- MockitoAnnotations.initMocks(this);
- Mockito.reset(cambriaHandler);
- }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java
index 4e27c30f8a..4257a88a02 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/ServiceDistributionArtifactsBuilderTest.java
@@ -20,17 +20,9 @@
package org.openecomp.sdc.be.distribution;
-import static org.junit.Assert.assertTrue;
-
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
import org.junit.Test;
import org.mockito.InjectMocks;
-import org.openecomp.sdc.be.components.BaseConfDependentTest;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
import org.openecomp.sdc.be.components.distribution.engine.ArtifactInfoImpl;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -38,69 +30,77 @@ import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-public class ServiceDistributionArtifactsBuilderTest extends BaseConfDependentTest {
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.junit.Assert.assertTrue;
+
+public class ServiceDistributionArtifactsBuilderTest extends BeConfDependentTest {
+
+ @InjectMocks
+ ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = new ServiceDistributionArtifactsBuilder();
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Test
+ public void testConvertServiceArtifactsToArtifactInfo() {
+
+ Service service = new Service();
+ String serviceName = "myService";
+ String serviceVersion = "1.0";
+ String serviceId = "serviceId";
+ service.setName(serviceName);
+ service.setVersion(serviceVersion);
+ service.setUniqueId(serviceId);
+
+
+ String artifactName = "service-Myservice-template.yml";
+ String artifactLabel = "assettoscatemplate";
+ String esArtifactId = "123123dfgdfgd0";
+ byte[] payload = "some payload".getBytes();
+
+ ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition();
+ toscaTemplateArtifact.setArtifactName(artifactName);
+ toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType());
+ toscaTemplateArtifact.setArtifactLabel(artifactLabel);
+ toscaTemplateArtifact.setEsId(esArtifactId);
+ toscaTemplateArtifact.setUniqueId(esArtifactId);
+ toscaTemplateArtifact.setPayload(payload);
+
+ Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();
+ toscaArtifacts.put(artifactLabel, toscaTemplateArtifact);
+ service.setToscaArtifacts(toscaArtifacts);
- @InjectMocks
- ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder = new ServiceDistributionArtifactsBuilder();
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void testConvertServiceArtifactsToArtifactInfo() {
+ ArtifactDefinition deploymentArtifact = new ArtifactDefinition();
+ deploymentArtifact.setArtifactName("deployment.yaml");
+ deploymentArtifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
+ deploymentArtifact.setArtifactType(ArtifactTypeEnum.OTHER.getType());
+ deploymentArtifact.setArtifactLabel("deployment");
+ deploymentArtifact.setEsId("deployment007");
+ deploymentArtifact.setUniqueId("deployment007");
+ deploymentArtifact.setPayload(payload);
+ Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
+ deploymentArtifacts.put("deployment", deploymentArtifact);
+ service.setDeploymentArtifacts(deploymentArtifacts);
- Service service = new Service();
- String serviceName = "myService";
- String serviceVersion = "1.0";
- String serviceId = "serviceId";
- service.setName(serviceName);
- service.setVersion(serviceVersion);
- service.setUniqueId(serviceId);
-
-
- String artifactName = "service-Myservice-template.yml";
- String artifactLabel = "assettoscatemplate";
- String esArtifactId = "123123dfgdfgd0";
- byte[] payload = "some payload".getBytes();
-
- ArtifactDefinition toscaTemplateArtifact = new ArtifactDefinition();
- toscaTemplateArtifact.setArtifactName(artifactName);
- toscaTemplateArtifact.setArtifactType(ArtifactTypeEnum.TOSCA_TEMPLATE.getType());
- toscaTemplateArtifact.setArtifactLabel(artifactLabel);
- toscaTemplateArtifact.setEsId(esArtifactId);
- toscaTemplateArtifact.setUniqueId(esArtifactId);
- toscaTemplateArtifact.setPayload(payload);
-
- Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();
- toscaArtifacts.put(artifactLabel, toscaTemplateArtifact);
- service.setToscaArtifacts(toscaArtifacts);
-
- ArtifactDefinition deploymentArtifact = new ArtifactDefinition();
- deploymentArtifact.setArtifactName("deployment.yaml");
- deploymentArtifact.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
- deploymentArtifact.setArtifactType(ArtifactTypeEnum.OTHER.getType());
- deploymentArtifact.setArtifactLabel("deployment");
- deploymentArtifact.setEsId("deployment007");
- deploymentArtifact.setUniqueId("deployment007");
- deploymentArtifact.setPayload(payload);
- Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
- deploymentArtifacts.put("deployment", deploymentArtifact);
- service.setDeploymentArtifacts(deploymentArtifacts);
-
- Class<ServiceDistributionArtifactsBuilder> targetClass = ServiceDistributionArtifactsBuilder.class;
- String methodName = "convertServiceArtifactsToArtifactInfo";
- Object[] argObjects = {service};
- Class[] argClasses = {Service.class};
- try {
- Method method = targetClass.getDeclaredMethod(methodName, argClasses);
- method.setAccessible(true);
- List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfoRes =
- (List<ArtifactInfoImpl>) method.invoke(serviceDistributionArtifactsBuilder, argObjects);
- assertTrue(convertServiceArtifactsToArtifactInfoRes != null);
- assertTrue(convertServiceArtifactsToArtifactInfoRes.size() == 2);
- List<String> artifactsNames = convertServiceArtifactsToArtifactInfoRes.stream().map(a->a.getArtifactName()).collect(Collectors.toList());
- assertTrue(artifactsNames.contains(artifactName) && artifactsNames.contains("deployment.yaml"));
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
+ Class<ServiceDistributionArtifactsBuilder> targetClass = ServiceDistributionArtifactsBuilder.class;
+ String methodName = "convertServiceArtifactsToArtifactInfo";
+ Object[] argObjects = {service};
+ Class[] argClasses = {Service.class};
+ try {
+ Method method = targetClass.getDeclaredMethod(methodName, argClasses);
+ method.setAccessible(true);
+ List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfoRes =
+ (List<ArtifactInfoImpl>) method.invoke(serviceDistributionArtifactsBuilder, argObjects);
+ assertTrue(convertServiceArtifactsToArtifactInfoRes != null);
+ assertTrue(convertServiceArtifactsToArtifactInfoRes.size() == 2);
+ List<String> artifactsNames = convertServiceArtifactsToArtifactInfoRes.stream().map(a->a.getArtifactName()).collect(Collectors.toList());
+ assertTrue(artifactsNames.contains(artifactName) && artifactsNames.contains("deployment.yaml"));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java
index 74f0eac5ad..29b43c1920 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/TestQueue.java
@@ -20,6 +20,11 @@
package org.openecomp.sdc.be.distribution;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler;
+import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
+import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
@@ -35,154 +40,148 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import org.openecomp.sdc.be.components.distribution.engine.CambriaHandler;
-import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
-import org.openecomp.sdc.be.components.distribution.engine.NotificationDataImpl;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-
public class TestQueue {
- public static void main(String[] args) {
- ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
- threadFactoryBuilder.setNameFormat("distribution-notification-thread");
- ThreadFactory threadFactory = threadFactoryBuilder.build();
- // TODO: add the package of google to the pom
-
- ExecutorService executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
- // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L,
- // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20));
-
- // 2 threads are always up and they handle the tasks. in case core size
- // is 0, only one is handles the tasks.
- // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L,
- // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20));
-
- // TODO : check what happen when the number of threads are full. Throw
- // RejectedExecutionException
- // TODO : check what happen whether the pool is full and the size of
- // pool
-
- ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(threadFactory);
- Runnable task = new Runnable() {
-
- @Override
- public void run() {
- try {
- System.out.println("iN SLEEP" + Thread.currentThread());
- Thread.sleep(10 * 1000);
- System.out.println("OUT SLEEP");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- };
-
- for (int i = 0; i < 4; i++) {
- try {
- executorService.submit(task);
- } catch (RejectedExecutionException e) {
- e.printStackTrace();
- }
- }
-
- newCachedThreadPool.submit(task);
- System.out.println("After submitting the task");
-
- MyWorker[] watchThreads = new MyWorker[1];
- BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
- for (int i = 0; i < watchThreads.length; i++) {
- MyWorker myWorker = new MyWorker(queue);
- myWorker.start();
- }
-
- for (int i = 0; i < 1; i++) {
- try {
- queue.put("message " + i);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- }
-
- public static class MyTimerTask extends TimerTask {
-
- AtomicBoolean state;
- Thread thread;
-
- public MyTimerTask(AtomicBoolean state, Thread thread) {
- super();
- this.state = state;
- this.thread = thread;
-
- System.out.println("After create timer");
- }
-
- @Override
- public void run() {
- System.out.println("In running of Timer task");
- if (state.get() == false) {
- System.out.println("In running of Timer task. Going to interrupt thread");
- // thread.interrupt();
- } else {
- System.out.println("In running of Timer task. Finished.");
- }
- }
-
- }
-
- public static class MyWorker extends Thread {
-
- boolean active = true;
- private final BlockingQueue<String> queue;
-
- public MyWorker(BlockingQueue<String> queue) {
- this.queue = queue;
- }
-
- Timer timer = new Timer();
-
- public void run() {
- try {
- while (active) {
- String s = queue.take();
- System.out.println("Thread " + Thread.currentThread() + " fecthed a message " + s);
-
- AtomicBoolean atomicBoolean = new AtomicBoolean(false);
- MyTimerTask myTimerTask = new MyTimerTask(atomicBoolean, this);
- timer.schedule(myTimerTask, 10 * 1000);
- doWork(s);
- atomicBoolean.set(true);
-
- }
- } catch (InterruptedException ie) {
-
- System.out.println("Interrupted our thread");
- ie.printStackTrace();
- }
- }
-
- private void doWork(String s) {
- // TODO Auto-generated method stub
-
- CambriaHandler cambriaHandler = new CambriaHandler();
- INotificationData data = new NotificationDataImpl();
- List<String> servers = new ArrayList<>();
- servers.add("aaaaaaa");
- cambriaHandler.sendNotification("topicName", "uebPublicKey", "uebSecretKey", servers, data);
-
- System.out.println("IN WORK " + s);
- try {
- Thread.sleep(1 * 1000);
- } catch (InterruptedException e) {
-
- for (int i = 0; i < 10; i++) {
- System.out.println("*************************************************");
- }
- e.printStackTrace();
- }
- }
- }
+ public static void main(String[] args) {
+ ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
+ threadFactoryBuilder.setNameFormat("distribution-notification-thread");
+ ThreadFactory threadFactory = threadFactoryBuilder.build();
+ // TODO: add the package of google to the pom
+
+ ExecutorService executorService = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory);
+ // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L,
+ // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20));
+
+ // 2 threads are always up and they handle the tasks. in case core size
+ // is 0, only one is handles the tasks.
+ // ExecutorService executorService = new ThreadPoolExecutor(0, 2, 60L,
+ // TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20));
+
+ // TODO : check what happen when the number of threads are full. Throw
+ // RejectedExecutionException
+ // TODO : check what happen whether the pool is full and the size of
+ // pool
+
+ ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(threadFactory);
+ Runnable task = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ System.out.println("iN SLEEP" + Thread.currentThread());
+ Thread.sleep(10 * 1000);
+ System.out.println("OUT SLEEP");
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+
+ for (int i = 0; i < 4; i++) {
+ try {
+ executorService.submit(task);
+ } catch (RejectedExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+
+ newCachedThreadPool.submit(task);
+ System.out.println("After submitting the task");
+
+ MyWorker[] watchThreads = new MyWorker[1];
+ BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
+ for (int i = 0; i < watchThreads.length; i++) {
+ MyWorker myWorker = new MyWorker(queue);
+ myWorker.start();
+ }
+
+ for (int i = 0; i < 1; i++) {
+ try {
+ queue.put("message " + i);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ public static class MyTimerTask extends TimerTask {
+
+ AtomicBoolean state;
+ Thread thread;
+
+ public MyTimerTask(AtomicBoolean state, Thread thread) {
+ super();
+ this.state = state;
+ this.thread = thread;
+
+ System.out.println("After create timer");
+ }
+
+ @Override
+ public void run() {
+ System.out.println("In running of Timer task");
+ if (state.get() == false) {
+ System.out.println("In running of Timer task. Going to interrupt thread");
+ // thread.interrupt();
+ } else {
+ System.out.println("In running of Timer task. Finished.");
+ }
+ }
+
+ }
+
+ public static class MyWorker extends Thread {
+
+ boolean active = true;
+ private final BlockingQueue<String> queue;
+
+ public MyWorker(BlockingQueue<String> queue) {
+ this.queue = queue;
+ }
+
+ Timer timer = new Timer();
+
+ public void run() {
+ try {
+ while (active) {
+ String s = queue.take();
+ System.out.println("Thread " + Thread.currentThread() + " fecthed a message " + s);
+
+ AtomicBoolean atomicBoolean = new AtomicBoolean(false);
+ MyTimerTask myTimerTask = new MyTimerTask(atomicBoolean, this);
+ timer.schedule(myTimerTask, 10 * 1000);
+ doWork(s);
+ atomicBoolean.set(true);
+
+ }
+ } catch (InterruptedException ie) {
+
+ System.out.println("Interrupted our thread");
+ ie.printStackTrace();
+ }
+ }
+
+ private void doWork(String s) {
+ // TODO Auto-generated method stub
+
+ CambriaHandler cambriaHandler = new CambriaHandler();
+ INotificationData data = new NotificationDataImpl();
+ List<String> servers = new ArrayList<>();
+ servers.add("aaaaaaa");
+ cambriaHandler.sendNotification("topicName", "uebPublicKey", "uebSecretKey", servers, data);
+
+ System.out.println("IN WORK " + s);
+ try {
+ Thread.sleep(1 * 1000);
+ } catch (InterruptedException e) {
+
+ for (int i = 0; i < 10; i++) {
+ System.out.println("*************************************************");
+ }
+ e.printStackTrace();
+ }
+ }
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java
index 3aa143a389..253fd31390 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/distribution/servlet/DistributionServletTest.java
@@ -20,17 +20,8 @@
package org.openecomp.sdc.be.distribution.servlet;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import org.apache.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
@@ -42,6 +33,7 @@ import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.openecomp.sdc.be.components.distribution.engine.DistributionEngine;
+import org.openecomp.sdc.be.config.SpringConfig;
import org.openecomp.sdc.be.distribution.AuditHandler;
import org.openecomp.sdc.be.distribution.DistributionBusinessLogic;
import org.openecomp.sdc.be.distribution.api.client.RegistrationRequest;
@@ -52,107 +44,116 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class DistributionServletTest extends JerseyTest {
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- public static final HttpSession session = Mockito.mock(HttpSession.class);
- public static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
- public static final DistributionBusinessLogic distributionBusinessLogic = Mockito.mock(DistributionBusinessLogic.class);
- public static final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class);
-
- public static final String ENV_NAME = "myEnv";
- public static final String NOTIFICATION_TOPIC = ENV_NAME + "_Notification";
- public static final String STATUS_TOPIC = ENV_NAME + "_Status";
-
- @BeforeClass
- public static void setup() {
- ExternalConfiguration.setAppName("catalog-be");
- when(request.getSession()).thenReturn(session);
- when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("myApplicationInstanceID");
-
- when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(DistributionBusinessLogic.class)).thenReturn(distributionBusinessLogic);
- when(distributionBusinessLogic.getDistributionEngine()).thenReturn(distributionEngine);
- when(distributionEngine.isEnvironmentAvailable(ENV_NAME)).thenReturn(StorageOperationStatus.OK);
- when(distributionEngine.isEnvironmentAvailable()).thenReturn(StorageOperationStatus.OK);
-
- mockBusinessLogicResponse();
-
- }
-
- private static void mockBusinessLogicResponse() {
- // Mock Register
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- Wrapper<Response> responseWrapper = (Wrapper<Response>) args[0];
- TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse();
- okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC);
- okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC);
- responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
-
- return true;
- }
- }).when(distributionBusinessLogic).handleRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class));
-
- // Mock Unregister
- Mockito.doAnswer(new Answer<Object>() {
- @Override
- public Object answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- Wrapper<Response> responseWrapper = (Wrapper<Response>) args[0];
- TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse();
- okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC);
- okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC);
- responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
-
- return true;
- }
- }).when(distributionBusinessLogic).handleUnRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class));
- }
-
- @Test
- public void registerSuccessTest() {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME);
- Response response = target().path("/v1/registerForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class);
- assertTrue(response.getStatus() == HttpStatus.SC_OK);
-
- }
-
- @Test
- public void unRegisterSuccessTest() {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME);
- Response response = target().path("/v1/unRegisterForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class);
- assertTrue(response.getStatus() == HttpStatus.SC_OK);
-
- }
-
- @Override
- protected Application configure() {
-
- ResourceConfig resourceConfig = new ResourceConfig(DistributionServlet.class);
- forceSet(TestProperties.CONTAINER_PORT, "0");
- resourceConfig.register(new AbstractBinder() {
-
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- });
-
- return resourceConfig;
- }
+ public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ public static final HttpSession session = Mockito.mock(HttpSession.class);
+ public static final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
+ public static final DistributionBusinessLogic distributionBusinessLogic = Mockito.mock(DistributionBusinessLogic.class);
+ public static final DistributionEngine distributionEngine = Mockito.mock(DistributionEngine.class);
+
+ public static final String ENV_NAME = "myEnv";
+ public static final String NOTIFICATION_TOPIC = ENV_NAME + "_Notification";
+ public static final String STATUS_TOPIC = ENV_NAME + "_Status";
+
+ @BeforeClass
+ public static void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+ when(request.getSession()).thenReturn(session);
+ when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("myApplicationInstanceID");
+
+ when(session.getServletContext()).thenReturn(servletContext);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(DistributionBusinessLogic.class)).thenReturn(distributionBusinessLogic);
+ when(distributionBusinessLogic.getDistributionEngine()).thenReturn(distributionEngine);
+ when(distributionEngine.isEnvironmentAvailable(ENV_NAME)).thenReturn(StorageOperationStatus.OK);
+ when(distributionEngine.isEnvironmentAvailable()).thenReturn(StorageOperationStatus.OK);
+
+ mockBusinessLogicResponse();
+
+ }
+
+ private static void mockBusinessLogicResponse() {
+ // Mock Register
+ Mockito.doAnswer(new Answer<Object>() {
+ @Override
+ public Object answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ Wrapper<Response> responseWrapper = (Wrapper<Response>) args[0];
+ TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse();
+ okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC);
+ okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC);
+ responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
+
+ return true;
+ }
+ }).when(distributionBusinessLogic).handleRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class));
+
+ // Mock Unregister
+ Mockito.doAnswer(new Answer<Object>() {
+ @Override
+ public Object answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ Wrapper<Response> responseWrapper = (Wrapper<Response>) args[0];
+ TopicRegistrationResponse okTopicResponse = new TopicRegistrationResponse();
+ okTopicResponse.setDistrNotificationTopicName(NOTIFICATION_TOPIC);
+ okTopicResponse.setDistrStatusTopicName(STATUS_TOPIC);
+ responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
+
+ return true;
+ }
+ }).when(distributionBusinessLogic).handleUnRegistration(Mockito.any(Wrapper.class), Mockito.any(RegistrationRequest.class), Mockito.any(AuditHandler.class));
+ }
+
+ @Test
+ public void registerSuccessTest() {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME, false);
+ Response response = target().path("/v1/registerForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class);
+ assertTrue(response.getStatus() == HttpStatus.SC_OK);
+
+ }
+
+ @Test
+ public void unRegisterSuccessTest() {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ RegistrationRequest registrationRequest = new RegistrationRequest("myPublicKey", ENV_NAME, false);
+ Response response = target().path("/v1/unRegisterForDistribution").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(registrationRequest)), Response.class);
+ assertTrue(response.getStatus() == HttpStatus.SC_OK);
+
+ }
+
+ @Override
+ protected Application configure() {
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ return new ResourceConfig(DistributionServlet.class)
+ .register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .property("contextConfig", context);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java
index 1df88c3686..8a40e83506 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/ecomp/GenerateEcompErrorFileTest.java
@@ -20,56 +20,56 @@
package org.openecomp.sdc.be.ecomp;
-import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.openecomp.sdc.common.config.EcompClassification;
+import org.openecomp.sdc.common.config.EcompErrorCode;
+import org.openecomp.sdc.common.config.EcompErrorEnum;
+import org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Test;
-import org.openecomp.sdc.common.config.EcompClassification;
-import org.openecomp.sdc.common.config.EcompErrorCode;
-import org.openecomp.sdc.common.config.EcompErrorEnum;
-import org.openecomp.sdc.common.config.generation.GenerateEcompErrorsCsv;
+import static org.junit.Assert.assertTrue;
public class GenerateEcompErrorFileTest {
- @Test
- public void verifyNoDuplicatesInEcompErrorCodes() {
+ @Test
+ public void verifyNoDuplicatesInEcompErrorCodes() {
- EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values();
+ EcompErrorEnum[] ecompErrorEnums = EcompErrorEnum.values();
- Map<EcompErrorCode, List<EcompClassification>> map = new HashMap<EcompErrorCode, List<EcompClassification>>();
- for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) {
+ Map<EcompErrorCode, List<EcompClassification>> map = new HashMap<EcompErrorCode, List<EcompClassification>>();
+ for (EcompErrorEnum ecompErrorEnum : ecompErrorEnums) {
- List<EcompClassification> list = map.get(ecompErrorEnum.getEcompErrorCode());
- if (list == null) {
- list = new ArrayList<>();
+ List<EcompClassification> list = map.get(ecompErrorEnum.getEcompErrorCode());
+ if (list == null) {
+ list = new ArrayList<>();
- list.add(ecompErrorEnum.getClassification());
+ list.add(ecompErrorEnum.getClassification());
- map.put(ecompErrorEnum.getEcompErrorCode(), list);
- } else {
- if (list.contains(ecompErrorEnum.getClassification())) {
- assertTrue(ecompErrorEnum.getEcompErrorCode() + " already defined with ecomp classification " + ecompErrorEnum.getClassification(), false);
- } else {
- list.add(ecompErrorEnum.getClassification());
- }
+ map.put(ecompErrorEnum.getEcompErrorCode(), list);
+ } else {
+ if (list.contains(ecompErrorEnum.getClassification())) {
+ assertTrue(ecompErrorEnum.getEcompErrorCode() + " already defined with ecomp classification " + ecompErrorEnum.getClassification(), false);
+ } else {
+ list.add(ecompErrorEnum.getClassification());
+ }
- }
+ }
- }
+ }
- }
+ }
- @Test
- public void generateEcompErrorFileInTarget() {
+ @Test
+ public void generateEcompErrorFileInTarget() {
- GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv();
- boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false);
- assertTrue("check result from file generation", result);
+ GenerateEcompErrorsCsv ecompErrorsCsv = new GenerateEcompErrorsCsv();
+ boolean result = ecompErrorsCsv.generateEcompErrorsCsvFile("target", false);
+ assertTrue("check result from file generation", result);
- }
+ }
}
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 810da4c10b..fa43523c79 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
@@ -21,19 +21,7 @@
package org.openecomp.sdc.be.externalapi.servlet;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import fj.data.Either;
import org.apache.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
@@ -48,6 +36,7 @@ import org.mockito.stubbing.Answer;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceImportManager;
+import org.openecomp.sdc.be.config.SpringConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
@@ -62,77 +51,88 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Arrays;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class AssetsDataServletTest extends JerseyTest {
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- public static final HttpSession session = Mockito.mock(HttpSession.class);
- public static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
- public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
- public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
- public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
- public static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class);
- public static final Resource resource = Mockito.mock(Resource.class);
- public static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class);
- public static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class);
- public static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class);
-// public static final ResourceAssetMetadata resourceAssetMetadata = Mockito.mock(ResourceAssetMetadata.class);
- public static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();;
-
-
-
-
-
- @BeforeClass
- public static void setup() {
- ExternalConfiguration.setAppName("catalog-be");
- when(request.getSession()).thenReturn(session);
- when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId");
- when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn("mockAttID");
- when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources"));
-
- when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
-
- when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
- when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic);
-
- when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
- mockResponseFormat();
-
- when(resource.getName()).thenReturn("MockVFCMT");
- when(resource.getSystemName()).thenReturn("mockvfcmt");
- Either<Resource, ResponseFormat> eitherRet = Either.left(resource);
- when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet);
-
- when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
- when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic);
- when(categoryDefinition.getName()).thenReturn("Template");
- when(subCategoryDefinition.getName()).thenReturn("Monitoring Template");
- when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition));
- when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition)));
- when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Either.left(resource));
- when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter);
-
- Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(),
- Mockito.eq(true));
-
-
-
- }
-
-
-
- private static void mockResponseFormat() {
- when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer<ResponseFormat>) invocation -> {
+ public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ public static final HttpSession session = Mockito.mock(HttpSession.class);
+ public static final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
+ public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
+ public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
+ public static final ResourceBusinessLogic resourceBusinessLogic = Mockito.mock(ResourceBusinessLogic.class);
+ public static final ElementBusinessLogic elementBusinessLogic = Mockito.mock(ElementBusinessLogic.class);
+ public static final Resource resource = Mockito.mock(Resource.class);
+ public static final CategoryDefinition categoryDefinition = Mockito.mock(CategoryDefinition.class);
+ public static final SubCategoryDefinition subCategoryDefinition = Mockito.mock(SubCategoryDefinition.class);
+ public static final AssetMetadataConverter assetMetadataConverter = Mockito.mock(AssetMetadataConverter.class);
+// public static final ResourceAssetMetadata resourceAssetMetadata = Mockito.mock(ResourceAssetMetadata.class);
+ public static final ResourceAssetMetadata resourceAssetMetadata = new ResourceAssetMetadata();;
+
+
+
+
+
+ @BeforeClass
+ public static void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+ when(request.getSession()).thenReturn(session);
+ when(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER)).thenReturn("mockXEcompInstanceId");
+ when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn("mockAttID");
+ when(request.getRequestURL()).thenReturn(new StringBuffer("sdc/v1/catalog/resources"));
+
+ when(session.getServletContext()).thenReturn(servletContext);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(webApplicationContext.getBean(ResourceBusinessLogic.class)).thenReturn(resourceBusinessLogic);
+
+ when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
+ mockResponseFormat();
+
+ when(resource.getName()).thenReturn("MockVFCMT");
+ when(resource.getSystemName()).thenReturn("mockvfcmt");
+ Either<Resource, ResponseFormat> eitherRet = Either.left(resource);
+ when(componentsUtils.convertJsonToObjectUsingObjectMapper(Mockito.any(), Mockito.any(), Mockito.eq(Resource.class), Mockito.any(), Mockito.eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherRet);
+
+ when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
+ when(webApplicationContext.getBean(ElementBusinessLogic.class)).thenReturn(elementBusinessLogic);
+ when(categoryDefinition.getName()).thenReturn("Template");
+ when(subCategoryDefinition.getName()).thenReturn("Monitoring Template");
+ when(categoryDefinition.getSubcategories()).thenReturn(Arrays.asList(subCategoryDefinition));
+ when(elementBusinessLogic.getAllResourceCategories()).thenReturn(Either.left(Arrays.asList(categoryDefinition)));
+ when(resourceBusinessLogic.createResource(Mockito.eq(resource), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Either.left(resource));
+ when(webApplicationContext.getBean(AssetMetadataConverter.class)).thenReturn(assetMetadataConverter);
+
+ Mockito.doReturn(Either.left(resourceAssetMetadata)).when(assetMetadataConverter).convertToSingleAssetMetadata(Mockito.eq(resource), Mockito.anyString(),
+ Mockito.eq(true));
+
+
+
+ }
+
+
+ private static void mockResponseFormat() {
+ when(componentsUtils.getResponseFormat(Mockito.any(ActionStatus.class), Mockito.any(String[].class))).thenAnswer((Answer<ResponseFormat>) invocation -> {
ResponseFormat ret;
final ActionStatus actionStatus = invocation.getArgument(0);
switch( actionStatus ){
@@ -147,52 +147,52 @@ public class AssetsDataServletTest extends JerseyTest {
}
return ret;
});
- }
-
-
-
- @Test
- public void createVfcmtHappyScenario() {
- final JSONObject createRequest = buildCreateJsonRequest();
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID")
- .post(Entity.json(createRequest.toJSONString()), Response.class);
- assertTrue(response.getStatus() == HttpStatus.SC_CREATED);
-
- }
- private static final String BASIC_CREATE_REQUEST = "{\r\n" +
- " \"name\": \"VFCMT_1\",\r\n" +
- " \"description\": \"VFCMT Description\",\r\n" +
- " \"resourceType\" : \"VFCMT\",\r\n" +
- " \"category\": \"Template\",\r\n" +
- " \"subcategory\": \"Monitoring Template\",\r\n" +
- " \"vendorName\" : \"DCAE\",\r\n" +
- " \"vendorRelease\" : \"1.0\",\r\n" +
- " \"tags\": [\r\n" +
- " \"VFCMT_1\"\r\n" +
- " ],\r\n" +
- " \"icon\" : \"defaulticon\",\r\n" +
- " \"contactId\": \"cs0008\"\r\n" +
- "}";
- private JSONObject buildCreateJsonRequest() {
-
- JSONParser parser = new JSONParser();
- JSONObject jsonObj = (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST));
- return jsonObj;
-
- }
- @Override
- protected Application configure() {
-
- ResourceConfig resourceConfig = new ResourceConfig(CrudExternalServlet.class);
- forceSet(TestProperties.CONTAINER_PORT, "0");
- resourceConfig.register(new AbstractBinder() {
-
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- });
-
- return resourceConfig;
- }
+ }
+
+
+
+ @Test
+ public void createVfcmtHappyScenario() {
+ final JSONObject createRequest = buildCreateJsonRequest();
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").header(Constants.USER_ID_HEADER, "mockAttID")
+ .post(Entity.json(createRequest.toJSONString()), Response.class);
+ assertTrue(response.getStatus() == HttpStatus.SC_CREATED);
+
+ }
+ private static final String BASIC_CREATE_REQUEST = "{\r\n" +
+ " \"name\": \"VFCMT_1\",\r\n" +
+ " \"description\": \"VFCMT Description\",\r\n" +
+ " \"resourceType\" : \"VFCMT\",\r\n" +
+ " \"category\": \"Template\",\r\n" +
+ " \"subcategory\": \"Monitoring Template\",\r\n" +
+ " \"vendorName\" : \"DCAE\",\r\n" +
+ " \"vendorRelease\" : \"1.0\",\r\n" +
+ " \"tags\": [\r\n" +
+ " \"VFCMT_1\"\r\n" +
+ " ],\r\n" +
+ " \"icon\" : \"defaulticon\",\r\n" +
+ " \"contactId\": \"cs0008\"\r\n" +
+ "}";
+ private JSONObject buildCreateJsonRequest() {
+
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj = (JSONObject) FunctionalInterfaces.swallowException( () -> parser.parse(BASIC_CREATE_REQUEST));
+ return jsonObj;
+
+ }
+
+ @Override
+ protected Application configure() {
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ return new ResourceConfig(CrudExternalServlet.class)
+ .register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .property("contextConfig", context);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java
new file mode 100644
index 0000000000..f185bffc17
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefServletTest.java
@@ -0,0 +1,603 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.glassfish.hk2.utilities.binding.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.JerseyTest;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic;
+import org.openecomp.sdc.be.components.path.utils.GraphTestUtils;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.DAOTitanStrategy;
+import org.openecomp.sdc.be.dao.TitanClientStrategy;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dto.ExternalRefDTO;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.ServletUtils;
+import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.CategoryOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
+import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper;
+import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.impl.FSConfigurationSource;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.context.WebApplicationContext;
+
+import fj.data.Either;
+
+public class ExternalRefServletTest extends JerseyTest {
+
+ private static ConfigurationManager configurationManager;
+ static String serviceVertexUuid;
+ private static final HttpSession session = Mockito.mock(HttpSession.class);
+ private static final ServletContext servletContext = Mockito.mock(ServletContext.class);
+
+ public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
+ private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
+ private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
+ private static final ResponseFormat notFoundResponseFormat = Mockito.mock(ResponseFormat.class);
+ private static final ResponseFormat badRequestResponseFormat = Mockito.mock(ResponseFormat.class);
+ private static final ToscaOperationFacade toscaOperationFacadeMock = Mockito.mock(ToscaOperationFacade.class);
+ private static final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
+ private static final TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
+ private static final ICacheMangerOperation cacheManagerOperation = Mockito.mock(ICacheMangerOperation.class);
+
+ private static final String COMPONENT_ID = "ci-MyComponentName";
+
+ private static final String FAKE_COMPONENT_ID = "ci-MyFAKEComponentName";
+ private static final String MONITORING_OBJECT_TYPE = "monitoring";
+ private static final String WORKFLOW_OBJECT_TYPE = "workflow";
+ private static final String VERSION = "0.1";
+ private static final String FAKE_VERSION = "0.5";
+ private static final String REF_1 = "ref1";
+ private static final String REF_2 = "ref2";
+ private static final String REF_3 = "ref3";
+ private static final String REF_4 = "ref4";
+ private static final String REF_5 = "ref5";
+ //workflow
+ private static final String REF_6 = "ref6";
+
+ @Configuration
+ static class TestSpringConfig {
+
+ private GraphVertex serviceVertex;
+ private ExternalReferencesOperation externalReferenceOperation;
+ private TitanDao titanDao;
+
+ @Bean
+ ExternalRefsServlet externalRefsServlet(){
+ return new ExternalRefsServlet(externalRefsBusinessLogic(), componentUtils);
+ }
+
+ @Bean
+ ExternalRefsBusinessLogic externalRefsBusinessLogic() {
+ return new ExternalRefsBusinessLogic(externalReferencesOperation(), toscaOperationFacade(), graphLockOperation());
+ }
+
+ @Bean
+ ExternalReferencesOperation externalReferencesOperation() {
+ this.externalReferenceOperation = new ExternalReferencesOperation(titanDao(), nodeTypeOpertaion(), topologyTemplateOperation(), idMapper());
+ GraphTestUtils.clearGraph(titanDao);
+ initGraphForTest();
+ return this.externalReferenceOperation;
+ }
+
+ @Bean
+ ToscaOperationFacade toscaOperationFacade(){
+ Component componentMock = Mockito.mock(Component.class);
+ when(componentMock.getVersion()).thenReturn(VERSION);
+ when(componentMock.getUniqueId()).thenReturn(serviceVertexUuid);
+ List<Component> listComponents = new LinkedList<Component>();
+ listComponents.add(componentMock);
+ when(toscaOperationFacadeMock.getComponentListByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents));
+ when(toscaOperationFacadeMock.getComponentByUuidAndVersion(eq(serviceVertexUuid), eq(VERSION))).thenReturn(Either.left(componentMock));
+ when(toscaOperationFacadeMock.getLatestComponentByUuid(eq(serviceVertexUuid), any())).thenReturn(Either.left(listComponents.get(0)));
+ return toscaOperationFacadeMock;
+ }
+
+ @Bean
+ IdMapper idMapper() {
+ IdMapper idMapper = Mockito.mock(IdMapper.class);
+ when(idMapper.mapComponentNameToUniqueId(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID);
+ when(idMapper.mapUniqueIdToComponentNameTo(eq(COMPONENT_ID), any(GraphVertex.class))).thenReturn(COMPONENT_ID);
+ when(idMapper.mapComponentNameToUniqueId(eq(FAKE_COMPONENT_ID), any(GraphVertex.class))).thenReturn(null);
+ return idMapper;
+ }
+
+ @Bean
+ TopologyTemplateOperation topologyTemplateOperation() {
+ return new TopologyTemplateOperation();
+ }
+
+ @Bean
+ NodeTypeOperation nodeTypeOpertaion() {
+ return new NodeTypeOperation(null);
+ }
+
+ @Bean
+ NodeTemplateOperation nodeTemplateOperation(){
+ return new NodeTemplateOperation();
+ }
+
+ @Bean
+ GroupsOperation groupsOperation(){
+ return new GroupsOperation();
+ }
+
+ @Bean
+ ICacheMangerOperation cacheMangerOperation() { return cacheManagerOperation; }
+
+ @Bean
+ TitanDao titanDao() {
+ this.titanDao = new TitanDao(titanGraphClient());
+ return titanDao;
+ }
+
+ @Bean
+ TitanGraphClient titanGraphClient() {
+ return new TitanGraphClient(titanClientStrategy());
+ }
+
+ @Bean
+ TitanClientStrategy titanClientStrategy() {
+ return new DAOTitanStrategy();
+ }
+
+ @Bean
+ CategoryOperation categoryOperation(){
+ return new CategoryOperation();
+ }
+
+ @Bean
+ GraphLockOperation graphLockOperation() { return graphLockOperation; }
+
+ @Bean
+ TitanGenericDao titanGenericDao() { return titanGenericDao; }
+
+ private void initGraphForTest() {
+ //create a service and add 1 ref
+ serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>());
+ serviceVertexUuid = this.serviceVertex.getUniqueId();
+
+ //monitoring references
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1);
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2);
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3);
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+
+ //workflow references
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6);
+
+ final TitanOperationStatus commit = this.titanDao.commit();
+ assertThat(commit).isEqualTo(TitanOperationStatus.OK);
+ }
+
+
+ }
+
+ public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+
+ /* Users */
+ private static User adminUser = new User("admin", "admin", "admin", "admin@email.com", Role.ADMIN.name(), System.currentTimeMillis());
+ private static User designerUser = new User("designer", "designer", "designer", "designer@email.com", Role.DESIGNER.name(), System.currentTimeMillis());
+ private static User otherUser = new User("other", "other", "other", "other@email.com", Role.OPS.name(), System.currentTimeMillis());
+
+
+ @BeforeClass
+ public static void setup() {
+
+ //Needed for User Authorization
+ //========================================================================================================================
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
+ when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
+ when(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)).thenReturn(responseFormat);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.UNAUTHORIZED.value());
+
+ //Needed for error configuration
+ when(notFoundResponseFormat.getStatus()).thenReturn(HttpStatus.NOT_FOUND.value());
+ when(badRequestResponseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST.value());
+ when(componentUtils.getResponseFormat(eq(ActionStatus.RESOURCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_VERSION_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.EXT_REF_NOT_FOUND), (String[]) any())).thenReturn(notFoundResponseFormat);
+ when(componentUtils.getResponseFormat(eq(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID), (String[]) any())).thenReturn(badRequestResponseFormat);
+
+ when(graphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK);
+
+ Either<User, ActionStatus> adminEither = Either.left(adminUser);
+ Either<User, ActionStatus> designerEither = Either.left(designerUser);
+ Either<User, ActionStatus> otherEither = Either.left(otherUser);
+
+ when(userAdmin.getUser(adminUser.getUserId(), false)).thenReturn(adminEither);
+ when(userAdmin.getUser(designerUser.getUserId(), false)).thenReturn(designerEither);
+ when(userAdmin.getUser(otherUser.getUserId(), false)).thenReturn(otherEither);
+ //========================================================================================================================
+
+ //TODO DELETE after successfull merge
+ //if (ConfigurationManager.getConfigurationManager() == null) {
+ String appConfigDir = "src/test/resources/config";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+
+ org.openecomp.sdc.be.config.Configuration configuration = new org.openecomp.sdc.be.config.Configuration();
+ configuration.setTitanInMemoryGraph(true);
+
+ configurationManager.setConfiguration(configuration);
+ //}
+ ExternalConfiguration.setAppName("catalog-be");
+ }
+
+ @Before
+ public void beforeTest() {
+
+ }
+
+ @Test
+ public void testGetExternalRefsForExistingComponentInstance() {
+ String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target().
+ path(path).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ get();
+
+ List<String> dto = response.readEntity(new GenericType<List<String>>() { });
+ assertThat(dto).containsExactly(REF_1, REF_2, REF_3, REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ public void testGetExternalRefsForAsset() {
+ String path = String.format("/v1/catalog/services/%s/version/%s/externalReferences/%s", serviceVertexUuid, VERSION, MONITORING_OBJECT_TYPE);
+
+ Response response = target().
+ path(path).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ get();
+
+ Map<String, List<String>> dtoMap = response.readEntity(new GenericType<HashMap<String, List<String>>>() { });
+ assertThat(dtoMap.get(COMPONENT_ID)).containsExactly(REF_1, REF_2, REF_3, REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ public void testAddExternalRefForExistingComponentInstance(){
+ String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target().
+ path(path).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ post(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED.value());
+
+ //Check that GET will include the new reference
+ response = target().
+ path(getPath).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, adminUser.getUserId()).
+ get();
+
+ List<String> dto = response.readEntity(new GenericType<List<String>>() { });
+ assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4, REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ public void testDeleteExternalRefForExistingComponentInstance(){
+ String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target().
+ path(deletePath).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ delete();
+
+ //Verify that the deleted reference is returned in body
+ ExternalRefDTO dto = response.readEntity(ExternalRefDTO.class);
+ assertThat(dto.getReferenceUUID()).isEqualTo(REF_5);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+
+ //Check that GET will NOT include the deleted reference
+ response = target().
+ path(getPath).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ get();
+
+ List<String> getResponse = response.readEntity(new GenericType<List<String>>() { });
+ assertThat(getResponse).containsExactlyInAnyOrder(REF_1, REF_2, REF_3);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ @Test
+ public void testUpdateExternalRefForExistingComponentInstance(){
+ String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ String getPath = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target().
+ path(updatePath).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ put(Entity.json(new ExternalRefDTO(REF_4)));
+
+ //Verify that the updated reference is returned in body
+ ExternalRefDTO putResponseBody = response.readEntity(ExternalRefDTO.class);
+ assertThat(putResponseBody.getReferenceUUID()).isEqualTo(REF_4);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+
+ //Check that GET will include the updated reference
+ response = target().
+ path(getPath).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ get();
+
+
+ List<String> dto = response.readEntity(new GenericType<List<String>>() { });
+ assertThat(dto).containsExactlyInAnyOrder(REF_1, REF_2, REF_3, REF_4);
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
+ }
+
+
+ /*
+ * Rainy Scenarios
+ */
+ @Test
+ public void testAddExternalRefForNonExistingAssetId(){
+ String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", "non-existing-uuid", COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target().
+ path(path).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ post(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ public void testAddExternalRefForNonExistingCompInstId(){
+ String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, "FAKE_COM_ID", MONITORING_OBJECT_TYPE);
+ Response response = target().
+ path(path).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ post(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ public void testAddExistingExternalRef(){
+ String path = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+ Response response = target().
+ path(path).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ post(Entity.json(new ExternalRefDTO(REF_1)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); //Ref not created but still OK is returned
+ }
+
+ @Test
+ public void testUpdateExternalRefForNonExistingAssetId(){
+ String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "nonExistingServiceVertexUuid", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+
+ Response response = target().
+ path(updatePath).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ put(Entity.json(new ExternalRefDTO(REF_4)));
+
+ //Verify that the 404 is returned
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+
+ }
+
+ @Test
+ public void testUpdateExternalRefForNonExistingObjectIdOrOldRef(){
+ String updatePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, "FAKE_OBJ_TYPE", REF_5);
+
+ Response response = target().
+ path(updatePath).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ put(Entity.json(new ExternalRefDTO(REF_4)));
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ System.out.println(response.readEntity(String.class));
+ }
+
+ @Test
+ public void testDeleteExternalRefForNonExistingAssetId(){
+ String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", "non-existing-asset", COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ Response response = target().
+ path(deletePath).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ delete();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ public void testDeleteExternalRefForNonExistingRef(){
+ String deletePath = String.format("/v1/catalog/services/%s/resourceInstances/%s/externalReferences/%s/%s", serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, "FAKE_REF");
+ Response response = target().
+ path(deletePath).
+ request(MediaType.APPLICATION_JSON).
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ delete();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ System.out.println(response.readEntity(String.class));
+ }
+
+ @Test
+ public void testGetExternalRefsForNonExistingAsset() {
+ String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", "fake-asset-id", VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target().
+ path(path).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ get();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ public void testGetExternalRefsForNonExistingVersion() {
+ String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, FAKE_VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target().
+ path(path).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, designerUser.getUserId()).
+ get();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ @Test
+ public void testGetExternalRefsForExistingComponentInstanceWithUnauthorizedUser() {
+ String path = String.format("/v1/catalog/services/%s/version/%s/resourceInstances/%s/externalReferences/%s", serviceVertexUuid, VERSION, COMPONENT_ID, MONITORING_OBJECT_TYPE);
+
+ Response response = target().
+ path(path).
+ request().
+ accept(MediaType.APPLICATION_JSON).
+ header(Constants.X_ECOMP_INSTANCE_ID_HEADER, "mockXEcompInstanceId").
+ header(Constants.USER_ID_HEADER, otherUser.getUserId()).
+ get();
+
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
+ }
+
+ @Override
+ protected Application configure() {
+ ApplicationContext context = new AnnotationConfigApplicationContext(TestSpringConfig.class);
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ return new ResourceConfig(ExternalRefsServlet.class)
+ .register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ when(request.getSession()).thenReturn(session);
+ when(request.getHeader(eq(Constants.X_ECOMP_INSTANCE_ID_HEADER))).thenReturn("mockXEcompInstIdHeader");
+ when(session.getServletContext()).thenReturn(servletContext);
+ }
+ })
+ .property("contextConfig", context);
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java
deleted file mode 100644
index 811a3031ae..0000000000
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/impl/ComponentsUtilsTest.java
+++ /dev/null
@@ -1,288 +0,0 @@
-package org.openecomp.sdc.be.impl;
-
-import java.util.EnumMap;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-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.model.Component;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.tosca.ToscaError;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-import org.openecomp.sdc.exception.ResponseFormat;
-
-public class ComponentsUtilsTest {
-
- private ComponentsUtils createTestSubject() {
- return new ComponentsUtils();
- }
-
-
- @Test
- public void testInit() throws Exception {
- ComponentsUtils testSubject;
-
- // default test
- testSubject = createTestSubject();
- testSubject.Init();
- }
-
-
- @Test
- public void testGetAuditingManager() throws Exception {
- ComponentsUtils testSubject;
- IAuditingManager result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAuditingManager();
- }
-
-
- @Test
- public void testSetAuditingManager() throws Exception {
- ComponentsUtils testSubject;
- IAuditingManager auditingManager = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setAuditingManager(auditingManager);
- }
-
-
- @Test
- public void testAuditResource() throws Exception {
- ComponentsUtils testSubject;
- ResponseFormat responseFormat = null;
- User modifier = null;
- Resource resource = null;
- String prevState = "";
- String prevVersion = "";
- AuditingActionEnum actionEnum = null;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = null;
-
- // test 1
- testSubject = createTestSubject();
- actionEnum = null;
- testSubject.auditResource(responseFormat, modifier, resource, prevState, prevVersion, actionEnum,
- additionalParams);
- }
-
-
- @Test
- public void testConvertFromStorageResponse() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = null;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponse(storageResponse);
- }
-
-
- @Test
- public void testConvertFromStorageResponse_1() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = null;
- ComponentTypeEnum type = null;
- ActionStatus result;
-
- // test 1
- testSubject = createTestSubject();
- storageResponse = null;
- result = testSubject.convertFromStorageResponse(storageResponse, type);
- Assert.assertEquals(ActionStatus.GENERAL_ERROR, result);
- }
-
-
- @Test
- public void testConvertFromToscaError() throws Exception {
- ComponentsUtils testSubject;
- ToscaError toscaError = null;
- ActionStatus result;
-
- // test 1
- testSubject = createTestSubject();
- toscaError = null;
- result = testSubject.convertFromToscaError(toscaError);
- Assert.assertEquals(ActionStatus.GENERAL_ERROR, result);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForCapabilityType() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForCapabilityType(storageResponse);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForLifecycleType() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForLifecycleType(storageResponse);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForResourceInstance() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- boolean isRelation = false;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForResourceInstance(storageResponse, isRelation);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForResourceInstanceProperty() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForResourceInstanceProperty(storageResponse);
- }
-
-
- @Test
- public void testAuditComponentAdmin() throws Exception {
- ComponentsUtils testSubject;
- ResponseFormat responseFormat = null;
- User modifier = null;
- Component component = null;
- String prevState = "";
- String prevVersion = "";
- AuditingActionEnum actionEnum = null;
- ComponentTypeEnum type = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.auditComponentAdmin(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type);
- }
-
-
- @Test
- public void testAuditComponent() throws Exception {
- ComponentsUtils testSubject;
- ResponseFormat responseFormat = null;
- User modifier = null;
- Component component = null;
- String prevState = "";
- String prevVersion = "";
- AuditingActionEnum actionEnum = null;
- ComponentTypeEnum type = null;
- EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = null;
-
- // test 1
- testSubject = createTestSubject();
- actionEnum = null;
- testSubject.auditComponent(responseFormat, modifier, component, prevState, prevVersion, actionEnum, type,
- additionalParams);
- }
-
-
- @Test
- public void testValidateStringNotEmpty_1() throws Exception {
- ComponentsUtils testSubject;
- String value = "";
- Boolean result;
-
- // test 1
- testSubject = createTestSubject();
- value = null;
- result = testSubject.validateStringNotEmpty(value);
- Assert.assertEquals(false, result);
-
- // test 2
- testSubject = createTestSubject();
- value = "";
- result = testSubject.validateStringNotEmpty(value);
- Assert.assertEquals(false, result);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForAdditionalInformation() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForAdditionalInformation(storageResponse);
- }
-
-
- @Test
- public void testConvertFromResultStatusEnum() throws Exception {
- ComponentsUtils testSubject;
- ResultStatusEnum resultStatus = ResultStatusEnum.ELEMENT_NOT_FOUND;
- JsonPresentationFields elementType = null;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromResultStatusEnum(resultStatus, elementType);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForConsumer() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForConsumer(storageResponse);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForGroupType() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForGroupType(storageResponse);
- }
-
-
- @Test
- public void testConvertFromStorageResponseForDataType() throws Exception {
- ComponentsUtils testSubject;
- StorageOperationStatus storageResponse = StorageOperationStatus.ARTIFACT_NOT_FOUND;
- ActionStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.convertFromStorageResponseForDataType(storageResponse);
- }
-
-
-
-} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java
index cee856d905..be43fa7d62 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/AbstractValidationsServletTest.java
@@ -20,9 +20,17 @@
package org.openecomp.sdc.be.servlets;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
+import fj.data.Either;
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.model.UploadResourceInfo;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.slf4j.Logger;
+import javax.ws.rs.core.Response;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -32,73 +40,60 @@ import java.nio.file.Paths;
import java.util.Map;
import java.util.stream.Stream;
-import javax.ws.rs.core.Response;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
-import org.apache.commons.codec.binary.Base64;
-import org.junit.Before;
-import org.junit.Test;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
+public class AbstractValidationsServletTest {
+ private static AbstractValidationsServlet servlet = new AbstractValidationsServlet() {};
-import fj.data.Either;
+ private static final String BASIC_TOSCA_TEMPLATE = "tosca_definitions_version: tosca_simple_yaml_%s";
-public class AbstractValidationsServletTest {
- private static AbstractValidationsServlet servlet = new AbstractValidationsServlet() {
- };
+ @Before
+ public void setUp() throws Exception {
+ servlet.initLog(mock(Logger.class));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testGetScarFromPayload() {
- private static final String BASIC_TOSCA_TEMPLATE = "tosca_definitions_version: tosca_simple_yaml_%s";
+ String payloadName = "valid_vf.csar";
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+ Either<Map<String, byte[]>, ResponseFormat> returnValue = null;
+ try {
+ path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ UploadResourceInfo resourceInfo = new UploadResourceInfo();
+ resourceInfo.setPayloadName(payloadName);
+ resourceInfo.setPayloadData(payloadData);
+ Method privateMethod = null;
+ privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getScarFromPayload", UploadResourceInfo.class);
+ privateMethod.setAccessible(true);
+ returnValue = (Either<Map<String, byte[]>, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo);
+ } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ assertTrue(returnValue.isLeft());
+ Map<String, byte[]> csar = returnValue.left().value();
+ assertTrue(csar != null);
+ }
- @Before
- public void setUp() throws Exception {
- servlet.initLog(mock(Logger.class));
- }
+ @Test
+ public void testValidToscaVersion() throws Exception {
+ Stream.of("1_0", "1_0_0", "1_1", "1_1_0").forEach(this::testValidToscaVersion);
+ }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testGetScarFromPayload() {
- String payloadName = "valid_vf.csar";
- String rootPath = System.getProperty("user.dir");
- Path path = null;
- byte[] data = null;
- String payloadData = null;
- Either<Map<String, byte[]>, ResponseFormat> returnValue = null;
- try {
- path = Paths.get(rootPath + "/src/test/resources/valid_vf.csar");
- data = Files.readAllBytes(path);
- payloadData = Base64.encodeBase64String(data);
- UploadResourceInfo resourceInfo = new UploadResourceInfo();
- resourceInfo.setPayloadName(payloadName);
- resourceInfo.setPayloadData(payloadData);
- Method privateMethod = null;
- privateMethod = AbstractValidationsServlet.class.getDeclaredMethod("getScarFromPayload",
- UploadResourceInfo.class);
- privateMethod.setAccessible(true);
- returnValue = (Either<Map<String, byte[]>, ResponseFormat>) privateMethod.invoke(servlet, resourceInfo);
- } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException
- | IllegalArgumentException | InvocationTargetException e) {
- e.printStackTrace();
- }
- assertTrue(returnValue.isLeft());
- Map<String, byte[]> csar = returnValue.left().value();
- assertTrue(csar != null);
- }
+ private void testValidToscaVersion(String version) {
+ Wrapper<Response> responseWrapper = new Wrapper<>();
+ servlet.validatePayloadIsTosca(responseWrapper, new UploadResourceInfo(), new User(), String.format(BASIC_TOSCA_TEMPLATE, version));
+ assertTrue(responseWrapper.isEmpty());
+ }
- @Test
- public void testValidToscaVersion() throws Exception {
- Stream.of("1_0", "1_0_0", "1_1", "1_1_0").forEach(this::testValidToscaVersion);
- }
- private void testValidToscaVersion(String version) {
- Wrapper<Response> responseWrapper = new Wrapper<>();
- servlet.validatePayloadIsTosca(responseWrapper, new UploadResourceInfo(), new User(),
- String.format(BASIC_TOSCA_TEMPLATE, version));
- assertTrue(responseWrapper.isEmpty());
- }
-
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java
index 6ef8091921..6fe303b495 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ApplicationConfig.java
@@ -20,42 +20,41 @@
package org.openecomp.sdc.be.servlets;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Application;
-
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.server.ResourceConfig;
import org.mockito.Mockito;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Application;
+import java.util.HashSet;
+import java.util.Set;
+
public class ApplicationConfig extends Application {
- public Set<Class<?>> getClasses() {
- final Set<Class<?>> resources = new HashSet<Class<?>>();
+ public Set<Class<?>> getClasses() {
+ final Set<Class<?>> resources = new HashSet<Class<?>>();
- // Add your resources.
- resources.add(ResourceUploadServlet.class);
- resources.add(MultiPart.class);
- resources.add(FormDataContentDisposition.class);
+ // Add your resources.
+ resources.add(ResourceUploadServlet.class);
+ resources.add(MultiPart.class);
+ resources.add(FormDataContentDisposition.class);
- final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- ResourceConfig resourceConfig = ResourceConfig.forApplication(this);
+ ResourceConfig resourceConfig = ResourceConfig.forApplication(this);
- resourceConfig.register(new AbstractBinder() {
+ resourceConfig.register(new AbstractBinder() {
- @Override
- protected void configure() {
- // TODO Auto-generated method stub
- bind(request).to(HttpServletRequest.class);
- }
- });
+ @Override
+ protected void configure() {
+ // TODO Auto-generated method stub
+ bind(request).to(HttpServletRequest.class);
+ }
+ });
- return resources;
- }
+ return resources;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java
new file mode 100644
index 0000000000..218505d8ef
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/BaseTestConfig.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.servlets;
+
+import org.openecomp.sdc.be.auditing.impl.AuditingManager;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.springframework.context.annotation.Bean;
+
+import static org.mockito.Mockito.mock;
+
+public class BaseTestConfig {
+
+ @Bean
+ ComponentsUtils componentsUtils() {return new ComponentsUtils(mock(AuditingManager.class));}
+
+ @Bean
+ DefaultExceptionMapper defaultExceptionMapper() {return new DefaultExceptionMapper();}
+
+ @Bean
+ ComponentExceptionMapper componentExceptionMapper() {
+ return new ComponentExceptionMapper(componentsUtils());
+ }
+
+ @Bean
+ StorageExceptionMapper storageExceptionMapper() {
+ return new StorageExceptionMapper(componentsUtils());
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java
index 97b1fe2a81..c723e0e664 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ComponentInstanceServletTest.java
@@ -1,17 +1,7 @@
package org.openecomp.sdc.be.servlets;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.glassfish.grizzly.http.util.HttpStatus;
+import fj.data.Either;
+import org.eclipse.jetty.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
@@ -19,8 +9,8 @@ import org.glassfish.jersey.test.TestProperties;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.config.SpringConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -29,108 +19,114 @@ import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
/**
* The test suite designed for test functionality of ComponentInstanceServlet class
*/
public class ComponentInstanceServletTest extends JerseyTest {
-
- private final static String USER_ID = "jh0003";
- private static HttpServletRequest request;
- private static HttpSession session;
- private static ServletContext servletContext;
- private static WebAppContextWrapper webAppContextWrapper;
- private static WebApplicationContext webApplicationContext;
- private static VFComponentInstanceBusinessLogic vfBusinessLogic;
- private static ServiceComponentInstanceBusinessLogic serviceBusinessLogic;
- private static ComponentsUtils componentsUtils;
- private static ServletUtils servletUtils;
- private static ResponseFormat responseFormat;
-
- @BeforeClass
- public static void setup() {
- createMocks();
- stubMethods();
- }
- @Test
- public void testGetRelationByIdSuccess(){
-
- String containerComponentType = "resources";
- String componentId = "componentId";
- String relationId = "relationId";
- String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId";
- Either<RequirementCapabilityRelDef, ResponseFormat> successResponse = Either.left(new RequirementCapabilityRelDef());
- when(vfBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode());
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .get( Response.class);
+ private final static String USER_ID = "jh0003";
+ private static HttpServletRequest request;
+ private static HttpSession session;
+ private static ServletContext servletContext;
+ private static WebAppContextWrapper webAppContextWrapper;
+ private static WebApplicationContext webApplicationContext;
+ private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ private static ComponentsUtils componentsUtils;
+ private static ServletUtils servletUtils;
+ private static ResponseFormat responseFormat;
+
+ @BeforeClass
+ public static void setup() {
+ createMocks();
+ stubMethods();
+ }
+
+ @Test
+ public void testGetRelationByIdSuccess(){
+
+ String containerComponentType = "resources";
+ String componentId = "componentId";
+ String relationId = "relationId";
+ String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId";
+ Either<RequirementCapabilityRelDef, ResponseFormat> successResponse = Either.left(new RequirementCapabilityRelDef());
+ when(componentInstanceBusinessLogic.getRelationById(eq(componentId), eq(relationId), eq(USER_ID), eq(ComponentTypeEnum.RESOURCE))).thenReturn(successResponse);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
+ when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get( Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.OK_200);
+ }
+
+ @Test
+ public void testGetRelationByIdFailure(){
+
+ String containerComponentType = "unknown_type";
+ String componentId = "componentId";
+ String relationId = "relationId";
+ String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId";
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400);
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get( Response.class);
- assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode());
- }
-
- @Test
- public void testGetRelationByIdFailure(){
-
- String containerComponentType = "unknown_type";
- String componentId = "componentId";
- String relationId = "relationId";
- String path = "/v1/catalog/" + containerComponentType + "/" + componentId + "/" + relationId + "/relationId";
- when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode());
- when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(containerComponentType))).thenReturn(responseFormat);
- Response response = target()
- .path(path)
- .request(MediaType.APPLICATION_JSON)
- .header("USER_ID", USER_ID)
- .get( Response.class);
+ assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400);
+ }
- assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode());
- }
+ @Override
+ protected ResourceConfig configure() {
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ return new ResourceConfig(ComponentInstanceServlet.class)
+ .register(new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .property("contextConfig", context);
+ }
- @Override
- protected Application configure() {
+ private static void createMocks() {
+ request = Mockito.mock(HttpServletRequest.class);
+ session = Mockito.mock(HttpSession.class);
+ servletContext = Mockito.mock(ServletContext.class);
+ webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ componentInstanceBusinessLogic = Mockito.mock(ComponentInstanceBusinessLogic.class);
+ componentsUtils = Mockito.mock(ComponentsUtils.class);
+ servletUtils = Mockito.mock(ServletUtils.class);
+ responseFormat = Mockito.mock(ResponseFormat.class);
+ }
- ResourceConfig resourceConfig = new ResourceConfig(ComponentInstanceServlet.class);
- forceSet(TestProperties.CONTAINER_PORT, "0");
-
- resourceConfig.register(new AbstractBinder() {
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- });
- return resourceConfig;
- }
-
- private static void createMocks() {
- request = Mockito.mock(HttpServletRequest.class);
- session = Mockito.mock(HttpSession.class);
- servletContext = Mockito.mock(ServletContext.class);
- webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- webApplicationContext = Mockito.mock(WebApplicationContext.class);
- vfBusinessLogic = Mockito.mock(VFComponentInstanceBusinessLogic.class);
- serviceBusinessLogic = Mockito.mock(ServiceComponentInstanceBusinessLogic.class);
- componentsUtils = Mockito.mock(ComponentsUtils.class);
- servletUtils = Mockito.mock(ServletUtils.class);
- responseFormat = Mockito.mock(ResponseFormat.class);
- }
-
- private static void stubMethods() {
- when(request.getSession()).thenReturn(session);
- when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(VFComponentInstanceBusinessLogic.class)).thenReturn(vfBusinessLogic);
- when(webApplicationContext.getBean(ServiceComponentInstanceBusinessLogic.class)).thenReturn(serviceBusinessLogic);
- when(request.getHeader("USER_ID")).thenReturn(USER_ID);
- when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
- when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
- }
+ private static void stubMethods() {
+ when(request.getSession()).thenReturn(session);
+ when(session.getServletContext()).thenReturn(servletContext);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(ComponentInstanceBusinessLogic.class)).thenReturn(componentInstanceBusinessLogic);
+ when(request.getHeader("USER_ID")).thenReturn(USER_ID);
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java
new file mode 100644
index 0000000000..414ffaad59
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupEndpointTest.java
@@ -0,0 +1,179 @@
+//package org.openecomp.sdc.be.servlets;
+//
+//import com.fasterxml.jackson.databind.DeserializationFeature;
+//import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+//import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
+//import fj.data.Either;
+//import org.eclipse.jetty.http.HttpStatus;
+//import org.glassfish.hk2.utilities.binding.AbstractBinder;
+//import org.glassfish.jersey.client.ClientConfig;
+//import org.glassfish.jersey.server.ResourceConfig;
+//import org.glassfish.jersey.test.JerseyTest;
+//import org.glassfish.jersey.test.TestProperties;
+//import org.junit.Before;
+//import org.junit.Test;
+//import org.junit.runner.RunWith;
+//import org.mockito.Mock;
+//import org.mockito.junit.MockitoJUnitRunner;
+//import org.openecomp.sdc.be.DummyConfigurationManager;
+//import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
+//import org.openecomp.sdc.be.dao.api.ActionStatus;
+//import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+//import org.openecomp.sdc.be.impl.ComponentsUtils;
+//import org.openecomp.sdc.be.impl.ServletUtils;
+//import org.openecomp.sdc.be.impl.WebAppContextWrapper;
+//import org.openecomp.sdc.be.info.GroupDefinitionInfo;
+//import org.openecomp.sdc.be.model.GroupDefinition;
+//import org.openecomp.sdc.common.api.Constants;
+//import org.openecomp.sdc.exception.ResponseFormat;
+//import org.springframework.web.context.WebApplicationContext;
+//
+//import javax.servlet.ServletContext;
+//import javax.servlet.http.HttpServletRequest;
+//import javax.servlet.http.HttpSession;
+//import javax.ws.rs.client.ClientBuilder;
+//import javax.ws.rs.client.Invocation;
+//import javax.ws.rs.core.Application;
+//import javax.ws.rs.core.MediaType;
+//import javax.ws.rs.core.Response;
+//
+//import static org.assertj.core.api.Assertions.assertThat;
+//import static org.junit.Assert.assertEquals;
+//import static org.mockito.ArgumentMatchers.*;
+//import static org.mockito.Mockito.when;
+//
+//@RunWith(MockitoJUnitRunner.class)
+//public class GroupEndpointTest extends JerseyTest {
+//
+// public static final String USER_ID = "jh0003";
+// public static final String INVALID_USER_ID = "jh0001";
+// final static String RESOURCE_TYPE = "resources";
+// private static final String COMPONENT_ID = "1234";
+// private static final String VALID_GROUP_ID = "1";
+// private static final String INVALID_GROUP_ID = "2";
+// private static final String NEW_GROUP_NAME = "new group";
+// private static final String VALID_GROUP_TYPE = "networkConnection";
+//
+// @Mock
+// private GroupBusinessLogic groupBusinessLogic;
+// @Mock
+// private ServletContext servletContext;
+// @Mock
+// private WebAppContextWrapper webAppContextWrapper;
+// @Mock
+// private WebApplicationContext webApplicationContext;
+// @Mock
+// private HttpServletRequest request;
+// @Mock
+// private HttpSession session;
+// @Mock
+// private ComponentsUtils componentUtils;
+// @Mock
+// private ServletUtils servletUtils;
+// @Mock
+// private ResponseFormat responseFormat;
+//
+// @Override
+// protected Application configure() {
+// ResourceConfig resourceConfig = new ResourceConfig()
+// .register(GroupServlet.class)
+// //.register(mapper)
+// ;
+// forceSet(TestProperties.CONTAINER_PORT, "0");
+// resourceConfig.register(new AbstractBinder() {
+// @Override
+// protected void configure() {
+// bind(request).to(HttpServletRequest.class);
+// }
+// });
+// return resourceConfig;
+// }
+//
+// @Before
+// public void before() {
+// when(request.getSession()).thenReturn(session);
+// when(session.getServletContext()).thenReturn(servletContext);
+// when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+// when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+// when(webApplicationContext.getBean(GroupBusinessLogic.class)).thenReturn(groupBusinessLogic);
+//// when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentUtils);
+// when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+// when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
+//// when(request.getHeader("USER_ID")).thenReturn(USER_ID);
+// final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+// setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider)));
+// new DummyConfigurationManager();
+//// when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping()).thenReturn(buildExcludePolicyTypesMap());
+// }
+//
+// //@Test
+// public void createGroup() {
+// GroupDefinition groupDefinition = new GroupDefinition();
+// groupDefinition.setName(NEW_GROUP_NAME);
+// groupDefinition.setType(VALID_GROUP_TYPE);
+// when(groupBusinessLogic.createGroup(eq(NEW_GROUP_NAME), eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(USER_ID)))
+// .thenReturn(groupDefinition);
+// //List<GroupDefinition> gdList = buildCreateGroupCall().post(Response.class);
+//
+// }
+//
+// //@Test
+// public void deleteGroup_withInvalidUser_shouldReturn_401() {
+// int unauthorized401 = HttpStatus.UNAUTHORIZED_401;
+// int unauthorized403 = HttpStatus.FORBIDDEN_403;
+// when(groupBusinessLogic.validateUserExists(eq(INVALID_USER_ID), anyString(), anyBoolean()))
+// .thenReturn(Either.right(new ResponseFormat(unauthorized401)));
+//
+// Response response = buildDeleteGroupCall(INVALID_USER_ID, VALID_GROUP_ID).delete();
+// assertThat(response.getStatus()).isEqualTo(unauthorized401);
+// }
+//
+// @Test
+// public void getGroupById_internalServerError() {
+// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(VALID_GROUP_ID), eq(USER_ID), eq(false) ))
+// .thenReturn(Either.right(new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR_500)));
+// Response response = buildGetGroupCall(VALID_GROUP_ID).get();
+// assertEquals(response.getStatus(), 500);
+// }
+//
+// @Test
+// public void getGroupById_Success() {
+// GroupDefinitionInfo groupDefinitionInfo = new GroupDefinitionInfo();
+// groupDefinitionInfo.setUniqueId(VALID_GROUP_ID);
+// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(VALID_GROUP_ID), eq(USER_ID), eq(false) ))
+// .thenReturn(Either.left(groupDefinitionInfo));
+// when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
+// when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200);
+// GroupDefinitionInfo gdi = buildGetGroupCall(VALID_GROUP_ID).get(GroupDefinitionInfo.class);
+// assertEquals(gdi.getUniqueId(), VALID_GROUP_ID);
+// }
+//
+// @Test
+// public void getGroupById_Failure() {
+// when(groupBusinessLogic.getGroupWithArtifactsById(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(INVALID_GROUP_ID), eq(USER_ID), eq(false) ))
+// .thenReturn(Either.right(new ResponseFormat(HttpStatus.NOT_FOUND_404)));
+// Response response = buildGetGroupCall(INVALID_GROUP_ID).get();
+// assertEquals(response.getStatus(), 404);
+// }
+//
+// private Invocation.Builder buildGetGroupCall(String groupId) {
+// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups/" + groupId;
+// return target(path)
+// .request(MediaType.APPLICATION_JSON)
+// .header(Constants.USER_ID_HEADER, USER_ID);
+// }
+//
+// private Invocation.Builder buildDeleteGroupCall(String userId, String groupId) {
+// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups/" + groupId;
+// return target(path)
+// .request(MediaType.APPLICATION_JSON)
+// .header(Constants.USER_ID_HEADER, userId);
+// }
+//
+// private Invocation.Builder buildCreateGroupCall() {
+// String path = "/v1/catalog/" + RESOURCE_TYPE + "/" + COMPONENT_ID + "/groups";
+// return target(path)
+// .request(MediaType.APPLICATION_JSON)
+// .header(Constants.USER_ID_HEADER, USER_ID);
+// }
+//}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java
new file mode 100644
index 0000000000..2d5494354d
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/GroupTypesEndpointTest.java
@@ -0,0 +1,197 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Sets;
+import fj.data.Either;
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.sdc.be.DummyConfigurationManager;
+import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
+import org.openecomp.sdc.be.components.utils.GroupTypeBuilder;
+import org.openecomp.sdc.be.components.validation.UserValidations;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.StorageException;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.http.HttpStatus;
+
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class GroupTypesEndpointTest extends JerseySpringBaseTest {
+
+ private static final String USER_ID = "a001";
+ private static final String INVALID_USER_ID = "a002";
+ private static final GroupTypeDefinition EMPTY_GROUP_TYPE = new GroupTypeDefinition();
+ private static final String COMPONENT_TYPE = "VF";
+ private static final HashSet<String> EXCLUDED_TYPES = Sets.newHashSet("Root", "Heat");
+
+ private static ComponentsUtils componentsUtils;
+ private static GroupTypeOperation groupTypeOperation;
+ private static TitanDao titanDao;
+ private static UserValidations userValidations;
+ private static User user;
+
+ @Configuration
+ @Import(BaseTestConfig.class)
+ static class GroupTypesTestConfig {
+
+ @Bean
+ GroupTypesEndpoint groupTypesEndpoint() {
+ return new GroupTypesEndpoint(groupTypeBusinessLogic());
+ }
+
+ @Bean
+ GroupTypeBusinessLogic groupTypeBusinessLogic() {
+ return new GroupTypeBusinessLogic(groupTypeOperation, titanDao, userValidations);
+ }
+ }
+
+ @BeforeClass
+ public static void initClass() {
+ componentsUtils = mock(ComponentsUtils.class);
+ groupTypeOperation = mock(GroupTypeOperation.class);
+ titanDao = mock(TitanDao.class);
+ userValidations = mock(UserValidations.class);
+ user = mock(User.class);
+ }
+
+ @Before
+ public void init() {
+ new DummyConfigurationManager();
+ when(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping()).thenReturn(buildExcludeGroupTypesMap());
+ ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();
+ when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(Either.left(user));
+ // TODO: handle for invalid user test
+// when(userValidations.validateUserExists(eq(INVALID_USER_ID), anyString(), anyBoolean())).thenReturn(Either.right(???)));
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ config.register(jacksonJsonProvider);
+ }
+
+ @Override
+ protected ResourceConfig configure() {
+ return super.configure(GroupTypesTestConfig.class)
+ .register(GroupTypesEndpoint.class);
+ }
+
+ @Test
+ public void getGroupTypes_validUser_Success() {
+ List<GroupTypeDefinition> testConfigGroupTypes = buildGroupTypesList();
+ when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenReturn(buildGroupTypesList());
+ List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCall(USER_ID).get(new GenericType<List<GroupTypeDefinition>>(){});
+ verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes);
+ }
+
+ @Test
+ public void getGroupTypes_whenNoInteranlComponentType_passEmptyAsExcludedTypes() {
+ List<GroupTypeDefinition> testConfigGroupTypes = buildGroupTypesList();
+ when(groupTypeOperation.getAllGroupTypes(null)).thenReturn(buildGroupTypesList());
+ List<GroupTypeDefinition> fetchedGroupTypes = buildGetGroupTypesCallNoInternalComponent(USER_ID).get(new GenericType<List<GroupTypeDefinition>>(){});
+ verifyGroupTypesList(testConfigGroupTypes, fetchedGroupTypes);
+ }
+
+ @Ignore
+ public void getGroupTypes_dbError() {
+ when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenThrow(new StorageException(StorageOperationStatus.NOT_FOUND));
+ when(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND)).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
+ when(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND)).thenReturn(new ResponseFormat(HttpStatus.NOT_FOUND.value()));
+ Response response = buildGetGroupTypesCall(USER_ID).get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
+ }
+
+ // TODO: simulate proper error with configuration error mapping and eactivate the test
+ @Ignore
+ public void getGroupTypes_invalidUser_Failure() {
+ when(groupTypeOperation.getAllGroupTypes(EXCLUDED_TYPES)).thenReturn(buildGroupTypesList());
+ Response response = buildGetGroupTypesCall(INVALID_USER_ID).get();
+ assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
+ }
+
+ private void verifyGroupTypesList(List<GroupTypeDefinition> groupTypes, List<GroupTypeDefinition> fetchedGroupTypes) {
+ assertThat(fetchedGroupTypes)
+ .usingElementComparatorOnFields("version", "type", "uniqueId")
+ .isEqualTo(groupTypes);
+ verifyOnlySpecificFieldsInResponse(fetchedGroupTypes, "version", "type", "uniqueId");
+ }
+
+ private void verifyOnlySpecificFieldsInResponse(List<GroupTypeDefinition> fetchedGroupTypes, String ... fields) {
+ assertThat(fetchedGroupTypes)
+ .usingElementComparatorIgnoringFields(fields)
+ .containsOnly(EMPTY_GROUP_TYPE);
+ }
+
+ private Invocation.Builder buildGetGroupTypesCall(String userId) {
+ return target("/v1/catalog/groupTypes")
+ .queryParam("internalComponentType", COMPONENT_TYPE)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId);
+ }
+
+ private Invocation.Builder buildGetGroupTypesCallNoInternalComponent(String userId) {
+ return target("/v1/catalog/groupTypes")
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, userId);
+ }
+
+ private Map<String, Set<String>> buildExcludeGroupTypesMap() {
+ return new ImmutableMap.Builder<String, Set<String>>()
+ .put("CR", Sets.newHashSet("VFModule", "Root", "Heat"))
+ .put(COMPONENT_TYPE, EXCLUDED_TYPES)
+ .build();
+ }
+
+
+ private List<GroupTypeDefinition> buildGroupTypesList() {
+ GroupTypeDefinition type1 = GroupTypeBuilder.create()
+ .setDerivedFrom("root")
+ .setType("VFModule")
+ .setUniqueId("id1")
+ .setVersion("1.0")
+ .build();
+ GroupTypeDefinition type2 = GroupTypeBuilder.create().setDerivedFrom("root").setType("Heat").setUniqueId("id2").build();
+ return asList(type1, type2);
+ }
+
+ private GroupTypeDefinition[] listOfEmptyGroupTypes(int size) {
+ return Stream.generate(GroupTypeDefinition::new).limit(size).toArray(GroupTypeDefinition[]::new);
+ }
+
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java
new file mode 100644
index 0000000000..9a074c95c2
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/JerseySpringBaseTest.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.be.servlets;
+
+import org.glassfish.hk2.utilities.binding.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.JerseyTest;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.BeforeClass;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+import javax.servlet.http.HttpServletRequest;
+
+import static org.mockito.Mockito.mock;
+
+public class JerseySpringBaseTest extends JerseyTest {
+
+ protected static HttpServletRequest request;
+
+ @BeforeClass
+ public static void initBaseClass() {
+ request = mock(HttpServletRequest.class);
+ }
+
+ protected ResourceConfig configure() {
+ return configure(BaseTestConfig.class);
+ }
+
+ protected ResourceConfig configure(Class<?> springConfig) {
+ ApplicationContext context = new AnnotationConfigApplicationContext(springConfig);
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ return new ResourceConfig()
+ .register(new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .register(DefaultExceptionMapper.class)
+ .register(ComponentExceptionMapper.class)
+ .register(StorageExceptionMapper.class)
+ .property("jersey.config.server.provider.classnames", "org.openecomp.sdc.be.view.MixinModelWriter")
+ .property("contextConfig", context);
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java
new file mode 100644
index 0000000000..bb949253b2
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyServletTest.java
@@ -0,0 +1,338 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import fj.data.Either;
+import org.glassfish.grizzly.http.util.HttpStatus;
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
+import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.impl.ServletUtils;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.PolicyTargetDTO;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+public class PolicyServletTest extends JerseySpringBaseTest{
+
+ private final static String USER_ID = "jh0003";
+ private static final String COMPONENT_ID = "componentId";
+ private static PolicyBusinessLogic businessLogic;
+ private static ComponentsUtils componentsUtils;
+ private static ServletUtils servletUtils;
+ private static ResponseFormat responseFormat;
+
+ private static String validComponentType = "resources";
+ private static String unsupportedComponentType = "unsupported";
+ private static String componentId = "componentId";
+ private static String policyTypeName = "policyTypeName";
+
+ private static final String PROPS_URL = "/v1/catalog/{componentType}/{serviceId}/policies/{policyId}/properties";
+ private static final String SERVICE_ID = "serviceId";
+ private static final String POLICY_ID = "policyId";
+
+ private static final String UPDATE_TARGETS_URL = "/v1/catalog/{componentType}/{componentId}/policies/{policyId}/targets";
+
+ @BeforeClass
+ public static void initClass() {
+ createMocks();
+ when(servletUtils.getComponentsUtils()).thenReturn(componentsUtils);
+ }
+
+ @Before
+ public void beforeMethod() {
+ final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ setClient(ClientBuilder.newClient(new ClientConfig(jacksonJsonProvider)));
+ }
+
+ @Test
+ public void testGetPolicySuccess(){
+ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
+ Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(new PolicyDefinition());
+ when(businessLogic.getPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID))).thenReturn(successResponse);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode());
+ when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get(Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode());
+ }
+
+ @Test
+ public void testGetPolicyFailure(){
+ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode());
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .get(Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode());
+ }
+
+ @Test
+ public void testPostPolicySuccess(){
+ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + policyTypeName;
+ PolicyDefinition policy = new PolicyDefinition();
+ Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(policy);
+ when(businessLogic.createPolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(policyTypeName), eq(USER_ID), eq(true))).thenReturn(successResponse);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode());
+ when(componentsUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode());
+ }
+
+ @Test
+ public void testPostPolicyFailure(){
+ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + policyTypeName;
+ PolicyDefinition policy = new PolicyDefinition();
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode());
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .post(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode());
+ }
+
+ @Test
+ public void testPutPolicySuccess(){
+ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
+ PolicyDefinition policy = new PolicyDefinition();
+ policy.setUniqueId(POLICY_ID);
+ Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(policy);
+ when(businessLogic.updatePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), any(PolicyDefinition.class), eq(USER_ID), eq(true))).thenReturn(successResponse);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.OK_200.getStatusCode());
+ when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.OK_200.getStatusCode());
+ }
+
+ @Test
+ public void testPutPolicyFailure(){
+ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
+ PolicyDefinition policy = new PolicyDefinition();
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode());
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .put(Entity.entity(policy, MediaType.APPLICATION_JSON),Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode());
+ }
+
+ @Test
+ public void testDeletePolicySuccess(){
+ String path = "/v1/catalog/" + validComponentType + "/" + componentId + "/policies/" + POLICY_ID;
+ Either<PolicyDefinition, ResponseFormat> successResponse = Either.left(new PolicyDefinition());
+ when(businessLogic.deletePolicy(eq(ComponentTypeEnum.RESOURCE), eq(componentId), eq(POLICY_ID), eq(USER_ID), eq(true))).thenReturn(successResponse);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.NO_CONTENT_204.getStatusCode());
+ when(componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT)).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .delete(Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.NO_CONTENT_204.getStatusCode());
+ }
+
+ @Test
+ public void testDeletePolicyFailure(){
+ String path = "/v1/catalog/" + unsupportedComponentType + "/" + componentId + "/policies/" + POLICY_ID;
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.BAD_REQUEST_400.getStatusCode());
+ when(componentsUtils.getResponseFormat(eq(ActionStatus.UNSUPPORTED_ERROR), eq(unsupportedComponentType))).thenReturn(responseFormat);
+ Response response = target()
+ .path(path)
+ .request(MediaType.APPLICATION_JSON)
+ .header("USER_ID", USER_ID)
+ .delete(Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST_400.getStatusCode());
+ }
+
+ @Test
+ public void getPolicyProperties_operationForbidden() {
+ when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.right(new ResponseFormat(Response.Status.FORBIDDEN.getStatusCode())));
+ Response response = buildGetPropertiesRequest().get();
+ assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode());
+ }
+
+ @Test
+ public void getPolicyProperties_unHandledError_returnGeneralError() {
+ when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenThrow(new RuntimeException());
+ Response response = buildGetPropertiesRequest().get();
+ assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
+
+ @Test
+ @Ignore
+ public void getPolicyProperties_wrongComponentType() {
+ Response response = buildGetPropertiesRequest("unknownType").get();
+ assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
+ verifyZeroInteractions(businessLogic);
+ }
+
+ @Test
+ public void getPolicyProperties() {
+ List<PropertyDataDefinition> properties = getPropertiesList();
+ when(businessLogic.getPolicyProperties(ComponentTypeEnum.SERVICE, SERVICE_ID, POLICY_ID, USER_ID)).thenReturn(Either.left(properties));
+ List<PropertyDataDefinition> policyProps = buildGetPropertiesRequest().get(new GenericType<List<PropertyDataDefinition>>() {});
+ assertThat(policyProps)
+ .usingElementComparatorOnFields("uniqueId")
+ .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
+ }
+
+ @Test
+ public void updatePolicyPropertiesSuccess() {
+ List<PropertyDataDefinition> properties = getPropertiesList();
+ when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.left(properties));
+ List<PropertyDataDefinition> policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke(new GenericType<List<PropertyDataDefinition>>() {});
+ assertThat(policyProps)
+ .usingElementComparatorOnFields("uniqueId")
+ .containsExactlyInAnyOrder(properties.get(0), properties.get(1));
+ }
+
+ @Test
+ public void updatePolicyTargetsSuccess() {
+ List<PolicyTargetDTO> targets = getTargetDTOList();
+ when(businessLogic.updatePolicyTargets(eq(ComponentTypeEnum.RESOURCE), eq(COMPONENT_ID), eq(POLICY_ID), anyMap(), eq(USER_ID))).thenReturn(Either.left(new PolicyDefinition()));
+ Response policyTargets = buildUpdateTargetsRequest(ComponentTypeEnum.RESOURCE_PARAM_NAME, targets).invoke();
+ assertThat(policyTargets.getStatus()).isEqualTo(200);
+ }
+
+ @Test
+ public void updatePolicyPropertiesFailure() {
+ List<PropertyDataDefinition> properties = getPropertiesList();
+ ResponseFormat notFoundResponse = new ResponseFormat(HttpStatus.NOT_FOUND_404.getStatusCode());
+ when(businessLogic.updatePolicyProperties(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID), eq(POLICY_ID), any(PropertyDataDefinition[].class), eq(USER_ID), eq(true))).thenReturn(Either.right(notFoundResponse));
+ Response policyProps = buildUpdatePropertiesRequest(ComponentTypeEnum.SERVICE_PARAM_NAME, properties).invoke();
+ assertEquals(HttpStatus.NOT_FOUND_404.getStatusCode(), policyProps.getStatus());
+ }
+
+ private List<PropertyDataDefinition> getPropertiesList() {
+ PropertyDefinition prop1 = new PropertyDataDefinitionBuilder()
+ .setUniqueId("prop1")
+ .build();
+
+ PropertyDefinition prop2 = new PropertyDataDefinitionBuilder()
+ .setUniqueId("prop2")
+ .build();
+ return Arrays.asList(prop1, prop2);
+ }
+
+ private List<PolicyTargetDTO> getTargetDTOList() {
+ PolicyTargetDTO target1 = new PolicyTargetDTO();
+ target1.setUniqueIds(Collections.singletonList("uniqueId"));
+ target1.setType("GROUPS");
+
+ PolicyTargetDTO target2 = new PolicyTargetDTO();
+ target2.setUniqueIds(Collections.singletonList("uniqueId"));
+ target2.setType("component_Instances");
+
+ return Arrays.asList(target1, target2);
+ }
+
+ private Invocation.Builder buildGetPropertiesRequest(String componentType) {
+ return target(PROPS_URL)
+ .resolveTemplate("componentType", componentType)
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
+
+ }
+
+ private Invocation buildUpdatePropertiesRequest(String componentType, List<PropertyDataDefinition> properties) {
+ return target(PROPS_URL)
+ .resolveTemplate("componentType", componentType)
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID)
+ .buildPut(Entity.entity(properties, MediaType.APPLICATION_JSON));
+ }
+
+ private Invocation buildUpdateTargetsRequest(String componentType, List<PolicyTargetDTO> targets) {
+ return target(UPDATE_TARGETS_URL)
+ .resolveTemplate("componentType", componentType)
+ .resolveTemplate("componentId", COMPONENT_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID)
+ .buildPut(Entity.entity(targets, MediaType.APPLICATION_JSON));
+ }
+
+ private Invocation.Builder buildGetPropertiesRequest() {
+ return target(PROPS_URL)
+ .resolveTemplate("componentType", "services")
+ .resolveTemplate("serviceId", SERVICE_ID)
+ .resolveTemplate("policyId", POLICY_ID)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
+ }
+
+ @Override
+ protected ResourceConfig configure() {
+ return super.configure()
+ .register(new PolicyServlet(businessLogic, servletUtils, null, componentsUtils));
+ }
+
+ private static void createMocks() {
+ businessLogic = Mockito.mock(PolicyBusinessLogic.class);
+ componentsUtils = Mockito.mock(ComponentsUtils.class);
+ servletUtils = Mockito.mock(ServletUtils.class);
+ responseFormat = Mockito.mock(ResponseFormat.class);
+ }
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java
new file mode 100644
index 0000000000..23f32d169b
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpointTest.java
@@ -0,0 +1,101 @@
+package org.openecomp.sdc.be.servlets;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import fj.data.Either;
+import org.apache.http.HttpStatus;
+import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
+import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.junit.Test;
+import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
+import org.openecomp.sdc.be.components.utils.PolicyTypeBuilder;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.exception.ResponseFormat;
+
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.List;
+
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class PolicyTypesEndpointTest extends JerseySpringBaseTest {
+
+ public static final String USER_ID = "userId";
+ public static final String COMPONENT_TYPE = "VF";
+ private PolicyTypeBusinessLogic policyTypeBusinessLogic;
+ private ComponentsUtils componentUtils;
+
+ @Override
+ protected ResourceConfig configure() {
+ policyTypeBusinessLogic = mock(PolicyTypeBusinessLogic.class);
+ componentUtils = mock(ComponentsUtils.class);
+ final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ return super.configure()
+ .register(new PolicyTypesEndpoint(policyTypeBusinessLogic))
+ .register(jacksonJsonProvider);
+ }
+
+ @Test
+ public void getPolicyTypes() {
+ List<PolicyTypeDefinition> policyTypes = buildPolicyTypesList();
+ when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(Either.left(policyTypes));
+ when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK));
+ List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCall().get(new GenericType<List<PolicyTypeDefinition>>(){});
+ verifyPolicyTypesList(policyTypes, fetchedPolicyTypes);
+ }
+
+ @Test
+ public void getPolicyTypes_whenNoInternalComponent_passNullAsComponentType() {
+ List<PolicyTypeDefinition> policyTypes = buildPolicyTypesList();
+ when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, null)).thenReturn(Either.left(policyTypes));
+ when(componentUtils.getResponseFormat(ActionStatus.OK)).thenReturn(new ResponseFormat(HttpStatus.SC_OK));
+ List<PolicyTypeDefinition> fetchedPolicyTypes = buildGetPolicyTypesCallNoInternalComponent().get(new GenericType<List<PolicyTypeDefinition>>(){});
+ verifyPolicyTypesList(policyTypes, fetchedPolicyTypes);
+ }
+
+ @Test
+ public void getPolicyTypes_error() {
+ when(policyTypeBusinessLogic.getAllPolicyTypes(USER_ID, COMPONENT_TYPE)).thenReturn(Either.right(new ResponseFormat(HttpStatus.SC_INTERNAL_SERVER_ERROR)));
+ Response response = buildGetPolicyTypesCall().get();
+ assertThat(response.getStatus()).isEqualTo(500);
+ }
+
+ private void verifyPolicyTypesList(List<PolicyTypeDefinition> policyTypes, List<PolicyTypeDefinition> fetchedPolicyTypes) {
+ assertThat(fetchedPolicyTypes)
+ .usingElementComparatorOnFields("version", "type", "uniqueId")
+ .isEqualTo(policyTypes);
+ assertThat(fetchedPolicyTypes).extracting("derivedFrom")//derivedFrom is not on the PolicyTypeMixin and should not return in response
+ .containsOnly((String)null);
+ }
+
+ private Invocation.Builder buildGetPolicyTypesCall() {
+ return target("/v1/catalog/policyTypes")
+ .queryParam("internalComponentType", COMPONENT_TYPE)
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
+ }
+
+ private Invocation.Builder buildGetPolicyTypesCallNoInternalComponent() {
+ return target("/v1/catalog/policyTypes")
+ .request(MediaType.APPLICATION_JSON)
+ .header(Constants.USER_ID_HEADER, USER_ID);
+ }
+
+ private List<PolicyTypeDefinition> buildPolicyTypesList() {
+ PolicyTypeDefinition type1 = new PolicyTypeBuilder().setDerivedFrom("root").setType("type1").setUniqueId("id1").setVersion("1.0").build();
+ PolicyTypeDefinition type2 = new PolicyTypeBuilder().setDerivedFrom("type1").setType("type2").setUniqueId("id2").setVersion("1.0").build();
+ PolicyTypeDefinition type3 = new PolicyTypeBuilder().setDerivedFrom("root").setType("type3").setUniqueId("id3").setVersion("1.0").build();
+ return asList(type1, type2, type3);
+ }
+
+
+
+}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java
index 7e0c6b7647..e8aeb5fc70 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceServletTest.java
@@ -20,19 +20,9 @@
package org.openecomp.sdc.be.servlets;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
@@ -46,6 +36,7 @@ import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.openecomp.sdc.be.components.impl.ResourceImportManager;
+import org.openecomp.sdc.be.config.SpringConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.ServletUtils;
@@ -59,209 +50,217 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.Arrays;
-import fj.data.Either;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class ResourceServletTest extends JerseyTest {
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
- final static HttpSession session = Mockito.mock(HttpSession.class);
- final static ServletContext servletContext = Mockito.mock(ServletContext.class);
- final static WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- final static WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
- public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- @BeforeClass
- public static void setup() {
- ExternalConfiguration.setAppName("catalog-be");
- when(request.getSession()).thenReturn(session);
- when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
- when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
- when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
- when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
- String userId = "jh0003";
- User user = new User();
- user.setUserId(userId);
- user.setRole(Role.ADMIN.name());
- Either<User, ActionStatus> eitherUser = Either.left(user);
- when(userAdmin.getUser(userId, false)).thenReturn(eitherUser);
- when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId);
-
- ImmutablePair<Resource, ActionStatus> pair = new ImmutablePair<Resource, ActionStatus>(new Resource(), ActionStatus.OK);
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> ret = Either.left(pair);
- when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(ret);
-
- }
-
- @Before
- public void beforeTest() {
- Mockito.reset(componentUtils);
-
- Mockito.doAnswer(new Answer<ResponseFormat>() {
- public ResponseFormat answer(InvocationOnMock invocation) {
- Object[] args = invocation.getArguments();
- ActionStatus action = (ActionStatus) args[0];
- ResponseFormat resp = (action == ActionStatus.OK) ? new ResponseFormat(HttpStatus.CREATED.value()) : new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR.value());
- return resp;
- }
- }).when(componentUtils).getResponseFormat(Mockito.any(ActionStatus.class));
-
- }
-
- @Test
- public void testHappyScenarioTest() {
- UploadResourceInfo validJson = buildValidJson();
- setMD5OnRequest(true, validJson);
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
- Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
- Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK);
- assertTrue(response.getStatus() == HttpStatus.CREATED.value());
-
- }
-
- @Test
- public void testNonValidMd5Fail() {
- UploadResourceInfo validJson = buildValidJson();
-
- setMD5OnRequest(false, validJson);
-
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
- Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
- Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM);
- assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value());
-
- }
-
- @Test
- public void testNonValidPayloadNameFail() {
- UploadResourceInfo mdJson = buildValidJson();
- mdJson.setPayloadName("myCompute.xml");
-
- runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
-
- }
-
- @Test
- public void testNullPayloadFail() {
- UploadResourceInfo mdJson = buildValidJson();
- mdJson.setPayloadData(null);
- runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD);
-
- }
-
- @Test
- public void testNonYmlPayloadFail() {
- UploadResourceInfo mdJson = buildValidJson();
- String payload = "{ json : { isNot : yaml } ";
- encodeAndSetPayload(mdJson, payload);
- runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE);
-
- }
-
- @Test
- public void testNonToscaPayloadFail() {
- UploadResourceInfo mdJson = buildValidJson();
-
- String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
- encodeAndSetPayload(mdJson, payload);
- runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE);
-
- }
-
- @Test
- public void testServiceToscaPayloadFail() {
- UploadResourceInfo mdJson = buildValidJson();
-
- 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" + " topology_template: thisIsService\r\n"
- + " description: update update";
-
- encodeAndSetPayload(mdJson, payload);
- runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE);
-
- }
-
- @Test
- public void testMultipleResourcesInPayloadFail() {
- UploadResourceInfo mdJson = buildValidJson();
-
- String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n"
- + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
-
- encodeAndSetPayload(mdJson, payload);
- runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE);
-
- }
-
- @Test
- public void testNonValidNameSpaceInPayloadFail() {
- UploadResourceInfo mdJson = buildValidJson();
-
- String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
-
- encodeAndSetPayload(mdJson, payload);
- runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE);
-
- }
-
- private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) {
- byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes());
- mdJson.setPayloadData(new String(encodedBase64Payload));
- }
-
- private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) {
- setMD5OnRequest(true, mdJson);
- Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class);
- Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
- Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload);
- assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value());
- }
-
- private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) {
- String md5 = (isValid) ? GeneralUtility.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam=";
- when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5);
+ public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ public static final ResourceImportManager resourceImportManager = Mockito.mock(ResourceImportManager.class);
+ final static HttpSession session = Mockito.mock(HttpSession.class);
+ final static ServletContext servletContext = Mockito.mock(ServletContext.class);
+ final static WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ final static WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
+ public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ @BeforeClass
+ public static void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+ when(request.getSession()).thenReturn(session);
+ when(session.getServletContext()).thenReturn(servletContext);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(ResourceImportManager.class)).thenReturn(resourceImportManager);
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
+ when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
+ String userId = "jh0003";
+ User user = new User();
+ user.setUserId(userId);
+ user.setRole(Role.ADMIN.name());
+ Either<User, ActionStatus> eitherUser = Either.left(user);
+ when(userAdmin.getUser(userId, false)).thenReturn(eitherUser);
+ when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId);
+
+ ImmutablePair<Resource, ActionStatus> pair = new ImmutablePair<Resource, ActionStatus>(new Resource(), ActionStatus.OK);
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> ret = Either.left(pair);
+ when(resourceImportManager.importUserDefinedResource(Mockito.anyString(), Mockito.any(UploadResourceInfo.class), Mockito.any(User.class), Mockito.anyBoolean())).thenReturn(ret);
+
+ }
+
+ @Before
+ public void beforeTest() {
+ Mockito.reset(componentUtils);
+
+ Mockito.doAnswer(new Answer<ResponseFormat>() {
+ public ResponseFormat answer(InvocationOnMock invocation) {
+ Object[] args = invocation.getArguments();
+ ActionStatus action = (ActionStatus) args[0];
+ ResponseFormat resp = (action == ActionStatus.OK) ? new ResponseFormat(HttpStatus.CREATED.value()) : new ResponseFormat(HttpStatus.INTERNAL_SERVER_ERROR.value());
+ return resp;
+ }
+ }).when(componentUtils).getResponseFormat(Mockito.any(ActionStatus.class));
+
+ }
+
+ @Test
+ public void testHappyScenarioTest() {
+ UploadResourceInfo validJson = buildValidJson();
+ setMD5OnRequest(true, validJson);
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
+ Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
+ Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.OK);
+ assertTrue(response.getStatus() == HttpStatus.CREATED.value());
+
+ }
+
+ @Test
+ public void testNonValidMd5Fail() {
+ UploadResourceInfo validJson = buildValidJson();
+
+ setMD5OnRequest(false, validJson);
+
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(validJson)), Response.class);
+ Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
+ Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(ActionStatus.INVALID_RESOURCE_CHECKSUM);
+ assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value());
+
+ }
+
+ @Test
+ public void testNonValidPayloadNameFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+ mdJson.setPayloadName("myCompute.xml");
+
+ runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
+
+ }
+
+ @Test
+ public void testNullPayloadFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+ mdJson.setPayloadData(null);
+ runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_PAYLOAD);
+
+ }
+
+ @Test
+ public void testNonYmlPayloadFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+ String payload = "{ json : { isNot : yaml } ";
+ encodeAndSetPayload(mdJson, payload);
+ runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_YAML_FILE);
+
+ }
+
+ @Test
+ public void testNonToscaPayloadFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+
+ String payload = "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
+ encodeAndSetPayload(mdJson, payload);
+ runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_TOSCA_TEMPLATE);
+
+ }
+
+ @Test
+ public void testServiceToscaPayloadFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+
+ 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" + " topology_template: thisIsService\r\n"
+ + " description: update update";
+
+ encodeAndSetPayload(mdJson, payload);
+ runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE);
+
+ }
+
+ @Test
+ public void testMultipleResourcesInPayloadFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+
+ String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test2:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " org.openecomp.resource.importResource4test:\r\n"
+ + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
+
+ encodeAndSetPayload(mdJson, payload);
+ runAndVerifyActionStatusError(mdJson, ActionStatus.NOT_SINGLE_RESOURCE);
+
+ }
+
+ @Test
+ public void testNonValidNameSpaceInPayloadFail() {
+ UploadResourceInfo mdJson = buildValidJson();
+
+ String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resourceX.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: update update";
+
+ encodeAndSetPayload(mdJson, payload);
+ runAndVerifyActionStatusError(mdJson, ActionStatus.INVALID_RESOURCE_NAMESPACE);
+
+ }
+
+ private void encodeAndSetPayload(UploadResourceInfo mdJson, String payload) {
+ byte[] encodedBase64Payload = Base64.encodeBase64(payload.getBytes());
+ mdJson.setPayloadData(new String(encodedBase64Payload));
+ }
+
+ private void runAndVerifyActionStatusError(UploadResourceInfo mdJson, ActionStatus invalidResourcePayload) {
+ setMD5OnRequest(true, mdJson);
+ Response response = target().path("/v1/catalog/resources").request(MediaType.APPLICATION_JSON).post(Entity.json(gson.toJson(mdJson)), Response.class);
+ Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(Mockito.any(ActionStatus.class));
+ Mockito.verify(componentUtils, Mockito.times(1)).getResponseFormat(invalidResourcePayload);
+ assertTrue(response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value());
+ }
- }
+ private void setMD5OnRequest(boolean isValid, UploadResourceInfo json) {
+ String md5 = (isValid) ? GeneralUtility.calculateMD5Base64EncodedByString(gson.toJson(json)) : "stam=";
+ when(request.getHeader(Constants.MD5_HEADER)).thenReturn(md5);
+
+ }
- private UploadResourceInfo buildValidJson() {
- UploadResourceInfo ret = new UploadResourceInfo();
- ret.setName("ciMyCompute");
- ret.setPayloadName("ciMyCompute.yml");
- ret.addSubCategory("Application Layer 4+", "Application Servers");
- ret.setDescription("ResourceDescription");
- ret.setVendorName("VendorName");
- ret.setVendorRelease("VendorRelease");
- ret.setContactId("AT1234");
- ret.setIcon("router");
- ret.setTags(Arrays.asList(new String[] { "ciMyCompute" }));
- ret.setPayloadData(
- "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl");
- return ret;
- }
-
- @Override
- protected Application configure() {
-
- ResourceConfig resourceConfig = new ResourceConfig(ResourcesServlet.class);
- forceSet(TestProperties.CONTAINER_PORT, "0");
- resourceConfig.register(new AbstractBinder() {
-
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- });
-
- return resourceConfig;
- }
+ private UploadResourceInfo buildValidJson() {
+ UploadResourceInfo ret = new UploadResourceInfo();
+ ret.setName("ciMyCompute");
+ ret.setPayloadName("ciMyCompute.yml");
+ ret.addSubCategory("Application Layer 4+", "Application Servers");
+ ret.setDescription("ResourceDescription");
+ ret.setVendorName("VendorName");
+ ret.setVendorRelease("VendorRelease");
+ ret.setContactId("AT1234");
+ ret.setIcon("router");
+ ret.setTags(Arrays.asList(new String[] { "ciMyCompute" }));
+ ret.setPayloadData(
+ "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxl");
+ return ret;
+ }
+
+ @Override
+ protected Application configure() {
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ forceSet(TestProperties.CONTAINER_PORT, "0");
+ return new ResourceConfig(ResourcesServlet.class)
+ .register(new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ })
+ .property("contextConfig", context);
+
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java
index ff69241263..23daab9bf9 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/ResourceUploadServletTest.java
@@ -20,25 +20,7 @@
package org.openecomp.sdc.be.servlets;
-import static org.mockito.ArgumentMatchers.anyObject;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.when;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
@@ -53,6 +35,7 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.SpringConfig;
import org.openecomp.sdc.be.dao.api.ResourceUploadStatus;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.UploadResourceInfo;
@@ -64,125 +47,105 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
public class ResourceUploadServletTest extends JerseyTest {
- private static Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class.getName());
- final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- final HttpSession session = Mockito.mock(HttpSession.class);
- final ServletContext servletContext = Mockito.mock(ServletContext.class);
- final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class);
- final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class);
-
- Gson gson = new Gson();
-
- public void zipDirectory() {
-
- }
-
- @Before
- public void setup() {
- ExternalConfiguration.setAppName("catalog-be");
-
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader);
- when(iResourceUploader.saveArtifact((ESArtifactData) anyObject(), eq(true))).thenReturn(ResourceUploadStatus.OK);
- when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager);
- }
-
- @Override
- protected Application configure() {
-
- ResourceConfig resourceConfig = new ResourceConfig(ResourceUploadServlet.class);
-
- resourceConfig.register(MultiPartFeature.class);
- resourceConfig.register(new AbstractBinder() {
-
- @Override
- protected void configure() {
- // The below code was cut-pasted to here from setup() because
- // due to it now has
- // to be executed during servlet initialization
- bind(request).to(HttpServletRequest.class);
- when(request.getSession()).thenReturn(session);
- when(session.getServletContext()).thenReturn(servletContext);
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) {
-
- when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader);
-
- }
-
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- }
- });
-
- return resourceConfig;
- }
-
- @Override
- protected void configureClient(ClientConfig config) {
- config.register(MultiPartFeature.class);
- }
-
- public class DelegatingServletInputStream extends ServletInputStream {
-
- private final InputStream sourceStream;
-
- /**
- * Create a DelegatingServletInputStream for the given source stream.
- *
- * @param sourceStream
- * the source stream (never <code>null</code>)
- */
- public DelegatingServletInputStream(InputStream sourceStream) {
- // Assert.notNull(sourceStream,
- // "Source InputStream must not be null");
- this.sourceStream = sourceStream;
- }
-
- /**
- * Return the underlying source stream (never <code>null</code>).
- */
- public final InputStream getSourceStream() {
- return this.sourceStream;
- }
-
- public int read() throws IOException {
- return this.sourceStream.read();
- }
-
- public void close() throws IOException {
- super.close();
- this.sourceStream.close();
- }
-
- }
-
- @Test
- public void testMultipart() {
- FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip"));
-
- List<String> tags = new ArrayList<String>();
- tags.add("tag1");
- tags.add("tag2");
- UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null);
-
- FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE);
- MultiPart multipartEntity = new FormDataMultiPart();
- multipartEntity.bodyPart(filePart);
- multipartEntity.bodyPart(metadataPart);
-
- Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
- log.debug("{}", response);
- }
+ private static final Logger log = LoggerFactory.getLogger(ResourceUploadServletTest.class);
+ final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ final HttpSession session = Mockito.mock(HttpSession.class);
+ final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ final IResourceUploader iResourceUploader = Mockito.mock(IResourceUploader.class);
+ final AuditingManager iAuditingManager = Mockito.mock(AuditingManager.class);
+
+ Gson gson = new Gson();
+
+ public void zipDirectory() {
+
+ }
+
+ @Before
+ public void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ // when(servletContext.getAttribute(Constants.AUDITING_MANAGER)).thenReturn(iAuditingManager);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(IResourceUploader.class)).thenReturn(iResourceUploader);
+ when(iResourceUploader.saveArtifact((ESArtifactData) anyObject(), eq(true))).thenReturn(ResourceUploadStatus.OK);
+ when(webApplicationContext.getBean(AuditingManager.class)).thenReturn(iAuditingManager);
+ }
+
+ @Override
+ protected Application configure() {
+
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ return new ResourceConfig(ResourceUploadServlet.class)
+ .register(MultiPartFeature.class)
+ .register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ // The below code was cut-pasted to here from setup() because
+ // due to it now has
+ // to be executed during servlet initialization
+ bind(request).to(HttpServletRequest.class);
+ when(request.getSession()).thenReturn(session);
+ when(session.getServletContext()).thenReturn(servletContext);
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) {
+
+ when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader);
+
+ }
+
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+ }
+ })
+ .property("contextConfig", context);
+
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ config.register(MultiPartFeature.class);
+ }
+
+ @Test
+ public void testMultipart() {
+ FileDataBodyPart filePart = new FileDataBodyPart("resourceZip", new File("src/test/resources/config/normative-types-root.zip"));
+ List<String> tags = new ArrayList<String>();
+ tags.add("tag1");
+ tags.add("tag2");
+ UploadResourceInfo resourceInfo = new UploadResourceInfo("payload", "normative-types-root.yml", "my_description", "category/mycategory", tags, null);
+
+ FormDataBodyPart metadataPart = new FormDataBodyPart("resourceMetadata", gson.toJson(resourceInfo), MediaType.APPLICATION_JSON_TYPE);
+ MultiPart multipartEntity = new FormDataMultiPart();
+ multipartEntity.bodyPart(filePart);
+ multipartEntity.bodyPart(metadataPart);
+
+ Response response = target().path("/v1/catalog/upload/" + ResourceUploadServlet.NORMATIVE_TYPE_RESOURCE).request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
+ log.debug("{}", response);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java
index 37a493de37..690f7427a8 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/TypesUploadServletTest.java
@@ -20,22 +20,8 @@
package org.openecomp.sdc.be.servlets;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.glassfish.grizzly.http.util.HttpStatus;
+import fj.data.Either;
+import org.eclipse.jetty.http.HttpStatus;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
@@ -49,6 +35,7 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.SpringConfig;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.ServletUtils;
@@ -62,182 +49,109 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.WebApplicationContext;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class TypesUploadServletTest extends JerseyTest {
- public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
- public static final HttpSession session = Mockito.mock(HttpSession.class);
- public static final ServletContext servletContext = Mockito.mock(ServletContext.class);
- public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
- public static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
- public static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class);
- public static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
- public static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
- public static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
- public static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
-
- @BeforeClass
- public static void setup() {
- ExternalConfiguration.setAppName("catalog-be");
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
- .thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
- when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager);
- when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
- when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
- when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
- String userId = "jh0003";
- User user = new User();
- user.setUserId(userId);
- user.setRole(Role.ADMIN.name());
- Either<User, ActionStatus> eitherUser = Either.left(user);
- when(userAdmin.getUser(userId, false)).thenReturn(eitherUser);
- when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId);
- when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201.getStatusCode());
- when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat);
-
- }
-
- @Test
- public void creatingCapabilityTypeSuccessTest() {
- List<CapabilityTypeDefinition> emptyList = new ArrayList<CapabilityTypeDefinition>();
- Either<List<CapabilityTypeDefinition>, ResponseFormat> either = Either.left(emptyList);
- when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either);
- FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip",
- new File("src/test/resources/types/capabilityTypes.zip"));
- MultiPart multipartEntity = new FormDataMultiPart();
- multipartEntity.bodyPart(filePart);
-
- Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON)
- .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
-
- assertTrue(response.getStatus() == HttpStatus.CREATED_201.getStatusCode());
-
- }
-
- @Override
- protected void configureClient(ClientConfig config) {
- config.register(MultiPartFeature.class);
- }
-
- @Override
- protected Application configure() {
- ResourceConfig resourceConfig = new ResourceConfig(TypesUploadServlet.class);
-
- resourceConfig.register(MultiPartFeature.class);
- resourceConfig.register(new AbstractBinder() {
-
- @Override
- protected void configure() {
- // The below code was cut-pasted to here from setup() because
- // due to it now has
- // to be executed during servlet initialization
- bind(request).to(HttpServletRequest.class);
- when(request.getSession()).thenReturn(session);
- when(session.getServletContext()).thenReturn(servletContext);
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(
- ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) {
-
- when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader);
-
- }
-
- when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
- .thenReturn(configurationManager);
- }
- });
-
- return resourceConfig;
- }
-
- private TypesUploadServlet createTestSubject() {
- return new TypesUploadServlet();
- }
-
-
- @Test
- public void testUploadCapabilityType() throws Exception {
- TypesUploadServlet testSubject;
- File file = null;
- HttpServletRequest request = null;
- String creator = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUploadInterfaceLifecycleType() throws Exception {
- TypesUploadServlet testSubject;
- File file = null;
- HttpServletRequest request = null;
- String creator = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUploadCategories() throws Exception {
- TypesUploadServlet testSubject;
- File file = null;
- HttpServletRequest request = null;
- String creator = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUploadDataTypes() throws Exception {
- TypesUploadServlet testSubject;
- File file = null;
- HttpServletRequest request = null;
- String creator = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUploadGroupTypes() throws Exception {
- TypesUploadServlet testSubject;
- File file = null;
- HttpServletRequest request = null;
- String creator = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUploadPolicyTypes() throws Exception {
- TypesUploadServlet testSubject;
- File file = null;
- HttpServletRequest request = null;
- String creator = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
-
+ public static final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+ private static final HttpSession session = Mockito.mock(HttpSession.class);
+ public static final ServletContext servletContext = Mockito.mock(ServletContext.class);
+ public static final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
+ private static final WebApplicationContext webApplicationContext = Mockito.mock(WebApplicationContext.class);
+ private static final CapabilityTypeImportManager importManager = Mockito.mock(CapabilityTypeImportManager.class);
+ private static final ServletUtils servletUtils = Mockito.mock(ServletUtils.class);
+ private static final UserBusinessLogic userAdmin = Mockito.mock(UserBusinessLogic.class);
+ private static final ComponentsUtils componentUtils = Mockito.mock(ComponentsUtils.class);
+ private static final ResponseFormat responseFormat = Mockito.mock(ResponseFormat.class);
+
+ @BeforeClass
+ public static void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+ when(webApplicationContext.getBean(CapabilityTypeImportManager.class)).thenReturn(importManager);
+ when(webApplicationContext.getBean(ServletUtils.class)).thenReturn(servletUtils);
+ when(servletUtils.getComponentsUtils()).thenReturn(componentUtils);
+ when(servletUtils.getUserAdmin()).thenReturn(userAdmin);
+ String userId = "jh0003";
+ User user = new User();
+ user.setUserId(userId);
+ user.setRole(Role.ADMIN.name());
+ Either<User, ActionStatus> eitherUser = Either.left(user);
+ when(userAdmin.getUser(userId, false)).thenReturn(eitherUser);
+ when(request.getHeader(Constants.USER_ID_HEADER)).thenReturn(userId);
+ when(responseFormat.getStatus()).thenReturn(HttpStatus.CREATED_201);
+ when(componentUtils.getResponseFormat(ActionStatus.CREATED)).thenReturn(responseFormat);
+
+ }
+
+ @Test
+ public void creatingCapabilityTypeSuccessTest() {
+ List<CapabilityTypeDefinition> emptyList = new ArrayList<CapabilityTypeDefinition>();
+ Either<List<CapabilityTypeDefinition>, ResponseFormat> either = Either.left(emptyList);
+ when(importManager.createCapabilityTypes(Mockito.anyString())).thenReturn(either);
+ FileDataBodyPart filePart = new FileDataBodyPart("capabilityTypeZip", new File("src/test/resources/types/capabilityTypes.zip"));
+ MultiPart multipartEntity = new FormDataMultiPart();
+ multipartEntity.bodyPart(filePart);
+
+ Response response = target().path("/v1/catalog/uploadType/capability").request(MediaType.APPLICATION_JSON).post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA), Response.class);
+
+ assertTrue(response.getStatus() == HttpStatus.CREATED_201);
+
+ }
+
+ @Override
+ protected void configureClient(ClientConfig config) {
+ config.register(MultiPartFeature.class);
+ }
+
+ @Override
+ protected ResourceConfig configure() {
+
+ ResourceConfig resourceConfig = new ResourceConfig()
+ .register(new TypesUploadServlet(importManager, null, null, null, null, null));
+
+ resourceConfig.register(MultiPartFeature.class);
+ resourceConfig.register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ // The below code was cut-pasted to here from setup() because
+ // due to it now has
+ // to be executed during servlet initialization
+ bind(request).to(HttpServletRequest.class);
+ when(request.getSession()).thenReturn(session);
+ when(session.getServletContext()).thenReturn(servletContext);
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ for (String mandatoryHeader : configurationManager.getConfiguration().getIdentificationHeaderFields()) {
+
+ when(request.getHeader(mandatoryHeader)).thenReturn(mandatoryHeader);
+
+ }
+
+ when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
+ }
+ });
+ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
+ resourceConfig.property("contextConfig", context);
+
+ return resourceConfig;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java
index afa0907f25..696214f49d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/UserAdminServletTest.java
@@ -20,24 +20,13 @@
package org.openecomp.sdc.be.servlets;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.Response;
-
+import com.google.gson.Gson;
+import fj.data.Either;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Before;
import org.junit.BeforeClass;
-import org.junit.Test;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
@@ -52,238 +41,105 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.core.Application;
-import fj.data.Either;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
public class UserAdminServletTest extends JerseyTest {
- final static HttpServletRequest request = mock(HttpServletRequest.class);
- final static HttpSession session = mock(HttpSession.class);
- final static ServletContext servletContext = mock(ServletContext.class);
- final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class);
- final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class);
- final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class);
- final static AuditingManager auditingManager = mock(AuditingManager.class);
- final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
- final static ResponseFormat okResponseFormat = mock(ResponseFormat.class);
-
- final static String ADMIN_ATT_UID = "jh0003";
- Gson gson = new Gson();
-
- @BeforeClass
- public static void setup() {
- ExternalConfiguration.setAppName("catalog-be");
-
- when(session.getServletContext()).thenReturn(servletContext);
- when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR))
- .thenReturn(webAppContextWrapper);
- when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
-
- when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager);
- when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils);
- when(componentsUtils.getAuditingManager()).thenReturn(auditingManager);
- when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat);
- when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value());
-
- }
-
- @Before
- public void beforeTest() {
- reset(userAdminManager);
- doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false);
-
- reset(request);
- when(request.getSession()).thenReturn(session);
- when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID);
- }
-
- /*
- * @Test public void deactivateUserSuccessfullyTest(){ String
- * userToDeleteUserId = "admin1"; User adminUser = new User();
- * adminUser.setUserId(ADMIN_ATT_UID); Either<User, ActionStatus>
- * eitherActiveUser = buildEitherUser(userToDeleteUserId, true); User
- * userToDelete = eitherActiveUser.left().value();
- * doReturn(eitherActiveUser).when(userAdminManager).getUser(
- * userToDeleteUserId);
- *
- * Either<User, ActionStatus> eitherInactiveUser =
- * buildEitherUser(userToDeleteUserId, false);
- * doReturn(eitherInactiveUser).when(userAdminManager).deActivateUser(
- * adminUser, userToDelete.getUserId());
- *
- *
- * Response response =
- * target().path("/v1/user/"+userToDeleteUserId).request().delete();
- * assertTrue(response.getStatus() == HttpStatus.OK.value());
- * verify(userAdminManager, times(1)).deActivateUser(adminUser,
- * userToDelete.getUserId()); }
- *
- *
- * @Test public void forceDeleteUserSuccessfullyTest(){ String
- * userToDeleteUserId = "admin1";
- * when(request.getHeader(User.FORCE_DELETE_HEADER_FLAG)).thenReturn(User.
- * FORCE_DELETE_HEADER_FLAG);
- *
- * User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID);
- *
- * Either<User, ActionStatus> eitherActiveUser =
- * buildEitherUser(userToDeleteUserId, true); User userToDelete =
- * eitherActiveUser.left().value();
- * doReturn(eitherActiveUser).when(userAdminManager).getUser(
- * userToDeleteUserId);
- *
- * Either<User, ActionStatus> eitherUser =
- * buildEitherUser(userToDeleteUserId, true);
- * doReturn(eitherUser).when(userAdminManager).deleteUser(userToDelete.
- * getUserId());
- *
- *
- * Response response =
- * target().path("/v1/user/"+userToDeleteUserId).request().delete();
- * assertTrue(response.getStatus() == HttpStatus.OK.value());
- * verify(userAdminManager, times(0)).deActivateUser(adminUser,
- * userToDelete.getUserId()); verify(userAdminManager,
- * times(1)).deleteUser(userToDelete.getUserId()); }
- */
-
- @Override
- protected Application configure() {
-
- ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class);
-
- resourceConfig.register(new AbstractBinder() {
-
- @Override
- protected void configure() {
- bind(request).to(HttpServletRequest.class);
- }
- });
-
- return resourceConfig;
- }
-
- private static Either<User, ActionStatus> buildEitherUser(String userId, boolean isActive) {
- User user = new User();
- user.setUserId(userId);
- user.setRole(UserRoleEnum.ADMIN.getName());
- if (!isActive) {
- user.setStatus(UserStatusEnum.INACTIVE);
- }
- return Either.left(user);
- }
-
- private UserAdminServlet createTestSubject() {
- return new UserAdminServlet();
- }
-
-
- @Test
- public void testGet() throws Exception {
- UserAdminServlet testSubject;
- String userId = "";
- HttpServletRequest request = null;
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetRole() throws Exception {
- UserAdminServlet testSubject;
- String userId = "";
- HttpServletRequest request = null;
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testUpdateUserRole() throws Exception {
- UserAdminServlet testSubject;
- String userIdUpdateUser = "";
- HttpServletRequest request = null;
- String data = "";
- String modifierUserId = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testCreateUser() throws Exception {
- UserAdminServlet testSubject;
- HttpServletRequest request = null;
- String newUserData = "";
- String modifierAttId = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testAuthorize() throws Exception {
- UserAdminServlet testSubject;
- HttpServletRequest request = null;
- String userId = "";
- String firstName = "";
- String lastName = "";
- String email = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetAdminsUser() throws Exception {
- UserAdminServlet testSubject;
- String userId = "";
- HttpServletRequest request = null;
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
-
-
- @Test
- public void testGetUsersList() throws Exception {
- UserAdminServlet testSubject;
- HttpServletRequest request = null;
- String userId = "";
- String roles = "";
- Response result;
-
- // test 1
- testSubject = createTestSubject();
- roles = null;
-
- // test 2
- testSubject = createTestSubject();
- roles = "";
- }
-
-
- @Test
- public void testDeActivateUser() throws Exception {
- UserAdminServlet testSubject;
- String userId = "";
- HttpServletRequest request = null;
- String userIdHeader = "";
- Response result;
-
- // default test
- testSubject = createTestSubject();
- }
+ final static HttpServletRequest request = mock(HttpServletRequest.class);
+ final static HttpSession session = mock(HttpSession.class);
+ final static ServletContext servletContext = mock(ServletContext.class);
+ final static WebAppContextWrapper webAppContextWrapper = mock(WebAppContextWrapper.class);
+ final static WebApplicationContext webApplicationContext = mock(WebApplicationContext.class);
+ final static UserBusinessLogic userAdminManager = spy(UserBusinessLogic.class);
+ final static AuditingManager auditingManager = mock(AuditingManager.class);
+ final static ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
+ final static ResponseFormat okResponseFormat = mock(ResponseFormat.class);
+
+ final static String ADMIN_ATT_UID = "jh0003";
+ Gson gson = new Gson();
+
+ @BeforeClass
+ public static void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+
+ when(session.getServletContext()).thenReturn(servletContext);
+ when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
+ when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webApplicationContext);
+
+ when(webApplicationContext.getBean(UserBusinessLogic.class)).thenReturn(userAdminManager);
+ when(webApplicationContext.getBean(ComponentsUtils.class)).thenReturn(componentsUtils);
+ when(componentsUtils.getAuditingManager()).thenReturn(auditingManager);
+ when(componentsUtils.getResponseFormat(ActionStatus.OK)).thenReturn(okResponseFormat);
+ when(okResponseFormat.getStatus()).thenReturn(HttpStatus.OK.value());
+
+ }
+
+ @Before
+ public void beforeTest() {
+ reset(userAdminManager);
+ doReturn(buildEitherUser(ADMIN_ATT_UID, true)).when(userAdminManager).getUser(ADMIN_ATT_UID, false);
+
+ reset(request);
+ when(request.getSession()).thenReturn(session);
+ when(request.getHeader("USER_ID")).thenReturn(ADMIN_ATT_UID);
+ }
+
+ /*
+ * @Test public void deactivateUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID); Either<User, ActionStatus> eitherActiveUser = buildEitherUser(userToDeleteUserId, true);
+ * User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId);
+ *
+ * Either<User, ActionStatus> eitherInactiveUser = buildEitherUser(userToDeleteUserId, false); doReturn(eitherInactiveUser).when(userAdminManager).deActivateUser( adminUser, userToDelete.getUserId());
+ *
+ *
+ * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(1)).deActivateUser(adminUser, userToDelete.getUserId()); }
+ *
+ *
+ * @Test public void forceDeleteUserSuccessfullyTest(){ String userToDeleteUserId = "admin1"; when(request.getHeader(User.FORCE_DELETE_HEADER_FLAG)).thenReturn(User. FORCE_DELETE_HEADER_FLAG);
+ *
+ * User adminUser = new User(); adminUser.setUserId(ADMIN_ATT_UID);
+ *
+ * Either<User, ActionStatus> eitherActiveUser = buildEitherUser(userToDeleteUserId, true); User userToDelete = eitherActiveUser.left().value(); doReturn(eitherActiveUser).when(userAdminManager).getUser( userToDeleteUserId);
+ *
+ * Either<User, ActionStatus> eitherUser = buildEitherUser(userToDeleteUserId, true); doReturn(eitherUser).when(userAdminManager).deleteUser(userToDelete. getUserId());
+ *
+ *
+ * Response response = target().path("/v1/user/"+userToDeleteUserId).request().delete(); assertTrue(response.getStatus() == HttpStatus.OK.value()); verify(userAdminManager, times(0)).deActivateUser(adminUser, userToDelete.getUserId());
+ * verify(userAdminManager, times(1)).deleteUser(userToDelete.getUserId()); }
+ */
+
+ @Override
+ protected Application configure() {
+
+ ResourceConfig resourceConfig = new ResourceConfig(UserAdminServlet.class);
+
+ resourceConfig.register(new AbstractBinder() {
+
+ @Override
+ protected void configure() {
+ bind(request).to(HttpServletRequest.class);
+ }
+ });
+
+ return resourceConfig;
+ }
+
+ private static Either<User, ActionStatus> buildEitherUser(String userId, boolean isActive) {
+ User user = new User();
+ user.setUserId(userId);
+ user.setRole(UserRoleEnum.ADMIN.getName());
+ if (!isActive) {
+ user.setStatus(UserStatusEnum.INACTIVE);
+ }
+ return Either.left(user);
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java
new file mode 100644
index 0000000000..3c42257446
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertorTest.java
@@ -0,0 +1,124 @@
+package org.openecomp.sdc.be.tosca;
+//
+
+import org.junit.Test;
+import org.mockito.Mockito;
+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.Resource;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.doReturn;
+
+public class CapabiltyRequirementConvertorTest {
+
+ CapabiltyRequirementConvertor capabiltyRequirementConvertor = Mockito.spy(new CapabiltyRequirementConvertor());
+ ComponentInstance instanceProxy = Mockito.spy( new ComponentInstance() );
+ ComponentInstance vfInstance = Mockito.spy( new ComponentInstance() );
+ Component vfComponent = Mockito.spy( new Resource() );
+ ComponentInstance vfcInstance = Mockito.spy( new ComponentInstance() );
+ Component vfcComponent = Mockito.spy( new Resource() );
+
+ @Test
+ public void getReducedPathByOwner() throws Exception {
+ List<String> pathList = new ArrayList<>();
+ String uniqueId = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_2";
+
+ String exerpt = "41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1";
+ String duplicate = "a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi";
+ pathList.add(exerpt);
+ pathList.add(duplicate);
+ pathList.add(duplicate);
+ pathList.add(uniqueId);
+
+ pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0");
+ pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0");
+
+ List<String> reducedMap = new CapabiltyRequirementConvertor().getReducedPathByOwner( pathList , uniqueId );
+
+ assertThat( reducedMap ).isNotNull().doesNotContain(exerpt).containsOnlyOnce(duplicate).hasSize(4);
+ }
+
+ //generate stub capability
+ private Map<String, List<CapabilityDefinition>> newCapabilities(String capabilityName){
+ Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
+ List<CapabilityDefinition> list = new ArrayList<>();
+ CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
+ capabilityDefinition.setName( capabilityName );
+ capabilityDefinition.setType("att.Node");
+ List<String> pathList = new ArrayList<>();
+
+ capabilityDefinition.setOwnerId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693");
+ pathList.add("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1");
+ //pathList.add("a77df84e-83eb-4edc-9823-d1f9f6549693.c79e9a4a-b172-4323-a2e2-1c48d6603241.lb_swu_direct_4_rvmi");
+ pathList.add("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0");
+ pathList.add("86ae128e-3d0a-41f7-a957-db1df9fe598c.9cc8f8ac-6869-4dd6-a6e1-74ecb9570dc4.vepdgtp4837svc_proxy0");
+
+ capabilityDefinition.setPath(pathList);
+ list.add(capabilityDefinition);
+ capabilities.put(capabilityDefinition.getType() , list );
+
+ return capabilities;
+ }
+
+
+ @Test
+ public void testBuildName(){
+ doReturn("1").when(instanceProxy).getActualComponentUid();
+ doReturn("2").when(vfInstance).getActualComponentUid();
+ doReturn("3").when(vfcInstance).getActualComponentUid();
+ //region proxy
+ Component proxyOrigin = new Resource();
+
+ proxyOrigin.setName( "vepdgtp4837svc_proxy0" );
+ proxyOrigin.setComponentType(ComponentTypeEnum.RESOURCE);
+ proxyOrigin.setComponentInstances( asList( vfInstance ) );
+
+ //endregion
+ //region vf+vfc
+ vfInstance.setName("vepdgtp4837vf0");
+ vfInstance.setNormalizedName("vepdgtp4837vf0");
+ vfInstance.setUniqueId("5f172af9-1588-443e-8897-1432b19aad8c.2cb7514a-1e50-4280-8457-baacb97b50bf.vepdgtp4837vf0");
+ vfComponent.setName("vepdgtp4837vf0"); //origin
+ vfComponent.setComponentInstances(Arrays.asList(vfcInstance));
+ vfcInstance.setUniqueId("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1");
+ vfcInstance.setName("lb_1");
+ vfcInstance.setNormalizedName("lb_1");
+ vfcInstance.setName("41d3a665-1313-4b5e-9bf0-e901ecf4b806.a77df84e-83eb-4edc-9823-d1f9f6549693.lb_1");
+ vfcComponent.setName("lb_1");
+ //endregion
+ Map<String, List<CapabilityDefinition>> capabilities = newCapabilities("port");
+ vfcComponent.setCapabilities(capabilities);
+ Map<Component, ComponentInstance> map = Collections.unmodifiableMap(new HashMap<Component, ComponentInstance>() {
+ {
+ put( proxyOrigin, null );
+ put( vfComponent, vfInstance );
+ put( vfcComponent, vfcInstance );
+ } } ) ;
+ Map<String, Component> cache = Collections.unmodifiableMap(new HashMap<String, Component>() {{
+ put( "1",proxyOrigin);
+ put( "2" ,vfComponent);
+ put( "3" ,vfcComponent);
+ }});
+ instanceProxy.setCapabilities(capabilities);
+ proxyOrigin.setCapabilities( capabilities );
+ List<CapabilityDefinition> flatList = capabilities.values().stream().flatMap(List::stream).collect(Collectors.toList());
+ flatList.stream().forEach( (CapabilityDefinition capabilityDefinition) -> {
+ String name = capabiltyRequirementConvertor.buildCapabilityNameForComponentInstance(cache, instanceProxy, capabilityDefinition);
+ System.out.println("built name -> " + name);
+ assertThat(name).isEqualTo( "vepdgtp4837vf0.lb_1."+capabilityDefinition.getName() );
+ });
+ }
+}
+
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java
index 7348156923..8883786d7e 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/CsarUtilsTest.java
@@ -20,116 +20,71 @@
package org.openecomp.sdc.be.tosca;
-import static org.junit.Assert.assertTrue;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.junit.Assert;
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
-import fj.data.Either;
-
-public class CsarUtilsTest {
- @Before
- public void setup() {
- ExternalConfiguration.setAppName("catalog-be");
-
- // Init Configuration
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(),
- appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- }
-
- @Test
- public void testValidateNonMetaArtifactHappyScenario() {
- String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml";
- byte[] payloadData = "some payload data".getBytes();
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
- Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath,
- payloadData, collectedWarningMessages);
- assertTrue(eitherNonMetaArtifact.isLeft());
- assertTrue(collectedWarningMessages.isEmpty());
-
- artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml";
- eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
- assertTrue(eitherNonMetaArtifact.isLeft());
- assertTrue(collectedWarningMessages.isEmpty());
- }
-
- @Test
- public void testValidateNonMetaArtifactScenarioWithWarnnings() {
- String artifactPath = "Artifacts/Deployment/Buga/myYang.xml";
- byte[] payloadData = "some payload data".getBytes();
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
- Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath,
- payloadData, collectedWarningMessages);
- assertTrue(eitherNonMetaArtifact.isLeft());
-
- artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml";
- eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
- assertTrue(eitherNonMetaArtifact.isLeft());
-
- assertTrue(collectedWarningMessages.size() == 1);
- assertTrue(collectedWarningMessages.values().iterator().next().size() == 2);
- }
-
- @Test
- public void testValidateNonMetaArtifactUnhappyScenario() {
- String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml";
- byte[] payloadData = "some payload data".getBytes();
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
- Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath,
- payloadData, collectedWarningMessages);
- assertTrue(eitherNonMetaArtifact.isRight());
- assertTrue(!collectedWarningMessages.isEmpty());
- }
-
- private CsarUtils createTestSubject() {
- return new CsarUtils();
- }
-
-
- @Test
- public void testExtractVfcsArtifactsFromCsar() throws Exception {
- Map<String, byte[]> csar = null;
- Map<String, List<ArtifactDefinition>> result;
-
- // test 1
- csar = null;
- result = CsarUtils.extractVfcsArtifactsFromCsar(csar);
- Assert.assertEquals(new HashMap<String, List<ArtifactDefinition>>() , result);
- }
-
-
- @Test
- public void testHandleWarningMessages() throws Exception {
- Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
-
- // default test
- CsarUtils.handleWarningMessages(collectedWarningMessages);
- }
-
-
- @Test
- public void testValidateNonMetaArtifact() throws Exception {
- String artifactPath = "";
- byte[] payloadData = new byte[] { ' ' };
- Map<String, Set<List<String>>> collectedWarningMessages = null;
- Either<NonMetaArtifactInfo, Boolean> result;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
- // default test
- result = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
- }
+import static org.junit.Assert.assertTrue;
+public class CsarUtilsTest {
+ @Before
+ public void setup() {
+ ExternalConfiguration.setAppName("catalog-be");
+
+ // init Configuration
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ }
+
+ @Test
+ public void testValidateNonMetaArtifactHappyScenario(){
+ String artifactPath = "Artifacts/Deployment/YANG_XML/myYang.xml";
+ byte[] payloadData = "some payload data".getBytes();
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+ Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
+ assertTrue(eitherNonMetaArtifact.isLeft() );
+ assertTrue(collectedWarningMessages.isEmpty() );
+
+ artifactPath = "Artifacts/Informational/OTHER/someArtifact.xml";
+ eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
+ assertTrue(eitherNonMetaArtifact.isLeft() );
+ assertTrue(collectedWarningMessages.isEmpty() );
+ }
+
+ @Test
+ public void testValidateNonMetaArtifactScenarioWithWarnnings(){
+ String artifactPath = "Artifacts/Deployment/Buga/myYang.xml";
+ byte[] payloadData = "some payload data".getBytes();
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+ Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
+ assertTrue(eitherNonMetaArtifact.isLeft() );
+
+ artifactPath = "Artifacts/Informational/Buga2/someArtifact.xml";
+ eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
+ assertTrue(eitherNonMetaArtifact.isLeft() );
+
+ assertTrue(collectedWarningMessages.size() == 1 );
+ assertTrue(collectedWarningMessages.values().iterator().next().size() == 2);
+ }
+
+ @Test
+ public void testValidateNonMetaArtifactUnhappyScenario(){
+ String artifactPath = "Artifacts/Buga/YANG_XML/myYang.xml";
+ byte[] payloadData = "some payload data".getBytes();
+ Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+ Either<NonMetaArtifactInfo, Boolean> eitherNonMetaArtifact = CsarUtils.validateNonMetaArtifact(artifactPath, payloadData, collectedWarningMessages);
+ assertTrue(eitherNonMetaArtifact.isRight() );
+ assertTrue( !collectedWarningMessages.isEmpty() );
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java
index 139de137d9..dbdec12193 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java
@@ -1,18 +1,6 @@
package org.openecomp.sdc.be.tosca;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-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 fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.openecomp.sdc.be.components.utils.PropertyDataDefinitionBuilder;
@@ -23,7 +11,18 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
import org.openecomp.sdc.be.tosca.model.ToscaProperty;
-import fj.data.Either;
+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 static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
public class PropertyConvertorTest {
private PropertyDefinition property;
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java
index acfeaf1abc..839095f1ca 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/SchemaFiles.java
@@ -20,8 +20,8 @@
package org.openecomp.sdc.be.tosca;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.IOException;
@@ -31,46 +31,46 @@ import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
-import org.junit.Test;
-import org.yaml.snakeyaml.Yaml;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
public class SchemaFiles {
-
- @Test
- public void testValidateYamlNormativeFiles(){
- String importToscaPath = "src/main/resources/import/tosca";
- assertTrue(checkValidYamlInFileTree(importToscaPath));
- }
-
- @Test
- public void testRainyYamlNormativeFiles(){
- String importToscaPathTest = "src/test/resources/yamlValidation";
- assertFalse(checkValidYamlInFileTree(importToscaPathTest));
- }
-
- private boolean checkValidYamlInFileTree(String fileTree) {
-
- try {
- List<Path> fileTreeYamlList = Files.walk(Paths.get(fileTree))
- .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".yml"))
- .collect(Collectors.toList());
-
- for (Path yamlFile : fileTreeYamlList) {
- try {
- FileInputStream inputStream = new FileInputStream(yamlFile.toAbsolutePath().toString());
- Yaml yaml = new Yaml();
- Object content = yaml.load(inputStream);
- } catch (Exception e) {
- System.out.println("Not valid yaml in file creation : " + yamlFile.toAbsolutePath().toString());
- return false;
- }
- }
- } catch (IOException e) {
- System.out.println("Error in reading file from folder : " + fileTree);
- return false;
- }
- return true;
- }
-
-
+
+ @Test
+ public void testValidateYamlNormativeFiles(){
+ String importToscaPath = "src/main/resources/import/tosca";
+ assertTrue(checkValidYamlInFileTree(importToscaPath));
+ }
+
+ @Test
+ public void testRainyYamlNormativeFiles(){
+ String importToscaPathTest = "src/test/resources/yamlValidation";
+ assertFalse(checkValidYamlInFileTree(importToscaPathTest));
+ }
+
+ private boolean checkValidYamlInFileTree(String fileTree) {
+
+ try {
+ List<Path> fileTreeYamlList = Files.walk(Paths.get(fileTree))
+ .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".yml"))
+ .collect(Collectors.toList());
+
+ for (Path yamlFile : fileTreeYamlList) {
+ try {
+ FileInputStream inputStream = new FileInputStream(yamlFile.toAbsolutePath().toString());
+ Yaml yaml = new Yaml();
+ Object content = yaml.load(inputStream);
+ } catch (Exception e) {
+ System.out.println("Not valid yaml in file creation : " + yamlFile.toAbsolutePath().toString());
+ return false;
+ }
+ }
+ } catch (IOException e) {
+ System.out.println("Error in reading file from folder : " + fileTree);
+ return false;
+ }
+ return true;
+ }
+
+
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java
index 4c22cf3599..efc89a9f9d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportUtilsTest.java
@@ -1,124 +1,120 @@
package org.openecomp.sdc.be.tosca;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import org.junit.Test;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.VFComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
public class ToscaExportUtilsTest {
- private static Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class.getName());
- @javax.annotation.Resource
- private VFComponentInstanceBusinessLogic componentInstanceBusinessLogic;
- @javax.annotation.Resource
- private ServiceComponentInstanceBusinessLogic serviceInstanceBusinessLogic;
- @Autowired
- private ToscaExportHandler exportUtils;
- @Autowired
- private ComponentInstanceOperation componentInstanceOperation;
-
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- @Test
- public void testExportService() {
- /* Resource resource1 = ResourceTestUtils.prepareResource(0);
- resource1.setResourceType(ResourceTypeEnum.VF);
- Either<Resource, ResponseFormat> createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null);
- assertTrue(createResource1.isLeft());
- Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value());
-
- Resource resource2 = ResourceTestUtils.prepareResource(1);
- resource2.setResourceType(ResourceTypeEnum.VF);
- Either<Resource, ResponseFormat> createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null);
- assertTrue(createResource2.isLeft());
- Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value());
-
- Service service = ResourceTestUtils.prepareService(0);
- Either<Service, ResponseFormat> createService = serviceBusinessLogic.createService(service, getAdminUser());
- assertTrue(createService.isLeft());
-
- // add VFC instance to VF
- ComponentInstance vfcResourceInstance1 = new ComponentInstance();
- vfcResourceInstance1.setDescription("VFC instance 1");
- vfcResourceInstance1.setName(certifiedVFC1.getName());
- vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId());
-
- Either<ComponentInstance, ResponseFormat> createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(),
- vfcResourceInstance1);
- assertTrue(createResourceVfcInstance1.isLeft());
-
- ComponentInstance vfcResourceInstance2 = new ComponentInstance();
- vfcResourceInstance2.setDescription("VFC instance 2");
- vfcResourceInstance2.setName(certifiedVFC2.getName());
- vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId());
- Either<ComponentInstance, ResponseFormat> createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(),
- vfcResourceInstance2);
- assertTrue(createResourceVfcInstance2.isLeft());
-
- Either<Service, ResponseFormat> serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser);
- assertTrue(serviceFetch.isLeft());
-
- List<ComponentInstance> componentInstances = serviceFetch.left().value().getComponentInstances();
- String ciname1 = null;
- String ciname2 = null;
-
- for (ComponentInstance ci : componentInstances) {
- if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) {
- ciname1 = ci.getName();
- }
- if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) {
- ciname2 = ci.getName();
- }
- }
-
- Either<ToscaRepresentation, ToscaError> result = exportUtils.exportComponent(serviceFetch.left().value());
- assertTrue(result.isLeft());
-
- String mainYaml = result.left().value().getMainYaml();
- assertNotNull(mainYaml);
-
- YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
- assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes()));
- log.debug(mainYaml);
-
- Yaml yaml = new Yaml();
-
- InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes());
- Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
- Map<String, Object> imports = (Map<String, Object>) load.get("imports");
- assertNotNull(imports);
- assertEquals("Validate imports size in yml", 2, imports.size());
-
- Map<String, Object> metadata = (Map<String, Object>) load.get("metadata");
- assertNotNull(metadata);
- validateMetadata(metadata, serviceFetch.left().value(), false);
-
- Map<String, Object> vf1 = (Map<String, Object>) imports.get(certifiedVFC1.getName());
- String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY);
- ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName);
-
- Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
- Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
- Map<String, Object> inst1 = (Map<String, Object>) node_templates.get(ciname1);
- Map<String, Object> inst2 = (Map<String, Object>) node_templates.get(ciname2);
-
- Map<String, Object> inst1MD = (Map<String, Object>) inst1.get("metadata");
- Map<String, Object> inst2MD = (Map<String, Object>) inst2.get("metadata");
-
- validateMetadata(inst1MD, certifiedVFC1, true);
-
- Map<String, Object> vf2 = (Map<String, Object>) imports.get(certifiedVFC2.getName());
- fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY);
- artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName);
-
- validateMetadata(inst2MD, certifiedVFC2, true);*/
- }
+ private static final Logger log = LoggerFactory.getLogger(ToscaExportUtilsTest.class);
+ @javax.annotation.Resource
+ private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+ @Autowired
+ private ToscaExportHandler exportUtils;
+ @Autowired
+ private ComponentInstanceOperation componentInstanceOperation;
+
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ @Test
+ public void testExportService() {
+ /* Resource resource1 = ResourceTestUtils.prepareResource(0);
+ resource1.setResourceType(ResourceTypeEnum.VF);
+ Either<Resource, ResponseFormat> createResource1 = resourceBusinessLogic.createResource(resource1, getAdminUser(), null, null);
+ assertTrue(createResource1.isLeft());
+ Resource certifiedVFC1 = changeResourceStateToCertify(createResource1.left().value());
+
+ Resource resource2 = ResourceTestUtils.prepareResource(1);
+ resource2.setResourceType(ResourceTypeEnum.VF);
+ Either<Resource, ResponseFormat> createResource2 = resourceBusinessLogic.createResource(resource2, getAdminUser(), null, null);
+ assertTrue(createResource2.isLeft());
+ Resource certifiedVFC2 = changeResourceStateToCertify(createResource2.left().value());
+
+ Service service = ResourceTestUtils.prepareService(0);
+ Either<Service, ResponseFormat> createService = serviceBusinessLogic.createService(service, getAdminUser());
+ assertTrue(createService.isLeft());
+
+ // add VFC instance to VF
+ ComponentInstance vfcResourceInstance1 = new ComponentInstance();
+ vfcResourceInstance1.setDescription("VFC instance 1");
+ vfcResourceInstance1.setName(certifiedVFC1.getName());
+ vfcResourceInstance1.setComponentUid(certifiedVFC1.getUniqueId());
+
+ Either<ComponentInstance, ResponseFormat> createResourceVfcInstance1 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(),
+ vfcResourceInstance1);
+ assertTrue(createResourceVfcInstance1.isLeft());
+
+ ComponentInstance vfcResourceInstance2 = new ComponentInstance();
+ vfcResourceInstance2.setDescription("VFC instance 2");
+ vfcResourceInstance2.setName(certifiedVFC2.getName());
+ vfcResourceInstance2.setComponentUid(certifiedVFC2.getUniqueId());
+ Either<ComponentInstance, ResponseFormat> createResourceVfcInstance2 = serviceInstanceBusinessLogic.createComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, createService.left().value().getUniqueId(), adminUser.getAttuid(),
+ vfcResourceInstance2);
+ assertTrue(createResourceVfcInstance2.isLeft());
+
+ Either<Service, ResponseFormat> serviceFetch = serviceBusinessLogic.getService(createService.left().value().getUniqueId(), adminUser);
+ assertTrue(serviceFetch.isLeft());
+
+ List<ComponentInstance> componentInstances = serviceFetch.left().value().getComponentInstances();
+ String ciname1 = null;
+ String ciname2 = null;
+
+ for (ComponentInstance ci : componentInstances) {
+ if (ci.getComponentUid().equals(certifiedVFC1.getUniqueId())) {
+ ciname1 = ci.getName();
+ }
+ if (ci.getComponentUid().equals(certifiedVFC2.getUniqueId())) {
+ ciname2 = ci.getName();
+ }
+ }
+
+ Either<ToscaRepresentation, ToscaError> result = exportUtils.exportComponent(serviceFetch.left().value());
+ assertTrue(result.isLeft());
+
+ String mainYaml = result.left().value().getMainYaml();
+ assertNotNull(mainYaml);
+
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+ assertTrue(yamlToObjectConverter.isValidYaml(mainYaml.getBytes()));
+ log.debug(mainYaml);
+
+ Yaml yaml = new Yaml();
+
+ InputStream inputStream = new ByteArrayInputStream(mainYaml.getBytes());
+ Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
+ Map<String, Object> imports = (Map<String, Object>) load.get("imports");
+ assertNotNull(imports);
+ assertEquals("Validate imports size in yml", 2, imports.size());
+
+ Map<String, Object> metadata = (Map<String, Object>) load.get("metadata");
+ assertNotNull(metadata);
+ validateMetadata(metadata, serviceFetch.left().value(), false);
+
+ Map<String, Object> vf1 = (Map<String, Object>) imports.get(certifiedVFC1.getName());
+ String fileName = (String) vf1.get(ToscaExportHandler.IMPORTS_FILE_KEY);
+ ArtifactDefinition artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ assertEquals("Validate 1 file name", artifactDefinition.getArtifactName(), fileName);
+
+ Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
+ Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
+ Map<String, Object> inst1 = (Map<String, Object>) node_templates.get(ciname1);
+ Map<String, Object> inst2 = (Map<String, Object>) node_templates.get(ciname2);
+
+ Map<String, Object> inst1MD = (Map<String, Object>) inst1.get("metadata");
+ Map<String, Object> inst2MD = (Map<String, Object>) inst2.get("metadata");
+
+ validateMetadata(inst1MD, certifiedVFC1, true);
+
+ Map<String, Object> vf2 = (Map<String, Object>) imports.get(certifiedVFC2.getName());
+ fileName = (String) vf2.get(ToscaExportHandler.IMPORTS_FILE_KEY);
+ artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+ assertEquals("Validate 2 file name", artifactDefinition.getArtifactName(), fileName);
+
+ validateMetadata(inst2MD, certifiedVFC2, true);*/
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java
index 2984d25e20..8d45e42357 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/common/transaction/mngr/SdncTransactionTest.java
@@ -20,12 +20,7 @@
package org.openecomp.sdc.common.transaction.mngr;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -51,385 +46,389 @@ import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionCode
import org.openecomp.sdc.common.transaction.api.TransactionUtils.TransactionStatusEnum;
import org.slf4j.Logger;
-import fj.data.Either;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class SdncTransactionTest {
- private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class);
- private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
- private static Logger log = Mockito.spy(Logger.class);
- private static int transactionId = 0;
- private static ConfigurationManager configurationManager;
-
- public enum TestAction {
- TitanAction, Rollback, GeneralAction
- }
-
- public enum TestResponse {
- TitanResponseSuccess, GeneralSuccess
- }
-
- @BeforeClass
- public static void beforeClass() {
- TransactionSdncImpl.setLog(log);
- CommitManager.setLog(log);
- RollbackHandler.setLog(log);
- String appConfigDir = "src/test/resources/config/catalog-be";
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- configurationManager = new ConfigurationManager(configurationSource);
- }
-
- @Before
- public void beforeTest() {
- reset(log);
- reset(esCatalogDao);
- reset(titanGenericDao);
- }
-
- @Test
- public void testInvokeTitanAction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
-
- doBasicTitanAction(transactionId, tx, false, true);
- assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
- }
-
- @Test
- public void testInvokeESAction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
-
- doESAddArtifactAction(transactionId, tx, true, true);
- assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
- }
-
- @Test
- public void testfinishTransaction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doFinishTransaction(transactionId, tx, true);
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
- }
-
- @Test
- public void testFinishOnClosedTransaction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doFinishTransaction(transactionId, tx, true);
-
- TransactionCodeEnum finishTransaction = tx.finishTransaction();
- assertTrue(finishTransaction == TransactionCodeEnum.TRANSACTION_CLOSED);
- // verify(log).error(LogMessages.COMMIT_ON_CLOSED_TRANSACTION,
- // transactionId, TransactionStatusEnum.CLOSED.name(),
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, TransactionStatusEnum.CLOSED.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
-
- }
-
- @Test
- public void testCallingLastActionTwice() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doBasicTitanAction(transactionId, tx, true, true);
- Either<TestResponse, TransactionCodeEnum> doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false);
- assertTrue(doBasicTitanAction.isRight());
- assertTrue(tx.getStatus() != TransactionStatusEnum.OPEN);
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- // verify(log).error( LogMessages.DOUBLE_FINISH_FLAG_ACTION,
- // transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER,
- // ActionTypeEnum.ADD_ARTIFACT.name());
- }
-
- @Test
- public void testActionOnClosedTransaction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doFinishTransaction(transactionId, tx, true);
-
- Either<DBActionCodeEnum, TransactionCodeEnum> eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData());
- assertTrue(eitherESResult.isRight());
- assertTrue(eitherESResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED);
-
- Either<Object, TransactionCodeEnum> eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess));
- assertTrue(eitherTitanResult.isRight());
- assertTrue(eitherTitanResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED);
-
- Either<Object, TransactionCodeEnum> eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess),
- createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess));
- assertTrue(eitherGeneralDBAction.isRight());
- assertTrue(eitherGeneralDBAction.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED);
-
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
- // verify(log, times(3)).error(LogMessages.ACTION_ON_CLOSED_TRANSACTION,
- // transactionId, TransactionUtils.DUMMY_USER,
- // ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(3)).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- }
-
- @Test
- public void testBasicHappyScenario() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
-
- doBasicTitanAction(transactionId, tx, false, true);
- assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
-
- doESAddArtifactAction(transactionId, tx, true, true);
- assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
-
- doFinishTransaction(transactionId, tx, true);
-
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
-
- }
-
- @Test
- public void testRollbackSucceededOnAction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doESAddArtifactAction(transactionId, tx, false, true);
-
- when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
- String crushMessage = "DB Crush Simulation";
- Either<TestResponse, TransactionCodeEnum> eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage));
-
- assertTrue(eitherTransactionResult.isRight());
- assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS);
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
- // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION,
- // DBTypeEnum.TITAN.name(), transactionId, crushMessage,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- }
-
- @Test
- public void testRollbackFailedOnAction() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
-
- doESAddArtifactAction(transactionId, tx, false, true);
-
- when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED);
- String crushMessage = "DB Crush Simulation";
- Either<TestResponse, TransactionCodeEnum> eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage));
-
- assertTrue(eitherTransactionResult.isRight());
- assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK);
- assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_FAILED);
- // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION,
- // DBTypeEnum.TITAN.name(), transactionId, crushMessage,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL,
- // transactionId, TransactionUtils.DUMMY_USER,
- // ActionTypeEnum.ADD_ARTIFACT.name());
- // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER,
- // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- }
-
- @Test
- public void testRollbackSucceededOnCommit() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doESAddArtifactAction(transactionId, tx, false, true);
- doBasicTitanAction(transactionId, tx, true, true);
-
- when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR);
- when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
- // finishTransaction
- TransactionCodeEnum transactionCode = tx.finishTransaction();
- assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_SUCCESS);
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- }
-
- @Test
- public void testRollbackFailedOnCommit() {
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- doESAddArtifactAction(transactionId, tx, false, true);
- doBasicTitanAction(transactionId, tx, true, true);
-
- when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR);
- when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
- String esError = "No Connection to Es";
- Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString());
- // finishTransaction
- TransactionCodeEnum transactionCode = tx.finishTransaction();
- assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_FAILED);
- assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK);
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- // verify(log).error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION,
- // transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), esError,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- // verify(log).error(TransactionUtils.TRANSACTION_MARKER,
- // LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId,
- // DBTypeEnum.ELASTIC_SEARCH.name(), esError,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL,
- // transactionId, TransactionUtils.DUMMY_USER,
- // ActionTypeEnum.ADD_ARTIFACT.name());
- // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER,
- // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- }
-
- @Test
- public void testInvokeGeneralAction() {
- when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
- int transactionId = getNextTransactionId();
- TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
- IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess);
- IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess);
- String crushMessage = "No DB Connection";
- IDBAction crushingAction = createCrushingAction(TestAction.GeneralAction, crushMessage);
-
- Either<TestResponse, TransactionCodeEnum> eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, generalAction, rollbackAction);
- assertTrue(eitherResult.isLeft());
- assertTrue(eitherResult.left().value() == TestResponse.GeneralSuccess);
- assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
- eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, crushingAction, rollbackAction);
-
- assertTrue(eitherResult.isRight());
- assertTrue(eitherResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS);
- assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
-
- // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION,
- // DBTypeEnum.MYSTERY.name(), transactionId, crushMessage,
- // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log, times(2)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log, times(2)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
-
- }
-
- private Either<TestResponse, TransactionCodeEnum> doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) {
- // Add Titan Action
- Either<TestResponse, TransactionCodeEnum> eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess));
- if (isVerifyAction) {
- // Check Titan Action
- assertTrue(eitherTitanResult.isLeft());
- assertTrue(eitherTitanResult.left().value() == TestResponse.TitanResponseSuccess);
- verify(log).debug(TestAction.TitanAction.name());
- verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verifyNoErrorsInLog();
- verifyNoInfoInLog();
- }
- return eitherTitanResult;
- }
-
- private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) {
- // Prerequisite finishTransaction
- when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK);
- // finishTransaction
- TransactionCodeEnum transactionCode = tx.finishTransaction();
- if (isVerifyAction) {
- // Check finishTransaction
- verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- assertTrue(transactionCode == TransactionCodeEnum.SUCCESS);
- }
- return transactionCode;
- }
-
- private void doESAddArtifactAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) {
- // Prerequisite ES Action
- Either<ESArtifactData, ResourceUploadStatus> eitherBeforeAddArtifact = Either.right(ResourceUploadStatus.NOT_EXIST);
- when(esCatalogDao.getArtifact(Mockito.anyString())).thenReturn(eitherBeforeAddArtifact);
-
- // Add ES Action
- Either<DBActionCodeEnum, TransactionCodeEnum> eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData());
-
- if (isVerifyAction) {
- // Check Titan Action
- assertTrue(eitherEsAction.isLeft());
- assertTrue(eitherEsAction.left().value() == DBActionCodeEnum.SUCCESS);
- verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
- verifyNoErrorsInLog();
- verifyNoInfoInLog();
- }
- }
-
- private ESArtifactData createDummyArtifactData() {
- String strData = "qweqwqweqw34e4wrwer";
- String myNodeType = "MyNewNodeType";
- ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes());
- return arData;
- }
-
- private void verifyNoErrorsInLog() {
- verify(log, Mockito.times(0)).error(Mockito.anyString(), Mockito.any(Object[].class));
- verify(log, Mockito.times(0)).error(Mockito.anyString());
- }
-
- private void verifyNoInfoInLog() {
- verify(log, Mockito.times(0)).info(Mockito.anyString(), Mockito.any(Object[].class));
- verify(log, Mockito.times(0)).info(Mockito.anyString());
- }
-
- private IDBAction createBasicAction(TestAction action, TestResponse resp) {
- final TestAction finalAction = action;
- final TestResponse finalResp = resp;
- return new IDBAction() {
- @Override
- public TestResponse doAction() {
- log.debug(finalAction.name());
- return finalResp;
- }
- };
- }
-
- private IDBAction createCrushingAction(TestAction action, final String crushMessage) {
- final TestAction finalAction = action;
- return new IDBAction() {
- @Override
- public TestResponse doAction() {
- log.debug(finalAction.name());
- throw new RuntimeException(crushMessage);
- }
- };
- }
-
- public int getNextTransactionId() {
- transactionId++;
- return transactionId;
- }
+ private static ESCatalogDAO esCatalogDao = Mockito.mock(ESCatalogDAO.class);
+ private static TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
+ private static final Logger log = Mockito.spy(Logger.class);
+ private static int transactionId = 0;
+ private static ConfigurationManager configurationManager;
+
+ public enum TestAction {
+ TitanAction, Rollback, GeneralAction
+ }
+
+ public enum TestResponse {
+ TitanResponseSuccess, GeneralSuccess
+ }
+
+ @BeforeClass
+ public static void beforeClass() {
+ TransactionSdncImpl.setLog(log);
+ CommitManager.setLog(log);
+ RollbackHandler.setLog(log);
+ String appConfigDir = "src/test/resources/config/catalog-be";
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ configurationManager = new ConfigurationManager(configurationSource);
+ }
+
+ @Before
+ public void beforeTest() {
+ reset(log);
+ reset(esCatalogDao);
+ reset(titanGenericDao);
+ }
+
+ @Test
+ public void testInvokeTitanAction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+
+ doBasicTitanAction(transactionId, tx, false, true);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
+ }
+
+ @Test
+ public void testInvokeESAction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+
+ doESAddArtifactAction(transactionId, tx, true, true);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
+ }
+
+ @Test
+ public void testfinishTransaction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doFinishTransaction(transactionId, tx, true);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+ }
+
+ @Test
+ public void testFinishOnClosedTransaction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doFinishTransaction(transactionId, tx, true);
+
+ TransactionCodeEnum finishTransaction = tx.finishTransaction();
+ assertTrue(finishTransaction == TransactionCodeEnum.TRANSACTION_CLOSED);
+ // verify(log).error(LogMessages.COMMIT_ON_CLOSED_TRANSACTION,
+ // transactionId, TransactionStatusEnum.CLOSED.name(),
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.COMMIT_ON_CLOSED_TRANSACTION, transactionId, TransactionStatusEnum.CLOSED.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+
+ }
+
+ @Test
+ public void testCallingLastActionTwice() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doBasicTitanAction(transactionId, tx, true, true);
+ Either<TestResponse, TransactionCodeEnum> doBasicTitanAction = doBasicTitanAction(transactionId, tx, true, false);
+ assertTrue(doBasicTitanAction.isRight());
+ assertTrue(tx.getStatus() != TransactionStatusEnum.OPEN);
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DOUBLE_FINISH_FLAG_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ // verify(log).error( LogMessages.DOUBLE_FINISH_FLAG_ACTION,
+ // transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER,
+ // ActionTypeEnum.ADD_ARTIFACT.name());
+ }
+
+ @Test
+ public void testActionOnClosedTransaction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doFinishTransaction(transactionId, tx, true);
+
+ Either<DBActionCodeEnum, TransactionCodeEnum> eitherESResult = tx.invokeESAction(false, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData());
+ assertTrue(eitherESResult.isRight());
+ assertTrue(eitherESResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED);
+
+ Either<Object, TransactionCodeEnum> eitherTitanResult = tx.invokeTitanAction(false, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess));
+ assertTrue(eitherTitanResult.isRight());
+ assertTrue(eitherTitanResult.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED);
+
+ Either<Object, TransactionCodeEnum> eitherGeneralDBAction = tx.invokeGeneralDBAction(true, DBTypeEnum.TITAN, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess),
+ createBasicAction(TestAction.Rollback, TestResponse.TitanResponseSuccess));
+ assertTrue(eitherGeneralDBAction.isRight());
+ assertTrue(eitherGeneralDBAction.right().value() == TransactionCodeEnum.TRANSACTION_CLOSED);
+
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+ // verify(log, times(3)).error(LogMessages.ACTION_ON_CLOSED_TRANSACTION,
+ // transactionId, TransactionUtils.DUMMY_USER,
+ // ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(3)).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ACTION_ON_CLOSED_TRANSACTION, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ }
+
+ @Test
+ public void testBasicHappyScenario() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+
+ doBasicTitanAction(transactionId, tx, false, true);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
+
+ doESAddArtifactAction(transactionId, tx, true, true);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
+
+ doFinishTransaction(transactionId, tx, true);
+
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+
+ }
+
+ @Test
+ public void testRollbackSucceededOnAction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doESAddArtifactAction(transactionId, tx, false, true);
+
+ when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
+ String crushMessage = "DB Crush Simulation";
+ Either<TestResponse, TransactionCodeEnum> eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage));
+
+ assertTrue(eitherTransactionResult.isRight());
+ assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+ // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION,
+ // DBTypeEnum.TITAN.name(), transactionId, crushMessage,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ }
+
+ @Test
+ public void testRollbackFailedOnAction() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+
+ doESAddArtifactAction(transactionId, tx, false, true);
+
+ when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.NOT_CONNECTED);
+ String crushMessage = "DB Crush Simulation";
+ Either<TestResponse, TransactionCodeEnum> eitherTransactionResult = tx.invokeTitanAction(false, createCrushingAction(TestAction.TitanAction, crushMessage));
+
+ assertTrue(eitherTransactionResult.isRight());
+ assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK);
+ assertTrue(eitherTransactionResult.right().value() == TransactionCodeEnum.ROLLBACK_FAILED);
+ // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION,
+ // DBTypeEnum.TITAN.name(), transactionId, crushMessage,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.TITAN.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL,
+ // transactionId, TransactionUtils.DUMMY_USER,
+ // ActionTypeEnum.ADD_ARTIFACT.name());
+ // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER,
+ // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ }
+
+ @Test
+ public void testRollbackSucceededOnCommit() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doESAddArtifactAction(transactionId, tx, false, true);
+ doBasicTitanAction(transactionId, tx, true, true);
+
+ when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR);
+ when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
+ // finishTransaction
+ TransactionCodeEnum transactionCode = tx.finishTransaction();
+ assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_SUCCESS);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ }
+
+ @Test
+ public void testRollbackFailedOnCommit() {
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ doESAddArtifactAction(transactionId, tx, false, true);
+ doBasicTitanAction(transactionId, tx, true, true);
+
+ when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.GENERAL_ERROR);
+ when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
+ String esError = "No Connection to Es";
+ Mockito.doThrow(new RuntimeException(esError)).when(esCatalogDao).deleteArtifact(Mockito.anyString());
+ // finishTransaction
+ TransactionCodeEnum transactionCode = tx.finishTransaction();
+ assertTrue(transactionCode == TransactionCodeEnum.ROLLBACK_FAILED);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.FAILED_ROLLBACK);
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.ELASTIC_SEARCH.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(1)).debug(LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(1)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_NON_PERSISTENT_ACTION, DBTypeEnum.TITAN.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ // verify(log).error(LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION,
+ // transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), esError,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ // verify(log).error(TransactionUtils.TRANSACTION_MARKER,
+ // LogMessages.ROLLBACK_FAILED_ON_DB_WITH_EXCEPTION, transactionId,
+ // DBTypeEnum.ELASTIC_SEARCH.name(), esError,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ // verify(log, times(1)).error(LogMessages.ROLLBACK_FAILED_GENERAL,
+ // transactionId, TransactionUtils.DUMMY_USER,
+ // ActionTypeEnum.ADD_ARTIFACT.name());
+ // verify(log, times(1)).error(TransactionUtils.TRANSACTION_MARKER,
+ // LogMessages.ROLLBACK_FAILED_GENERAL, transactionId,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ }
+
+ @Test
+ public void testInvokeGeneralAction() {
+ when(titanGenericDao.rollback()).thenReturn(TitanOperationStatus.OK);
+ int transactionId = getNextTransactionId();
+ TransactionSdncImpl tx = new TransactionSdncImpl(transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT, esCatalogDao, titanGenericDao);
+ IDBAction generalAction = createBasicAction(TestAction.GeneralAction, TestResponse.GeneralSuccess);
+ IDBAction rollbackAction = createBasicAction(TestAction.Rollback, TestResponse.GeneralSuccess);
+ String crushMessage = "No DB Connection";
+ IDBAction crushingAction = createCrushingAction(TestAction.GeneralAction, crushMessage);
+
+ Either<TestResponse, TransactionCodeEnum> eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, generalAction, rollbackAction);
+ assertTrue(eitherResult.isLeft());
+ assertTrue(eitherResult.left().value() == TestResponse.GeneralSuccess);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.OPEN);
+ eitherResult = tx.invokeGeneralDBAction(false, DBTypeEnum.MYSTERY, crushingAction, rollbackAction);
+
+ assertTrue(eitherResult.isRight());
+ assertTrue(eitherResult.right().value() == TransactionCodeEnum.ROLLBACK_SUCCESS);
+ assertTrue(tx.getStatus() == TransactionStatusEnum.CLOSED);
+
+ // verify(log).error(LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION,
+ // DBTypeEnum.MYSTERY.name(), transactionId, crushMessage,
+ // TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.DB_ACTION_FAILED_WITH_EXCEPTION, DBTypeEnum.MYSTERY.name(), transactionId, crushMessage, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log, times(2)).debug(LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log, times(2)).debug(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_PERSISTENT_ACTION, DBTypeEnum.MYSTERY.name(), transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ verify(log).info(LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).info(TransactionUtils.TRANSACTION_MARKER, LogMessages.ROLLBACK_SUCCEEDED_GENERAL, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+
+ }
+
+ private Either<TestResponse, TransactionCodeEnum> doBasicTitanAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) {
+ // Add Titan Action
+ Either<TestResponse, TransactionCodeEnum> eitherTitanResult = tx.invokeTitanAction(isLastAction, createBasicAction(TestAction.TitanAction, TestResponse.TitanResponseSuccess));
+ if (isVerifyAction) {
+ // Check Titan Action
+ assertTrue(eitherTitanResult.isLeft());
+ assertTrue(eitherTitanResult.left().value() == TestResponse.TitanResponseSuccess);
+ verify(log).debug(TestAction.TitanAction.name());
+ verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verifyNoErrorsInLog();
+ verifyNoInfoInLog();
+ }
+ return eitherTitanResult;
+ }
+
+ private TransactionCodeEnum doFinishTransaction(int transactionId, TransactionSdncImpl tx, boolean isVerifyAction) {
+ // Prerequisite finishTransaction
+ when(titanGenericDao.commit()).thenReturn(TitanOperationStatus.OK);
+ // finishTransaction
+ TransactionCodeEnum transactionCode = tx.finishTransaction();
+ if (isVerifyAction) {
+ // Check finishTransaction
+ verify(log).debug(LogMessages.COMMIT_ACTION_ALL_DB, transactionId, TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verify(log).debug(LogMessages.COMMIT_ACTION_SPECIFIC_DB, transactionId, DBTypeEnum.TITAN.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ assertTrue(transactionCode == TransactionCodeEnum.SUCCESS);
+ }
+ return transactionCode;
+ }
+
+ private void doESAddArtifactAction(int transactionId, TransactionSdncImpl tx, boolean isLastAction, boolean isVerifyAction) {
+ // Prerequisite ES Action
+ Either<ESArtifactData, ResourceUploadStatus> eitherBeforeAddArtifact = Either.right(ResourceUploadStatus.NOT_EXIST);
+ when(esCatalogDao.getArtifact(Mockito.anyString())).thenReturn(eitherBeforeAddArtifact);
+
+ // Add ES Action
+ Either<DBActionCodeEnum, TransactionCodeEnum> eitherEsAction = tx.invokeESAction(isLastAction, ESActionTypeEnum.ADD_ARTIFACT, createDummyArtifactData());
+
+ if (isVerifyAction) {
+ // Check Titan Action
+ assertTrue(eitherEsAction.isLeft());
+ assertTrue(eitherEsAction.left().value() == DBActionCodeEnum.SUCCESS);
+ verify(log).debug(LogMessages.INVOKE_ACTION, transactionId, DBTypeEnum.ELASTIC_SEARCH.name(), TransactionUtils.DUMMY_USER, ActionTypeEnum.ADD_ARTIFACT.name());
+ verifyNoErrorsInLog();
+ verifyNoInfoInLog();
+ }
+ }
+
+ private ESArtifactData createDummyArtifactData() {
+ String strData = "qweqwqweqw34e4wrwer";
+ String myNodeType = "MyNewNodeType";
+ ESArtifactData arData = new ESArtifactData("artifactNewMarina11", strData.getBytes());
+ return arData;
+ }
+
+ private void verifyNoErrorsInLog() {
+ verify(log, Mockito.times(0)).error(Mockito.anyString(), Mockito.any(Object[].class));
+ verify(log, Mockito.times(0)).error(Mockito.anyString());
+ }
+
+ private void verifyNoInfoInLog() {
+ verify(log, Mockito.times(0)).info(Mockito.anyString(), Mockito.any(Object[].class));
+ verify(log, Mockito.times(0)).info(Mockito.anyString());
+ }
+
+ private IDBAction createBasicAction(TestAction action, TestResponse resp) {
+ final TestAction finalAction = action;
+ final TestResponse finalResp = resp;
+ return new IDBAction() {
+ @Override
+ public TestResponse doAction() {
+ log.debug(finalAction.name());
+ return finalResp;
+ }
+ };
+ }
+
+ private IDBAction createCrushingAction(TestAction action, final String crushMessage) {
+ final TestAction finalAction = action;
+ return new IDBAction() {
+ @Override
+ public TestResponse doAction() {
+ log.debug(finalAction.name());
+ throw new RuntimeException(crushMessage);
+ }
+ };
+ }
+
+ public int getNextTransactionId() {
+ transactionId++;
+ return transactionId;
+ }
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java
new file mode 100644
index 0000000000..95c2ac7bdd
--- /dev/null
+++ b/catalog-be/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationTest.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.cucumber.runners;
+
+import cucumber.api.CucumberOptions;
+import cucumber.api.junit.Cucumber;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.components.BeConfDependentTest;
+
+@RunWith(Cucumber.class)
+@CucumberOptions(features = "classpath:cucumber/tenantIsolation.feature", glue = "org.openecomp.sdc.be.components.distribution.engine")
+
+public class RunTenantIsolationTest extends BeConfDependentTest{
+
+
+
+} \ No newline at end of file
diff --git a/catalog-be/src/test/resources/application-context-test.xml b/catalog-be/src/test/resources/application-context-test.xml
new file mode 100644
index 0000000000..9d50219354
--- /dev/null
+++ b/catalog-be/src/test/resources/application-context-test.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+
+ <context:annotation-config />
+ <aop:aspectj-autoproxy proxy-target-class="true" />
+
+ <bean class="org.openecomp.sdc.be.components.distribution.engine.DmaapConsumer" />
+ <bean class="org.openecomp.sdc.be.components.distribution.engine.DmaapClientFactory" />
+ <bean class="org.openecomp.sdc.be.components.distribution.engine.ExecutorFactory" />
+ <bean class="org.openecomp.sdc.be.components.distribution.engine.DmaapHealth" />
+
+</beans>
diff --git a/catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt b/catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/catalog-be/src/test/resources/config/catalog-be/DME2preferredRouter.txt
diff --git a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
index 2ec7124e1c..f948f6e3cc 100644
--- a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
+++ b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
@@ -6,7 +6,8 @@ identificationHeaderFields:
- HTTP_CSP_WSTYPE
# catalog backend hostname
-beFqdn: sdccatalog.att.com
+beFqdn: localhost
+# sdccatalog.att.com
# catalog backend http port
beHttpPort: 8080
@@ -20,14 +21,14 @@ beProtocol: http
# catalog backend ssl port
beSslPort: 8443
-version: 1.0
+version: 1.1.0
released: 2012-11-30
toscaConformanceLevel: 5.0
minToscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
-titanInMemoryGraph: true
-titanLockTimeout: 600
+titanInMemoryGraph: false
+titanLockTimeout: 1800
# The interval to try and reconnect to titan DB when it is down during ASDC startup:
titanReconnectIntervalInSeconds: 3
@@ -40,7 +41,6 @@ esReconnectIntervalInSeconds: 3
uebHealthCheckReconnectIntervalInSeconds: 15
uebHealthCheckReadTimeout: 4
-
# Protocols
protocols:
- http
@@ -74,7 +74,7 @@ neo4j:
cassandraConfig:
cassandraHosts: ['localhost']
- localDataCenter:
+ localDataCenter: datacenter1
reconnectTimeout : 30000
authenticate: false
username: koko
@@ -147,6 +147,7 @@ resourceTypes: &allResourceTypes
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
@@ -296,9 +297,6 @@ serviceDeploymentArtifacts:
YANG_XML:
acceptedTypes:
- xml
- UCPE_LAYER_2_CONFIGURATION:
- acceptedTypes:
- - xml
VNF_CATALOG:
acceptedTypes:
- xml
@@ -308,6 +306,10 @@ serviceDeploymentArtifacts:
MODEL_QUERY_SPEC:
acceptedTypes:
- xml
+ UCPE_LAYER_2_CONFIGURATION:
+ acceptedTypes:
+ - xml
+
#AAI Artifacts
AAI_SERVICE_MODEL:
acceptedTypes:
@@ -507,6 +509,7 @@ resourceInformationalArtifacts:
acceptedTypes:
validForResourceTypes:
- VFC
+ - CVFC
- CP
- VL
- VF
@@ -524,6 +527,7 @@ resourceInformationalArtifacts:
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
@@ -552,6 +556,11 @@ onboarding:
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
healthCheckUri: "/onboarding-api/v1.0/healthcheck"
+dcae:
+ protocol: http
+ host: 127.0.0.1
+ port: 8080
+ healthCheckUri: "/dcae/healthCheck"
switchoverDetector:
gBeFqdn: AIO-BE.ecomp.idns.cip.com
@@ -574,7 +583,7 @@ switchoverDetector:
applicationL1Cache:
datatypes:
- enabled: false
+ enabled: true
firstRunDelay: 10
pollIntervalInSec: 60
@@ -586,8 +595,8 @@ applicationL2Cache:
servicesSizeInCache: 200
productsSizeInCache: 100
queue:
- syncIntervalInSecondes: 60
- waitOnShutDownInMinutes: 30
+ syncIntervalInSecondes: 43200
+ waitOnShutDownInMinutes: 10
numberOfCacheWorkers: 4
toscaValidators:
@@ -611,10 +620,12 @@ vfModuleProperties:
genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
+ CVFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
+workloadContext: Production
environmentContext:
defaultValue: General_Revenue-Bearing
validValues:
@@ -632,3 +643,35 @@ environmentContext:
- Needed_Non-Revenue
- Useful_Non-Revenue
- General_Non-Revenue
+
+dmaapConsumerConfiguration:
+ hosts: olsd004.wnsnet.attws.com:3905
+ consumerGroup: asdc
+ consumerId: invalidMamaUser #mama - in Order To Consume Remove This String And Replace It With -> mama
+ timeoutMs: 15000
+ limit: 1
+ pollingInterval: 2
+ topic: com.att.sdc.23911-SDCforTestDev-v001
+ latitude: 32.109333
+ longitude: 34.855499
+ version: 1.0
+ serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+ environment: TEST
+ partner: BOT_R
+ routeOffer: MR1
+ protocol: https
+ contenttype: application/json
+ dme2TraceOn: true
+ aftEnvironment: AFTUAT
+ aftDme2ConnectionTimeoutMs: 15000
+ aftDme2RoundtripTimeoutMs: 240000
+ aftDme2ReadTimeoutMs: 50000
+ dme2preferredRouterFilePath: DME2preferredRouter.txt
+ timeLimitForNotificationHandleMs: 0
+ credential:
+ username: m09875@sdc.att.com
+ password: hmXYcznAljMSisdy8zgcag==
+
+dmeConfiguration:
+ dme2Search: DME2SEARCH
+ dme2Resolve: DME2RESOLVE
diff --git a/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml
index ac6ff13473..b59d8cc22a 100644
--- a/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml
+++ b/catalog-be/src/test/resources/config/catalog-be/distribution-engine-configuration.yaml
@@ -40,4 +40,41 @@ createTopic:
partitionCount: 1
replicationCount: 1
-startDistributionEngine: true \ No newline at end of file
+startDistributionEngine: true
+
+opEnvRecoveryIntervalSec: 180
+allowedTimeBeforeStaleSec: 300
+
+aaiConfig:
+ httpRequestConfig:
+ serverRootUrl: https://aai-uint3.test.att.com:8443
+ resourceNamespaces:
+ operationalEnvironments: /aai/v12/cloud-infrastructure/operational-environments
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 5000
+ connectTimeoutMs: 1000
+ clientCertificate:
+ keyStore: /opt/app/jetty/base/be/etc/non-prod.jks
+ keyStorePassword: hmXYcznAljMSisdy8zgcag==
+ headers:
+ X-FromAppId: asdc
+ numOfRetries: 3
+
+msoConfig:
+ httpRequestConfig:
+ serverRootUrl: https://127.0.0.1/onap/mso/infra/modelDistributions/v1
+ resourceNamespaces:
+ distributions: /distributions
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 2000
+ connectTimeoutMs: 500
+ basicAuthorization:
+ userName: asdc
+ password: OTLEp5lfVhYdyw5EAtTUBQ==
+ numOfRetries: 3
+
+currentArtifactInstallationTimeout: 120
diff --git a/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
index 591a961150..69fef0f979 100644
--- a/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
+++ b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
@@ -1,4 +1,4 @@
-# Errors
+# Errors
errors:
OK: {
code: 200,
@@ -8,6 +8,10 @@ errors:
code: 201,
message: "OK"
}
+ ACCEPTED: {
+ code: 202,
+ message: "Accepted"
+ }
NO_CONTENT: {
code: 204,
message: "No Content"
@@ -1832,16 +1836,230 @@ errors:
messageId: "SVC4668"
}
- #---------SVC4669-----------------------------
+#---------SVC4669-----------------------------
INVALID_RESOURCE_TYPE: {
code: 400,
message: "Error: Invalid resource type.",
messageId: "SVC4669"
}
-
- #---------SVC4670------------------------------
+#---------SVC4670------------------------------
ARTIFACT_NAME_INVALID: {
code: 400,
message: "Error: Artifact name is invalid.",
messageId: "SVC4670"
- } \ No newline at end of file
+ }
+#---------SVC4671------------------------------
+# %1 - VSP name
+# %2 - VFC name
+ CFVC_LOOP_DETECTED: {
+ code: 400,
+ message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2',
+ messageId: "SVC4671"
+ }
+#---------SVC4672------------------------------
+# %1 - capability uniqueId
+# %2 - instance uniqueId
+# %3 - container uniqueId
+ CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested capability %1 of instance %2 was not found on the container %3.",
+ messageId: "SVC4672"
+ }
+#---------SVC4673------------------------------
+# %1 - requirement uniqueId
+# %2 - instance uniqueId
+# %3 - container uniqueId
+ REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested requirement %1 of instance %2 was not found on the container %3.",
+ messageId: "SVC4673"
+ }
+#---------SVC4674-----------------------------
+# %1 - relation Id
+# %2 - container uniqueId
+ RELATION_NOT_FOUND: {
+ code: 404,
+ message: "Error: Requested relation %1 was not found on the container %2.",
+ messageId: "SVC4674"
+ }
+
+
+#---------SVC4675------------------------------
+ INVALID_SERVICE_STATE: {
+ code: 409,
+ message: "Service state is invalid for this action",
+ messageId: "SVC4675"
+ }
+
+#---------SVC4676------------------------------
+ INVALID_RESPONSE_FROM_PROXY: {
+ code: 502,
+ message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server",
+ messageId: "SVC4676"
+ }
+
+#---------SVC4677------------------------------
+ API_RESOURCE_NOT_FOUND: {
+ code: 404,
+ message: "Error: Requested '%1' was not found.",
+ messageId: "SVC4677"
+ }
+
+#---------SVC4678------------------------------
+ BAD_REQUEST_MISSING_RESOURCE: {
+ code: 400,
+ message: "Error: The required resource name/id is missing in the request",
+ messageId: "SVC4678"
+ }
+#---------SVC4679------------------------------
+# %1 invalid forwarding path name
+ FORWARDING_PATH_INVALID_NAME: {
+ code: 400,
+ message: "Invalid forwarding path name : '%1'.",
+ messageId: "SVC4679"
+ }
+#---------SVC4680------------------------------
+# %1 Forwarding path name
+ FORWARDING_PATH_INVALID_UNIQUE_NAME: {
+ code: 400,
+ message: "Forwarding path name is not unique : '%1'.",
+ messageId: "SVC4680"
+ }
+#---------SVC4681------------------------------
+# %1 Forwarding path missing name
+ FORWARDING_PATH_MISSING_NAME: {
+ code: 400,
+ message: "Forwarding path name is missing.",
+ messageId: "SVC4681"
+ }
+#---------SVC4671------------------------------
+# %1 - VSP name
+# %2 - VFC name
+ CFVC_LOOP_DETECTED: {
+ code: 400,
+ message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2',
+ messageId: "SVC4671"
+ }
+#---------SVC4672------------------------------
+# %1 - capability uniqueId
+# %2 - instance uniqueId
+# %3 - container uniqueId
+ CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested capability %1 of instance %2 was not found on the container %3.",
+ messageId: "SVC4672"
+ }
+#---------SVC4673------------------------------
+# %1 - requirement uniqueId
+# %2 - instance uniqueId
+# %3 - container uniqueId
+ REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested requirement %1 of instance %2 was not found on the container %3.",
+ messageId: "SVC4673"
+ }
+#---------SVC4674-----------------------------
+# %1 - relation Id
+# %2 - container uniqueId
+ RELATION_NOT_FOUND: {
+ code: 404,
+ message: "Error: Requested relation %1 was not found on the container %2.",
+ messageId: "SVC4674"
+ }
+
+
+#---------SVC4675------------------------------
+ INVALID_SERVICE_STATE: {
+ code: 409,
+ message: "Service state is invalid for this action",
+ messageId: "SVC4675"
+ }
+
+#---------SVC4676------------------------------
+ INVALID_RESPONSE_FROM_PROXY: {
+ code: 502,
+ message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server",
+ messageId: "SVC4676"
+ }
+
+#---------SVC4677------------------------------
+ API_RESOURCE_NOT_FOUND: {
+ code: 404,
+ message: "Error: Requested '%1' was not found.",
+ messageId: "SVC4677"
+ }
+
+#---------SVC4678------------------------------
+ BAD_REQUEST_MISSING_RESOURCE: {
+ code: 400,
+ message: "Error: The required resource name/id is missing in the request",
+ messageId: "SVC4678"
+ }
+#---------SVC4679------------------------------
+# %1 invalid forwarding path name
+ FORWARDING_PATH_INVALID_NAME: {
+ code: 400,
+ message: "Invalid forwarding path name : '%1'.",
+ messageId: "SVC4679"
+ }
+#---------SVC4680------------------------------
+# %1 Forwarding path name
+ FORWARDING_PATH_INVALID_UNIQUE_NAME: {
+ code: 400,
+ message: "Forwarding path name is not unique : '%1'.",
+ messageId: "SVC4680"
+ }
+#---------SVC4681------------------------------
+# %1 Forwarding path missing name
+ FORWARDING_PATH_MISSING_NAME: {
+ code: 400,
+ message: "Forwarding path name is missing.",
+ messageId: "SVC4681"
+ }
+#---------SVC4682------------------------------
+# %1 - resource uniqueId
+# %2 - resource component type
+ RESOURCE_CANNOT_CONTAIN_POLICIES: {
+ code: 400,
+ message: "Error: The resource %1 type of %2 cannot contain policies.",
+ messageId: "SVC4682"
+ }
+#---------SVC4683------------------------------
+# %1 - policy uniqueId
+# %2 - component uniqueId
+ POLICY_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested policy %1 was not found on the container %2.",
+ messageId: "SVC4683"
+}
+#---------SVC4684------------------------------
+# %1 - policy name
+ INVALID_POLICY_NAME: {
+ code: 400,
+ message: "Error: Invalid policy name %1 received.",
+ messageId: "SVC4684"
+ }
+#---------SVC4685------------------------------
+# %1 - policy name
+ POLICY_NAME_ALREADY_EXIST: {
+ code: 409,
+ message: "Error: The policy with the name %1 already exists.",
+ messageId: "SVC4685"
+ }
+#---------SVC4686------------------------------
+# %1 - policy type
+# %2 - policy type
+ EXCLUDED_POLICY_TYPE: {
+ code: 400,
+ message: "Error: The policy of the type %1 excluded to add to a component of the type %2.",
+ messageId: "SVC4686"
+ }
+
+#---------SVC4687------------------------------
+# %1 External Reference Value
+ EXT_REF_NOT_FOUND: {
+ code: 404,
+ message: "Error: External Reference '%1' was not found.",
+ messageId: "SVC4687"
+ }
+ \ No newline at end of file
diff --git a/catalog-be/src/test/resources/cucumber/tenantIsolation.feature b/catalog-be/src/test/resources/cucumber/tenantIsolation.feature
new file mode 100644
index 0000000000..8eaac41c49
--- /dev/null
+++ b/catalog-be/src/test/resources/cucumber/tenantIsolation.feature
@@ -0,0 +1,42 @@
+Feature: Tenant Isolation Feature
+
+ Scenario Outline: Recieve Notification Create Environment
+ #Example {"operationalEnvironmentId": "28122015552391", "operationalEnvironmentType": "ECOMP","action": "Create" }
+ Given Dmaap consumer recieved notification with fields <notificationFields>
+ #UP, DOWN
+ And AAI service status is <AAIServiceStatus> and Tenant returned is <tenant> and worload returned is <worload>
+ And AFT_DME service status is <AftDmeServiceStatus>
+ And UEB service status is <UebServiceStatus>
+ And Cassandra service status is <CassandraServiceStatus>
+ #NOT_RELEVANT, NOT_FOUND, FOUND_IN_PROGRESS (Status In Progress), FOUND_COMPLETED (Status Complete), FOUND_FAILED (Status Failed)
+ And Record status is <recordStatus>
+ ####################################################################################
+ When handle message is activated
+ ####################################################################################
+ Then handle message activates validation of eventType <isEventTypeValidated>
+ And trying to write message to audit log and table <isAuditUpdated>
+ And handle message activates validation of action <isActionValidated>
+ And handle message activates validation of state <isStateValidated>
+ And trying to save in-progress record <isSaveActivated>
+ And trying to get environment info from A&AI API <isAAIActivated>
+ And trying to retrieve Ueb Addresses From AftDme <isAftDmeActivated>
+ And trying to create Ueb keys <isCreateKeysActivated>
+ And trying to create Ueb Topics <isCreateTopicsActivated>
+ And handle message finished successfully <isSuccessfull>
+
+ Examples:
+ | notificationFields | AAIServiceStatus | tenant | worload | AftDmeServiceStatus | UebServiceStatus | CassandraServiceStatus | recordStatus | isEventTypeValidated | isAuditUpdated | isActionValidated | isStateValidated | isSaveActivated | isAAIActivated | isAftDmeActivated | isCreateKeysActivated | isCreateTopicsActivated | isSuccessfull |
+ | {"operationalEnvironmentType": "NON-ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | true | false | false | false | false | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Delete" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | false | true | false | false | false | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | DOWN | NOT_RELEVANT | true | false | true | true | false | false | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_IN_PROGRESS | true | false | true | true | false | false | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | | | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | DOWN | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | false | true | true | true | true | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | DOWN | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_FAILED | true | false | true | true | true | true | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Update" } | DOWN | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | FOUND_COMPLETED | true | false | true | true | true | true | false | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | DOWN | DOWN | UP | NOT_FOUND | true | false | true | true | true | true | true | false | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | UP | DOWN | UP | NOT_FOUND | true | false | true | true | true | true | true | true | false | false |
+ | {"operationalEnvironmentType": "ECOMP","action": "Create" } | UP | TEST | ECOMP_E2E-IST | UP | UP | UP | NOT_FOUND | true | false | true | true | true | true | true | true | true | true |
+ | {"operationalEnvironmentType": "ECOMP","action": "Update" } | UP | TEST | ECOMP_E2E-IST | UP | UP | UP | NOT_FOUND | true | false | true | true | true | true | true | true | true | true |
diff --git a/catalog-be/src/test/resources/logback-test.xml b/catalog-be/src/test/resources/logback-test.xml
index d2b9bff23f..f1c51e2567 100644
--- a/catalog-be/src/test/resources/logback-test.xml
+++ b/catalog-be/src/test/resources/logback-test.xml
@@ -7,7 +7,7 @@
</Pattern>
</encoder>
</appender>
- <root level="OFF">
+ <root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration> \ No newline at end of file
diff --git a/catalog-be/src/test/resources/paths/elasticsearch.yml b/catalog-be/src/test/resources/paths/elasticsearch.yml
new file mode 100644
index 0000000000..e1808ad7cc
--- /dev/null
+++ b/catalog-be/src/test/resources/paths/elasticsearch.yml
@@ -0,0 +1,392 @@
+
+elasticSearch.local: true
+elasticSearch.transportclient: false
+cluster.name: elasticsearch_1_5_2222
+
+discovery.zen.ping.multicast.enabled: false
+discovery.zen.ping.unicast.enabled: true
+discovery.zen.ping.unicast.hosts: 1.2.3.4
+transport.client.initial_nodes:
+ - 1.2.3.4:9300
+
+
+#plugin.types: "DeleteByQueryPlugin"
+
+##################### Elasticsearch Configuration Example #####################
+
+# This file contains an overview of various configuration settings,
+# targeted at operations staff. Application developers should
+# consult the guide at <http://elasticsearch.org/guide>.
+#
+# The installation procedure is covered at
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup.html>.
+#
+# Elasticsearch comes with reasonable defaults for most settings,
+# so you can try it out without bothering with configuration.
+#
+# Most of the time, these defaults are just fine for running a production
+# cluster. If you're fine-tuning your cluster, or wondering about the
+# effect of certain configuration option, please _do ask_ on the
+# mailing list or IRC channel [http://elasticsearch.org/community].
+
+# Any element in the configuration can be replaced with environment variables
+# by placing them in ${...} notation. For example:
+#
+# node.rack: ${RACK_ENV_VAR}
+
+# For information on supported formats and syntax for the config file, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup-configuration.html>
+
+
+################################### Cluster ###################################
+
+# Cluster name identifies your cluster for auto-discovery. If you're running
+# multiple clusters on the same network, make sure you're using unique names.
+#
+# cluster.name: elasticsearch
+
+
+#################################### Node #####################################
+
+# Node names are generated dynamically on startup, so you're relieved
+# from configuring them manually. You can tie this node to a specific name:
+#
+# node.name: "Franz Kafka"
+
+# Every node can be configured to allow or deny being eligible as the master,
+# and to allow or deny to store the data.
+#
+# Allow this node to be eligible as a master node (enabled by default):
+#
+# node.master: true
+#
+# Allow this node to store data (enabled by default):
+#
+# node.data: true
+
+# You can exploit these settings to design advanced cluster topologies.
+#
+# 1. You want this node to never become a master node, only to hold data.
+# This will be the "workhorse" of your cluster.
+#
+# node.master: false
+# node.data: true
+#
+# 2. You want this node to only serve as a master: to not store any data and
+# to have free resources. This will be the "coordinator" of your cluster.
+#
+# node.master: true
+# node.data: false
+#
+# 3. You want this node to be neither master nor data node, but
+# to act as a "search load balancer" (fetching data from nodes,
+# aggregating results, etc.)
+#
+# node.master: false
+# node.data: false
+
+# Use the Cluster Health API [http://localhost:9200/_cluster/health], the
+# Node Info API [http://localhost:9200/_nodes] or GUI tools
+# such as <http://www.elasticsearch.org/overview/marvel/>,
+# <http://github.com/karmi/elasticsearch-paramedic>,
+# <http://github.com/lukas-vlcek/bigdesk> and
+# <http://mobz.github.com/elasticsearch-head> to inspect the cluster state.
+
+# A node can have generic attributes associated with it, which can later be used
+# for customized shard allocation filtering, or allocation awareness. An attribute
+# is a simple key value pair, similar to node.key: value, here is an example:
+#
+# node.rack: rack314
+
+# By default, multiple nodes are allowed to start from the same installation location
+# to disable it, set the following:
+# node.max_local_storage_nodes: 1
+
+
+#################################### Index ####################################
+
+# You can set a number of options (such as shard/replica options, mapping
+# or analyzer definitions, translog settings, ...) for indices globally,
+# in this file.
+#
+# Note, that it makes more sense to configure index settings specifically for
+# a certain index, either when creating it or by using the index templates API.
+#
+# See <http://elasticsearch.org/guide/en/elasticsearch/reference/current/index-modules.html> and
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
+# for more information.
+
+# Set the number of shards (splits) of an index (5 by default):
+#
+# index.number_of_shards: 5
+
+# Set the number of replicas (additional copies) of an index (1 by default):
+#
+# index.number_of_replicas: 1
+
+# Note, that for development on a local machine, with small indices, it usually
+# makes sense to "disable" the distributed features:
+#
+index.number_of_shards: 1
+index.number_of_replicas: 0
+
+# These settings directly affect the performance of index and search operations
+# in your cluster. Assuming you have enough machines to hold shards and
+# replicas, the rule of thumb is:
+#
+# 1. Having more *shards* enhances the _indexing_ performance and allows to
+# _distribute_ a big index across machines.
+# 2. Having more *replicas* enhances the _search_ performance and improves the
+# cluster _availability_.
+#
+# The "number_of_shards" is a one-time setting for an index.
+#
+# The "number_of_replicas" can be increased or decreased anytime,
+# by using the Index Update Settings API.
+#
+# Elasticsearch takes care about load balancing, relocating, gathering the
+# results from nodes, etc. Experiment with different settings to fine-tune
+# your setup.
+
+# Use the Index Status API (<http://localhost:9200/A/_status>) to inspect
+# the index status.
+
+
+#################################### Paths ####################################
+path.home: /src/test/resources
+# Path to directory containing configuration (this file and logging.yml):
+#
+path.conf: /src/test/resources
+
+# Path to directory where to store index data allocated for this node.
+#
+path.data: target/esdata
+#
+# Can optionally include more than one location, causing data to be striped across
+# the locations (a la RAID 0) on a file level, favouring locations with most free
+# space on creation. For example:
+#
+# path.data: /path/to/data1,/path/to/data2
+
+# Path to temporary files:
+#
+path.work: /target/eswork
+
+# Path to log files:
+#
+path.logs: /target/eslogs
+
+# Path to where plugins are installed:
+#
+# path.plugins: /path/to/plugins
+
+
+#################################### Plugin ###################################
+
+# If a plugin listed here is not installed for current node, the node will not start.
+#
+# plugin.mandatory: mapper-attachments,lang-groovy
+
+
+################################### Memory ####################################
+
+# Elasticsearch performs poorly when JVM starts swapping: you should ensure that
+# it _never_ swaps.
+#
+# Set this property to true to lock the memory:
+#
+# bootstrap.mlockall: true
+
+# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set
+# to the same value, and that the machine has enough memory to allocate
+# for Elasticsearch, leaving enough memory for the operating system itself.
+#
+# You should also make sure that the Elasticsearch process is allowed to lock
+# the memory, eg. by using `ulimit -l unlimited`.
+
+
+############################## Network And HTTP ###############################
+
+# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens
+# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node
+# communication. (the range means that if the port is busy, it will automatically
+# try the next port).
+
+# Set the bind address specifically (IPv4 or IPv6):
+#
+# network.bind_host: 192.168.0.1
+
+# Set the address other nodes will use to communicate with this node. If not
+# set, it is automatically derived. It must point to an actual IP address.
+#
+# network.publish_host: 192.168.0.1
+
+# Set both 'bind_host' and 'publish_host':
+#
+# network.host: 192.168.0.1
+
+# Set a custom port for the node to node communication (9300 by default):
+#
+# transport.tcp.port: 9300
+
+# Enable compression for all communication between nodes (disabled by default):
+#
+# transport.tcp.compress: true
+
+# Set a custom port to listen for HTTP traffic:
+#
+# http.port: 9200
+
+# Set a custom allowed content length:
+#
+# http.max_content_length: 100mb
+
+# Disable HTTP completely:
+#
+# http.enabled: false
+
+
+################################### Gateway ###################################
+
+# The gateway allows for persisting the cluster state between full cluster
+# restarts. Every change to the state (such as adding an index) will be stored
+# in the gateway, and when the cluster starts up for the first time,
+# it will read its state from the gateway.
+
+# There are several types of gateway implementations. For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-gateway.html>.
+
+# The default gateway type is the "local" gateway (recommended):
+#
+# gateway.type: local
+
+# Settings below control how and when to start the initial recovery process on
+# a full cluster restart (to reuse as much local data as possible when using shared
+# gateway).
+
+# Allow recovery process after N nodes in a cluster are up:
+#
+gateway.recover_after_nodes: 1
+
+# Set the timeout to initiate the recovery process, once the N nodes
+# from previous setting are up (accepts time value):
+#
+# gateway.recover_after_time: 5m
+
+# Set how many nodes are expected in this cluster. Once these N nodes
+# are up (and recover_after_nodes is met), begin recovery process immediately
+# (without waiting for recover_after_time to expire):
+#
+gateway.expected_nodes: 1
+
+
+############################# Recovery Throttling #############################
+
+# These settings allow to control the process of shards allocation between
+# nodes during initial recovery, replica allocation, rebalancing,
+# or when adding and removing nodes.
+
+# Set the number of concurrent recoveries happening on a node:
+#
+# 1. During the initial recovery
+#
+# cluster.routing.allocation.node_initial_primaries_recoveries: 4
+#
+# 2. During adding/removing nodes, rebalancing, etc
+#
+# cluster.routing.allocation.node_concurrent_recoveries: 2
+
+# Set to throttle throughput when recovering (eg. 100mb, by default 20mb):
+#
+# indices.recovery.max_bytes_per_sec: 20mb
+
+# Set to limit the number of open concurrent streams when
+# recovering a shard from a peer:
+#
+# indices.recovery.concurrent_streams: 5
+
+
+################################## Discovery ##################################
+
+# Discovery infrastructure ensures nodes can be found within a cluster
+# and master node is elected. Multicast discovery is the default.
+
+# Set to ensure a node sees N other master eligible nodes to be considered
+# operational within the cluster. Its recommended to set it to a higher value
+# than 1 when running more than 2 nodes in the cluster.
+#
+# discovery.zen.minimum_master_nodes: 1
+
+# Set the time to wait for ping responses from other nodes when discovering.
+# Set this option to a higher value on a slow or congested network
+# to minimize discovery failures:
+#
+# discovery.zen.ping.timeout: 3s
+
+# For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-zen.html>
+
+# Unicast discovery allows to explicitly control which nodes will be used
+# to discover the cluster. It can be used when multicast is not present,
+# or to restrict the cluster communication-wise.
+#
+# 1. Disable multicast discovery (enabled by default):
+#
+# discovery.zen.ping.multicast.enabled: false
+#
+# 2. Configure an initial list of master nodes in the cluster
+# to perform discovery when new nodes (master or data) are started:
+#
+# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"]
+
+# EC2 discovery allows to use AWS EC2 API in order to perform discovery.
+#
+# You have to install the cloud-aws plugin for enabling the EC2 discovery.
+#
+# For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-ec2.html>
+#
+# See <http://elasticsearch.org/tutorials/elasticsearch-on-ec2/>
+# for a step-by-step tutorial.
+
+# GCE discovery allows to use Google Compute Engine API in order to perform discovery.
+#
+# You have to install the cloud-gce plugin for enabling the GCE discovery.
+#
+# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-gce>.
+
+# Azure discovery allows to use Azure API in order to perform discovery.
+#
+# You have to install the cloud-azure plugin for enabling the Azure discovery.
+#
+# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-azure>.
+
+################################## Slow Log ##################################
+
+# Shard level query and fetch threshold logging.
+
+#index.search.slowlog.threshold.query.warn: 10s
+#index.search.slowlog.threshold.query.info: 5s
+#index.search.slowlog.threshold.query.debug: 2s
+#index.search.slowlog.threshold.query.trace: 500ms
+
+#index.search.slowlog.threshold.fetch.warn: 1s
+#index.search.slowlog.threshold.fetch.info: 800ms
+#index.search.slowlog.threshold.fetch.debug: 500ms
+#index.search.slowlog.threshold.fetch.trace: 200ms
+
+#index.indexing.slowlog.threshold.index.warn: 10s
+#index.indexing.slowlog.threshold.index.info: 5s
+#index.indexing.slowlog.threshold.index.debug: 2s
+#index.indexing.slowlog.threshold.index.trace: 500ms
+
+################################## GC Logging ################################
+
+#monitor.jvm.gc.young.warn: 1000ms
+#monitor.jvm.gc.young.info: 700ms
+#monitor.jvm.gc.young.debug: 400ms
+
+#monitor.jvm.gc.old.warn: 10s
+#monitor.jvm.gc.old.info: 5s
+#monitor.jvm.gc.old.debug: 2s
+
diff --git a/catalog-be/src/test/resources/paths/path-context.xml b/catalog-be/src/test/resources/paths/path-context.xml
new file mode 100644
index 0000000000..f0067dfe55
--- /dev/null
+++ b/catalog-be/src/test/resources/paths/path-context.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
+
+ <context:annotation-config />
+ <aop:aspectj-autoproxy proxy-target-class="true" />
+
+ <context:component-scan
+ base-package="org.openecomp.sdc.be.dao.impl,
+ org.openecomp.sdc.be.dao.es,
+ org.openecomp.sdc.be.resources.impl,
+ org.openecomp.sdc.be.dao.neo4j,
+ org.openecomp.sdc.be.model.operations.impl,
+ org.openecomp.sdc.be.model.cache,
+ org.openecomp.sdc.be.dao.titan,
+ org.openecomp.sdc.be.user,
+ org.openecomp.sdc.be.impl,
+ org.openecomp.sdc.be.auditing.impl,
+ org.openecomp.sdc.be.components.impl,
+ org.openecomp.sdc.be.components.merge,
+ org.openecomp.sdc.be.components.property,
+ org.openecomp.sdc.be.components.distribution.engine,
+ org.openecomp.sdc.be.distribution,
+ org.openecomp.sdc.be.components.validation
+ org.openecomp.sdc.be.switchover.detector,
+ org.openecomp.sdc.be.tosca,
+ org.openecomp.sdc.be.model.jsontitan.operations,
+ org.openecomp.sdc.be.model.jsontitan.utils,
+ org.openecomp.sdc.be.components.csar,
+ org.openecomp.sdc.be.dao.jsongraph">
+
+ </context:component-scan>
+
+ <bean id="resourceImportManager" class="org.openecomp.sdc.be.components.impl.ResourceImportManager" />
+ <bean id="capabilityTypeImportManager" class="org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager" />
+ <bean id="servletUtils" class="org.openecomp.sdc.be.impl.ServletUtils" />
+ <bean id="resourceBusinessLogic" class="org.openecomp.sdc.be.components.impl.ResourceBusinessLogic" />
+ <bean id="productBusinessLogic" class="org.openecomp.sdc.be.components.impl.ProductBusinessLogic" />
+ <bean id="artifactBusinessLogic" class="org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic" />
+ <bean id="lifecycleBusinessLogic" class="org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic" />
+ <bean id="transactionManager" class="org.openecomp.sdc.common.transaction.mngr.TransactionManager" />
+ <bean id="userBusinessLogic" class="org.openecomp.sdc.be.user.UserBusinessLogic" />
+ <bean id="elementsBusinessLogic" class="org.openecomp.sdc.be.components.impl.ElementBusinessLogic" />
+ <bean id="propertyBusinessLogic" class="org.openecomp.sdc.be.components.impl.PropertyBusinessLogic" />
+ <bean id="auditingManager" class="org.openecomp.sdc.be.auditing.impl.AuditingManager" />
+ <bean id="distributionBusinessLogic" class="org.openecomp.sdc.be.distribution.DistributionBusinessLogic" />
+ <bean id="interfaceLifecycleTypeImportManager" class="org.openecomp.sdc.be.components.impl.InterfaceLifecycleTypeImportManager" />
+ <bean id="distributionMonitoringBusinessLogic" class="org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic" />
+ <bean id="additionalInformationBusinessLogic" class="org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic" />
+ <bean id="distribution-engine-cluster-health" class="org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth" />
+ <bean id="categoriesImportManager" class="org.openecomp.sdc.be.components.impl.CategoriesImportManager" />
+ <bean id="asset-metadata-utils" class="org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter" />
+ <bean id="titan-client" class="org.openecomp.sdc.be.components.path.beans.InMemoryTitanGraphClient" />
+ <bean class="org.openecomp.sdc.be.dao.config.DAOSpringConfig"/>
+ <bean id="component-cassandra-dao" class="org.openecomp.sdc.be.components.path.beans.ComponentCassandraDaoMock" />
+ <bean id="cassandra-client" class="org.openecomp.sdc.be.components.path.beans.CassandraClientMock" />
+ <bean id="audit-cassandra-dao" class="org.openecomp.sdc.be.components.path.beans.AuditCassandraDaoMock" />
+ <bean id="artifact-cassandra-dao" class="org.openecomp.sdc.be.components.path.beans.ArtifactCassandraDaoMock" />
+ <bean id="operational-environment-dao" class="org.openecomp.sdc.be.components.path.beans.EnvironmentCassandraDaoMock"/>
+ <bean id="sdc-schema-files-cassandra-dao" class="org.openecomp.sdc.be.components.path.beans.SdcSchemaFilesCassandraDaoMock" />
+ <bean id="tosca-operation-facade" class="org.openecomp.sdc.be.components.path.beans.ForwardingPathToscaOperationFacade" />
+ <bean id="distributionEngine" class="org.openecomp.sdc.be.components.path.beans.DistributionEngineMock"/>
+ <bean id="forwardingPathValidator" class="org.openecomp.sdc.be.components.path.beans.ForwardingPathValidatorMock" />
+ <util:properties id="elasticsearchConfig" location="paths/elasticsearch.yml" />
+
+</beans>
diff --git a/catalog-dao/pom.xml b/catalog-dao/pom.xml
index af4f76c4de..a6dd88a968 100644
--- a/catalog-dao/pom.xml
+++ b/catalog-dao/pom.xml
@@ -11,6 +11,9 @@
<version>1.2.0-SNAPSHOT</version>
</parent>
+ <properties>
+ <sonar.skip>true</sonar.skip>
+ </properties>
<dependencies>
<!-- Common of SDC -->
<dependency>
@@ -35,16 +38,9 @@
</dependency>
<dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
- <version>${elastic-search.version}</version>
+ <version>${elastic-search.version}</version>
<scope>provided</scope>
</dependency>
@@ -90,18 +86,17 @@
</dependency>
<dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
+ <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
- <scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
- <scope>provided</scope>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>${jackson.version}</version>
</dependency>
+
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
@@ -118,7 +113,6 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
@@ -167,6 +161,12 @@
<!-- TEST -->
<dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
@@ -254,8 +254,7 @@
<scope>provided</scope>
</dependency>
<!-- CASSANDRA END -->
-
- </dependencies>
+ </dependencies>
<build>
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 3b440df653..c2bff0a935 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
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,74 +21,90 @@
package org.openecomp.sdc.be.dao.api;
public enum ActionStatus {
- OK, CREATED, NO_CONTENT, GENERAL_ERROR, NOT_ALLOWED, MISSING_INFORMATION, RESTRICTED_OPERATION, RESTRICTED_ACCESS, INVALID_CONTENT,
- // User related
- USER_ALREADY_EXIST, USER_INACTIVE, USER_NOT_FOUND, USER_HAS_ACTIVE_ELEMENTS, INVALID_EMAIL_ADDRESS, INVALID_ROLE, DELETE_USER_ADMIN_CONFLICT, UPDATE_USER_ADMIN_CONFLICT, CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, INVALID_USER_ID,
- // CapabilityType related
- CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
- CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, RELATION_NOT_FOUND,
- // Resource related
- RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND,INVALID_RESOURCE_TYPE, TOSCA_PARSE_ERROR,
- // Service related
- SERVICE_TYPE_EXCEEDS_LIMIT, INVALID_SERVICE_TYPE, SERVICE_ROLE_EXCEEDS_LIMIT, INVALID_SERVICE_ROLE,
- // Component name related
- COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME,
- // Component description related
- COMPONENT_INVALID_DESCRIPTION, COMPONENT_MISSING_DESCRIPTION, COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
- // Component icon related
- COMPONENT_MISSING_ICON, COMPONENT_INVALID_ICON, COMPONENT_ICON_EXCEEDS_LIMIT,
- // Tag related
- COMPONENT_MISSING_TAGS, COMPONENT_TAGS_EXCEED_LIMIT, COMPONENT_SINGLE_TAG_EXCEED_LIMIT, INVALID_FIELD_FORMAT, COMPONENT_INVALID_TAGS_NO_COMP_NAME,
- // contactId related
- COMPONENT_MISSING_CONTACT, COMPONENT_INVALID_CONTACT,
- // Vendor related
- VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE, RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, INVALID_RESOURCE_VENDOR_MODEL_NUMBER,
- // Category related
- COMPONENT_MISSING_CATEGORY, COMPONENT_INVALID_CATEGORY, COMPONENT_ELEMENT_INVALID_NAME_FORMAT, COMPONENT_ELEMENT_INVALID_NAME_LENGTH, COMPONENT_CATEGORY_ALREADY_EXISTS, COMPONENT_CATEGORY_NOT_FOUND, COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY, COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY,
- // Service API URL
- INVALID_SERVICE_API_URL,
- // Property related
- PROPERTY_ALREADY_EXIST, PROPERTY_NAME_ALREADY_EXISTS, PROPERTY_NOT_FOUND, INVALID_PROPERTY, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_INNER_TYPE,
- // Attribute related
- ATTRIBUTE_ALREADY_EXIST, ATTRIBUTE_NOT_FOUND,
- // State related
- COMPONENT_IN_CHECKOUT_STATE, ILLEGAL_COMPONENT_STATE, COMPONENT_IN_CERT_IN_PROGRESS_STATE, COMPONENT_SENT_FOR_CERTIFICATION, COMPONENT_VERSION_ALREADY_EXIST, COMPONENT_ALREADY_CHECKED_IN, COMPONENT_CHECKOUT_BY_ANOTHER_USER, COMPONENT_IN_USE, COMPONENT_HAS_NEWER_VERSION, COMPONENT_ALREADY_CERTIFIED, COMPONENT_NOT_READY_FOR_CERTIFICATION, COMPONENT_ARTIFACT_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, SERVICE_NOT_FOUND, SERVICE_CATEGORY_CANNOT_BE_CHANGED, SERVICE_NAME_CANNOT_BE_CHANGED, SERVICE_ICON_CANNOT_BE_CHANGED, COMPONENT_TOO_MUCH_CATEGORIES, SERVICE_CANNOT_CONTAIN_SUBCATEGORY, RESOURCE_CATEGORY_CANNOT_BE_CHANGED, RESOURCE_NAME_CANNOT_BE_CHANGED, RESOURCE_ICON_CANNOT_BE_CHANGED, RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED, RESOURCE_TOO_MUCH_SUBCATEGORIES, SERVICE_ICON_EXCEEDS_LIMIT, RESOURCE_INSTANCE_NOT_FOUND, RESOURCE_INSTANCE_BAD_REQUEST, RESOURCE_INSTANCE_MATCH_NOT_FOUND, RESOURCE_INSTANCE_ALREADY_EXIST, RESOURCE_INSTANCE_RELATION_NOT_FOUND, COMPONENT_MISSING_SUBCATEGORY, COMPONENT_INVALID_SUBCATEGORY, ARTIFACT_TYPE_NOT_SUPPORTED, MISSING_ARTIFACT_TYPE, ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED, ARTIFACT_EXIST, ARTIFACT_NOT_FOUND, ARTIFACT_INVALID_MD5, MISSING_ARTIFACT_NAME, MISSING_PROJECT_CODE, INVALID_PROJECT_CODE, COMPONENT_MISSING_MANDATORY_ARTIFACTS, LIFECYCLE_TYPE_ALREADY_EXIST, SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, MISSING_LIFECYCLE_TYPE,RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID,
- // Distribution
- MISSING_USER_ID, MISSING_X_ECOMP_INSTANCE_ID, MISSING_PUBLIC_KEY, MISSING_ENV_NAME, DISTRIBUTION_ENV_DOES_NOT_EXIST, MISSING_BODY, ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS, ECOMP_COMPONENT_NOT_AUTHORIZED, METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT, REGISTRATION_FAILED, DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, DISTRIBUTION_ENVIRONMENT_NOT_FOUND, DISTRIBUTION_ENVIRONMENT_INVALID, DISTRIBUTION_ARTIFACT_NOT_FOUND, DISTRIBUTION_REQUESTED_NOT_FOUND, DISTRIBUTION_REQUESTED_FAILED, DISTRIBUTION_NOT_FOUND, ADDITIONAL_INFORMATION_ALREADY_EXISTS, COMPONENT_VERSION_NOT_FOUND, ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_NOT_FOUND, ASDC_VERSION_NOT_FOUND, MISSING_DATA, EXCEEDS_LIMIT, UNSUPPORTED_ERROR, ARTIFACT_INVALID_TIMEOUT, SERVICE_IS_VNF_CANNOT_BE_CHANGED, RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, WRONG_ARTIFACT_FILE_EXTENSION, INVALID_YAML, INVALID_XML, INVALID_JSON, INVALID_DEPLOYMENT_ARTIFACT_HEAT, INVALID_HEAT_PARAMETER_TYPE, INVALID_HEAT_PARAMETER_VALUE, DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, MISSING_HEAT, MISMATCH_HEAT_VS_HEAT_ENV, CORRUPTED_FORMAT, MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, INVALID_PARAMS_IN_HEAT_ENV_FILE,
- // auth
- AUTH_FAILED_INVALIDE_HEADER, AUTH_FAILED, AUTH_REQUIRED, CONSUMER_ALREADY_EXISTS, INVALID_LENGTH, ECOMP_USER_NOT_FOUND, INVALID_CONTENT_PARAM, INVALID_FILTER_KEY, SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, VALIDATED_RESOURCE_NOT_FOUND, FOUND_ALREADY_VALIDATED_RESOURCE, FOUND_LIST_VALIDATED_RESOURCES,
+ OK, ACCEPTED, CREATED, NO_CONTENT, GENERAL_ERROR, NOT_ALLOWED, MISSING_INFORMATION, RESTRICTED_OPERATION, RESTRICTED_ACCESS, INVALID_CONTENT,
+ // User related
+ USER_ALREADY_EXIST, USER_INACTIVE, USER_NOT_FOUND, USER_HAS_ACTIVE_ELEMENTS, INVALID_EMAIL_ADDRESS, INVALID_ROLE, DELETE_USER_ADMIN_CONFLICT, UPDATE_USER_ADMIN_CONFLICT, CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, INVALID_USER_ID,
+ // CapabilityType related
+ CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
+ CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, RELATION_NOT_FOUND,
+ // Resource related
+ RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND, INVALID_RESOURCE_TYPE, TOSCA_PARSE_ERROR,
+ // Service related
+ SERVICE_TYPE_EXCEEDS_LIMIT, INVALID_SERVICE_TYPE, SERVICE_ROLE_EXCEEDS_LIMIT, INVALID_SERVICE_ROLE,
+ // Component name related
+ COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME,
+ // Component description related
+ COMPONENT_INVALID_DESCRIPTION, COMPONENT_MISSING_DESCRIPTION, COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ // Component icon related
+ COMPONENT_MISSING_ICON, COMPONENT_INVALID_ICON, COMPONENT_ICON_EXCEEDS_LIMIT,
+ // Tag related
+ COMPONENT_MISSING_TAGS, COMPONENT_TAGS_EXCEED_LIMIT, COMPONENT_SINGLE_TAG_EXCEED_LIMIT, INVALID_FIELD_FORMAT, COMPONENT_INVALID_TAGS_NO_COMP_NAME,
+ // contactId related
+ COMPONENT_MISSING_CONTACT, COMPONENT_INVALID_CONTACT,
+ // Vendor related
+ VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE, RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, INVALID_RESOURCE_VENDOR_MODEL_NUMBER,
+ // Category related
+ COMPONENT_MISSING_CATEGORY, COMPONENT_INVALID_CATEGORY, COMPONENT_ELEMENT_INVALID_NAME_FORMAT, COMPONENT_ELEMENT_INVALID_NAME_LENGTH, COMPONENT_CATEGORY_ALREADY_EXISTS, COMPONENT_CATEGORY_NOT_FOUND, COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY, COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY,
+ // Service API URL
+ INVALID_SERVICE_API_URL,
+ // Property related
+ PROPERTY_ALREADY_EXIST, PROPERTY_NAME_ALREADY_EXISTS, PROPERTY_NOT_FOUND, INVALID_PROPERTY, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_INNER_TYPE,
+ // Attribute related
+ ATTRIBUTE_ALREADY_EXIST, ATTRIBUTE_NOT_FOUND,
+ // State related
+ INVALID_SERVICE_STATE, COMPONENT_IN_CHECKOUT_STATE, ILLEGAL_COMPONENT_STATE, COMPONENT_IN_CERT_IN_PROGRESS_STATE, COMPONENT_SENT_FOR_CERTIFICATION, COMPONENT_VERSION_ALREADY_EXIST, COMPONENT_ALREADY_CHECKED_IN, COMPONENT_CHECKOUT_BY_ANOTHER_USER, COMPONENT_IN_USE, COMPONENT_HAS_NEWER_VERSION, COMPONENT_ALREADY_CERTIFIED, COMPONENT_NOT_READY_FOR_CERTIFICATION, COMPONENT_ARTIFACT_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND, COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, SERVICE_NOT_FOUND, SERVICE_CATEGORY_CANNOT_BE_CHANGED, SERVICE_NAME_CANNOT_BE_CHANGED, SERVICE_ICON_CANNOT_BE_CHANGED, COMPONENT_TOO_MUCH_CATEGORIES, SERVICE_CANNOT_CONTAIN_SUBCATEGORY, RESOURCE_CATEGORY_CANNOT_BE_CHANGED, RESOURCE_NAME_CANNOT_BE_CHANGED, RESOURCE_ICON_CANNOT_BE_CHANGED, RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED, RESOURCE_TOO_MUCH_SUBCATEGORIES, SERVICE_ICON_EXCEEDS_LIMIT, RESOURCE_INSTANCE_NOT_FOUND, RESOURCE_INSTANCE_BAD_REQUEST, RESOURCE_INSTANCE_MATCH_NOT_FOUND, RESOURCE_INSTANCE_ALREADY_EXIST, RESOURCE_INSTANCE_RELATION_NOT_FOUND, COMPONENT_MISSING_SUBCATEGORY, COMPONENT_INVALID_SUBCATEGORY, ARTIFACT_TYPE_NOT_SUPPORTED, MISSING_ARTIFACT_TYPE, ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED, ARTIFACT_EXIST, ARTIFACT_NOT_FOUND, ARTIFACT_INVALID_MD5, MISSING_ARTIFACT_NAME, MISSING_PROJECT_CODE, INVALID_PROJECT_CODE, COMPONENT_MISSING_MANDATORY_ARTIFACTS, LIFECYCLE_TYPE_ALREADY_EXIST, SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, MISSING_LIFECYCLE_TYPE, RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID,
+ // Distribution
+ BAD_REQUEST_MISSING_RESOURCE, MISSING_USER_ID, MISSING_X_ECOMP_INSTANCE_ID, MISSING_PUBLIC_KEY, MISSING_ENV_NAME, DISTRIBUTION_ENV_DOES_NOT_EXIST, MISSING_BODY, ECOMP_RESEND_WITH_BASIC_AUTHENTICATION_CREDENTIALS, ECOMP_COMPONENT_NOT_AUTHORIZED, METHOD_NOT_ALLOWED_TO_DOWNLOAD_ARTIFACT, REGISTRATION_FAILED, DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, DISTRIBUTION_ENVIRONMENT_NOT_FOUND, DISTRIBUTION_ENVIRONMENT_INVALID, DISTRIBUTION_ARTIFACT_NOT_FOUND, DISTRIBUTION_REQUESTED_NOT_FOUND, DISTRIBUTION_REQUESTED_FAILED, DISTRIBUTION_NOT_FOUND, ADDITIONAL_INFORMATION_ALREADY_EXISTS, COMPONENT_VERSION_NOT_FOUND, ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, ADDITIONAL_INFORMATION_NOT_FOUND, ASDC_VERSION_NOT_FOUND, MISSING_DATA, EXCEEDS_LIMIT, UNSUPPORTED_ERROR, ARTIFACT_INVALID_TIMEOUT, SERVICE_IS_VNF_CANNOT_BE_CHANGED, RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, WRONG_ARTIFACT_FILE_EXTENSION, INVALID_YAML, INVALID_XML, INVALID_JSON, INVALID_DEPLOYMENT_ARTIFACT_HEAT, INVALID_HEAT_PARAMETER_TYPE, INVALID_HEAT_PARAMETER_VALUE, DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, MISSING_HEAT, MISMATCH_HEAT_VS_HEAT_ENV, CORRUPTED_FORMAT, MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, INVALID_PARAMS_IN_HEAT_ENV_FILE, API_RESOURCE_NOT_FOUND,
+ //UEB
+ UNKNOWN_HOST, AUTHENTICATION_ERROR, CONNNECTION_ERROR, OBJECT_NOT_FOUND, INVALID_RESPONSE_FROM_PROXY,
+ // auth
+ AUTH_FAILED_INVALIDE_HEADER, AUTH_FAILED, AUTH_REQUIRED, CONSUMER_ALREADY_EXISTS, INVALID_LENGTH, ECOMP_USER_NOT_FOUND, INVALID_CONTENT_PARAM, INVALID_FILTER_KEY, SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, VALIDATED_RESOURCE_NOT_FOUND, FOUND_ALREADY_VALIDATED_RESOURCE, FOUND_LIST_VALIDATED_RESOURCES,
- // product
- PRODUCT_NOT_FOUND, INVALID_GROUP_ASSOCIATION, EMPTY_PRODUCT_CONTACTS_LIST, INVALID_PRODUCT_CONTACT, MISSING_ONE_OF_COMPONENT_NAMES, COMPONENT_PARAMETER_CANNOT_BE_CHANGED,
+ // product
+ PRODUCT_NOT_FOUND, INVALID_GROUP_ASSOCIATION, EMPTY_PRODUCT_CONTACTS_LIST, INVALID_PRODUCT_CONTACT, MISSING_ONE_OF_COMPONENT_NAMES, COMPONENT_PARAMETER_CANNOT_BE_CHANGED,
- // occurrences
- EMPTY_OCCURRENCES_LIST, INVALID_OCCURRENCES, NOT_TOPOLOGY_TOSCA_TEMPLATE, INVALID_NODE_TEMPLATE,
+ // occurrences
+ EMPTY_OCCURRENCES_LIST, INVALID_OCCURRENCES, NOT_TOPOLOGY_TOSCA_TEMPLATE, INVALID_NODE_TEMPLATE,
- // Data type related
- DATA_TYPE_ALREADY_EXIST, DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, DATA_TYPE_DERIVED_IS_MISSING, DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, DATA_TYPE_DUPLICATE_PROPERTY, DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, DATA_TYPE_CANNOT_HAVE_PROPERTIES, DATA_TYPE_CANNOT_BE_EMPTY, DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST,
+ // Data type related
+ DATA_TYPE_ALREADY_EXIST, DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, DATA_TYPE_DERIVED_IS_MISSING, DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, DATA_TYPE_DUPLICATE_PROPERTY, DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, DATA_TYPE_CANNOT_HAVE_PROPERTIES, DATA_TYPE_CANNOT_BE_EMPTY, DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST,
- // Policy Type related
- TARGETS_EMPTY, TARGETS_NON_VALID, POLICY_TYPE_ALREADY_EXIST,
+ // Policy Type related
+ TARGETS_EMPTY, TARGETS_NON_VALID, POLICY_TYPE_ALREADY_EXIST,
- // Group Type related
- GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST,
+ // Group Type related
+ GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST, GROUP_TYPE_ILLEGAL_PER_COMPONENT,
- // CSAR
- MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID,
+ // CSAR
+ MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID,
- // Group
- GROUP_HAS_CYCLIC_DEPENDENCY, GROUP_ALREADY_EXIST, GROUP_TYPE_IS_INVALID, GROUP_MISSING_GROUP_TYPE, GROUP_INVALID_COMPONENT_INSTANCE, GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, GROUP_IS_MISSING, GROUP_ARTIFACT_ALREADY_ASSOCIATED, GROUP_ARTIFACT_ALREADY_DISSOCIATED, GROUP_PROPERTY_NOT_FOUND, INVALID_VF_MODULE_NAME, INVALID_VF_MODULE_NAME_MODIFICATION, INVALID_VF_MODULE_TYPE,
-
- // Group instance
- GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
-
- ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, FAILED_RETRIVE_ARTIFACTS_TYPES, ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, ARTIFACT_NOT_VALID_IN_MASTER, ARTIFACT_NOT_VALID_ENV,
+ // 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,
- // cache
- CONVERT_COMPONENT_ERROR, COMPONENT_NOT_FOUND,
+ // Group instance
+ GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
- // Inputs
- INPUT_IS_NOT_CHILD_OF_COMPONENT,
- CFVC_LOOP_DETECTED,
- ;
+ ARTIFACT_NOT_FOUND_IN_CSAR, ARTIFACT_ALRADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, FAILED_RETRIVE_ARTIFACTS_TYPES, ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, ARTIFACT_NOT_VALID_IN_MASTER, ARTIFACT_NOT_VALID_ENV,
+
+ // cache
+ CONVERT_COMPONENT_ERROR, COMPONENT_NOT_FOUND,
+
+ // Inputs
+ INPUT_IS_NOT_CHILD_OF_COMPONENT,
+ CFVC_LOOP_DETECTED,
+ //Forwarding Path related
+ FORWARDING_PATH_NAME_MAXIMUM_LENGTH, FORWARDING_PATH_NAME_ALREADY_IN_USE, FORWARDING_PATH_NAME_EMPTY,
+ FORWARDING_PATH_PROTOCOL_MAXIMUM_LENGTH, FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH,
+ MISSING_OLD_COMPONENT_INSTANCE, MISSING_NEW_COMPONENT_INSTANCE,
+ //policies
+ RESOURCE_CANNOT_CONTAIN_POLICIES,
+ POLICY_NOT_FOUND_ON_CONTAINER,
+ INVALID_POLICY_NAME,
+ POLICY_NAME_ALREADY_EXIST, EXCLUDED_POLICY_TYPE,
+
+ //External References Statuses
+ EXT_REF_ALREADY_EXIST,
+ EXT_REF_NOT_FOUND,
+
+ POLICY_TARGET_DOES_NOT_EXIST, POLICY_TARGET_TYPE_DOES_NOT_EXIST;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java
index 73b55b909c..681d20cde3 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/AuditCassandraDao.java
@@ -106,10 +106,7 @@ public class AuditCassandraDao extends CassandraDao {
});
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
-
logger.debug("failed to get distribution statuses for ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -133,10 +130,7 @@ public class AuditCassandraDao extends CassandraDao {
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution Deploy By Status");
-
logger.debug("failed to get distribution deploy by status for ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -158,10 +152,7 @@ public class AuditCassandraDao extends CassandraDao {
});
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution request");
-
logger.debug("failed to get distribution request for ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -184,10 +175,7 @@ public class AuditCassandraDao extends CassandraDao {
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
-
logger.debug("failed to get distribution notify for ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -209,10 +197,7 @@ public class AuditCassandraDao extends CassandraDao {
});
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
-
logger.debug("failed to get distribution notify for ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -241,8 +226,6 @@ public class AuditCassandraDao extends CassandraDao {
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Service DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
logger.debug("failed to get distribution statuses for action {}",
AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), e);
@@ -259,8 +242,6 @@ public class AuditCassandraDao extends CassandraDao {
});
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Service DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
logger.debug("failed to get distribution statuses for action {}",
AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), e);
@@ -277,8 +258,6 @@ public class AuditCassandraDao extends CassandraDao {
});
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Service DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
logger.debug("failed to get distribution statuses for action {}",
AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), e);
@@ -307,10 +286,7 @@ public class AuditCassandraDao extends CassandraDao {
});
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "get Audit By ServiceId And PrevVersion");
BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And PrevVersion");
-
logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -335,8 +311,6 @@ public class AuditCassandraDao extends CassandraDao {
});
return Either.left(remainingElements);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "get Audit By ServiceId And CurrVersion");
BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And CurrVersion");
logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java
index eff094a3a0..10b9b0578c 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/CassandraClient.java
@@ -24,9 +24,8 @@ import java.util.List;
import javax.annotation.PreDestroy;
-import com.datastax.driver.core.SocketOptions;
+import com.datastax.driver.core.policies.*;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,11 +33,6 @@ import org.springframework.stereotype.Component;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
-import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
-import com.datastax.driver.core.policies.DefaultRetryPolicy;
-import com.datastax.driver.core.policies.LoadBalancingPolicy;
-import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;
@@ -50,27 +44,23 @@ public class CassandraClient {
private Cluster cluster;
private boolean isConnected;
- private Configuration.CassandrConfig configuration;
public CassandraClient() {
super();
isConnected = false;
List<String> cassandraHosts = null;
try {
-
- this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig();
- cassandraHosts = configuration.getCassandraHosts();
- Long reconnectTimeout = configuration.getReconnectTimeout();
-
+ cassandraHosts = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
+ .getCassandraHosts();
+ Long reconnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
+ .getCassandraConfig().getReconnectTimeout();
logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout);
Cluster.Builder clusterBuilder = Cluster.builder()
.withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
.withRetryPolicy(DefaultRetryPolicy.INSTANCE);
-
cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
- setSocketOptions(clusterBuilder);
enableAuthentication(clusterBuilder);
enableSsl(clusterBuilder);
setLocalDc(clusterBuilder);
@@ -84,26 +74,11 @@ public class CassandraClient {
logger.info("** CassandraClient created");
}
- private void setSocketOptions(Cluster.Builder clusterBuilder) {
- SocketOptions socketOptions =new SocketOptions();
- Integer socketConnectTimeout = this.configuration.getSocketConnectTimeout();
- if( socketConnectTimeout!=null ){
- logger.info("SocketConnectTimeout was provided, setting Cassandra client to use SocketConnectTimeout: {} .",socketConnectTimeout);
- socketOptions.setConnectTimeoutMillis(socketConnectTimeout);
- }
- Integer socketReadTimeout = this.configuration.getSocketReadTimeout();
- if( socketReadTimeout != null ){
- logger.info("SocketReadTimeout was provided, setting Cassandra client to use SocketReadTimeout: {} .",socketReadTimeout);
- socketOptions.setReadTimeoutMillis(socketReadTimeout);
- }
- clusterBuilder.withSocketOptions(socketOptions);
- }
-
private void setLocalDc(Cluster.Builder clusterBuilder) {
String localDataCenter = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig()
.getLocalDataCenter();
if (localDataCenter != null) {
- logger.info("localDatacenter was provided, setting Cassandra client to use datacenter: {} as local.",
+ logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.",
localDataCenter);
LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java
new file mode 100644
index 0000000000..a803f0b165
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentDao.java
@@ -0,0 +1,89 @@
+package org.openecomp.sdc.be.dao.cassandra;
+
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.MappingManager;
+import com.datastax.driver.mapping.Result;
+
+import fj.data.Either;
+
+@Component("operational-environment-dao")
+public class OperationalEnvironmentDao extends CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(OperationalEnvironmentDao.class.getName());
+ private OperationalEnvironmentsAccessor operationalEnvironmentsAccessor;
+
+ public OperationalEnvironmentDao() {
+ super();
+ }
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.REPO_KEYSPACE;
+ if (client.isConnected()) {
+ Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
+ if (result.isLeft()) {
+ session = result.left().value().left;
+ manager = result.left().value().right;
+ operationalEnvironmentsAccessor = manager.createAccessor(OperationalEnvironmentsAccessor.class);
+ logger.info("** OperationalEnvironmentDao created");
+ } else {
+ logger.info("** OperationalEnvironmentDao failed");
+ throw new RuntimeException("OperationalEnvironment keyspace [" + keyspace + "] failed to connect with error : "
+ + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** OperationalEnvironmentDao created, but not connected");
+ }
+ }
+ public CassandraOperationStatus save(OperationalEnvironmentEntry operationalEnvironmentEntry) {
+ return client.save(operationalEnvironmentEntry, OperationalEnvironmentEntry.class, manager);
+ }
+
+ public Either<OperationalEnvironmentEntry, CassandraOperationStatus> get(String envId) {
+ return client.getById(envId, OperationalEnvironmentEntry.class, manager);
+ }
+
+ public CassandraOperationStatus delete(String envId) {
+ return client.delete(envId, OperationalEnvironmentEntry.class, manager);
+ }
+
+ public CassandraOperationStatus deleteAll() {
+ logger.info("cleaning all operational environments.");
+ String query = "truncate sdcrepository.operationalenvironment;";
+ try {
+ session.execute(query);
+ } catch (Exception e) {
+ logger.debug("Failed to clean operational environment", e);
+ return CassandraOperationStatus.GENERAL_ERROR;
+ }
+ logger.info("cleaning all operational environment finished succsesfully.");
+ return CassandraOperationStatus.OK;
+ }
+
+ public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
+ return super.isTableEmpty(tableName);
+ }
+
+ //accessors
+ public Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> getByEnvironmentsStatus(EnvironmentStatusEnum status) {
+ Result<OperationalEnvironmentEntry> operationalEnvironments = operationalEnvironmentsAccessor.getByEnvironmentsStatus(status.getName());
+ if (operationalEnvironments == null) {
+ return Either.right(CassandraOperationStatus.NOT_FOUND);
+ }
+ return Either.left(operationalEnvironments.all());
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java
new file mode 100644
index 0000000000..e72df9b42d
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/OperationalEnvironmentsAccessor.java
@@ -0,0 +1,14 @@
+package org.openecomp.sdc.be.dao.cassandra;
+
+import com.datastax.driver.mapping.Result;
+import com.datastax.driver.mapping.annotations.Accessor;
+import com.datastax.driver.mapping.annotations.Param;
+import com.datastax.driver.mapping.annotations.Query;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+
+@Accessor
+public interface OperationalEnvironmentsAccessor {
+ @Query("SELECT * FROM sdcrepository.operationalenvironment WHERE status = :envStatus")
+ Result<OperationalEnvironmentEntry> getByEnvironmentsStatus(@Param("envStatus") String envStatus);
+}
+
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java
index 4de57ded64..56cf32a152 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/SdcSchemaUtils.java
@@ -20,15 +20,12 @@
package org.openecomp.sdc.be.dao.cassandra.schema;
-import java.util.List;
-
-import com.datastax.driver.core.SocketOptions;
+import com.datastax.driver.core.*;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.Session;
+import java.util.List;
public class SdcSchemaUtils {
@@ -74,19 +71,6 @@ public class SdcSchemaUtils {
System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
clusterBuilder.withSSL();
}
-
- SocketOptions socketOptions =new SocketOptions();
- Integer socketConnectTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getSocketConnectTimeout();
- if( socketConnectTimeout!=null ){
- log.info("SocketConnectTimeout was provided, setting Cassandra client to use SocketConnectTimeout: {} .",socketConnectTimeout);
- socketOptions.setConnectTimeoutMillis(socketConnectTimeout);
- }
- Integer socketReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getSocketReadTimeout();
- if( socketReadTimeout != null ){
- log.info("SocketReadTimeout was provided, setting Cassandra client to use SocketReadTimeout: {} .",socketReadTimeout);
- socketOptions.setReadTimeoutMillis(socketReadTimeout);
- }
- clusterBuilder.withSocketOptions(socketOptions);
return clusterBuilder.build();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
index 5cbe2508b1..96bd68ac79 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
@@ -30,11 +30,13 @@ import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDownloadEventTabl
import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribEngineEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribNotifEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribStatusEventTableDesc;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.EcompOperationalEnvironmentEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.ExternalApiEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetCatHierEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.OperationalEnvironmentsTableDescription;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.ResAdminEventTableDescription;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.SdcSchemaFilesTableDescription;
import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAccessEventTableDescription;
@@ -42,25 +44,28 @@ import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescr
public enum Table {
- ARTIFACT(new ArtifactTableDescription()),
- USER_ADMIN_EVENT(new UserAdminEventTableDescription()),
- USER_ACCESS_EVENT(new UserAccessEventTableDescription()),
- RESOURCE_ADMIN_EVENT(new ResAdminEventTableDescription()),
- DISTRIBUTION_DOWNLOAD_EVENT(new DistribDownloadEventTableDesc()),
- DISTRIBUTION_ENGINE_EVENT(new DistribEngineEventTableDesc()),
- DISTRIBUTION_NOTIFICATION_EVENT(new DistribNotifEventTableDesc()),
- DISTRIBUTION_STATUS_EVENT(new DistribStatusEventTableDesc()),
- DISTRIBUTION_DEPLOY_EVENT(new DistribDeployEventTableDesc()),
- DISTRIBUTION_GET_UEB_CLUSTER_EVENT(new GetUebClusterEventTableDesc()),
- AUTH_EVENT(new AuthEventTableDescription()),
- CONSUMER_EVENT(new ConsumerEventTableDefinition()),
- CATEGORY_EVENT(new CategoryEventTableDescription()),
- GET_USERS_LIST_EVENT(new GetUsersListEventTableDesc()),
- GET_CATEGORY_HIERARCHY_EVENT(new GetCatHierEventTableDesc()),
- EXTERNAL_API_EVENT(new ExternalApiEventTableDesc()),
- COMPONENT_CACHE(new ComponentCacheTableDescription()),
- SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription()),
- SDC_REPO(new MigrationTasksTableDescription());
+ ARTIFACT(new ArtifactTableDescription()),
+ USER_ADMIN_EVENT(new UserAdminEventTableDescription()),
+ USER_ACCESS_EVENT(new UserAccessEventTableDescription()),
+ RESOURCE_ADMIN_EVENT(new ResAdminEventTableDescription()),
+ DISTRIBUTION_DOWNLOAD_EVENT(new DistribDownloadEventTableDesc()),
+ DISTRIBUTION_ENGINE_EVENT(new DistribEngineEventTableDesc()),
+ DISTRIBUTION_NOTIFICATION_EVENT(new DistribNotifEventTableDesc()),
+ DISTRIBUTION_STATUS_EVENT(new DistribStatusEventTableDesc()),
+ DISTRIBUTION_DEPLOY_EVENT(new DistribDeployEventTableDesc()),
+ DISTRIBUTION_GET_UEB_CLUSTER_EVENT(new GetUebClusterEventTableDesc()),
+ AUTH_EVENT(new AuthEventTableDescription()),
+ CONSUMER_EVENT(new ConsumerEventTableDefinition()),
+ CATEGORY_EVENT(new CategoryEventTableDescription()),
+ GET_USERS_LIST_EVENT(new GetUsersListEventTableDesc()),
+ GET_CATEGORY_HIERARCHY_EVENT(new GetCatHierEventTableDesc()),
+ EXTERNAL_API_EVENT(new ExternalApiEventTableDesc()),
+ COMPONENT_CACHE(new ComponentCacheTableDescription()),
+ SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription()),
+ SDC_REPO(new MigrationTasksTableDescription()),
+ SDC_OPERATIONAL_ENVIRONMENT(new OperationalEnvironmentsTableDescription()),
+ AUDIT_ECOMP_OPERATIONAL_ENVIRONMENT(new EcompOperationalEnvironmentEventTableDesc());
+
ITableDescription tableDescription;
Table(ITableDescription tableDescription) {
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java
new file mode 100644
index 0000000000..cbd70ca9fe
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribBaseEventTableDesc.java
@@ -0,0 +1,76 @@
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import com.datastax.driver.core.DataType;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public abstract class DistribBaseEventTableDesc implements ITableDescription {
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ for (DistFieldsDescription field : DistFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+ updateColumnDistribDescription(columns);
+ return columns;
+ }
+
+ protected abstract void updateColumnDistribDescription(final Map<String, ImmutablePair<DataType, Boolean>> columns);
+
+
+ enum DistFieldsDescription {
+ ACTION("action", DataType.varchar(), true),
+ STATUS("status", DataType.varchar(), false),
+ DESCRIPTION("description", DataType.varchar(), false),
+ REQUEST_ID("request_id", DataType.varchar(), false),
+ SERVICE_INST_ID("service_instance_id", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ DistFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java
index a233110f9e..ceacdeab0e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDeployEventTableDesc.java
@@ -20,61 +20,36 @@
package org.openecomp.sdc.be.dao.cassandra.schema.tables;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import com.datastax.driver.core.DataType;
-public class DistribDeployEventTableDesc implements ITableDescription {
+public class DistribDeployEventTableDesc extends DistribBaseEventTableDesc {
- @Override
- public List<ImmutablePair<String, DataType>> primaryKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
- return keys;
- }
@Override
- public List<ImmutablePair<String, DataType>> clusteringKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
- return keys;
+ public String getTableName() {
+ return AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE;
}
@Override
- public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
- Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
-
+ protected void updateColumnDistribDescription(Map<String, ImmutablePair<DataType, Boolean>> columns) {
for (DSEFieldsDescription field : DSEFieldsDescription.values()) {
columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
}
+ //replace the base indexed flag value with the correct one for a given table:
+ columns.put(DistFieldsDescription.STATUS.getName(),
+ new ImmutablePair<DataType, Boolean>(DistFieldsDescription.STATUS.getType(), true));
+ columns.put(DistFieldsDescription.SERVICE_INST_ID.getName(),
+ new ImmutablePair<DataType, Boolean>(DistFieldsDescription.SERVICE_INST_ID.getType(), true));
- return columns;
- }
-
- @Override
- public String getKeyspace() {
- return AuditingTypesConstants.AUDIT_KEYSPACE;
- }
-
- @Override
- public String getTableName() {
- return AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE;
- }
+ }
enum DSEFieldsDescription {
- ACTION("action", DataType.varchar(), true),
- STATUS("status", DataType.varchar(), true),
- DESCRIPTION("description", DataType.varchar(), false),
- REQUEST_ID("request_id", DataType.varchar(), false),
- SERVICE_INST_ID("service_instance_id", DataType.varchar(), true),
- MODIFIER("modifier", DataType.varchar(), false),
+ MODIFIER("modifier", DataType.varchar(), false),
CURR_VERSION("curr_version", DataType.varchar(), false),
DID("did", DataType.varchar(), true),
RESOURCE_NAME("resource_name", DataType.varchar(), false),
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java
index 0ac31352f2..61968be9ec 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribDownloadEventTableDesc.java
@@ -20,47 +20,20 @@
package org.openecomp.sdc.be.dao.cassandra.schema.tables;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import com.datastax.driver.core.DataType;
-public class DistribDownloadEventTableDesc implements ITableDescription {
+public class DistribDownloadEventTableDesc extends DistribBaseEventTableDesc {
@Override
- public List<ImmutablePair<String, DataType>> primaryKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
- return keys;
- }
-
- @Override
- public List<ImmutablePair<String, DataType>> clusteringKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
- return keys;
- }
-
- @Override
- public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
- Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
-
+ protected void updateColumnDistribDescription(Map<String, ImmutablePair<DataType, Boolean>> columns) {
for (DSEFieldsDescription field : DSEFieldsDescription.values()) {
columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
}
-
- return columns;
- }
-
- @Override
- public String getKeyspace() {
- return AuditingTypesConstants.AUDIT_KEYSPACE;
}
@Override
@@ -69,12 +42,7 @@ public class DistribDownloadEventTableDesc implements ITableDescription {
}
enum DSEFieldsDescription {
- REQUEST_ID("request_Id", DataType.varchar(), false),
- SERVICE_INST_ID("service_Instance_Id", DataType.varchar(),false),
- ACTION("action", DataType.varchar(), true),
- STATUS("status", DataType.varchar(), false),
- DESCRIPTION("description", DataType.varchar(), false),
- CONSUMER_ID("consumer_Id", DataType.varchar(), false),
+ CONSUMER_ID("consumer_Id", DataType.varchar(), false),
RESOURCE_URL("resource_URL", DataType.varchar(), false);
private String name;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java
index 16d9af084f..5b1aaee04e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribEngineEventTableDesc.java
@@ -20,61 +20,34 @@
package org.openecomp.sdc.be.dao.cassandra.schema.tables;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import com.datastax.driver.core.DataType;
-public class DistribEngineEventTableDesc implements ITableDescription {
- @Override
- public List<ImmutablePair<String, DataType>> primaryKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
- return keys;
- }
-
- @Override
- public List<ImmutablePair<String, DataType>> clusteringKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
- return keys;
- }
-
- @Override
- public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
- Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+public class DistribEngineEventTableDesc extends DistribBaseEventTableDesc {
- for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
- columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
- }
-
- return columns;
- }
+ @Override
+ protected void updateColumnDistribDescription(Map<String, ImmutablePair<DataType, Boolean>> columns) {
+ for (DEEFieldsDescription field : DEEFieldsDescription.values()) {
+ columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
+ }
+ //replace the base indexed flag value with the correct one for a given table:
+ columns.put(DistFieldsDescription.REQUEST_ID.getName(),
+ new ImmutablePair<DataType, Boolean>(DistFieldsDescription.REQUEST_ID.getType(), true));
+ }
- @Override
- public String getKeyspace() {
- return AuditingTypesConstants.AUDIT_KEYSPACE;
- }
- @Override
+ @Override
public String getTableName() {
return AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE;
}
enum DEEFieldsDescription {
- ACTION("action", DataType.varchar(), true),
- STATUS("status", DataType.varchar(), false),
- DESCRIPTION("description", DataType.varchar(), false),
CONSUMER_ID("consumer_id", DataType.varchar(), false),
- REQUEST_ID("request_id", DataType.varchar(), true),
- SERVICE_INST_ID("service_instance_id", DataType.varchar(), false),
- ROLE("role", DataType.varchar(), false),
+ ROLE("role", DataType.varchar(), false),
D_ENV("d_env", DataType.varchar(), false),
API_KEY("api_key", DataType.varchar(), false),
DSTATUS_TOPIC("dstatus_topic", DataType.varchar(), false),
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java
index 371b5c4886..7db070f2d5 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribNotifEventTableDesc.java
@@ -20,46 +20,23 @@
package org.openecomp.sdc.be.dao.cassandra.schema.tables;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import com.datastax.driver.core.DataType;
-public class DistribNotifEventTableDesc implements ITableDescription {
- @Override
- public List<ImmutablePair<String, DataType>> primaryKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
- return keys;
- }
-
- @Override
- public List<ImmutablePair<String, DataType>> clusteringKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
- return keys;
- }
+public class DistribNotifEventTableDesc extends DistribBaseEventTableDesc {
@Override
- public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
- Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
-
+ protected void updateColumnDistribDescription(Map<String, ImmutablePair<DataType, Boolean>> columns) {
for (DNEFieldsDescription field : DNEFieldsDescription.values()) {
columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
}
-
- return columns;
- }
-
- @Override
- public String getKeyspace() {
- return AuditingTypesConstants.AUDIT_KEYSPACE;
+ //replace the base indexed flag value with the correct one for a given table:
+ columns.put(DistFieldsDescription.SERVICE_INST_ID.getName(),
+ new ImmutablePair<DataType, Boolean>(DistFieldsDescription.SERVICE_INST_ID.getType(), true));
}
@Override
@@ -68,18 +45,16 @@ public class DistribNotifEventTableDesc implements ITableDescription {
}
enum DNEFieldsDescription {
- ACTION("action", DataType.varchar(), true),
- STATUS("status", DataType.varchar(), false),
- DESCRIPTION("description", DataType.varchar(), false),
- REQUEST_ID("request_id", DataType.varchar(), false),
- SERVICE_INST_ID("service_instance_id", DataType.varchar(), true),
- TOPIC_NAME("topic_name", DataType.varchar(), false),
+ TOPIC_NAME("topic_name", DataType.varchar(), false),
MODIFIER("modifier", DataType.varchar(), false),
CURR_STATE("curr_state", DataType.varchar(), false),
CURR_VERSION("curr_version", DataType.varchar(), false),
DID("did", DataType.varchar(), true),
RESOURCE_NAME("resource_name", DataType.varchar(), false),
- RESOURCE_TYPE("resource_type", DataType.varchar(), false);
+ RESOURCE_TYPE("resource_type", DataType.varchar(), false),
+ ENV_ID("env_id", DataType.varchar(), false),
+ VNF_WORKLOAD_CONTEXT("vnf_workload_context", DataType.varchar(), false),
+ TENANT("tenant", DataType.varchar(), false);
private String name;
private DataType type;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java
index fe5bb465c3..bc5dcec41b 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/DistribStatusEventTableDesc.java
@@ -20,46 +20,20 @@
package org.openecomp.sdc.be.dao.cassandra.schema.tables;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import com.datastax.driver.core.DataType;
-public class DistribStatusEventTableDesc implements ITableDescription {
- @Override
- public List<ImmutablePair<String, DataType>> primaryKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMEBASED_UUID_FIELD, DataType.timeuuid()));
- return keys;
- }
-
- @Override
- public List<ImmutablePair<String, DataType>> clusteringKeys() {
- List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
- keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
- return keys;
- }
+public class DistribStatusEventTableDesc extends DistribBaseEventTableDesc{
@Override
- public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
- Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
-
+ protected void updateColumnDistribDescription(Map<String, ImmutablePair<DataType, Boolean>> columns) {
for (DSEFieldsDescription field : DSEFieldsDescription.values()) {
columns.put(field.getName(), new ImmutablePair<DataType, Boolean>(field.type, field.indexed));
}
-
- return columns;
- }
-
- @Override
- public String getKeyspace() {
- return AuditingTypesConstants.AUDIT_KEYSPACE;
}
@Override
@@ -68,15 +42,10 @@ public class DistribStatusEventTableDesc implements ITableDescription {
}
enum DSEFieldsDescription {
- ACTION("action", DataType.varchar(), true),
- STATUS("status", DataType.varchar(), false),
- DESCRIPTION("description", DataType.varchar(), false),
- DID("did", DataType.varchar(), true),
+ DID("did", DataType.varchar(), true),
CONSUMER_ID("consumer_id", DataType.varchar(), false),
- REQUEST_ID("request_id", DataType.varchar(), false),
- RESOURCE_URL("resoure_URL", DataType.varchar(), false),
- SERVICE_INST_ID("service_instance_id", DataType.varchar(), false),
- TOPIC_NAME("topic_name", DataType.varchar(), false),
+ RESOURCE_URL("resoure_URL", DataType.varchar(), false),
+ TOPIC_NAME("topic_name", DataType.varchar(), false),
STATUS_TIME("status_time", DataType.varchar(), false);
private String name;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java
new file mode 100644
index 0000000000..6c8fcb4991
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/EcompOperationalEnvironmentEventTableDesc.java
@@ -0,0 +1,76 @@
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import com.datastax.driver.core.DataType;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import java.util.*;
+
+public class EcompOperationalEnvironmentEventTableDesc implements ITableDescription {
+
+ private static final String OPERATIONAL_ENVIRONMENT_ID = "operational_environment_id";
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(OPERATIONAL_ENVIRONMENT_ID, DataType.varchar()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>(TIMESTAMP_FIELD, DataType.timestamp()));
+ return keys;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.AUDIT_KEYSPACE;
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+
+ Arrays.stream(EcompOpEnvFieldsDescription.values())
+ .forEach(column -> columns.put(column.getName(), ImmutablePair.of(column.getType(), column.isIndexed())));
+ return columns;
+ }
+
+ @Override
+ public String getTableName() {
+ return AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE;
+ }
+
+ enum EcompOpEnvFieldsDescription {
+ ACTION("action", DataType.varchar(), false),
+ OPERATIONAL_ENVIRONMENT_NAME("operational_environment_name", DataType.varchar(), false),
+ OPERATIONAL_ENVIRONMENT_TYPE("operational_environment_type", DataType.varchar(), false),
+ OPERATIONAL_ENVIRONMENT_ACTION("operational_environment_action", DataType.varchar(), false),
+ TENANT_CONTEXT("tenant_context", DataType.varchar(), false);
+
+ private String name;
+ private DataType type;
+ private boolean indexed;
+
+ EcompOpEnvFieldsDescription(String name, DataType type, boolean indexed) {
+ this.name = name;
+ this.type = type;
+ this.indexed = indexed;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public DataType getType() {
+ return type;
+ }
+
+ public boolean isIndexed() {
+ return indexed;
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java
new file mode 100644
index 0000000000..f14e50b8aa
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/OperationalEnvironmentsTableDescription.java
@@ -0,0 +1,79 @@
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import com.datastax.driver.core.DataType;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import java.util.*;
+
+
+public class OperationalEnvironmentsTableDescription implements ITableDescription {
+
+ private static final String OPERATIONAL_ENVIRONMENT_TABLE = "operationalEnvironment";
+ private static final String ENVIRONMENT_ID = "environment_id";
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ List<ImmutablePair<String, DataType>> keys = new ArrayList<>();
+ keys.add(new ImmutablePair<String, DataType>( ENVIRONMENT_ID, DataType.varchar()));
+ return keys;
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ return new LinkedList<>();
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+ Arrays.stream(SdcOperationalEnvironmentFieldsDescription.values())
+ .forEach(column -> columns.put(column.getFieldName(), ImmutablePair.of(column.getFieldType(), column.isIndexed())));
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.REPO_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return OPERATIONAL_ENVIRONMENT_TABLE;
+ }
+
+ enum SdcOperationalEnvironmentFieldsDescription {
+ //there is also PK field "environmentID"
+ TENANT("tenant", DataType.varchar(), false),
+ IS_PRODUCTION("is_production", DataType.cboolean(), false),
+ ECOMP_WORKLOAD_CONTEXT("ecomp_workload_context", DataType.varchar(), false),
+ DMAAP_UEB_ADDRESS("dmaap_ueb_address", DataType.set(DataType.varchar()), false),
+ UEB_API_KEY("ueb_api_key",DataType.varchar(), false),
+ UEB_SECRET_KEY("ueb_secret_key",DataType.varchar(), false),
+ STATUS("status",DataType.varchar() ,true),
+ LAST_MODIFIED("last_modified",DataType.timestamp() ,false);
+
+ private String fieldName;
+ private boolean isIndexed;
+ private DataType fieldType;
+
+ SdcOperationalEnvironmentFieldsDescription(String fieldName, DataType dataType, boolean indexed ) {
+ this.fieldName = fieldName;
+ this.fieldType = dataType;
+ this.isIndexed = indexed;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public boolean isIndexed() {
+ return isIndexed;
+ }
+
+ public DataType getFieldType() {
+ return fieldType;
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java
index c5f066bb4b..99979bac0c 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/DAOSpringConfig.java
@@ -20,34 +20,22 @@
package org.openecomp.sdc.be.dao.config;
-import org.openecomp.sdc.be.dao.DAOTitanStrategy;
-import org.openecomp.sdc.be.dao.TitanClientStrategy;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
+import org.springframework.context.annotation.Import;
@Configuration
+@Import({TitanSpringConfig.class})
+@ComponentScan({
+ "org.openecomp.sdc.be.dao.cassandra",
+ "org.openecomp.sdc.be.dao.neo4j",
+ "org.openecomp.sdc.be.dao.es",
+ "org.openecomp.sdc.be.dao.impl",
+ "org.openecomp.sdc.be.resources.impl"
+ })
public class DAOSpringConfig {
- @Bean(name = "titan-generic-dao")
- @Primary
- public TitanGenericDao titanGenericDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) {
- return new TitanGenericDao(titanGraphClient);
- }
-
- @Bean(name = "titan-client", initMethod = "createGraph")
- @Primary
- public TitanGraphClient titanGraphClient(@Qualifier("dao-client-strategy") TitanClientStrategy titanClientStrategy) {
- return new TitanGraphClient(titanClientStrategy);
- }
-
- @Bean(name = "dao-client-strategy")
- public TitanClientStrategy titanClientStrategy() {
- return new DAOTitanStrategy();
- }
+
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java
new file mode 100644
index 0000000000..111c63e53c
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/config/TitanSpringConfig.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.be.dao.config;
+
+import org.openecomp.sdc.be.dao.DAOTitanStrategy;
+import org.openecomp.sdc.be.dao.TitanClientStrategy;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+@Configuration
+@ComponentScan({
+ "org.openecomp.sdc.be.dao.jsongraph",
+})
+public class TitanSpringConfig {
+
+ @Bean(name = "titan-generic-dao")
+ @Primary
+ public TitanGenericDao titanGenericDao(@Qualifier("titan-client") TitanGraphClient titanGraphClient) {
+ return new TitanGenericDao(titanGraphClient);
+ }
+
+ @Bean(name = "titan-client", initMethod = "createGraph")
+ @Primary
+ public TitanGraphClient titanGraphClient(@Qualifier("dao-client-strategy") TitanClientStrategy titanClientStrategy) {
+ return new TitanGraphClient(titanClientStrategy);
+ }
+
+ @Bean(name = "dao-client-strategy")
+ public TitanClientStrategy titanClientStrategy() {
+ return new DAOTitanStrategy();
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java
index 4bc1afc80e..c5d7d68b55 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/es/ElasticSearchClient.java
@@ -33,14 +33,10 @@ import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.commons.lang.SystemUtils;
-import org.elasticsearch.action.admin.cluster.health.ClusterHealthAction;
-import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder;
-import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
-import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.elasticsearch.shield.ShieldPlugin;
@@ -174,34 +170,6 @@ public class ElasticSearchClient {
return serverPort;
}
- /**
- * Wait for green status for the given indices.
- *
- * @param indices
- * The indices to wait for.
- * @return A {@link ClusterHealthResponse} that contains the cluster health
- * after waiting maximum 5 minutes for green status.
- */
- public ClusterHealthResponse waitForGreenStatus(String... indices) {
- ClusterHealthAction healthAction = ClusterHealthAction.INSTANCE;
-
- ClusterHealthRequestBuilder builder = healthAction.newRequestBuilder(this.client.admin().cluster());
- builder.setIndices(indices);
- builder.setWaitForGreenStatus();
- builder.setTimeout(TimeValue.timeValueSeconds(30));
- ClusterHealthResponse response = builder.execute().actionGet();
- log.debug("getStatus : {}", response.getStatus());
- log.debug("getActivePrimaryShards : {}", response.getActivePrimaryShards());
- log.debug("getActiveShards : {}", response.getActiveShards());
- log.debug("getInitializingShards : {}", response.getInitializingShards());
- log.debug("getNumberOfDataNodes : {}", response.getNumberOfDataNodes());
- log.debug("getNumberOfNodes : {}", response.getNumberOfNodes());
- log.debug("getRelocatingShards : {}", response.getRelocatingShards());
- log.debug("getUnassignedShards : {}", response.getUnassignedShards());
- log.debug("getAllValidationFailures : {}", response.getAllValidationFailures());
- return response;
- }
-
@Value("#{elasticsearchConfig['cluster.name']}")
public void setClusterName(final String clusterName) {
this.clusterName = clusterName;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java
index 5da11cb738..968381d662 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphNode.java
@@ -20,14 +20,13 @@
package org.openecomp.sdc.be.dao.graph.datatype;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.Gson;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.Gson;
+import java.util.List;
+import java.util.Map;
public abstract class GraphNode extends GraphElement {
@@ -67,7 +66,7 @@ public abstract class GraphNode extends GraphElement {
return GraphPropertiesDictionary.UNIQUE_ID.getProperty();
}
- public abstract Object getUniqueId();
+ public abstract String getUniqueId();
@Override
public String toString() {
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java
index 2cf479ec64..dfa2b3ac4a 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java
@@ -92,6 +92,13 @@ public class AuditingDao extends ESTimeBasedDao {
return write(type, auditingGenericEvent);
}
+ public ActionStatus addRecord(AuditingGenericEvent auditEvent, String type) {
+
+ log.debug("Auditing: Persisting object of type {}, fields: {}", type, auditEvent.getAction());
+// auditEvent.fillFields();
+ return write(type, auditEvent);
+ }
+
public Either<List<ESTimeBasedEvent>, ActionStatus> getListOfDistributionStatuses(String did) {
QueryBuilder componentNameMatch = QueryBuilders.matchQuery(DISTRIBUTION_ID_FIELD, did);
@@ -104,10 +111,7 @@ public class AuditingDao extends ESTimeBasedDao {
remainingElements = customFindEvent(AuditingTypesConstants.DISTRIBUTION_STATUS_EVENT_TYPE,
remainingElementQueryBuilder, null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
-
log.debug("failed to get distribution statuses for ", e);
return Either.right(ActionStatus.GENERAL_ERROR);
}
@@ -134,8 +138,6 @@ public class AuditingDao extends ESTimeBasedDao {
remainingElements = customFindEvent(AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE,
remainingElementQueryBuilder, null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Service DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
log.debug("failed to get distribution statuses for action {}",
AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), e);
@@ -153,8 +155,6 @@ public class AuditingDao extends ESTimeBasedDao {
dResultElements = customFindEvent(AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE,
remainingElementQueryBuilder, null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Service DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
log.debug("failed to get distribution statuses for action {}",
AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), e);
@@ -172,8 +172,6 @@ public class AuditingDao extends ESTimeBasedDao {
dNotifyElements = customFindEvent(AuditingTypesConstants.DISTRIBUTION_NOTIFICATION_EVENT_TYPE,
remainingElementQueryBuilder, null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Service DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
log.debug("failed to get distribution statuses for action {}",
AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), e);
@@ -229,8 +227,6 @@ public class AuditingDao extends ESTimeBasedDao {
remainingElements = customFindEvent(clazz.getSimpleName().toLowerCase(), remainingElementQueryBuilder,
null);
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get DistributionStatuses List");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
log.debug("failed to get distribution statuses for action {}", actionType, e);
return Either.right(ActionStatus.GENERAL_ERROR);
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java
index 0efff500d0..6a2600a3b2 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java
@@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
-import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
+import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.common.unit.TimeValue;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -111,11 +111,8 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO {
private void logAlarm() {
if (lastHealthState == HealthCheckStatus.UP) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery,
- ES_HEALTH_CHECK_STR);
BeEcompErrorManager.getInstance().logBeHealthCheckElasticSearchRecovery(ES_HEALTH_CHECK_STR);
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, ES_HEALTH_CHECK_STR);
BeEcompErrorManager.getInstance().logBeHealthCheckElasticSearchError(ES_HEALTH_CHECK_STR);
}
}
@@ -148,8 +145,6 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO {
resData = findById(getTypeFromClass(ESArtifactData.class), id, ESArtifactData.class);
} catch (Exception e) {
resData = null;
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Get Artifact from database");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Artifact from database");
log.debug("ESCatalogDAO:getArtifact failed with exception ", e);
return Either.right(ResourceUploadStatus.ERROR);
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java
index d38e9c03df..c55902a62b 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertex.java
@@ -20,10 +20,7 @@
package org.openecomp.sdc.be.dao.jsongraph;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
+import com.thinkaurelius.titan.core.TitanVertex;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
@@ -32,7 +29,9 @@ 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 com.thinkaurelius.titan.core.TitanVertex;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
public class GraphVertex {
private String uniqueId;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
index 387b413dd5..27303613ea 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
@@ -64,860 +64,964 @@ import fj.data.Either;
@Component("titan-dao")
public class TitanDao {
- TitanGraphClient titanClient;
-
- private static Logger logger = LoggerFactory.getLogger(TitanDao.class.getName());
-
- public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) {
- this.titanClient = titanClient;
- logger.info("** TitanDao created");
- }
-
- public TitanOperationStatus commit() {
- logger.debug("doing commit.");
- return titanClient.commit();
- }
-
- public TitanOperationStatus rollback() {
- return titanClient.rollback();
- }
-
- public Either<TitanGraph, TitanOperationStatus> getGraph() {
- return titanClient.getGraph();
- }
-
- /**
- *
- * @param graphVertex
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> createVertex(GraphVertex graphVertex) {
- logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId());
- Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
- if (graph.isLeft()) {
- try {
- TitanGraph tGraph = graph.left().value();
-
- TitanVertex vertex = tGraph.addVertex();
-
- setVertexProperties(vertex, graphVertex);
-
- graphVertex.setVertex(vertex);
-
- return Either.left(graphVertex);
-
- } catch (Exception e) {
- logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e);
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- } else {
- logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value());
- return Either.right(graph.right().value());
- }
- }
-
- /**
- *
- * @param name
- * @param value
- * @param label
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) {
- return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll);
- }
-
- /**
- *
- * @param name
- * @param value
- * @param label
- * @param parseFlag
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label, JsonParseFlagEnum parseFlag) {
-
- Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
- if (graph.isLeft()) {
- try {
- TitanGraph tGraph = graph.left().value();
-
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertecies = tGraph.query().has(name.getProperty(), value).has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices();
-
- java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
- if (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- GraphVertex graphVertex = createAndFill(vertex, parseFlag);
-
- return Either.left(graphVertex);
- }
- if (logger.isDebugEnabled()) {
- logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label);
- }
- return Either.right(TitanOperationStatus.NOT_FOUND);
- } catch (Exception e) {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label);
- }
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
-
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value());
- }
- return Either.right(graph.right().value());
- }
- }
-
- /**
- *
- * @param id
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> getVertexById(String id) {
- return getVertexById(id, JsonParseFlagEnum.ParseAll);
- }
-
- /**
- *
- * @param id
- * @param parseFlag
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> getVertexById(String id, JsonParseFlagEnum parseFlag) {
-
- Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
- if (id == null) {
- if (logger.isDebugEnabled()) {
- logger.debug("No vertex in graph for id = {} ", id);
- }
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- if (graph.isLeft()) {
- try {
- TitanGraph tGraph = graph.left().value();
-
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices();
-
- java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
- if (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- GraphVertex graphVertex = createAndFill(vertex, parseFlag);
- return Either.left(graphVertex);
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("No vertex in graph for id = {}", id);
- }
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- } catch (Exception e) {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed to get vertex in graph for id {} ", id);
- }
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value());
- }
- return Either.right(graph.right().value());
- }
- }
-
- private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException {
-
- if (graphVertex.getMetadataProperties() != null) {
- for (Map.Entry<GraphPropertyEnum, Object> entry : graphVertex.getMetadataProperties().entrySet()) {
- if (entry.getValue() != null) {
- vertex.property(entry.getKey().getProperty(), entry.getValue());
- }
- }
- }
- vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName());
-
- Map<String, ? extends ToscaDataDefinition> json = graphVertex.getJson();
- if (json != null) {
- String jsonStr = JsonParserUtils.jsonToString(json);
- vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr);
-
- }
- Map<String, Object> jsonMetadata = graphVertex.getMetadataJson();
- if (jsonMetadata != null) {
- String jsonMetadataStr = JsonParserUtils.jsonToString(jsonMetadata);
- vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr);
- }
- }
-
- public void setVertexProperties(Vertex vertex, Map<String, Object> properties) throws IOException {
- for (Map.Entry<String, Object> entry : properties.entrySet()) {
- if (entry.getValue() != null) {
- vertex.property(entry.getKey(), entry.getValue());
- }
- }
- }
-
- private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) {
- GraphVertex graphVertex = new GraphVertex();
- graphVertex.setVertex(vertex);
- parseVertexProperties(graphVertex, parseFlag);
- return graphVertex;
- }
-
- public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag ) {
- TitanVertex vertex = graphVertex.getVertex();
- Map<GraphPropertyEnum, Object> properties = getVertexProperties(vertex);
- VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL)));
- for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) {
- GraphPropertyEnum key = entry.getKey();
- switch (key) {
- case UNIQUE_ID:
- graphVertex.setUniqueId((String) entry.getValue());
- break;
- case LABEL:
- graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue()));
- break;
- case COMPONENT_TYPE:
- String type = (String) entry.getValue();
- if (type != null) {
- graphVertex.setType(ComponentTypeEnum.valueOf(type));
- }
- break;
- case JSON:
- if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) {
- String json = (String) entry.getValue();
- Map<String, ? extends ToscaDataDefinition> jsonObj = JsonParserUtils.parseToJson(json, label.getClassOfJson());
- graphVertex.setJson(jsonObj);
- }
- break;
- case METADATA:
- if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) {
- String json = (String) entry.getValue();
- Map<String, Object> metadatObj = JsonParserUtils.parseToJson(json);
- graphVertex.setMetadataJson(metadatObj);
- }
- break;
- default:
- graphVertex.addMetadataProperty(key, entry.getValue());
- break;
- }
- }
- }
-
- public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) {
- return createEdge(from.getVertex(), to.getVertex(), label, properties);
- }
-
- public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) {
- if (logger.isTraceEnabled()) {
- logger.trace("Try to connect {} with {} label {} properties {}", from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties);
- }
- if (from == null || to == null) {
- logger.trace("No Titan vertex for id from {} or id to {}", from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
- return TitanOperationStatus.NOT_FOUND;
- }
- Edge edge = from.addEdge(label.name(), to);
- setEdgeProperties(edge, properties);
- return TitanOperationStatus.OK;
- }
-
- public Map<GraphPropertyEnum, Object> getVertexProperties(Element element) {
-
- Map<GraphPropertyEnum, Object> result = new HashMap<GraphPropertyEnum, Object>();
-
- if (element != null && element.keys() != null && element.keys().size() > 0) {
- Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
-
- for (Entry<String, Property> entry : propertyMap.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue().value();
-
- GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key);
- if (valueOf != null) {
- result.put(valueOf, value);
- }
- }
- }
- return result;
- }
-
- public Map<EdgePropertyEnum, Object> getEdgeProperties(Element element) {
-
- Map<EdgePropertyEnum, Object> result = new HashMap<EdgePropertyEnum, Object>();
-
- if (element != null && element.keys() != null && element.keys().size() > 0) {
- Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
-
- for (Entry<String, Property> entry : propertyMap.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue().value();
-
- EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key);
- if (valueOf != null) {
- result.put(valueOf, value);
- }
- }
- }
- return result;
- }
-
- public void setEdgeProperties(Element element, Map<EdgePropertyEnum, Object> properties) {
-
- if (properties != null && !properties.isEmpty()) {
-
- Object[] propertyKeyValues = new Object[properties.size() * 2];
- int i = 0;
- for (Entry<EdgePropertyEnum, Object> entry : properties.entrySet()) {
- propertyKeyValues[i++] = entry.getKey().getProperty();
- propertyKeyValues[i++] = entry.getValue();
- }
-
- ElementHelper.attachProperties(element, propertyKeyValues);
-
- }
-
- }
-
- public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props) {
- return getByCriteria(type, props, JsonParseFlagEnum.ParseAll);
- }
-
- public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props, JsonParseFlagEnum parseFlag) {
- Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
- if (graph.isLeft()) {
- try {
- TitanGraph tGraph = graph.left().value();
-
- TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
- if (type != null) {
- query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
- }
-
- if (props != null && !props.isEmpty()) {
- for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) {
- query = query.has(entry.getKey().getProperty(), entry.getValue());
- }
- }
- Iterable<TitanVertex> vertices = query.vertices();
- if (vertices == null) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- Iterator<TitanVertex> iterator = vertices.iterator();
- List<GraphVertex> result = new ArrayList<GraphVertex>();
-
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
-
- Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex);
- GraphVertex graphVertex = createAndFill(vertex, parseFlag);
-
- result.add(graphVertex);
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size());
- }
- if (result.size() == 0) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- return Either.left(result);
- } catch (Exception e) {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
- }
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
-
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value());
- }
- return Either.right(graph.right().value());
- }
- }
- public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props, Map<GraphPropertyEnum, Object> hasNotProps, JsonParseFlagEnum parseFlag) {
- Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
- if (graph.isLeft()) {
- try {
- TitanGraph tGraph = graph.left().value();
-
- TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
- if (type != null) {
- query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
- }
-
- if (props != null && !props.isEmpty()) {
- for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) {
- query = query.has(entry.getKey().getProperty(), entry.getValue());
- }
- }
- if (hasNotProps != null && !hasNotProps.isEmpty()) {
- for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) {
- if(entry.getValue() instanceof List){
- buildMultipleNegateQueryFromList(entry, query);
- }else{
- query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
- }
- }
- }
- Iterable<TitanVertex> vertices = query.vertices();
- if (vertices == null) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- Iterator<TitanVertex> iterator = vertices.iterator();
- List<GraphVertex> result = new ArrayList<GraphVertex>();
-
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
-
- Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex);
- GraphVertex graphVertex = createAndFill(vertex, parseFlag);
-
- result.add(graphVertex);
- }
- if (logger.isDebugEnabled()) {
- logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size());
- }
- if (result.size() == 0) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- return Either.left(result);
- } catch (Exception e) {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
- }
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
-
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value());
- }
- return Either.right(graph.right().value());
- }
- }
-
-
-
- private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, TitanGraphQuery query){
- List<Object> negateList = (List<Object>) entry.getValue();
- for (Object listItem : negateList) {
- query.hasNot(entry.getKey().getProperty(), listItem);
- }
- }
-
-
- /**
- *
- * @param parentVertex
- * @param edgeLabel
- * @param parseFlag
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
- Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag);
- if (childrenVertecies.isRight()) {
- return Either.right(childrenVertecies.right().value());
- }
- return Either.left(childrenVertecies.left().value().get(0));
- }
-
- public Either<GraphVertex, TitanOperationStatus> getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
- Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag);
- if (childrenVertecies.isRight()) {
- return Either.right(childrenVertecies.right().value());
- }
- return Either.left(childrenVertecies.left().value().get(0));
- }
-
- /**
- *
- * @param parentVertex
- * @param edgeLabel
- * @param parseFlag
- * @return
- */
- public Either<List<GraphVertex>, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
- return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT);
- }
-
- public Either<List<GraphVertex>, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
- return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN);
- }
-
- private Either<List<GraphVertex>, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) {
- List<GraphVertex> list = new ArrayList<GraphVertex>();
-
- try {
- Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph();
- if (graphRes.isRight()) {
- logger.error("Failed to retrieve graph. status is {}", graphRes);
- return Either.right(graphRes.right().value());
- }
- Iterator<Edge> edgesCreatorIterator = parentVertex.getVertex().edges(direction, edgeLabel.name());
- if (edgesCreatorIterator != null) {
- while (edgesCreatorIterator.hasNext()) {
- Edge edge = edgesCreatorIterator.next();
- TitanVertex vertex;
- if (direction == Direction.IN) {
- vertex = (TitanVertex) edge.outVertex();
- } else {
- vertex = (TitanVertex) edge.inVertex();
- }
- GraphVertex graphVertex = createAndFill(vertex, parseFlag);
-
- list.add(graphVertex);
- }
- }
- if (true == list.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- } catch (Exception e) {
- logger.error("Failed to perform graph operation ", e);
- Either.right(TitanGraphClient.handleTitanException(e));
- }
-
- return Either.left(list);
- }
-
- /**
- * Searches Edge by received label and criteria
- *
- * @param vertex
- * @param label
- * @param properties
- * @return found edge or TitanOperationStatus
- */
- public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) {
-
- Either<Edge, TitanOperationStatus> result = null;
- Edge matchingEdge = null;
- String notFoundMsg = "No edges in graph for criteria";
- try {
- TitanVertexQuery<?> query = vertex.getVertex().query().labels(label.name());
-
- if (properties != null && !properties.isEmpty()) {
- for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) {
- query = query.has(entry.getKey().getProperty(), entry.getValue());
- }
- }
-
- Iterable<TitanEdge> edges = query.edges();
- if (edges == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
- result = Either.right(TitanOperationStatus.NOT_FOUND);
- } else {
- Iterator<TitanEdge> eIter = edges.iterator();
- if (eIter.hasNext()) {
- matchingEdge = eIter.next();
- } else {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
- result = Either.right(TitanOperationStatus.NOT_FOUND);
- }
- }
- if (result == null) {
- result = Either.left(matchingEdge);
- }
- } catch (Exception e) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e);
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- return result;
- }
-
- /**
- * Deletes Edge by received label and criteria
- *
- * @param vertex
- * @param label
- * @param properties
- * @return
- */
- public Either<Edge, TitanOperationStatus> deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) {
- Either<Edge, TitanOperationStatus> result = null;
- try {
- result = getBelongingEdgeByCriteria(vertex, label, properties);
- if (result.isLeft()) {
- Edge edge = result.left().value();
- CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId());
- edge.remove();
- result = Either.left(edge);
- } else {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId());
- }
- } catch (Exception e) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}", vertex.getUniqueId(), e);
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- return result;
- }
-
- @SuppressWarnings("unchecked")
- /**
- * Deletes an edge between vertices fromVertex and toVertex according to received label
- *
- * @param fromVertex
- * @param toVertex
- * @param label
- * @return
- */
- public Either<Edge, TitanOperationStatus> deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) {
- Either<Edge, TitanOperationStatus> result = null;
- try {
- Iterable<TitanEdge> edges = fromVertex.getVertex().query().labels(label.name()).edges();
- Iterator<TitanEdge> eIter = edges.iterator();
- while (eIter.hasNext()) {
- Edge edge = eIter.next();
- String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty());
- if (currVertexUniqueId != null && currVertexUniqueId.equals(toVertex.getUniqueId())) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), fromVertex.getUniqueId(), toVertex.getUniqueId());
- edge.remove();
- result = Either.left(edge);
- break;
- }
- }
- if (result == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), fromVertex.getUniqueId(), toVertex.getUniqueId());
- result = Either.right(TitanOperationStatus.NOT_FOUND);
- }
- } catch (Exception e) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), fromVertex.getUniqueId(), toVertex.getUniqueId(), e);
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- return result;
- }
-
- public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) {
- try {
- Iterator<Edge> edges = fromVertex.getVertex().edges(direction, label.name());
-
- while (edges.hasNext()) {
- Edge edge = edges.next();
- edge.remove();
- }
- } catch (Exception e) {
- logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e);
- return TitanGraphClient.handleTitanException(e);
- }
- return TitanOperationStatus.OK;
- }
-
- /**
- * Updates vertex properties. Note that graphVertex argument should contain updated data
- *
- * @param graphVertex
- * @return
- */
- public Either<GraphVertex, TitanOperationStatus> updateVertex(GraphVertex graphVertex) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId());
- try {
- graphVertex.updateMetadataJsonWithCurrentMetadataProperties();
- setVertexProperties(graphVertex.getVertex(), graphVertex);
-
- } catch (Exception e) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e);
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- return Either.left(graphVertex);
- }
-
- /**
- * Fetches vertices by uniqueId according to received parse flag
- *
- * @param verticesToGet
- * @return
- */
- public Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag(Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGet) {
-
- Either<Map<String, GraphVertex>, TitanOperationStatus> result = null;
- Map<String, GraphVertex> vertices = new HashMap<>();
- TitanOperationStatus titatStatus;
- Either<GraphVertex, TitanOperationStatus> getVertexRes = null;
- for (Map.Entry<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> entry : verticesToGet.entrySet()) {
- if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) {
- getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue());
- } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) {
- getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER, entry.getValue().getValue());
- }
- if (getVertexRes == null) {
- titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT;
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus);
- result = Either.right(titatStatus);
- }
- if (getVertexRes.isRight()) {
- titatStatus = getVertexRes.right().value();
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus);
- result = Either.right(titatStatus);
- break;
- } else {
- vertices.put(entry.getKey(), getVertexRes.left().value());
- }
- }
- if (result == null) {
- result = Either.left(vertices);
- }
- return result;
- }
-
- /**
- * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge
- *
- * @param from
- * @param to
- * @param label
- * @param edgeToCopy
- * @return
- */
- public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) {
- return createEdge(from, to, label, getEdgeProperties(edgeToCopy));
- }
-
- public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) {
-
- CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
- toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
- TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge);
- if (result == TitanOperationStatus.OK) {
- prevEdge.remove();
- }
- return result;
- }
-
- /**
- * Replaces previous label of edge with new label
- *
- * @param fromVertex
- * @param toVertex
- * @param prevLabel
- * @param newLabel
- * @return
- */
- public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) {
-
- TitanOperationStatus result = null;
- Iterator<Edge> prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name());
- if (prevEdgeIter == null || !prevEdgeIter.hasNext()) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
- toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
- result = TitanOperationStatus.NOT_FOUND;
- }
- if (result == null) {
- result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel);
- }
- return result;
- }
-
- /**
- * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too.
- *
- *
- * @param vertex
- * @param properties
- * @return
- */
- public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map<GraphPropertyEnum, Object> properties) {
- try {
- if (!MapUtils.isEmpty(properties)) {
- String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value();
- Map<String, Object> jsonMetadataMap = JsonParserUtils.parseToJson(jsonMetadataStr);
- for (Map.Entry<GraphPropertyEnum, Object> property : properties.entrySet()) {
- vertex.property(property.getKey().getProperty(), property.getValue());
- jsonMetadataMap.put(property.getKey().getProperty(), property.getValue());
- }
- vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap));
- }
- } catch (Exception e) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update vertex metadata properties with json{}. {}", vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage());
- return TitanGraphClient.handleTitanException(e);
- }
- return TitanOperationStatus.OK;
- }
-
- public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) {
- try {
- Iterator<Edge> edges = vertex.getVertex().edges(direction, label.name());
-
- while (edges.hasNext()) {
- Edge edge = edges.next();
- Vertex secondVertex;
- Direction reverseDirection;
- if (direction == Direction.IN) {
- secondVertex = edge.outVertex();
- reverseDirection = Direction.OUT;
- } else {
- secondVertex = edge.inVertex();
- reverseDirection = Direction.IN;
- }
- edge.remove();
- CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex());
-
- Iterator<Edge> restOfEdges = secondVertex.edges(reverseDirection, label.name());
- if (restOfEdges.hasNext() == false) {
- secondVertex.remove();
- CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId());
- }
- }
- } catch (Exception e) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction, vertex.getUniqueId(), e);
- return TitanGraphClient.handleTitanException(e);
- }
- return TitanOperationStatus.OK;
- }
-
- public Object getProperty(TitanVertex vertex, String key) {
- PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key);
- Object value = vertex.valueOrNull(propertyKey);
- return value;
- }
-
- public Object getProperty(Edge edge, EdgePropertyEnum key) {
- Object value = null;
- try {
- Property<Object> property = edge.property(key.getProperty());
- if (property != null) {
- return property.orElse(null);
- }
- } catch (Exception e) {
-
- }
- return value;
- }
- /**
- *
- * @param vertexA
- * @param vertexB
- * @param label
- * @param direction
- * @return
- */
- public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) {
- TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label);
- if ( result != TitanOperationStatus.OK ){
- logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result);
- return result;
- }
- TitanOperationStatus createRelation;
- if (direction == Direction.IN ){
- createRelation = createEdge(vertexB, vertexA, label, null);
- }else{
- createRelation = createEdge(vertexA, vertexB, label, null);
- }
- if (createRelation != TitanOperationStatus.OK) {
- return createRelation;
- }
- return TitanOperationStatus.OK;
- }
-
- public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) {
- Either<GraphVertex, TitanOperationStatus> getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse);
- if(getVertexRes.isRight()){
- return Either.right(getVertexRes.right().value());
- }
- return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties);
- }
+ TitanGraphClient titanClient;
+
+ private static Logger logger = LoggerFactory.getLogger(TitanDao.class.getName());
+
+ public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) {
+ this.titanClient = titanClient;
+ logger.info("** TitanDao created");
+ }
+
+ public TitanOperationStatus commit() {
+ logger.debug("doing commit.");
+ return titanClient.commit();
+ }
+
+ public TitanOperationStatus rollback() {
+ return titanClient.rollback();
+ }
+
+ public Either<TitanGraph, TitanOperationStatus> getGraph() {
+ return titanClient.getGraph();
+ }
+
+ /**
+ *
+ * @param graphVertex
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> createVertex(GraphVertex graphVertex) {
+ logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId());
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanVertex vertex = tGraph.addVertex();
+
+ setVertexProperties(vertex, graphVertex);
+
+ graphVertex.setVertex(vertex);
+
+ return Either.left(graphVertex);
+
+ } catch (Exception e) {
+ logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value());
+ return Either.right(graph.right().value());
+ }
+ }
+
+ /**
+ *
+ * @param name
+ * @param value
+ * @param label
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) {
+ return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll);
+ }
+
+ public Either<GraphVertex, TitanOperationStatus> getVertexByLabel(VertexTypeEnum label) {
+ return titanClient.getGraph().left().map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()).left().bind(titanVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, titanVertices));
+ }
+
+ private Either<GraphVertex, TitanOperationStatus> getFirstFoundVertex(JsonParseFlagEnum parseFlag, Iterable<TitanVertex> vertices) {
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ if (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ GraphVertex graphVertex = createAndFill(vertex, parseFlag);
+
+ return Either.left(graphVertex);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ /**
+ *
+ * @param name
+ * @param value
+ * @param label
+ * @param parseFlag
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label, JsonParseFlagEnum parseFlag) {
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertecies = tGraph.query().has(name.getProperty(), value).has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices();
+
+ java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ GraphVertex graphVertex = createAndFill(vertex, parseFlag);
+
+ return Either.left(graphVertex);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ /**
+ *
+ * @param id
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> getVertexById(String id) {
+ return getVertexById(id, JsonParseFlagEnum.ParseAll);
+ }
+
+ /**
+ *
+ * @param id
+ * @param parseFlag
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> getVertexById(String id, JsonParseFlagEnum parseFlag) {
+
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (id == null) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for id = {} ", id);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ @SuppressWarnings("unchecked")
+ Iterable<TitanVertex> vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices();
+
+ java.util.Iterator<TitanVertex> iterator = vertecies.iterator();
+ if (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+ GraphVertex graphVertex = createAndFill(vertex, parseFlag);
+ return Either.left(graphVertex);
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for id = {}", id);
+ }
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed to get vertex in graph for id {} ", id);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException {
+
+ if (graphVertex.getMetadataProperties() != null) {
+ for (Map.Entry<GraphPropertyEnum, Object> entry : graphVertex.getMetadataProperties().entrySet()) {
+ if (entry.getValue() != null) {
+ vertex.property(entry.getKey().getProperty(), entry.getValue());
+ }
+ }
+ }
+ vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName());
+
+ Map<String, ? extends ToscaDataDefinition> json = graphVertex.getJson();
+ if (json != null) {
+ String jsonStr = JsonParserUtils.toJson(json);
+ vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr);
+
+ }
+ Map<String, Object> jsonMetadata = graphVertex.getMetadataJson();
+ if (jsonMetadata != null) {
+ String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata);
+ vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr);
+ }
+ }
+
+ public void setVertexProperties(Vertex vertex, Map<String, Object> properties) throws IOException {
+ for (Map.Entry<String, Object> entry : properties.entrySet()) {
+ if (entry.getValue() != null) {
+ vertex.property(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
+ private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) {
+ GraphVertex graphVertex = new GraphVertex();
+ graphVertex.setVertex(vertex);
+ parseVertexProperties(graphVertex, parseFlag);
+ return graphVertex;
+ }
+
+ public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) {
+ TitanVertex vertex = graphVertex.getVertex();
+ Map<GraphPropertyEnum, Object> properties = getVertexProperties(vertex);
+ VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL)));
+ for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) {
+ GraphPropertyEnum key = entry.getKey();
+ switch (key) {
+ case UNIQUE_ID:
+ graphVertex.setUniqueId((String) entry.getValue());
+ break;
+ case LABEL:
+ graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue()));
+ break;
+ case COMPONENT_TYPE:
+ String type = (String) entry.getValue();
+ if (type != null) {
+ graphVertex.setType(ComponentTypeEnum.valueOf(type));
+ }
+ break;
+ case JSON:
+ if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) {
+ String json = (String) entry.getValue();
+ Map<String, ? extends ToscaDataDefinition> jsonObj = JsonParserUtils.toMap(json, label.getClassOfJson());
+ graphVertex.setJson(jsonObj);
+ }
+ break;
+ case METADATA:
+ if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) {
+ String json = (String) entry.getValue();
+ Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
+ graphVertex.setMetadataJson(metadatObj);
+ }
+ break;
+ default:
+ graphVertex.addMetadataProperty(key, entry.getValue());
+ break;
+ }
+ }
+ }
+
+ public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) {
+ return createEdge(from.getVertex(), to.getVertex(), label, properties);
+ }
+
+ public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Try to connect {} with {} label {} properties {}", from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties);
+ }
+ if (from == null || to == null) {
+ logger.trace("No Titan vertex for id from {} or id to {}", from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
+ return TitanOperationStatus.NOT_FOUND;
+ }
+ Edge edge = from.addEdge(label.name(), to);
+ setEdgeProperties(edge, properties);
+ return TitanOperationStatus.OK;
+ }
+
+ public Map<GraphPropertyEnum, Object> getVertexProperties(Element element) {
+
+ Map<GraphPropertyEnum, Object> result = new HashMap<GraphPropertyEnum, Object>();
+
+ if (element != null && element.keys() != null && element.keys().size() > 0) {
+ Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
+
+ for (Entry<String, Property> entry : propertyMap.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue().value();
+
+ GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key);
+ if (valueOf != null) {
+ result.put(valueOf, value);
+ }
+ }
+ }
+ return result;
+ }
+
+ public Map<EdgePropertyEnum, Object> getEdgeProperties(Element element) {
+
+ Map<EdgePropertyEnum, Object> result = new HashMap<EdgePropertyEnum, Object>();
+
+ if (element != null && element.keys() != null && element.keys().size() > 0) {
+ Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
+
+ for (Entry<String, Property> entry : propertyMap.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue().value();
+
+ EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key);
+ if (valueOf != null) {
+ result.put(valueOf, value);
+ }
+ }
+ }
+ return result;
+ }
+
+ public void setEdgeProperties(Element element, Map<EdgePropertyEnum, Object> properties) {
+
+ if (properties != null && !properties.isEmpty()) {
+
+ Object[] propertyKeyValues = new Object[properties.size() * 2];
+ int i = 0;
+ for (Entry<EdgePropertyEnum, Object> entry : properties.entrySet()) {
+ propertyKeyValues[i++] = entry.getKey().getProperty();
+ propertyKeyValues[i++] = entry.getValue();
+ }
+
+ ElementHelper.attachProperties(element, propertyKeyValues);
+
+ }
+
+ }
+
+ public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props) {
+ return getByCriteria(type, props, JsonParseFlagEnum.ParseAll);
+ }
+
+ public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props, JsonParseFlagEnum parseFlag) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ if (type != null) {
+ query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
+ }
+
+ if (props != null && !props.isEmpty()) {
+ for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) {
+ query = query.has(entry.getKey().getProperty(), entry.getValue());
+ }
+ }
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ List<GraphVertex> result = new ArrayList<GraphVertex>();
+
+ while (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+
+ Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex);
+ GraphVertex graphVertex = createAndFill(vertex, parseFlag);
+
+ result.add(graphVertex);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size());
+ }
+ if (result.size() == 0) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(result);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props, Map<GraphPropertyEnum, Object> hasNotProps, JsonParseFlagEnum parseFlag) {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
+ if (type != null) {
+ query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
+ }
+
+ if (props != null && !props.isEmpty()) {
+ for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) {
+ query = query.has(entry.getKey().getProperty(), entry.getValue());
+ }
+ }
+ if (hasNotProps != null && !hasNotProps.isEmpty()) {
+ for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) {
+ if (entry.getValue() instanceof List) {
+ buildMultipleNegateQueryFromList(entry, query);
+ } else {
+ query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
+ }
+ }
+ }
+ Iterable<TitanVertex> vertices = query.vertices();
+ if (vertices == null) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ Iterator<TitanVertex> iterator = vertices.iterator();
+ List<GraphVertex> result = new ArrayList<GraphVertex>();
+
+ while (iterator.hasNext()) {
+ TitanVertex vertex = iterator.next();
+
+ Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex);
+ GraphVertex graphVertex = createAndFill(vertex, parseFlag);
+
+ result.add(graphVertex);
+ }
+ if (logger.isDebugEnabled()) {
+ logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size());
+ }
+ if (result.size() == 0) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+
+ return Either.left(result);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ public Either<Iterator<Vertex>, TitanOperationStatus> getCatalogVerticies() {
+ Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
+ if (graph.isLeft()) {
+ try {
+ TitanGraph tGraph = graph.left().value();
+
+ Iterable<TitanVertex> vCatalogIter = tGraph.query().has(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()).vertices();
+ if (vCatalogIter == null) {
+ logger.debug("Failed to fetch catalog vertex");
+ return Either.right(TitanOperationStatus.GENERAL_ERROR);
+ }
+ TitanVertex catalogV = vCatalogIter.iterator().next();
+ if (catalogV == null) {
+ logger.debug("Failed to fetch catalog vertex");
+ return Either.right(TitanOperationStatus.GENERAL_ERROR);
+ }
+ Iterator<Vertex> vertices = catalogV.vertices(Direction.OUT, EdgeLabelEnum.CATALOG_ELEMENT.name());
+
+ return Either.left(vertices);
+ } catch (Exception e) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria: ", e);
+ }
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Failed get by criteria : ", graph.right().value());
+ }
+ return Either.right(graph.right().value());
+ }
+ }
+
+ private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, TitanGraphQuery query) {
+ List<Object> negateList = (List<Object>) entry.getValue();
+ for (Object listItem : negateList) {
+ query.hasNot(entry.getKey().getProperty(), listItem);
+ }
+ }
+
+ /**
+ *
+ * @param parentVertex
+ * @param edgeLabel
+ * @param parseFlag
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag);
+ if (childrenVertecies.isRight()) {
+ return Either.right(childrenVertecies.right().value());
+ }
+ return Either.left(childrenVertecies.left().value().get(0));
+ }
+
+ /**
+ *
+ * @param parentVertex
+ * @param edgeLabel
+ * @param parseFlag
+ * @return
+ */
+ public Either<Vertex, TitanOperationStatus> getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ Either<List<Vertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag);
+ if (childrenVertecies.isRight()) {
+ return Either.right(childrenVertecies.right().value());
+ }
+ return Either.left(childrenVertecies.left().value().get(0));
+ }
+
+ public Either<GraphVertex, TitanOperationStatus> getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag);
+ if (childrenVertecies.isRight()) {
+ return Either.right(childrenVertecies.right().value());
+ }
+ return Either.left(childrenVertecies.left().value().get(0));
+ }
+
+ public Either<Vertex, TitanOperationStatus> getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ Either<List<Vertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag);
+ if (childrenVertecies.isRight()) {
+ return Either.right(childrenVertecies.right().value());
+ }
+ return Either.left(childrenVertecies.left().value().get(0));
+ }
+
+ /**
+ *
+ * @param parentVertex
+ * @param edgeLabel
+ * @param parseFlag
+ * @return
+ */
+ public Either<List<GraphVertex>, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT);
+ }
+
+ public Either<List<GraphVertex>, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN);
+ }
+
+ public Either<List<Vertex>, TitanOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN);
+ }
+
+ private Either<List<Vertex>, TitanOperationStatus> getAdjacentVerticies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) {
+ List<Vertex> list = new ArrayList<>();
+ try {
+ Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph();
+ if (graphRes.isRight()) {
+ logger.error("Failed to retrieve graph. status is {}", graphRes);
+ return Either.right(graphRes.right().value());
+ }
+ Iterator<Edge> edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name());
+ if (edgesCreatorIterator != null) {
+ while (edgesCreatorIterator.hasNext()) {
+ Edge edge = edgesCreatorIterator.next();
+ TitanVertex vertex;
+ if (direction == Direction.IN) {
+ vertex = (TitanVertex) edge.outVertex();
+ } else {
+ vertex = (TitanVertex) edge.inVertex();
+ }
+ // GraphVertex graphVertex = createAndFill(vertex, parseFlag);
+
+ list.add(vertex);
+ }
+ }
+ if (true == list.isEmpty()) {
+ return Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ } catch (Exception e) {
+ logger.error("Failed to perform graph operation ", e);
+ Either.right(TitanGraphClient.handleTitanException(e));
+ }
+
+ return Either.left(list);
+ }
+
+ /**
+ *
+ * @param parentVertex
+ * @param edgeLabel
+ * @param parseFlag
+ * @return
+ */
+ public Either<List<Vertex>, TitanOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
+ return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT);
+ }
+
+ private Either<List<GraphVertex>, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) {
+ List<GraphVertex> list = new ArrayList<GraphVertex>();
+
+ Either<List<Vertex>, TitanOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), edgeLabel, parseFlag, direction);
+ if (adjacentVerticies.isRight()) {
+ return Either.right(adjacentVerticies.right().value());
+ }
+ adjacentVerticies.left().value().stream().forEach(vertex -> {
+ list.add(createAndFill((TitanVertex) vertex, parseFlag));
+ });
+
+ return Either.left(list);
+ }
+
+ /**
+ * Searches Edge by received label and criteria
+ *
+ * @param vertex
+ * @param label
+ * @param properties
+ * @return found edge or TitanOperationStatus
+ */
+ public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) {
+
+ Either<Edge, TitanOperationStatus> result = null;
+ Edge matchingEdge = null;
+ String notFoundMsg = "No edges in graph for criteria";
+ try {
+ TitanVertexQuery<?> query = vertex.getVertex().query().labels(label.name());
+
+ if (properties != null && !properties.isEmpty()) {
+ for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) {
+ query = query.has(entry.getKey().getProperty(), entry.getValue());
+ }
+ }
+
+ Iterable<TitanEdge> edges = query.edges();
+ if (edges == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
+ result = Either.right(TitanOperationStatus.NOT_FOUND);
+ } else {
+ Iterator<TitanEdge> eIter = edges.iterator();
+ if (eIter.hasNext()) {
+ matchingEdge = eIter.next();
+ } else {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
+ result = Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ }
+ if (result == null) {
+ result = Either.left(matchingEdge);
+ }
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ return result;
+ }
+
+ /**
+ * Deletes Edge by received label and criteria
+ *
+ * @param vertex
+ * @param label
+ * @param properties
+ * @return
+ */
+ public Either<Edge, TitanOperationStatus> deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) {
+ Either<Edge, TitanOperationStatus> result = null;
+ try {
+ result = getBelongingEdgeByCriteria(vertex, label, properties);
+ if (result.isLeft()) {
+ Edge edge = result.left().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId());
+ edge.remove();
+ result = Either.left(edge);
+ } else {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId());
+ }
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}", vertex.getUniqueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ /**
+ * Deletes an edge between vertices fromVertex and toVertex according to received label
+ *
+ * @param fromVertex
+ * @param toVertex
+ * @param label
+ * @return
+ */
+
+ public Either<Edge, TitanOperationStatus> deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) {
+ return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId());
+ }
+
+ public Either<Edge, TitanOperationStatus> deleteEdge(TitanVertex fromVertex, TitanVertex toVertex, EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo) {
+ Either<Edge, TitanOperationStatus> result = null;
+ try {
+ Iterable<TitanEdge> edges = fromVertex.query().labels(label.name()).edges();
+ Iterator<TitanEdge> eIter = edges.iterator();
+ while (eIter.hasNext()) {
+ Edge edge = eIter.next();
+ String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty());
+ if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo);
+ edge.remove();
+ result = Either.left(edge);
+ break;
+ }
+ }
+ if (result == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo);
+ result = Either.right(TitanOperationStatus.NOT_FOUND);
+ }
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), uniqueIdFrom, uniqueIdTo, e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ return result;
+ }
+
+ public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) {
+ try {
+ Iterator<Edge> edges = fromVertex.getVertex().edges(direction, label.name());
+
+ while (edges.hasNext()) {
+ Edge edge = edges.next();
+ edge.remove();
+ }
+ } catch (Exception e) {
+ logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e);
+ return TitanGraphClient.handleTitanException(e);
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ /**
+ * Updates vertex properties. Note that graphVertex argument should contain updated data
+ *
+ * @param graphVertex
+ * @return
+ */
+ public Either<GraphVertex, TitanOperationStatus> updateVertex(GraphVertex graphVertex) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId());
+ try {
+ graphVertex.updateMetadataJsonWithCurrentMetadataProperties();
+ setVertexProperties(graphVertex.getVertex(), graphVertex);
+
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e);
+ return Either.right(TitanGraphClient.handleTitanException(e));
+ }
+ return Either.left(graphVertex);
+ }
+
+ /**
+ * Fetches vertices by uniqueId according to received parse flag
+ *
+ * @param verticesToGet
+ * @return
+ */
+ public Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag(Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGet) {
+
+ Either<Map<String, GraphVertex>, TitanOperationStatus> result = null;
+ Map<String, GraphVertex> vertices = new HashMap<>();
+ TitanOperationStatus titatStatus;
+ Either<GraphVertex, TitanOperationStatus> getVertexRes = null;
+ for (Map.Entry<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> entry : verticesToGet.entrySet()) {
+ if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) {
+ getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue());
+ } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) {
+ getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER, entry.getValue().getValue());
+ }
+ if (getVertexRes == null) {
+ titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT;
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus);
+ result = Either.right(titatStatus);
+ }
+ if (getVertexRes.isRight()) {
+ titatStatus = getVertexRes.right().value();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus);
+ result = Either.right(titatStatus);
+ break;
+ } else {
+ vertices.put(entry.getKey(), getVertexRes.left().value());
+ }
+ }
+ if (result == null) {
+ result = Either.left(vertices);
+ }
+ return result;
+ }
+
+ /**
+ * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge
+ *
+ * @param from
+ * @param to
+ * @param label
+ * @param edgeToCopy
+ * @return
+ */
+ public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) {
+ return createEdge(from, to, label, getEdgeProperties(edgeToCopy));
+ }
+
+ public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) {
+
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
+ toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
+ TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge);
+ if (result == TitanOperationStatus.OK) {
+ prevEdge.remove();
+ }
+ return result;
+ }
+
+ /**
+ * Replaces previous label of edge with new label
+ *
+ * @param fromVertex
+ * @param toVertex
+ * @param prevLabel
+ * @param newLabel
+ * @return
+ */
+ public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) {
+
+ TitanOperationStatus result = null;
+ Iterator<Edge> prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name());
+ if (prevEdgeIter == null || !prevEdgeIter.hasNext()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
+ toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
+ result = TitanOperationStatus.NOT_FOUND;
+ }
+ if (result == null) {
+ result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel);
+ }
+ return result;
+ }
+
+ /**
+ * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too.
+ *
+ *
+ * @param vertex
+ * @param properties
+ * @return
+ */
+ public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map<GraphPropertyEnum, Object> properties) {
+ try {
+ if (!MapUtils.isEmpty(properties)) {
+ String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value();
+ Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr);
+ for (Map.Entry<GraphPropertyEnum, Object> property : properties.entrySet()) {
+ vertex.property(property.getKey().getProperty(), property.getValue());
+ jsonMetadataMap.put(property.getKey().getProperty(), property.getValue());
+ }
+ vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap));
+ }
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occurred during update vertex metadata properties with json{}. {}", vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage());
+ return TitanGraphClient.handleTitanException(e);
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) {
+ try {
+ Iterator<Edge> edges = vertex.getVertex().edges(direction, label.name());
+
+ while (edges.hasNext()) {
+ Edge edge = edges.next();
+ Vertex secondVertex;
+ Direction reverseDirection;
+ if (direction == Direction.IN) {
+ secondVertex = edge.outVertex();
+ reverseDirection = Direction.OUT;
+ } else {
+ secondVertex = edge.inVertex();
+ reverseDirection = Direction.IN;
+ }
+ edge.remove();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex());
+
+ Iterator<Edge> restOfEdges = secondVertex.edges(reverseDirection, label.name());
+ if (restOfEdges.hasNext() == false) {
+ secondVertex.remove();
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId());
+ }
+ }
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction, vertex.getUniqueId(), e);
+ return TitanGraphClient.handleTitanException(e);
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ public Object getProperty(TitanVertex vertex, String key) {
+ PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key);
+ Object value = vertex.valueOrNull(propertyKey);
+ return value;
+ }
+
+ public Object getProperty(Edge edge, EdgePropertyEnum key) {
+ Object value = null;
+ try {
+ Property<Object> property = edge.property(key.getProperty());
+ if (property != null) {
+ return property.orElse(null);
+ }
+ } catch (Exception e) {
+
+ }
+ return value;
+ }
+
+ /**
+ *
+ * @param vertexA
+ * @param vertexB
+ * @param label
+ * @param direction
+ * @return
+ */
+ public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) {
+ TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label);
+ if (result != TitanOperationStatus.OK) {
+ logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result);
+ return result;
+ }
+ TitanOperationStatus createRelation;
+ if (direction == Direction.IN) {
+ createRelation = createEdge(vertexB, vertexA, label, null);
+ } else {
+ createRelation = createEdge(vertexA, vertexB, label, null);
+ }
+ if (createRelation != TitanOperationStatus.OK) {
+ return createRelation;
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) {
+ Either<GraphVertex, TitanOperationStatus> getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse);
+ if (getVertexRes.isRight()) {
+ return Either.right(getVertexRes.right().value());
+ }
+ return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties);
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
index 3018915066..eda2805087 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
@@ -48,12 +48,17 @@ public enum EdgeLabelEnum {
INST_ATTRIBUTES,
INST_GROUPS,
SERVICE_API_ARTIFACTS,
+ FORWARDING_PATH,
CALCULATED_CAPABILITIES,
FULLFILLED_CAPABILITIES,
CALCULATED_REQUIREMENTS,
FULLFILLED_REQUIREMENTS,
LAST_DISTRIBUTION_STATE_MODIFIER,
- CALCULATED_CAP_PROPERTIES;
+ CALCULATED_CAP_PROPERTIES,
+ POLICIES,
+ EXTERNAL_REFS,
+ CATALOG_ELEMENT;
+
/**
* Returns EdgeLabelEnum according received name
* @param name
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 08652ba171..1bc9df5f4a 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
@@ -20,20 +20,7 @@
package org.openecomp.sdc.be.dao.jsongraph.types;
-import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.*;
public enum VertexTypeEnum {
@@ -66,8 +53,11 @@ public enum VertexTypeEnum {
FULLFILLED_CAPABILITIES ("fullfilledCapabilities", MapListCapabiltyDataDefinition.class),
CALCULATED_REQUIREMENTS ("calculatedRequirements", MapListRequirementDataDefinition.class),
FULLFILLED_REQUIREMENTS ("fullfilledRequirements", MapListRequirementDataDefinition.class),
- CALCULATED_CAP_PROPERTIES ("calculatedCapProperties", MapCapabiltyProperty.class)
-;
+ CALCULATED_CAP_PROPERTIES ("calculatedCapProperties", MapCapabiltyProperty.class),
+ FORWARDING_PATH ("path", ForwardingPathDataDefinition.class),
+ POLICIES ("policies", PolicyDataDefinition.class),
+ EXTERNAL_REF ("componentInstanceExtRefs", MapComponentInstanceExternalRefs.class),
+ CATALOG_ROOT ("catalogRoot", null);
private String name;
private Class classOfJson;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java
index da3d6530e4..b2530e8e8a 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/utils/JsonParserUtils.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,67 +20,73 @@
package org.openecomp.sdc.be.dao.jsongraph.utils;
-import java.io.IOException;
-import java.util.Map;
-
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.map.DeserializationConfig;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.codehaus.jackson.map.SerializationConfig.Feature;
-import org.codehaus.jackson.map.annotate.JsonSerialize;
-import org.codehaus.jackson.type.JavaType;
-import org.codehaus.jackson.type.TypeReference;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.google.common.base.Strings;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.util.Map;
+
public class JsonParserUtils {
- private static ObjectMapper mapper = new ObjectMapper();
- private static Logger logger = LoggerFactory.getLogger(JsonParserUtils.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(JsonParserUtils.class.getName());
+ private static final ObjectMapper mapper = buildObjectMapper();
+
+ private JsonParserUtils() {
+ // No instances allowed
+ }
+
+ private static ObjectMapper buildObjectMapper() {
+ return new ObjectMapper()
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
+ .setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ }
-
- public static <T> String jsonToString(T elementToRepresent) throws IOException, JsonGenerationException, JsonMappingException {
+ public static <T> String toJson(T object) throws IOException {
+ return mapper.writer()
+ .writeValueAsString(object);
+ }
-
- mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
- mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
- return mapper.writeValueAsString(elementToRepresent);
- }
+ public static Map<String, Object> toMap(String json) {
+ if (Strings.isNullOrEmpty(json)) {
+ return null;
+ }
- public static Map<String, Object> parseToJson(String json) {
- Map<String, Object> object = null;
- if (json == null || json.isEmpty()) {
- return null;
- }
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
- mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
- TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
- };
+ Map<String, Object> object = null;
+ try {
+ TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
+ };
+ object = mapper.readerFor(typeRef)
+ .readValue(json);
+ }
+ catch (Exception e) {
+ log.debug("Failed to parse json {}", json, e);
+ }
+ return object;
+ }
- try {
- object = mapper.readValue(json, typeRef);
- } catch (Exception e) {
- logger.debug("Failed to parse json {}", json, e);
- }
- return object;
- }
- public static <T extends ToscaDataDefinition> Map<String, T> parseToJson(String json, Class <T> clazz) {
- Map<String, T> object = null;
- if (json == null || json.isEmpty()) {
- return null;
- }
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
- mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
- JavaType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, clazz);
+ public static <T extends ToscaDataDefinition> Map<String, T> toMap(String json, Class<T> clazz) {
+ if (Strings.isNullOrEmpty(json)) {
+ return null;
+ }
- try {
- object = mapper.readValue(json, type);
- } catch (Exception e) {
- logger.debug("Failed to parse json {}", json, e);
- }
- return object;
- }
+ Map<String, T> object = null;
+ try {
+ JavaType type = mapper.getTypeFactory()
+ .constructMapType(Map.class, String.class, clazz);
+ object = mapper.readerFor(type)
+ .readValue(json);
+ }
+ catch (Exception e) {
+ log.debug("Failed to parse json {}", json, e);
+ }
+ return object;
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java
index 1b5222c0a0..790e92ec55 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabels.java
@@ -37,7 +37,7 @@ public enum GraphEdgeLabels {
CALCULATED_REQUIREMENT("CALCULATED_REQUIREMENT"), CALCULATED_CAPABILITY("CALCULATED_CAPABILITY"), RELATIONSHIP_ORIGIN("RELATIONSHIP_ORIGIN"), CAPABILITY_ORIGIN("CAPABILITY_ORIGIN"),
CALCULATED_REQUIREMENT_FULLFILLED("CALCULATED_REQUIREMENT_FULLFILLED"), CALCULATED_CAPABILITY_FULLFILLED("CALCULATED_CAPABILITY_FULLFILLED"),
// Group
- GROUP("GROUP"), GROUP_ARTIFACT_REF("GROUP_ARTIFACT_REF"), GROUP_MEMBER("GROUP_MEMBER"), INPUT("EDGE_INPUT"), GET_INPUT("GET_INPUT"), GROUP_INST("GROUP_INST");
+ GROUP("GROUP"), GROUP_ARTIFACT_REF("GROUP_ARTIFACT_REF"), GROUP_MEMBER("GROUP_MEMBER"), INPUT("EDGE_INPUT"), GET_INPUT("GET_INPUT"), GROUP_INST("GROUP_INST"), GROUP_TYPE_CAPABILITY_TYPE("GROUP_TYPE_CAPABILITY_TYPE");
private String property;
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java
deleted file mode 100644
index 563129937e..0000000000
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/HttpRestClient.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.dao.rest;
-
-import java.io.IOException;
-import java.io.InputStream;
-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.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpPut;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.entity.ContentType;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
-import org.apache.http.util.EntityUtils;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.common.rest.api.RestResponse;
-import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HttpRestClient {
-
- public final static int DEFAULT_CONNECTION_POOL_SIZE = 10;
-
- public final static int DEFAULT_READ_TIMEOUT_IN_SEC = 30;
-
- public final static int DEFAULT_CONNECT_TIMEOUT = 30;
-
- public final static int DEFAULT_SOCKET_TIMEOUT = 30;
-
- private CloseableHttpClient httpClient = null;
-
- private PoolingHttpClientConnectionManager cm = null;
-
- private static Logger logger = LoggerFactory.getLogger(HttpRestClient.class.getName());
-
- private RestResponse errorRestResponse = new RestResponse("internal server error", null, 500);
- private RestResponseAsByteArray errorRestResponseAsByteArray = new RestResponseAsByteArray(
- "internal server error".getBytes(), null, 500);
-
- boolean isInitialized = false;
-
- // public static void main(String[] argv) {
- // try {
- // RestClientService restClientService =
- // RestClientServiceFactory.createHttpRestClientService(new
- // RestConfigurationInfo());
- //
- // String uriCreateCell =
- // "http://172.20.37.245:9082/topology/management/cell/update";
- // String jsonStr = " { \"cellName\" : \"mycell118\" }";
- // String jsonUpdateStr =
- // " { \"cellName\" : \"mycell118\", \"hostName\" : \"myhost333\" }";
- //
- //
- // // jsonStr = " <note>dfd</note>";
- //
- // Properties headers = new Properties();
- // headers.put("Content-type", "application/json");
- // headers.put("Accept", "*/*");
- //
- // // RestResponse restResponse = restClientService.doPOST(uriCreateCell,
- // headers, jsonStr);
- //
- // RestResponse restResponse = restClientService.doPUT(uriCreateCell,
- // headers, jsonUpdateStr);
- //
- // System.out.println(restResponse);
- //
- //
- // } catch (RestClientServiceExeption e) {
- // e.printStackTrace();
- // }
- //
- // }
-
- public HttpRestClient() {
- super();
- isInitialized = init(new RestConfigurationInfo());
- }
-
- public HttpRestClient(RestConfigurationInfo restConfigurationInfo) {
- super();
- isInitialized = init(restConfigurationInfo);
- }
-
- public boolean init(RestConfigurationInfo restConfigurationInfo) {
-
- logger.debug("create HttpRestClient: restConfigurationInfo= {}", restConfigurationInfo);
- boolean result = false;
- createHttpClient(restConfigurationInfo);
- result = true;
-
- logger.debug("Finish creating HttpRestClient. Result is {}", result);
- return result;
- }
-
- public void destroy() {
-
- try {
- httpClient.close();
- logger.debug("Http client closed");
- } catch (Exception e) {
- logger.trace("Failed to close http client", e);
- }
-
- }
-
- private void createHttpClient(RestConfigurationInfo restConfigurationInfo) {
- // throws KeyManagementException, NoSuchAlgorithmException {
-
- PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
-
- int connPoolSize = getConnectionPoolSize(restConfigurationInfo);
- connManager.setMaxTotal(connPoolSize);
- connManager.setDefaultMaxPerRoute(10);
- connManager.setValidateAfterInactivity(15000);
-
- // Create common default configuration
- int socketTimeout = getTimeout(restConfigurationInfo.getSocketTimeoutInSec(), DEFAULT_SOCKET_TIMEOUT);
-
- int connectTimeoutInSec = getTimeout(restConfigurationInfo.getConnectTimeoutInSec(), DEFAULT_CONNECT_TIMEOUT);
-
- int readTimeOut = getTimeout(restConfigurationInfo.getReadTimeoutInSec(), DEFAULT_READ_TIMEOUT_IN_SEC);
-
- RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(connectTimeoutInSec)
- .setSocketTimeout(socketTimeout).setConnectionRequestTimeout(readTimeOut).build();
-
- this.cm = connManager;
-
- this.httpClient = HttpClients.custom().setDefaultRequestConfig(clientConfig).setConnectionManager(connManager)
- .build();
-
- }
-
- private int getConnectionPoolSize(RestConfigurationInfo restConfigurationInfo) {
- Integer connPoolSizeObj = restConfigurationInfo.getConnectionPoolSize();
- int connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
- if (connPoolSizeObj != null) {
- connPoolSize = connPoolSizeObj.intValue();
- if (connPoolSize <= 0) {
- connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
- }
- }
- return connPoolSize;
- }
-
- private int getTimeout(Integer value, Integer defaultValue) {
-
- int defaultTimeout = defaultValue != null ? defaultValue.intValue() * 1000 : 0;
-
- int timeout = defaultTimeout;
-
- if (value != null) {
- timeout = defaultValue.intValue() * 1000;
- if (timeout <= 0) {
- timeout = defaultTimeout;
- }
- }
-
- return timeout;
- }
-
- /**
- * Executes RS-GET to perform FIND.
- *
- * @param headerParameterKey
- * String
- * @param headerParameterValue
- * String
- * @return String
- */
- public RestResponse doGET(String uri, Properties headers) {
-
- logger.debug("Before executing uri {}. headers = {}", uri, headers);
-
- HttpGet httpGet = new HttpGet(uri);
-
- RestResponse response = execute(httpGet, headers);
-
- return response;
- }
-
- public RestResponse doPUT(String uri, Properties headers, String body) {
-
- logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
-
- HttpPut httpPut = new HttpPut(uri);
- StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
- httpPut.setEntity(data);
- RestResponse response = execute(httpPut, headers);
-
- return response;
- }
-
- public RestResponse doPOST(String uri, Properties headers, String body) {
-
- logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
-
- HttpPost httpPost = new HttpPost(uri);
- StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
- httpPost.setEntity(data);
- RestResponse response = execute(httpPost, headers);
-
- return response;
- }
-
- public RestResponseAsByteArray doGetAsByteArray(String uri, Properties headers) {
-
- logger.debug("Before executing uri {}. headers = {}", uri, headers);
-
- HttpGet httpGet = new HttpGet(uri);
-
- RestResponseAsByteArray response = executeAndReturnByteArray(httpGet, headers);
-
- return response;
- }
-
- private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {
-
- if (headers != null) {
- for (Entry<Object, Object> entry : headers.entrySet()) {
- httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
- }
- }
-
- }
-
- private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) {
-
- RestResponse restResponse = null;
-
- CloseableHttpResponse httpResponse = null;
-
- try {
-
- addHeadersToRequest(httpRequestBase, headers);
-
- httpResponse = this.httpClient.execute(httpRequestBase);
-
- restResponse = buildRestResponseFromResult(httpResponse);
-
- logger.debug("After executing uri {}. response = {}", httpRequestBase.getURI().toString(), restResponse);
-
- } catch (Exception exception) {
- httpRequestBase.abort();
-
- String description = "Failed executing http request " + httpRequestBase.getURI().toString() + "("
- + httpRequestBase.getMethod() + ")";
- BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description,
- ErrorSeverity.ERROR);
- restResponse = errorRestResponse;
- } finally {
- // ensure the connection gets released to the manager
- releaseResource(httpResponse);
- }
-
- return restResponse;
- }
-
- private RestResponse buildRestResponseFromResult(CloseableHttpResponse httpResponse) throws IOException {
-
- int statusCode = httpResponse.getStatusLine().getStatusCode();
- String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
-
- HttpEntity entity = httpResponse.getEntity();
- String response = null;
- if (entity != null) {
- response = EntityUtils.toString(entity);
- }
-
- RestResponse restResponse = new RestResponse(response, statusDesc, statusCode);
-
- return restResponse;
- }
-
- private RestResponseAsByteArray buildRestResponseByteArrayFromResult(CloseableHttpResponse httpResponse)
- throws IOException {
-
- int statusCode = httpResponse.getStatusLine().getStatusCode();
- String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
-
- HttpEntity entity = httpResponse.getEntity();
-
- byte[] response = null;
- if (entity != null) {
- InputStream content = entity.getContent();
- if (content != null) {
- response = IOUtils.toByteArray(content);
- }
- }
-
- RestResponseAsByteArray restResponse = new RestResponseAsByteArray(response, statusDesc, statusCode);
-
- return restResponse;
- }
-
- private RestResponseAsByteArray executeAndReturnByteArray(HttpRequestBase httpRequestBase, Properties headers) {
-
- RestResponseAsByteArray restResponse = null;
-
- CloseableHttpResponse httpResponse = null;
-
- try {
-
- addHeadersToRequest(httpRequestBase, headers);
-
- httpResponse = this.httpClient.execute(httpRequestBase);
-
- restResponse = buildRestResponseByteArrayFromResult(httpResponse);
-
- if (restResponse != null) {
- logger.debug("After executing uri {}. Response: {}", httpRequestBase.getURI().toString(), restResponse.toPrettyString());
- }
-
- } catch (Exception exception) {
- httpRequestBase.abort();
- String description = "Failed executing http request " + httpRequestBase.getURI().toString() + "("
- + httpRequestBase.getMethod() + ")";
- BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description,
- ErrorSeverity.ERROR);
- logger.debug(description, exception);
- restResponse = errorRestResponseAsByteArray;
- } finally {
- // ensure the connection gets released to the manager
- releaseResource(httpResponse);
- }
-
- return restResponse;
- }
-
- /**
- * This method print the JSON response from the REST Server
- *
- * @param response
- * the JSON response from the REST server
- * @param method
- * name of method
- */
- private void logResponse(String response, String method) {
- logger.trace("{} response = {}", method, response);
- }
-
- private void releaseResource(CloseableHttpResponse response) {
- if (response != null) {
- try {
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- EntityUtils.consume(entity);
- }
- response.close();
- } catch (Exception e) {
- logger.error("failed to close connection exception", e);
- }
- }
- }
-
- public boolean isInitialized() {
- return isInitialized;
- }
-
-}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java
deleted file mode 100644
index 1e45ba6ae3..0000000000
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfo.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.dao.rest;
-
-public class RestConfigurationInfo {
-
- private Integer readTimeoutInSec = null;
-
- private Boolean ignoreCertificate = null;
-
- private Integer connectionPoolSize = null;
-
- private Integer connectTimeoutInSec = null;
-
- private Integer socketTimeoutInSec = null;
-
- /**
- * @return the readTimeoutInSec
- */
- public Integer getReadTimeoutInSec() {
- return readTimeoutInSec;
- }
-
- /**
- * @param readTimeoutInSec
- * the readTimeoutInSec to set
- */
- public void setReadTimeoutInSec(Integer readTimeoutInSec) {
- this.readTimeoutInSec = readTimeoutInSec;
- }
-
- /**
- * @return the ignoreCertificate
- */
- public Boolean getIgnoreCertificate() {
- return ignoreCertificate;
- }
-
- /**
- * @param ignoreCertificate
- * the ignoreCertificate to set
- */
- public void setIgnoreCertificate(Boolean ignoreCertificate) {
- this.ignoreCertificate = ignoreCertificate;
- }
-
- /**
- * @return the connectionPoolSize
- */
- public Integer getConnectionPoolSize() {
- return connectionPoolSize;
- }
-
- /**
- * @param connectionPoolSize
- * the connectionPoolSize to set
- */
- public void setConnectionPoolSize(Integer connectionPoolSize) {
- this.connectionPoolSize = connectionPoolSize;
- }
-
- /**
- * @return the connectTimeoutInSec
- */
- public Integer getConnectTimeoutInSec() {
- return connectTimeoutInSec;
- }
-
- /**
- * @param connectTimeoutInSec
- * the connectTimeoutInSec to set
- */
- public void setConnectTimeoutInSec(Integer connectTimeoutInSec) {
- this.connectTimeoutInSec = connectTimeoutInSec;
- }
-
- public Integer getSocketTimeoutInSec() {
- return socketTimeoutInSec;
- }
-
- public void setSocketTimeoutInSec(Integer socketTimeoutInSec) {
- this.socketTimeoutInSec = socketTimeoutInSec;
- }
-
- @Override
- public String toString() {
- return "RestConfigurationInfo [readTimeoutInSec=" + readTimeoutInSec + ", ignoreCertificate="
- + ignoreCertificate + ", connectionPoolSize=" + connectionPoolSize + ", connectTimeoutInSec="
- + connectTimeoutInSec + ", socketTimeoutInSec=" + socketTimeoutInSec + "]";
- }
-
-}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java
index 8bd190f932..1db807fa0e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGenericDao.java
@@ -20,15 +20,14 @@
package org.openecomp.sdc.be.dao.titan;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-import java.util.stream.StreamSupport;
-
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanEdge;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.core.TitanVertexQuery;
+import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.tinkerpop.gremlin.structure.Direction;
@@ -52,15 +51,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import com.thinkaurelius.titan.core.PropertyKey;
-import com.thinkaurelius.titan.core.TitanEdge;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanGraphQuery;
-import com.thinkaurelius.titan.core.TitanVertex;
-import com.thinkaurelius.titan.core.TitanVertexQuery;
-import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
-
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
@Component("titan-generic-dao")
public class TitanGenericDao {
@@ -908,7 +906,7 @@ public class TitanGenericDao {
return true;
}
- public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteriaWithPradicat(NodeTypeEnum type, Map<String, Entry<TitanPredicate, Object>> props, Class<T> clazz) {
+ public <T extends GraphNode> Either<List<T>, TitanOperationStatus> getByCriteriaWithPredicate(NodeTypeEnum type, Map<String, Entry<TitanPredicate, Object>> props, Class<T> clazz) {
Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph();
if (graph.isLeft()) {
try {
@@ -1111,6 +1109,14 @@ public class TitanGenericDao {
}
+ public Either<Boolean, TitanOperationStatus> isRelationExist(GraphNode from, GraphNode to, GraphEdgeLabels edgeLabel) {
+ return getEdgeByNodes(from, to, edgeLabel)
+ .left()
+ .map(edge -> true)
+ .right()
+ .bind(err -> err == TitanOperationStatus.NOT_FOUND ? Either.left(false): Either.right(err));
+ }
+
public Either<GraphRelation, TitanOperationStatus> deleteRelation(GraphNode from, GraphNode to, GraphEdgeLabels label) {
logger.debug("try to delete relation from [{}] to [{}]", from.getKeyValueId(), to.getKeyValueId());
return deleteEdge(label.getProperty(), from.getKeyValueId(), to.getKeyValueId(), from.getLabel(), to.getLabel());
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java
index edcf70f093..7d151f1a3e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanGraphClient.java
@@ -392,10 +392,8 @@ public class TitanGraphClient {
private void logAlarm() {
if (lastHealthState == true) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckRecovery, TITAN_HEALTH_CHECK_STR);
BeEcompErrorManager.getInstance().logBeHealthCheckTitanRecovery(TITAN_HEALTH_CHECK_STR);
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeHealthCheckError, TITAN_HEALTH_CHECK_STR);
BeEcompErrorManager.getInstance().logBeHealthCheckTitanError(TITAN_HEALTH_CHECK_STR);
}
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java
new file mode 100644
index 0000000000..163ef807fb
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/titan/TitanUtils.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.dao.titan;
+
+import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import static com.thinkaurelius.titan.core.attribute.Contain.NOT_IN;
+import static java.util.Collections.emptyMap;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+public class TitanUtils {
+
+ private TitanUtils() {
+ }
+
+ public static <T> Map<String, Entry<TitanPredicate, Object>> buildNotInPredicate(String propKey, Collection<T> notInCollection) {
+ if (isEmpty(notInCollection)) {
+ return emptyMap();
+ }
+ Map<String, Entry<TitanPredicate, Object>> predicateCriteria = new HashMap<>();
+ predicateCriteria.put(propKey, new HashMap.SimpleEntry<>(NOT_IN, notInCollection));
+ return predicateCriteria;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java
index e8b2e0c9ad..991fb0b29f 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/utils/MapUtil.java
@@ -20,15 +20,13 @@
package org.openecomp.sdc.be.dao.utils;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
import java.util.function.Function;
+import java.util.stream.Collector;
import java.util.stream.Collectors;
+import static java.util.stream.Collectors.groupingBy;
+
/**
* Utility class to ease map manipulation.
*/
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java
index a5a6e6df76..8c3742e474 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/AdditionalInfoParameterData.java
@@ -20,16 +20,15 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
public class AdditionalInfoParameterData extends GraphNode {
@@ -118,7 +117,7 @@ public class AdditionalInfoParameterData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return additionalInfoParameterDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java
index 84d9663e59..7114413f41 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ArtifactData.java
@@ -20,18 +20,17 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class ArtifactData extends GraphNode {
@@ -104,7 +103,7 @@ public class ArtifactData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return artifactDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java
index 9f04c56be2..d2b1336ce1 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityData.java
@@ -20,17 +20,16 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class CapabilityData extends GraphNode {
@@ -76,6 +75,7 @@ public class CapabilityData extends GraphNode {
private String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
private String maxOccurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
+ @Override
public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java
index 0b5da1217d..1e456d3490 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CapabilityInstData.java
@@ -20,16 +20,15 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class CapabilityInstData extends GraphNode {
@@ -65,6 +64,7 @@ public class CapabilityInstData extends GraphNode {
private Long modificationTime;
+ @Override
public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java
index 4cfde8b0fa..7a2e0b5141 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/CategoryData.java
@@ -20,13 +20,13 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public abstract class CategoryData extends GraphNode {
private String name;
@@ -107,7 +107,7 @@ public abstract class CategoryData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return uniqueId;
}
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 fb58e9abff..52dd34be1b 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
@@ -20,17 +20,16 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public abstract class ComponentMetadataData extends GraphNode {
@@ -108,7 +107,7 @@ public abstract class ComponentMetadataData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return metadataDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java
index 3fb085f3d2..88c9c7097a 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/ConsumerData.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.datatypes.elements.ConsumerDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class ConsumerData extends GraphNode {
private ConsumerDataDefinition consumerDataDefinition;
@@ -67,7 +67,7 @@ public class ConsumerData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return consumerDataDefinition.getConsumerName();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java
index 200521c054..68b362b293 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GraphNodeLock.java
@@ -20,13 +20,13 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class GraphNodeLock extends GraphNode {
private String uniqueId;
@@ -50,7 +50,7 @@ public class GraphNodeLock extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java
index e354e95b27..93f03e415a 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/GroupData.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class GroupData extends GraphNode {
GroupDataDefinition groupDataDefinition;
@@ -63,7 +63,7 @@ public class GroupData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return groupDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java
index 7115a45bf3..c9dbc67b94 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterData.java
@@ -20,16 +20,16 @@
package org.openecomp.sdc.be.resources.data;
-import java.math.BigDecimal;
-import java.util.HashMap;
-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.HeatParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.math.BigDecimal;
+import java.util.HashMap;
+import java.util.Map;
+
public class HeatParameterData extends GraphNode {
private HeatParameterDataDefinition heatDataDefinition;
@@ -134,7 +134,7 @@ public class HeatParameterData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return heatDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java
index ecabe22b80..a7f52a0bf3 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/HeatParameterValueData.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class HeatParameterValueData extends GraphNode {
public HeatParameterValueData() {
@@ -52,7 +52,7 @@ public class HeatParameterValueData extends GraphNode {
private String value;
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java
index 1ed3ef1135..be45c855a4 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputValueData.java
@@ -20,15 +20,15 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
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.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
public class InputValueData extends GraphNode {
private String uniqueId;
@@ -68,6 +68,7 @@ public class InputValueData extends GraphNode {
}
+ @Override
public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java
index 3bb71d5bed..2152619d00 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/InputsData.java
@@ -20,11 +20,7 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
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;
@@ -32,7 +28,10 @@ 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;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class InputsData extends GraphNode {
@@ -129,7 +128,7 @@ public class InputsData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return propertyDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java
index d87cfe8853..cf05ad0eb9 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationData.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class OperationData extends GraphNode {
OperationDataDefinition operationDataDefinition;
@@ -69,7 +69,7 @@ public class OperationData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return operationDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java
new file mode 100644
index 0000000000..5b3c282bd7
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/OperationalEnvironmentEntry.java
@@ -0,0 +1,137 @@
+package org.openecomp.sdc.be.resources.data;
+
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+@Table(keyspace = "sdcrepository", name = "operationalEnvironment")
+public class OperationalEnvironmentEntry {
+
+ @PartitionKey(0)
+ @Column(name = "environment_id")
+ private String environmentId;
+
+ @Column(name = "tenant")
+ private String tenant;
+
+ @Column(name = "is_production")
+ private Boolean isProduction;
+
+ @Column(name = "ecomp_workload_context")
+ private String ecompWorkloadContext;
+
+ @Column(name = "dmaap_ueb_address")
+ private Set<String> dmaapUebAddress;
+
+ @Column(name = "ueb_api_key")
+ private String uebApikey;
+
+ @Column(name = "ueb_secret_key")
+ private String uebSecretKey;
+
+ @Column(name = "status")
+ private String status;
+
+ public Date getLastModified() {
+ return lastModified;
+ }
+
+ public void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
+
+ @Column(name = "last_modified")
+ private Date lastModified;
+
+
+ public String getEnvironmentId() {
+ return environmentId;
+ }
+
+ //must be unique, add any validation if neccessary
+ public void setEnvironmentId(String environmentId) {
+ this.environmentId = environmentId;
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public void setTenant(String tenant) {
+ this.tenant = tenant;
+ }
+
+ public Boolean getIsProduction() {
+ return isProduction;
+ }
+
+ public void setIsProduction(Boolean production) {
+ isProduction = production;
+ }
+
+ public String getEcompWorkloadContext() {
+ return ecompWorkloadContext;
+ }
+
+ public void setEcompWorkloadContext(String ecompWorkloadContext) {
+ this.ecompWorkloadContext = ecompWorkloadContext;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ //log if status doesn't exists in EnvironmentStatusEnum
+ this.status = status;
+ }
+
+ public void setStatus(EnvironmentStatusEnum status) {
+ this.status = status.getName();
+ }
+
+ public Set<String> getDmaapUebAddress() {
+ return dmaapUebAddress;
+ }
+
+ public void setDmaapUebAddress(Set<String> dmaapUebAddress) {
+ this.dmaapUebAddress = dmaapUebAddress;
+ }
+
+ public void addDmaapUebAddress(String address) {
+ if ( this.dmaapUebAddress == null )
+ this.dmaapUebAddress = new HashSet<>();
+ dmaapUebAddress.add(address);
+ }
+
+ public String getUebApikey() {
+ return uebApikey;
+ }
+
+ public void setUebApikey(String uebApikey) {
+ this.uebApikey = uebApikey;
+ }
+
+ public String getUebSecretKey() {
+ return uebSecretKey;
+ }
+
+ public void setUebSecretKey(String uebSecretKey) {
+ this.uebSecretKey = uebSecretKey;
+ }
+
+ @Override
+ public String toString() {
+ return "OperationalEnvironmentEntry [environmentId=" + environmentId + ", tenant=" + tenant + ", isProduction="
+ + isProduction + ", ecompWorkloadContext=" + ecompWorkloadContext + ", dmaapUebAddress="
+ + dmaapUebAddress + ", uebApikey=" + uebApikey + ", status=" + status
+ + ", lastModified=" + lastModified + "]";
+ }
+
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java
index 62f2ad5e12..8f2293aff7 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PolicyTypeData.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,111 +20,106 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class PolicyTypeData extends GraphNode {
- private PolicyTypeDataDefinition policyTypeDataDefinition;
- private static final Type mapType = new TypeToken<HashMap<String, String>>() {
- }.getType();
- private static final Type listType = new TypeToken<List<String>>() {
- }.getType();
-
- public PolicyTypeData() {
- super(NodeTypeEnum.PolicyType);
- policyTypeDataDefinition = new PolicyTypeDataDefinition();
- }
+ private PolicyTypeDataDefinition policyTypeDataDefinition;
+ private static final Type mapType = new TypeToken<HashMap<String, String>>() {
+ }.getType();
+ private static final Type listType = new TypeToken<List<String>>() {
+ }.getType();
- public PolicyTypeData(PolicyTypeDataDefinition policyTypeDataDefinition) {
- super(NodeTypeEnum.PolicyType);
- this.policyTypeDataDefinition = policyTypeDataDefinition;
- }
+ public PolicyTypeData() {
+ super(NodeTypeEnum.PolicyType);
+ policyTypeDataDefinition = new PolicyTypeDataDefinition();
+ }
- public PolicyTypeData(Map<String, Object> properties) {
+ public PolicyTypeData(PolicyTypeDataDefinition policyTypeDataDefinition) {
+ super(NodeTypeEnum.PolicyType);
+ this.policyTypeDataDefinition = policyTypeDataDefinition;
+ }
- this();
+ public PolicyTypeData(Map<String, Object> properties) {
- policyTypeDataDefinition
- .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
+ this();
- HashMap<String, String> metatdata = getGson()
- .fromJson((String) properties.get(GraphPropertiesDictionary.METADATA.getProperty()), mapType);
- policyTypeDataDefinition.setMetadata(metatdata);
+ policyTypeDataDefinition
+ .setUniqueId((String) properties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()));
- List<String> members = getGson()
- .fromJson((String) properties.get(GraphPropertiesDictionary.TARGETS.getProperty()), listType);
- policyTypeDataDefinition.setTargets(members);
+ HashMap<String, String> metatdata = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.METADATA.getProperty()), mapType);
+ policyTypeDataDefinition.setMetadata(metatdata);
- policyTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
+ List<String> members = getGson()
+ .fromJson((String) properties.get(GraphPropertiesDictionary.TARGETS.getProperty()), listType);
+ policyTypeDataDefinition.setTargets(members);
+ policyTypeDataDefinition.setType((String) properties.get(GraphPropertiesDictionary.TYPE.getProperty()));
- policyTypeDataDefinition
- .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
+ policyTypeDataDefinition
+ .setDescription((String) properties.get(GraphPropertiesDictionary.DESCRIPTION.getProperty()));
- policyTypeDataDefinition.setHighestVersion(
- (boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
+ policyTypeDataDefinition.setHighestVersion(
+ (boolean) properties.get(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()));
- policyTypeDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
+ policyTypeDataDefinition.setVersion((String) properties.get(GraphPropertiesDictionary.VERSION.getProperty()));
- policyTypeDataDefinition
- .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
+ policyTypeDataDefinition
+ .setCreationTime((Long) properties.get(GraphPropertiesDictionary.CREATION_DATE.getProperty()));
- policyTypeDataDefinition
- .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
+ policyTypeDataDefinition
+ .setModificationTime((Long) properties.get(GraphPropertiesDictionary.LAST_UPDATE_DATE.getProperty()));
- }
+ }
- @Override
- public Map<String, Object> toGraphMap() {
+ @Override
+ public Map<String, Object> toGraphMap() {
- Map<String, Object> map = new HashMap<String, Object>();
+ Map<String, Object> map = new HashMap<String, Object>();
- addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, policyTypeDataDefinition.getUniqueId());
+ addIfExists(map, GraphPropertiesDictionary.UNIQUE_ID, policyTypeDataDefinition.getUniqueId());
- addIfExists(map, GraphPropertiesDictionary.TYPE, policyTypeDataDefinition.getType());
+ addIfExists(map, GraphPropertiesDictionary.TYPE, policyTypeDataDefinition.getType());
- addIfExists(map, GraphPropertiesDictionary.VERSION, policyTypeDataDefinition.getVersion());
+ addIfExists(map, GraphPropertiesDictionary.VERSION, policyTypeDataDefinition.getVersion());
- addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, policyTypeDataDefinition.isHighestVersion());
+ addIfExists(map, GraphPropertiesDictionary.IS_HIGHEST_VERSION, policyTypeDataDefinition.isHighestVersion());
- addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, policyTypeDataDefinition.getDescription());
+ addIfExists(map, GraphPropertiesDictionary.DESCRIPTION, policyTypeDataDefinition.getDescription());
- addIfExists(map, GraphPropertiesDictionary.METADATA, policyTypeDataDefinition.getMetadata());
+ addIfExists(map, GraphPropertiesDictionary.METADATA, policyTypeDataDefinition.getMetadata());
- addIfExists(map, GraphPropertiesDictionary.TARGETS, policyTypeDataDefinition.getTargets());
+ addIfExists(map, GraphPropertiesDictionary.TARGETS, policyTypeDataDefinition.getTargets());
- addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, policyTypeDataDefinition.getCreationTime());
+ addIfExists(map, GraphPropertiesDictionary.CREATION_DATE, policyTypeDataDefinition.getCreationTime());
- addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, policyTypeDataDefinition.getModificationTime());
+ addIfExists(map, GraphPropertiesDictionary.LAST_UPDATE_DATE, policyTypeDataDefinition.getModificationTime());
- return map;
- }
+ return map;
+ }
- @Override
- public String toString() {
- return "PolicyTypeData [policyTypeDataDefinition=" + policyTypeDataDefinition + "]";
- }
+ @Override
+ public String toString() {
+ return "PolicyTypeData [policyTypeDataDefinition=" + policyTypeDataDefinition + "]";
+ }
- @Override
- public String getUniqueId() {
- return this.policyTypeDataDefinition.getUniqueId();
- }
+ @Override
+ public String getUniqueId() {
+ return this.policyTypeDataDefinition.getUniqueId();
+ }
- public PolicyTypeDataDefinition getPolicyTypeDataDefinition() {
- return policyTypeDataDefinition;
- }
+ public PolicyTypeDataDefinition getPolicyTypeDataDefinition() {
+ return policyTypeDataDefinition;
+ }
- public void setPolicyTypeDataDefinition(PolicyTypeDataDefinition policyTypeDataDefinition) {
- this.policyTypeDataDefinition = policyTypeDataDefinition;
- }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java
index a72ec9465b..403e27db1a 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyData.java
@@ -20,11 +20,7 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
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;
@@ -32,7 +28,10 @@ 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;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class PropertyData extends GraphNode {
@@ -129,7 +128,7 @@ public class PropertyData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return propertyDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java
index 7577e57a7e..80044e288d 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/PropertyValueData.java
@@ -20,18 +20,17 @@
package org.openecomp.sdc.be.resources.data;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
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.PropertyRule;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class PropertyValueData extends GraphNode {
@@ -77,6 +76,7 @@ public class PropertyValueData extends GraphNode {
private List<PropertyRule> rules;
+ @Override
public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java
index de2412d7ed..92b8323e0d 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/TagData.java
@@ -20,13 +20,13 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class TagData extends GraphNode {
private String name;
@@ -105,7 +105,7 @@ public class TagData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return name;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java
index 30f9a66d79..fd3b8659a1 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UniqueIdData.java
@@ -20,11 +20,11 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.Map;
-
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.Map;
+
public class UniqueIdData extends GraphNode {
private String uniqueId;
@@ -35,7 +35,7 @@ public class UniqueIdData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java
index 78974c4a77..dc4522fef9 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserData.java
@@ -20,15 +20,15 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.Date;
-import java.util.HashMap;
-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.DaoUtils;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
public class UserData extends GraphNode {
private String firstName;
@@ -213,7 +213,7 @@ public class UserData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return userId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java
index 2a31f4bb68..263cc89bba 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/UserFunctionalMenuData.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.resources.data;
-import java.util.HashMap;
-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.DaoUtils;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class UserFunctionalMenuData extends GraphNode {
private String uniqueId;
@@ -88,7 +88,7 @@ public class UserFunctionalMenuData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return uniqueId;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java
index 9e9836049f..09d37ac03d 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditRecordFactory.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.resources.data.auditing;
-import java.util.EnumMap;
+import java.util.Map;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
public final class AuditRecordFactory {
- public static AuditingGenericEvent createAuditRecord(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public static AuditingGenericEvent createAuditRecord(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
AuditingActionEnum actionEnum = AuditingActionEnum
.getActionByName((String) auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION));
String tableName = actionEnum.getAuditingEsType();
@@ -76,9 +76,12 @@ public final class AuditRecordFactory {
case AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE:
event = new ExternalApiEvent(auditingFields);
break;
+ case AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE:
+ event = new EcompOperationalEnvironmentEvent(auditingFields);
+ break;
}
- return event;
- }
+ return event;
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java
index cfc37f19e2..e810925fcd 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingActionEnum.java
@@ -23,6 +23,7 @@ package org.openecomp.sdc.be.resources.data.auditing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+//TODO rename to AuditAction
public enum AuditingActionEnum {
// User admininstration
@@ -53,6 +54,7 @@ public enum AuditingActionEnum {
DOWNLOAD_ARTIFACT("DownloadArtifact",AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
CREATE_RESOURCE_BY_API("CreateResourceByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
CHANGE_LIFECYCLE_BY_API("ChangeLifecycleByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
+ ACTIVATE_SERVICE_BY_API("ActivateServiceByAPI", AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE),
ARTIFACT_PAYLOAD_UPDATE("ArtifactPayloadUpdate", AuditingTypesConstants.RESOURCE_ADMIN_EVENT_TYPE),
@@ -76,7 +78,14 @@ public enum AuditingActionEnum {
DISTRIBUTION_DEPLOY("DResult",AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE),
GET_UEB_CLUSTER("GetUebCluster", AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE),
GET_VALID_ARTIFACT_TYPES("GetValidArtifactTypes", AuditingTypesConstants.DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE),
- // ....
+
+ //Environment
+ CREATE_ENVIRONMENT("CreateEnvironment", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE),
+ UPDATE_ENVIRONMENT("UpdateEnvironment", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE),
+ DELETE_ENVIRONMENT("DeleteEnvironment", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE),
+ UNKNOWN_ENVIRONMENT_NOTIFICATION("UnknownEnvironmentNotification", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE),
+ UNSUPPORTED_ENVIRONMENT_TYPE("UnsupportedEnvironmentType", AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE),
+ // ....
AUTH_REQUEST("HttpAuthentication", AuditingTypesConstants.AUTH_EVENT_TYPE),
ADD_ECOMP_USER_CREDENTIALS("AddECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE),
GET_ECOMP_USER_CREDENTIALS("GetECOMPUserCredentials", AuditingTypesConstants.CONSUMER_EVENT_TYPE),
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java
index bd8c032390..b5b99bf709 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingGetUebClusterEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -36,156 +34,167 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE)
public class AuditingGetUebClusterEvent extends AuditingGenericEvent {
- private static String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TEMPLATE = "action=\"%s\" "
- + " consumerId=\"%s\" statusTime=\"%s\" status=\"%s\" status_desc=\"%s\" ";
-
- @PartitionKey
- protected UUID timebaseduuid;
-
- @ClusteringColumn
- protected Date timestamp1;
-
- @Column(name = "request_id")
- protected String requestId;
-
- @Column(name = "service_instance_id")
- protected String serviceInstanceId;
- @Column
- protected String action;
- @Column
- protected String status;
-
- @Column(name = "description")
- protected String desc;
-
- @Column(name = "consumer_id")
- private String consumerId;
-
- public AuditingGetUebClusterEvent() {
- super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
-
- public AuditingGetUebClusterEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- this();
- Object value;
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
- if (value != null) {
- setRequestId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
- if (value != null) {
- setServiceInstanceId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
- if (value != null) {
- setAction((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- if (value != null) {
- setStatus((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- if (value != null) {
- setDesc((String) value);
- } else {
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC);
- if (value != null) {
- setDesc((String) value);
- }
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
- if (value != null) {
- setConsumerId((String) value);
- }
-
- }
-
- @Override
- public void fillFields() {
- fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
-
- fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
- fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
- fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
- simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
-
- }
-
- public String getConsumerId() {
- return consumerId;
- }
-
- public void setConsumerId(String consumerId) {
- this.consumerId = consumerId;
- }
-
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
-
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
-
- public Date getTimestamp1() {
- return timestamp1;
- }
-
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- 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;
- }
-
- @Override
- public String toString() {
- return "AuditingGetUebClusterEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
- + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
- + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + "]";
- }
+ private static String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TEMPLATE = "action=\"%s\" "
+ + " consumerId=\"%s\" statusTime=\"%s\" status=\"%s\" status_desc=\"%s\" ";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ public AuditingGetUebClusterEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public AuditingGetUebClusterEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ } else {
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+
+ }
+
+ public AuditingGetUebClusterEvent(String action, CommonAuditData commonAuditData, String consumerId) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.status = commonAuditData.getStatus();
+ //if no desc, keep distr desc
+ this.desc = commonAuditData.getDescription();
+ this.consumerId = consumerId;
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ 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;
+ }
+
+ @Override
+ public String toString() {
+ return "AuditingGetUebClusterEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ + ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
+ + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + "]";
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
index 9f25932b37..26cc463725 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
@@ -40,11 +40,13 @@ public interface AuditingTypesConstants {
String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent";
String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent";
+ String ECOMP_OPERATIONAL_ENV_EVENT_TYPE = "ecompopenvironmentevent";
String AUTH_EVENT_TYPE = "authevent";
String CONSUMER_EVENT_TYPE = "consumerevent";
String CATEGORY_EVENT_TYPE = "categoryevent";
String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent";
String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent";
String EXTERNAL_API_EVENT_TYPE = "externalapievent";
+ String ENVIRONMENT_ENGINE_EVENT_TYPE = "environmentengineevent";
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java
index 5c8cded0db..8e8a42310e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuthEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -153,7 +151,7 @@ public class AuthEvent extends AuditingGenericEvent {
this.requestId = requestId;
}
- public AuthEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public AuthEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_AUTH_URL);
@@ -191,6 +189,18 @@ public class AuthEvent extends AuditingGenericEvent {
}
+ public AuthEvent(String action, CommonAuditData commonAuditData, String user, String authUrl, String realm, String authStatus) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.desc = commonAuditData.getDescription();
+ this.status = commonAuditData.getStatus();
+ this.authStatus = authStatus;
+ this.url = authUrl;
+ this.realm = realm;
+ this.user = user;
+ }
+
@Override
public void fillFields() {
fields.put(AuditingFieldsKeysEnum.AUDIT_AUTH_URL.getDisplayName(), getUrl());
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java
index a970c84847..f85f67aa86 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/CategoryEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -76,7 +74,7 @@ public class CategoryEvent extends AuditingGenericEvent {
timebaseduuid = UUIDs.timeBased();
}
- public CategoryEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public CategoryEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
@@ -122,6 +120,21 @@ public class CategoryEvent extends AuditingGenericEvent {
}
+ public CategoryEvent(String action, CommonAuditData commonAuditData, String modifier, String categoryName, String subCategoryName,
+ String groupingName, String resourceType) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.resourceType = resourceType;
+ this.modifier = modifier;
+ this.categoryName = categoryName;
+ this.subCategoryName = subCategoryName;
+ this.groupingName = groupingName;
+ }
+
@Override
public void fillFields() {
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java
index 6c5bc3140d..81d27cae53 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ConsumerEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -36,149 +34,159 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.CONSUMER_EVENT_TYPE)
public class ConsumerEvent extends AuditingGenericEvent {
- private static String CONSUMER_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
- + "modifier=\"%s\" ecompUser=\"%s\" status=\"%s\" desc=\"%s\"";
-
- @PartitionKey
- protected UUID timebaseduuid;
-
- @ClusteringColumn
- protected Date timestamp1;
-
- @Column(name = "request_id")
- protected String requestId;
- @Column
- protected String action;
- @Column
- protected String status;
-
- @Column(name = "description")
- protected String desc;
-
- @Column
- private String modifier;
-
- @Column(name = "ecomp_user")
- private String ecompUser;
-
- public ConsumerEvent() {
- super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
-
- public ConsumerEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- this();
- Object value;
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
- if (value != null) {
- setRequestId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
- if (value != null) {
- setAction((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- if (value != null) {
- setStatus((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- if (value != null) {
- setDesc((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
- if (value != null) {
- setModifier((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER);
- if (value != null) {
- setEcompUser((String) value);
- }
- }
-
- @Override
- public void fillFields() {
- fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
-
- fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
- fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
- fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
- fields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER.getDisplayName(), getEcompUser());
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
- simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
- }
-
- public String getModifier() {
- return modifier;
- }
-
- public void setModifier(String modifier) {
- this.modifier = modifier;
- }
-
- public String getEcompUser() {
- return ecompUser;
- }
-
- public void setEcompUser(String ecompUser) {
- this.ecompUser = ecompUser;
- }
-
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
-
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
-
- public Date getTimestamp1() {
- return timestamp1;
- }
-
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- 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;
- }
-
- @Override
- public String toString() {
- return "ConsumerEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
- + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc + ", modifier=" + modifier
- + ", ecompUser=" + ecompUser + "]";
- }
+ private static String CONSUMER_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "modifier=\"%s\" ecompUser=\"%s\" status=\"%s\" desc=\"%s\"";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column(name = "ecomp_user")
+ private String ecompUser;
+
+ public ConsumerEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public ConsumerEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER);
+ if (value != null) {
+ setEcompUser((String) value);
+ }
+ }
+
+ public ConsumerEvent(String action, CommonAuditData commonAuditData, String ecompUser, String modifier) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.modifier = modifier;
+ this.ecompUser = ecompUser;
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ECOMP_USER.getDisplayName(), getEcompUser());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getEcompUser() {
+ return ecompUser;
+ }
+
+ public void setEcompUser(String ecompUser) {
+ this.ecompUser = ecompUser;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ 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;
+ }
+
+ @Override
+ public String toString() {
+ return "ConsumerEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc + ", modifier=" + modifier
+ + ", ecompUser=" + ecompUser + "]";
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java
index 6ee320575c..045263d645 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDeployEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -37,51 +35,51 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_DEPLOY_EVENT_TYPE)
public class DistributionDeployEvent extends AuditingGenericEvent {
- private static String DISTRIBUTION_DEPLOY_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
- + "resourceName=\"%s\" resourceType=\"%s\" currVersion=\"%s\" "
- + "modifierName=\"%s\" modifierUid=\"%s\" did=\"%s\" " + "status=\"%s\" desc=\"%s\"";
+ private static String DISTRIBUTION_DEPLOY_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "resourceName=\"%s\" resourceType=\"%s\" currVersion=\"%s\" "
+ + "modifierName=\"%s\" modifierUid=\"%s\" did=\"%s\" " + "status=\"%s\" desc=\"%s\"";
- @PartitionKey
- protected UUID timebaseduuid;
+ @PartitionKey
+ protected UUID timebaseduuid;
- @ClusteringColumn
- protected Date timestamp1;
+ @ClusteringColumn
+ protected Date timestamp1;
- @Column(name = "request_id")
- protected String requestId;
+ @Column(name = "request_id")
+ protected String requestId;
- @Column(name = "service_instance_id")
- protected String serviceInstanceId;
- @Column
- protected String action;
- @Column
- protected String status;
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
- @Column(name = "description")
- protected String desc;
+ @Column(name = "description")
+ protected String desc;
- @Column(name = "resource_name")
- private String resourceName;
+ @Column(name = "resource_name")
+ private String resourceName;
- @Column(name = "resource_type")
- private String resourceType;
+ @Column(name = "resource_type")
+ private String resourceType;
- @Column(name = "curr_version")
- private String currVersion;
+ @Column(name = "curr_version")
+ private String currVersion;
- @Column
- private String modifier;
+ @Column
+ private String modifier;
- @Column
- private String did;
+ @Column
+ private String did;
- public DistributionDeployEvent() {
+ public DistributionDeployEvent() {
super();
timestamp1 = new Date();
timebaseduuid = UUIDs.timeBased();
}
- public DistributionDeployEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public DistributionDeployEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -124,19 +122,33 @@ public class DistributionDeployEvent extends AuditingGenericEvent {
if (value != null) {
setResourceType((String) value);
}
-
- }
-
- @Override
+ }
+
+
+ public DistributionDeployEvent(String action, CommonAuditData commonAuditData, String did, String modifier,
+ String currVersion, String resourceName, String resourceType) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.did = did;
+ this.modifier = modifier;
+ this.currVersion = currVersion;
+ this.resourceName = resourceName;
+ this.resourceType = resourceType;
+ }
+
+ @Override
public void fillFields() {
fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
-
fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion());
fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
@@ -146,103 +158,103 @@ public class DistributionDeployEvent extends AuditingGenericEvent {
fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
}
- public String getResourceName() {
- return resourceName;
- }
+ public String getResourceName() {
+ return resourceName;
+ }
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
- public String getResourceType() {
- return resourceType;
- }
+ public String getResourceType() {
+ return resourceType;
+ }
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
- public String getCurrVersion() {
- return currVersion;
- }
+ public String getCurrVersion() {
+ return currVersion;
+ }
- public void setCurrVersion(String currVersion) {
- this.currVersion = currVersion;
- }
+ public void setCurrVersion(String currVersion) {
+ this.currVersion = currVersion;
+ }
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
- public Date getTimestamp1() {
- return timestamp1;
- }
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
- public String getRequestId() {
- return requestId;
- }
+ public String getRequestId() {
+ return requestId;
+ }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
- public String getAction() {
- return action;
- }
+ public String getAction() {
+ return action;
+ }
- public void setAction(String action) {
- this.action = action;
- }
+ public void setAction(String action) {
+ this.action = action;
+ }
- public String getStatus() {
- return status;
- }
+ public String getStatus() {
+ return status;
+ }
- public void setStatus(String status) {
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }
- public String getDesc() {
- return desc;
- }
+ public String getDesc() {
+ return desc;
+ }
- public void setDesc(String desc) {
- this.desc = desc;
- }
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
- public String getModifier() {
- return modifier;
- }
+ public String getModifier() {
+ return modifier;
+ }
- public void setModifier(String modifier) {
- this.modifier = modifier;
- }
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
- public String getDid() {
- return did;
- }
+ public String getDid() {
+ return did;
+ }
- public void setDid(String did) {
- this.did = did;
- }
+ public void setDid(String did) {
+ this.did = did;
+ }
- @Override
+ @Override
public String toString() {
return "DistributionDeployEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java
index 4b9fc0318f..474b713b9e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionDownloadEvent.java
@@ -21,11 +21,10 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -37,43 +36,43 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_DOWNLOAD_EVENT_TYPE)
public class DistributionDownloadEvent extends AuditingGenericEvent {
- private static String DISTRIBUTION_DOWNLOAD_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
- + "consumerId=\"%s\" resourceUrl=\"%s\" status=\"%s\" desc=\"%s\"";
+ private static String DISTRIBUTION_DOWNLOAD_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "consumerId=\"%s\" resourceUrl=\"%s\" status=\"%s\" desc=\"%s\"";
- @PartitionKey
- protected UUID timebaseduuid;
+ @PartitionKey
+ protected UUID timebaseduuid;
- @ClusteringColumn
- protected Date timestamp1;
+ @ClusteringColumn
+ protected Date timestamp1;
- @Column(name = "request_id")
- protected String requestId;
+ @Column(name = "request_id")
+ protected String requestId;
- @Column(name = "service_instance_id")
- protected String serviceInstanceId;
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
- @Column
- protected String action;
- @Column
- protected String status;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
- @Column(name = "description")
- protected String desc;
+ @Column(name = "description")
+ protected String desc;
- @Column(name = "consumer_id")
- private String consumerId;
+ @Column(name = "consumer_id")
+ private String consumerId;
- @Column(name = "resource_url")
- private String resourceUrl;
+ @Column(name = "resource_url")
+ private String resourceUrl;
- public DistributionDownloadEvent() {
+ public DistributionDownloadEvent() {
super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
- public DistributionDownloadEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public DistributionDownloadEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -104,17 +103,27 @@ public class DistributionDownloadEvent extends AuditingGenericEvent {
if (value != null) {
setResourceUrl((String) value);
}
-
}
+ public DistributionDownloadEvent(String action, CommonAuditData commonAuditData, DistributionData distributionData) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.consumerId = distributionData.getConsumerId();
+ this.resourceUrl = distributionData.getResourceUrl();
+ }
+
@Override
public void fillFields() {
fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
-
fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+
fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceUrl());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
@@ -122,84 +131,83 @@ public class DistributionDownloadEvent extends AuditingGenericEvent {
fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
}
- public String getConsumerId() {
- return consumerId;
- }
+ public String getConsumerId() {
+ return consumerId;
+ }
- public void setConsumerId(String consumerId) {
- this.consumerId = consumerId;
- }
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
- public String getResourceUrl() {
- return resourceUrl;
- }
+ public String getResourceUrl() {
+ return resourceUrl;
+ }
- public void setResourceUrl(String resourceUrl) {
- this.resourceUrl = resourceUrl;
- }
+ public void setResourceUrl(String resourceUrl) {
+ this.resourceUrl = resourceUrl;
+ }
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
- public Date getTimestamp1() {
- return timestamp1;
- }
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
- public String getRequestId() {
- return requestId;
- }
+ public String getRequestId() {
+ return requestId;
+ }
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
- public String getAction() {
- return action;
- }
+ public String getAction() {
+ return action;
+ }
- public void setAction(String action) {
- this.action = action;
- }
+ public void setAction(String action) {
+ this.action = action;
+ }
- public String getStatus() {
- return status;
- }
+ public String getStatus() {
+ return status;
+ }
- public void setStatus(String status) {
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }
- public String getDesc() {
- return desc;
- }
+ public String getDesc() {
+ return desc;
+ }
- public void setDesc(String desc) {
- this.desc = desc;
- }
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
- @Override
+ @Override
public String toString() {
return "DistributionDownloadEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
- + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceUrl="
- + resourceUrl + "]";
+ + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceUrl=" + resourceUrl + "]";
}
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java
index b125e7a712..70b2d4e7b1 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionEngineEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -37,115 +35,133 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.DISTRIBUTION_ENGINE_EVENT_TYPE)
public class DistributionEngineEvent extends AuditingGenericEvent {
- private static String DISTRIBUTION_ENGINE_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
- + "environmentName=\"%s\" topicName=\"%s\" role=\"%s\" apiKey=\"%s\" " + "status=\"%s\" ";
-
- @PartitionKey
- protected UUID timebaseduuid;
-
- @ClusteringColumn
- protected Date timestamp1;
-
- @Column(name = "request_id")
- protected String requestId;
-
- @Column(name = "service_instance_id")
- protected String serviceInstanceId;
-
- @Column
- protected String action;
- @Column
- protected String status;
-
- @Column(name = "description")
- protected String desc;
-
- @Column(name = "consumer_id")
- private String consumerId;
-
- @Column(name = "DSTATUS_TOPIC")
- private String dstatusTopic;
-
- @Column(name = "DNOTIF_TOPIC")
- private String dnotifTopic;
-
- @Column(name = "d_env")
- private String environmentName;
-
- @Column
- private String role;
-
- @Column(name = "api_key")
- private String apiKey;
-
- public DistributionEngineEvent() {
- super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
-
- public DistributionEngineEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- this();
- Object value;
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
- if (value != null) {
- setRequestId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
- if (value != null) {
- setServiceInstanceId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
- if (value != null) {
- setAction((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- if (value != null) {
- setStatus((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- if (value != null) {
- setDesc((String) value);
- } else {
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC);
- if (value != null) {
- setDesc((String) value);
- }
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
- if (value != null) {
- setConsumerId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME);
- if (value != null) {
- setDstatusTopic((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME);
- if (value != null) {
- setDnotifTopic((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY);
- if (value != null) {
- setApiKey((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME);
- if (value != null) {
- setEnvironmentName((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE);
- if (value != null) {
- setRole((String) value);
- }
- }
-
- @Override
- public void fillFields() {
- fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+ private static String DISTRIBUTION_ENGINE_EVENT_TEMPLATE = "action=\"%s\" timestamp=\"%s\" "
+ + "environmentName=\"%s\" topicName=\"%s\" role=\"%s\" apiKey=\"%s\" " + "status=\"%s\" ";
+
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ @Column(name = "DSTATUS_TOPIC")
+ private String dstatusTopic;
+
+ @Column(name = "DNOTIF_TOPIC")
+ private String dnotifTopic;
+
+ @Column(name = "d_env")
+ private String environmentName;
+
+ @Column
+ private String role;
+
+ @Column(name = "api_key")
+ private String apiKey;
+
+ public DistributionEngineEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public DistributionEngineEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ } else {
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_STATUS_TOPIC_NAME);
+ if (value != null) {
+ setDstatusTopic((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_NOTIFICATION_TOPIC_NAME);
+ if (value != null) {
+ setDnotifTopic((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY);
+ if (value != null) {
+ setApiKey((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME);
+ if (value != null) {
+ setEnvironmentName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ROLE);
+ if (value != null) {
+ setRole((String) value);
+ }
+ }
+
+ public DistributionEngineEvent(String action, CommonAuditData commonAuditData, String consumerId, String distStatusTopic, String distNotifTopic,
+ String apiKey, String envName, String role) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.status = commonAuditData.getStatus();
+ //if no desc, keep distr desc
+ this.desc = commonAuditData.getDescription();
+ this.consumerId = consumerId;
+ this.dstatusTopic = distStatusTopic;
+ this.dnotifTopic = distNotifTopic;
+ this.apiKey = apiKey;
+ this.environmentName = envName;
+ this.role = role;
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+
fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_API_KEY.getDisplayName(), getApiKey());
fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVRIONMENT_NAME.getDisplayName(), getEnvironmentName());
@@ -158,116 +174,116 @@ public class DistributionEngineEvent extends AuditingGenericEvent {
fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
}
- public String getDstatusTopic() {
- return dstatusTopic;
- }
+ public String getDstatusTopic() {
+ return dstatusTopic;
+ }
- public void setDstatusTopic(String dstatusTopic) {
- this.dstatusTopic = dstatusTopic;
- }
+ public void setDstatusTopic(String dstatusTopic) {
+ this.dstatusTopic = dstatusTopic;
+ }
- public String getDnotifTopic() {
- return dnotifTopic;
- }
-
- public void setDnotifTopic(String dnotifTopic) {
- this.dnotifTopic = dnotifTopic;
- }
-
- public String getEnvironmentName() {
- return environmentName;
- }
-
- public void setEnvironmentName(String environmentName) {
- this.environmentName = environmentName;
- }
-
- public String getRole() {
- return role;
- }
-
- public void setRole(String role) {
- this.role = role;
- }
-
- public String getApiKey() {
- return apiKey;
- }
-
- public void setApiKey(String apiKey) {
- this.apiKey = apiKey;
- }
-
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
-
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
-
- public Date getTimestamp1() {
- return timestamp1;
- }
-
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- 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 getConsumerId() {
- return consumerId;
- }
-
- public void setConsumerId(String consumerId) {
- this.consumerId = consumerId;
- }
-
- @Override
- public String toString() {
- return "DistributionEngineEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
- + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
- + ", desc=" + desc + ", consumerId=" + consumerId + ", dstatusTopic=" + dstatusTopic + ", dnotifTopic="
- + dnotifTopic + ", environmentName=" + environmentName + ", role=" + role + ", apiKey=" + apiKey + "]";
- }
+ public String getDnotifTopic() {
+ return dnotifTopic;
+ }
+
+ public void setDnotifTopic(String dnotifTopic) {
+ this.dnotifTopic = dnotifTopic;
+ }
+
+ public String getEnvironmentName() {
+ return environmentName;
+ }
+
+ public void setEnvironmentName(String environmentName) {
+ this.environmentName = environmentName;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public String getApiKey() {
+ return apiKey;
+ }
+
+ public void setApiKey(String apiKey) {
+ this.apiKey = apiKey;
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ 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 getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ @Override
+ public String toString() {
+ return "DistributionEngineEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
+ + ", desc=" + desc + ", consumerId=" + consumerId + ", dstatusTopic=" + dstatusTopic + ", dnotifTopic="
+ + dnotifTopic + ", environmentName=" + environmentName + ", role=" + role + ", apiKey=" + apiKey + "]";
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java
index 6420f08fb5..db48364f0f 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionNotificationEvent.java
@@ -21,11 +21,10 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -81,13 +80,22 @@ public class DistributionNotificationEvent extends AuditingGenericEvent {
@Column
private String did;
+ @Column(name = "env_id")
+ private String envId;
+
+ @Column(name = "vnf_workload_context")
+ private String vnfWorkloadContext;
+
+ @Column(name = "tenant")
+ private String tenant;
+
public DistributionNotificationEvent() {
super();
timestamp1 = new Date();
timebaseduuid = UUIDs.timeBased();
}
- public DistributionNotificationEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public DistributionNotificationEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -138,6 +146,40 @@ public class DistributionNotificationEvent extends AuditingGenericEvent {
if (value != null) {
setTopicName((String) value);
}
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID);
+ if (value != null) {
+ setEnvId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT);
+ if (value != null) {
+ setVnfWorkloadContext((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT);
+ if (value != null) {
+ setTenant((String) value);
+ }
+
+ }
+
+ public DistributionNotificationEvent(String action, CommonAuditData commonAuditData, String did, String modifier, String resourceCurrState,
+ String resourceCurrVersion, String resourceName, String resourceType, String topicName,
+ OperationalEnvAuditData opEnvFields) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.did = did;
+ this.modifier = modifier;
+ this.currState = resourceCurrState;
+ this.currVersion = resourceCurrVersion;
+ this.resourceName = resourceName;
+ this.resourceType = resourceType;
+ this.topicName = topicName;
+ this.envId = opEnvFields.getEnvId();
+ this.vnfWorkloadContext = opEnvFields.getVnfWorkloadContext();
+ this.tenant = opEnvFields.getTenant();
}
@@ -149,6 +191,9 @@ public class DistributionNotificationEvent extends AuditingGenericEvent {
fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ENVIRONMENT_ID.getDisplayName(), getEnvId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT.getDisplayName(), getVnfWorkloadContext());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_TENANT.getDisplayName(), getTenant());
fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(), getDid());
fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
@@ -274,13 +319,38 @@ public class DistributionNotificationEvent extends AuditingGenericEvent {
this.did = did;
}
+ public String getVnfWorkloadContext() {
+ return vnfWorkloadContext;
+ }
+
+ public void setVnfWorkloadContext(String vnfWorkloadContext) {
+ this.vnfWorkloadContext = vnfWorkloadContext;
+ }
+
+ public String getEnvId() {
+ return envId;
+ }
+
+ public void setEnvId(String envId) {
+ this.envId = envId;
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public void setTenant(String tenant) {
+ this.tenant = tenant;
+ }
+
@Override
public String toString() {
return "DistributionNotificationEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ ", requestId=" + requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action
+ ", status=" + status + ", desc=" + desc + ", resourceName=" + resourceName + ", resourceType="
+ resourceType + ", currVersion=" + currVersion + ", modifier=" + modifier + ", currState=" + currState
- + ", topicName=" + topicName + ", did=" + did + "]";
+ + ", topicName=" + topicName + ", did=" + did
+ + ", envId=" + envId + ", vnfWorkloadContext=" + vnfWorkloadContext + ", tenant=" + tenant + "]";
}
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java
index 6565b824ac..c05631ec74 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/DistributionStatusEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -82,7 +80,7 @@ public class DistributionStatusEvent extends AuditingGenericEvent {
}
- public DistributionStatusEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public DistributionStatusEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -125,6 +123,21 @@ public class DistributionStatusEvent extends AuditingGenericEvent {
if (value != null) {
setStatusTime((String) value);
}
+ }
+
+ public DistributionStatusEvent(String action, CommonAuditData commonAuditData, String did, String consumerId, String topicName,
+ String resourceURL, String statusTime) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.did = did;
+ this.consumerId = consumerId;
+ this.topicName = topicName;
+ this.resoureURL = resourceURL;
+ this.statusTime = statusTime;
}
@Override
@@ -243,7 +256,7 @@ public class DistributionStatusEvent extends AuditingGenericEvent {
this.statusTime = statusTime;
}
- @Override
+ @Override
public String toString() {
return "DistributionStatusEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ requestId + ", serviceInstanceId=" + serviceInstanceId + ", action=" + action + ", status=" + status
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java
new file mode 100644
index 0000000000..0ead1ff989
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/EcompOperationalEnvironmentEvent.java
@@ -0,0 +1,164 @@
+package org.openecomp.sdc.be.resources.data.auditing;
+
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Map;
+import java.util.TimeZone;
+
+@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.ECOMP_OPERATIONAL_ENV_EVENT_TYPE)
+public class EcompOperationalEnvironmentEvent extends AuditingGenericEvent {
+
+ @PartitionKey
+ protected String operationalEnvironmentId;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column
+ protected String action;
+
+ @Column(name = "operational_environment_action")
+ protected String operationalEnvironmentAction;
+
+ @Column(name = "operational_environment_name")
+ protected String operationalEnvironmentName;
+
+ @Column(name = "operational_environment_type")
+ protected String operationalEnvironmentType;
+
+ @Column(name = "tenant_context")
+ protected String tenantContext;
+
+
+ public EcompOperationalEnvironmentEvent() {
+ super();
+ timestamp1 = new Date();
+ }
+
+ public EcompOperationalEnvironmentEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID);
+ if (value != null) {
+ setOperationalEnvironmentId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME);
+ if (value != null) {
+ setOperationalEnvironmentName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE);
+ if (value != null) {
+ setOperational_environment_type((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION);
+ if (value != null) {
+ setOperationalEnvironmentAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT);
+ if (value != null) {
+ setTenantContext((String) value);
+ }
+ }
+
+ public EcompOperationalEnvironmentEvent(String action, String operationalEnvironmentId, String operationalEnvironmentName,
+ String operationalEnvironmentType, String operationalEnvironmentAction, String tenantContext) {
+ this();
+ this.action = action;
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ this.operationalEnvironmentType = operationalEnvironmentType;
+ this.operationalEnvironmentName = operationalEnvironmentName;
+ this.operationalEnvironmentAction = operationalEnvironmentAction;
+ this.tenantContext = tenantContext;
+ }
+
+ public String getOperationalEnvironmentId() {
+ return operationalEnvironmentId;
+ }
+
+ public void setOperationalEnvironmentId(String operationalEnvironmentId) {
+ this.operationalEnvironmentId = operationalEnvironmentId;
+ }
+
+ public String getOperationalEnvironmentAction() {
+ return operationalEnvironmentAction;
+ }
+
+ public void setOperationalEnvironmentAction(String operationalEnvironmentAction) {
+ this.operationalEnvironmentAction = operationalEnvironmentAction;
+ }
+
+ public String getOperationalEnvironmentName() {
+ return operationalEnvironmentName;
+ }
+
+ public void setOperationalEnvironmentName(String operationalEnvironmentName) {
+ this.operationalEnvironmentName = operationalEnvironmentName;
+ }
+
+ public String getOperationalEnvironmentType() {
+ return operationalEnvironmentType;
+ }
+
+ public void setOperational_environment_type(String operationalEnvironmentType) {
+ this.operationalEnvironmentType = operationalEnvironmentType;
+ }
+
+ public String getTenantContext() {
+ return tenantContext;
+ }
+
+ public void setTenantContext(String tenantContext) {
+ this.tenantContext = tenantContext;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp) {
+ this.timestamp1 = timestamp;
+ }
+
+ @Override
+ public String getAction() {
+ return action;
+ }
+
+ @Override
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ID.getDisplayName(), getOperationalEnvironmentId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_NAME.getDisplayName(), getOperationalEnvironmentName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_TYPE.getDisplayName(), getOperationalEnvironmentType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_OPERATIONAL_ENVIRONMENT_ACTION.getDisplayName(), getOperationalEnvironmentAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TENANT_CONTEXT.getDisplayName(), getTenantContext());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ @Override
+ public String toString() {
+ return "EcompOperationalEnvironmentEvent [timestamp1=" + timestamp1 + ", action = " + action
+ + ", operational_environment_id=" + operationalEnvironmentId + ", operational_environment_name=" + operationalEnvironmentName
+ + ", operational_environment_type=" + operationalEnvironmentType + ", operational_environment_action=" + operationalEnvironmentAction
+ + ", tenant_context=" + tenantContext + "]";
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java
index f32acc81c4..ed546301fc 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ExternalApiEvent.java
@@ -21,11 +21,10 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -40,334 +39,358 @@ import com.datastax.driver.mapping.annotations.Table;
*/
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)
public class ExternalApiEvent extends AuditingGenericEvent {
- @PartitionKey
- protected UUID timebaseduuid;
-
- @ClusteringColumn()
- protected Date timestamp1;
-
- @Column
- protected String action;
- @Column
- protected String status;
-
- @Column(name = "description")
- protected String desc;
-
- @Column(name = "consumer_id")
- private String consumerId;
-
- @Column(name = "resource_url")
- private String resourceURL;
-
- @Column(name = "resource_name")
- private String resourceName;
-
- @Column(name = "resource_type")
- private String resourceType;
-
- @Column(name = "service_instance_id")
- protected String serviceInstanceId;
-
- @Column(name = "invariant_uuid")
- protected String invariantUuid;
-
- @Column(name = "modifier")
- private String modifier;
-
- @Column(name = "prev_version")
- protected String prevVersion;
-
- @Column(name = "curr_version")
- private String currVersion;
-
- @Column(name = "prev_state")
- protected String prevState;
-
- @Column(name = "curr_state")
- protected String currState;
-
- @Column(name = "prev_artifact_uuid")
- private String prevArtifactUuid;
-
- @Column(name = "curr_artifact_uuid")
- private String currArtifactUuid;
-
- @Column(name = "artifact_data")
- private String artifactData;
-
- public ExternalApiEvent() {
- super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
-
- public ExternalApiEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- this();
- Object value;
-
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
- if (value != null) {
- setAction((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- if (value != null) {
- setStatus((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- if (value != null) {
- setDesc((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
- if (value != null) {
- setConsumerId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL);
- if (value != null) {
- setResourceURL((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME);
- if (value != null) {
- setResourceName((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
- if (value != null) {
- setResourceType((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
- if (value != null) {
- setServiceInstanceId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID);
- if (value != null) {
- setInvariantUuid((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
- if (value != null) {
- setModifier((String) value);
- }
-
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION);
- if (value != null) {
- setPrevVersion((String) value);
- }
-
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION);
- if (value != null) {
- setCurrVersion((String) value);
- }
-
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE);
- if (value != null) {
- setPrevState((String) value);
- }
-
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE);
- if (value != null) {
- setCurrState((String) value);
- }
-
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
- if (value != null) {
- setPrevArtifactUuid((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
- if (value != null) {
- setCurrArtifactUuid((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
- if (value != null) {
- setArtifactData((String) value);
- }
- }
-
- @Override
- public void fillFields() {
- fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
- fields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUuid());
- fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
- fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
- simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
- fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceURL());
- fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
- fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
- fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
-
- fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion());
- fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion());
- fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState());
- fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState());
-
- fields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUuid());
- fields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUuid());
- fields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData());
- }
-
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
-
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
-
- public Date getTimestamp1() {
- return timestamp1;
- }
-
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- 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 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 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 getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public String getInvariantUuid() {
- return invariantUuid;
- }
-
- public void setInvariantUuid(String invariantUuid) {
- this.invariantUuid = invariantUuid;
- }
-
- public String getModifier() {
- return modifier;
- }
-
- public void setModifier(String modifier) {
- this.modifier = modifier;
- }
-
- 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;
- }
-
- @Override
- public String toString() {
- return "ExternalApiEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action=" + action
- + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceURL="
- + resourceURL + ", resourceName=" + resourceName + ", resourceType=" + resourceType
- + ", serviceInstanceId=" + serviceInstanceId + ", invariantUuid=" + invariantUuid + ", modifier=" + modifier
- + ", prevVersion=" + prevVersion+ ", currVersion=" + currVersion
- + ", prevState=" + prevState + ", currState=" + currState
- + ", prevArtifactUuid="
- + prevArtifactUuid + ", currArtifactUuid=" + currArtifactUuid + ", artifactData=" + artifactData + "]";
- }
-
- 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 getPrevState() {
- return prevState;
- }
-
- public void setPrevState(String prevState) {
- this.prevState = prevState;
- }
-
- public String getCurrState() {
- return currState;
- }
-
- public void setCurrState(String currState) {
- this.currState = currState;
- }
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn()
+ protected Date timestamp1;
+
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column(name = "consumer_id")
+ private String consumerId;
+
+ @Column(name = "resource_url")
+ private String resourceURL;
+
+ @Column(name = "resource_name")
+ private String resourceName;
+
+ @Column(name = "resource_type")
+ private String resourceType;
+
+ @Column(name = "service_instance_id")
+ protected String serviceInstanceId;
+
+ @Column(name = "invariant_uuid")
+ protected String invariantUuid;
+
+ @Column(name = "modifier")
+ private String modifier;
+
+ @Column(name = "prev_version")
+ protected String prevVersion;
+
+ @Column(name = "curr_version")
+ private String currVersion;
+
+ @Column(name = "prev_state")
+ protected String prevState;
+
+ @Column(name = "curr_state")
+ protected String currState;
+
+ @Column(name = "prev_artifact_uuid")
+ private String prevArtifactUuid;
+
+ @Column(name = "curr_artifact_uuid")
+ private String currArtifactUuid;
+
+ @Column(name = "artifact_data")
+ private String artifactData;
+
+ public ExternalApiEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public ExternalApiEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID);
+ if (value != null) {
+ setConsumerId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL);
+ if (value != null) {
+ setResourceURL((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME);
+ if (value != null) {
+ setResourceName((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE);
+ if (value != null) {
+ setResourceType((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID);
+ if (value != null) {
+ setServiceInstanceId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID);
+ if (value != null) {
+ setInvariantUuid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION);
+ if (value != null) {
+ setPrevVersion((String) value);
+ }
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION);
+ if (value != null) {
+ setCurrVersion((String) value);
+ }
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE);
+ if (value != null) {
+ setPrevState((String) value);
+ }
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE);
+ if (value != null) {
+ setCurrState((String) value);
+ }
+
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID);
+ if (value != null) {
+ setPrevArtifactUuid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID);
+ if (value != null) {
+ setCurrArtifactUuid((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA);
+ if (value != null) {
+ setArtifactData((String) value);
+ }
+ }
+
+ public ExternalApiEvent(String action, CommonAuditData commonAuditData, String resourceType, String resourceName,
+ String distConsumerId, String distResourceUrl, ResourceAuditData prevParams, ResourceAuditData currParams,
+ String modifier, String invariantUuid, String artifactData) {
+ this();
+ this.action = action;
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.requestId = commonAuditData.getRequestId();
+ this.consumerId = distConsumerId;
+ this.resourceURL = distResourceUrl;
+ this.resourceName = resourceName;
+ this.resourceType = resourceType;
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.invariantUuid = invariantUuid;
+ this.modifier = modifier;
+ this.prevVersion = prevParams.getVersion();
+ this.prevState = prevParams.getState();
+ this.prevArtifactUuid = prevParams.getArtifactUuid();
+ this.currVersion = currParams.getVersion();
+ this.currState = currParams.getState();
+ this.currArtifactUuid = currParams.getArtifactUuid();
+ this.artifactData = artifactData;
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_INVARIANT_UUID.getDisplayName(), getInvariantUuid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID.getDisplayName(), getConsumerId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL.getDisplayName(), getResourceURL());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME.getDisplayName(), getResourceName());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE.getDisplayName(), getResourceType());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_VERSION.getDisplayName(), getPrevVersion());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_VERSION.getDisplayName(), getCurrVersion());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_PREV_STATE.getDisplayName(), getPrevState());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_CURR_STATE.getDisplayName(), getCurrState());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID.getDisplayName(), getPrevArtifactUuid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID.getDisplayName(), getCurrArtifactUuid());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA.getDisplayName(), getArtifactData());
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ 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 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 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 getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
+ public String getInvariantUuid() {
+ return invariantUuid;
+ }
+
+ public void setInvariantUuid(String invariantUuid) {
+ this.invariantUuid = invariantUuid;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ 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;
+ }
+
+ @Override
+ public String toString() {
+ return "ExternalApiEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", action=" + action
+ + ", status=" + status + ", desc=" + desc + ", consumerId=" + consumerId + ", resourceURL="
+ + resourceURL + ", resourceName=" + resourceName + ", resourceType=" + resourceType
+ + ", serviceInstanceId=" + serviceInstanceId + ", invariantUuid=" + invariantUuid + ", modifier=" + modifier
+ + ", prevVersion=" + prevVersion+ ", currVersion=" + currVersion
+ + ", prevState=" + prevState + ", currState=" + currState
+ + ", prevArtifactUuid="
+ + prevArtifactUuid + ", currArtifactUuid=" + currArtifactUuid + ", artifactData=" + artifactData + "]";
+ }
+
+ 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 getPrevState() {
+ return prevState;
+ }
+
+ public void setPrevState(String prevState) {
+ this.prevState = prevState;
+ }
+
+ public String getCurrState() {
+ return currState;
+ }
+
+ public void setCurrState(String currState) {
+ this.currState = currState;
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java
index 0b86651b8a..f80db7ef6e 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetCategoryHierarchyEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -36,147 +34,157 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.GET_CATEGORY_HIERARCHY_EVENT_TYPE)
public class GetCategoryHierarchyEvent extends AuditingGenericEvent {
- @PartitionKey
- protected UUID timebaseduuid;
-
- @ClusteringColumn()
- // @Column(name="timestamp")
- protected Date timestamp1;
-
- @Column(name = "request_id")
- protected String requestId;
- @Column
- protected String action;
- @Column
- protected String status;
-
- @Column(name = "description")
- protected String desc;
-
- @Column
- private String modifier;
-
- @Column
- private String details;
-
- public GetCategoryHierarchyEvent() {
- super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
-
- public GetCategoryHierarchyEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- this();
- Object value;
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
- if (value != null) {
- setRequestId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
- if (value != null) {
- setAction((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- if (value != null) {
- setStatus((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- if (value != null) {
- setDesc((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
- if (value != null) {
- setModifier((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS);
- if (value != null) {
- setDetails((String) value);
- }
- }
-
- @Override
- public void fillFields() {
- fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
-
- fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
- fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
- fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS.getDisplayName(), getDetails());
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
- simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
- }
-
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
-
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
-
- public Date getTimestamp1() {
- return timestamp1;
- }
-
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- 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 getModifier() {
- return modifier;
- }
-
- public void setModifier(String modifier) {
- this.modifier = modifier;
- }
-
- public String getDetails() {
- return details;
- }
-
- public void setDetails(String details) {
- this.details = details;
- }
-
- @Override
- public String toString() {
- return "GetCategoryHierarchyEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
- + ", requestId=" + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc
- + ", modifier=" + modifier + ", details=" + details + "]";
- }
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn()
+ // @Column(name="timestamp")
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column
+ private String details;
+
+ public GetCategoryHierarchyEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public GetCategoryHierarchyEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS);
+ if (value != null) {
+ setDetails((String) value);
+ }
+ }
+
+ public GetCategoryHierarchyEvent(String action, CommonAuditData commonAuditData, String modifier, String details) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.desc = commonAuditData.getDescription();
+ this.status = commonAuditData.getStatus();
+ this.modifier = modifier;
+ this.details = details;
+ }
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID.getDisplayName(), getServiceInstanceId());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DETAILS.getDisplayName(), getDetails());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ 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 getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ @Override
+ public String toString() {
+ return "GetCategoryHierarchyEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1
+ + ", requestId=" + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc
+ + ", modifier=" + modifier + ", details=" + details + "]";
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java
index 728a0430b0..41f7f05079 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/GetUsersListEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -36,151 +34,162 @@ import com.datastax.driver.mapping.annotations.Table;
@Table(keyspace = AuditingTypesConstants.AUDIT_KEYSPACE, name = AuditingTypesConstants.GET_USERS_LIST_EVENT_TYPE)
public class GetUsersListEvent extends AuditingGenericEvent {
- @PartitionKey
- protected UUID timebaseduuid;
-
- @ClusteringColumn
- protected Date timestamp1;
-
- @Column(name = "request_id")
- protected String requestId;
- @Column
- protected String action;
- @Column
- protected String status;
-
- @Column(name = "description")
- protected String desc;
-
- @Column
- private String modifier;
-
- @Column
- private String details;
-
- public GetUsersListEvent() {
- super();
- timestamp1 = new Date();
- timebaseduuid = UUIDs.timeBased();
- }
-
- public GetUsersListEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
- this();
- Object value;
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
- if (value != null) {
- setRequestId((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
- if (value != null) {
- setAction((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
- if (value != null) {
- setStatus((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
- if (value != null) {
- setDesc((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
- if (value != null) {
- setModifier((String) value);
- }
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS);
- if (value != null) {
- setDetails((String) value);
- } else {
- value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS);
- if (value != null) {
- setDetails((String) value);
- }
- }
- }
-
- @Override
- public void fillFields() {
- fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
-
- fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
- fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
- fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
- fields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS.getDisplayName(), getDetails());
- fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
- simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
- }
-
- public UUID getTimebaseduuid() {
- return timebaseduuid;
- }
-
- public void setTimebaseduuid(UUID timebaseduuid) {
- this.timebaseduuid = timebaseduuid;
- }
-
- public Date getTimestamp1() {
- return timestamp1;
- }
-
- public void setTimestamp1(Date timestamp1) {
- this.timestamp1 = timestamp1;
- }
-
- public String getRequestId() {
- return requestId;
- }
-
- public void setRequestId(String requestId) {
- this.requestId = requestId;
- }
-
- public String getAction() {
- return action;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- 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 getModifier() {
- return modifier;
- }
-
- public void setModifier(String modifier) {
- this.modifier = modifier;
- }
-
- public String getDetails() {
- return details;
- }
-
- public void setDetails(String details) {
- this.details = details;
- }
-
- @Override
- public String toString() {
- return "GetUsersListEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
- + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc + ", modifier=" + modifier
- + ", details=" + details + "]";
- }
+ @PartitionKey
+ protected UUID timebaseduuid;
+
+ @ClusteringColumn
+ protected Date timestamp1;
+
+ @Column(name = "request_id")
+ protected String requestId;
+ @Column
+ protected String action;
+ @Column
+ protected String status;
+
+ @Column(name = "description")
+ protected String desc;
+
+ @Column
+ private String modifier;
+
+ @Column
+ private String details;
+
+ public GetUsersListEvent() {
+ super();
+ timestamp1 = new Date();
+ timebaseduuid = UUIDs.timeBased();
+ }
+
+ public GetUsersListEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
+ this();
+ Object value;
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
+ if (value != null) {
+ setRequestId((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_ACTION);
+ if (value != null) {
+ setAction((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_STATUS);
+ if (value != null) {
+ setStatus((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DESC);
+ if (value != null) {
+ setDesc((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID);
+ if (value != null) {
+ setModifier((String) value);
+ }
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS);
+ if (value != null) {
+ setDetails((String) value);
+ } else {
+ value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_DETAILS);
+ if (value != null) {
+ setDetails((String) value);
+ }
+ }
+ }
+
+ public GetUsersListEvent(String action, CommonAuditData commonAuditData, String modifier, String userDetails) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.modifier = modifier;
+ this.details = userDetails;
+ }
+
+
+ @Override
+ public void fillFields() {
+ fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
+
+ fields.put(AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(), getAction());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(), getStatus());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_DESC.getDisplayName(), getDesc());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_USER_DETAILS.getDisplayName(), getDetails());
+ fields.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_UID.getDisplayName(), getModifier());
+ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern);
+ simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ fields.put(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP.getDisplayName(), simpleDateFormat.format(timestamp1));
+ }
+
+ public UUID getTimebaseduuid() {
+ return timebaseduuid;
+ }
+
+ public void setTimebaseduuid(UUID timebaseduuid) {
+ this.timebaseduuid = timebaseduuid;
+ }
+
+ public Date getTimestamp1() {
+ return timestamp1;
+ }
+
+ public void setTimestamp1(Date timestamp1) {
+ this.timestamp1 = timestamp1;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ 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 getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ @Override
+ public String toString() {
+ return "GetUsersListEvent [timebaseduuid=" + timebaseduuid + ", timestamp1=" + timestamp1 + ", requestId="
+ + requestId + ", action=" + action + ", status=" + status + ", desc=" + desc + ", modifier=" + modifier
+ + ", details=" + details + "]";
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java
index 21a84751da..214f2187af 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/ResourceAdminEvent.java
@@ -21,11 +21,10 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
+import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -118,7 +117,33 @@ public class ResourceAdminEvent extends AuditingGenericEvent {
timebaseduuid = UUIDs.timeBased();
}
- public ResourceAdminEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public ResourceAdminEvent(String action, CommonAuditData commonAuditData, ResourceAuditData prevParams, ResourceAuditData currParams, String resourceType,
+ String resourceName, String invariantUuid, String modifier, String artifactData, String comment, String did, String toscaNodeType) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.desc = commonAuditData.getDescription();
+ this.status = commonAuditData.getStatus();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.currState = currParams.getState();
+ this.currVersion = currParams.getVersion();
+ this.currArtifactUUID = currParams.getArtifactUuid();
+ this.prevState = prevParams.getState();
+ this.prevVersion = prevParams.getVersion();
+ this.prevArtifactUUID = prevParams.getArtifactUuid();
+ this.resourceName = resourceName;
+ this.resourceType = resourceType;
+ this.comment = comment;
+ this.dcurrStatus = currParams.getDistributionStatus();
+ this.dprevStatus = prevParams.getDistributionStatus();
+ this.artifactData = artifactData;
+ this.modifier = modifier;
+ this.invariantUUID = invariantUuid;
+ this.did = did;
+ this.toscaNodeType = toscaNodeType;
+ }
+
+ public ResourceAdminEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -209,6 +234,7 @@ public class ResourceAdminEvent extends AuditingGenericEvent {
}
+
@Override
public void fillFields() {
fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java
index a1ae1e2df1..80a370dc62 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAccessEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -69,7 +67,7 @@ public class UserAccessEvent extends AuditingGenericEvent {
timebaseduuid = UUIDs.timeBased();
}
- public UserAccessEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public UserAccessEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -99,6 +97,17 @@ public class UserAccessEvent extends AuditingGenericEvent {
}
+ public UserAccessEvent(String action, CommonAuditData commonAuditData, String user) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.userUid = user;
+ this.status = commonAuditData.getStatus();
+ this.desc = commonAuditData.getDescription();
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ }
+
+
@Override
public void fillFields() {
fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
@@ -137,6 +146,14 @@ public class UserAccessEvent extends AuditingGenericEvent {
this.requestId = requestId;
}
+ @Override
+ public String getServiceInstanceId() { return serviceInstanceId; }
+
+ @Override
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+
public String getStatus() {
return status;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java
index 72d7d2ff6d..1ab3ae783b 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/UserAdminEvent.java
@@ -21,11 +21,9 @@
package org.openecomp.sdc.be.resources.data.auditing;
import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.TimeZone;
-import java.util.UUID;
+import java.util.*;
+import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import com.datastax.driver.core.utils.UUIDs;
@@ -76,10 +74,9 @@ public class UserAdminEvent extends AuditingGenericEvent {
super();
timestamp1 = new Date();
timebaseduuid = UUIDs.timeBased();
-
}
- public UserAdminEvent(EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
+ public UserAdminEvent(Map<AuditingFieldsKeysEnum, Object> auditingFields) {
this();
Object value;
value = auditingFields.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID);
@@ -117,6 +114,18 @@ public class UserAdminEvent extends AuditingGenericEvent {
}
+ public UserAdminEvent(String action, CommonAuditData commonAuditData, String modifier, String userBefore, String userAfter) {
+ this();
+ this.action = action;
+ this.requestId = commonAuditData.getRequestId();
+ this.status = commonAuditData.getStatus();
+ this.modifier = modifier;
+ this.serviceInstanceId = commonAuditData.getServiceInstanceId();
+ this.desc = commonAuditData.getDescription();
+ this.userBefore = userBefore;
+ this.userAfter = userAfter;
+ }
+
@Override
public void fillFields() {
fields.put(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID.getDisplayName(), getRequestId());
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java
new file mode 100644
index 0000000000..ae5a02ee75
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/CommonAuditData.java
@@ -0,0 +1,75 @@
+package org.openecomp.sdc.be.resources.data.auditing.model;
+
+public class CommonAuditData {
+ private String description;
+ private String requestId;
+ private String serviceInstanceId;
+ private String status;
+
+ private CommonAuditData() {
+ //for builder
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId ;
+ }
+
+ public static Builder newBuilder() {
+ return new Builder();
+ }
+
+ public static class Builder {
+ private final CommonAuditData instance;
+
+ private Builder() {
+ instance = new CommonAuditData();
+ }
+
+ public Builder description(String description) {
+ instance.description = description;
+ return this;
+ }
+
+ public Builder status(int status) {
+ instance.status = String.valueOf(status);
+ return this;
+ }
+
+ public Builder status(String status) {
+ instance.status = status;
+ return this;
+ }
+
+ public Builder requestId(String requestId) {
+ instance.requestId = requestId;
+ return this;
+ }
+
+ public Builder serviceInstanceId(String serviceInstanceId) {
+ instance.serviceInstanceId = serviceInstanceId;
+ return this;
+ }
+
+ public CommonAuditData build() {
+ return instance;
+ }
+
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionData.java
new file mode 100644
index 0000000000..fe45050e07
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/DistributionData.java
@@ -0,0 +1,20 @@
+package org.openecomp.sdc.be.resources.data.auditing.model;
+
+public class DistributionData {
+
+ private final String consumerId;
+ private final String resourceUrl;
+
+ public DistributionData(String consumerId, String resourceUrl) {
+ this.consumerId = consumerId;
+ this.resourceUrl = resourceUrl;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public String getResourceUrl() {
+ return resourceUrl;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/OperationalEnvAuditData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/OperationalEnvAuditData.java
new file mode 100644
index 0000000000..968b41c74a
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/OperationalEnvAuditData.java
@@ -0,0 +1,26 @@
+package org.openecomp.sdc.be.resources.data.auditing.model;
+
+public class OperationalEnvAuditData {
+ private String envId;
+ private String vnfWorkloadContext;
+ private String tenant;
+
+ public String getEnvId() {
+ return envId;
+ }
+
+ public String getVnfWorkloadContext() {
+ return vnfWorkloadContext;
+ }
+
+ public String getTenant() {
+ return tenant;
+ }
+
+ public OperationalEnvAuditData(String envId, String vnfWorkloadContext, String tenant) {
+ this.envId = envId;
+ this.vnfWorkloadContext = vnfWorkloadContext;
+ this.tenant = tenant;
+ }
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java
new file mode 100644
index 0000000000..d66050a5f9
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/model/ResourceAuditData.java
@@ -0,0 +1,60 @@
+package org.openecomp.sdc.be.resources.data.auditing.model;
+
+public class ResourceAuditData {
+ private String artifactUuid;
+ private String state;
+ private String version;
+ private String distributionStatus;
+
+ private ResourceAuditData() {
+ //for builder
+ }
+
+ public static Builder newBuilder() {
+ return new Builder();
+ }
+
+ public String getArtifactUuid() {
+ return artifactUuid;
+ }
+ public String getState() {
+ return state;
+ }
+ public String getVersion() {
+ return version;
+ }
+ public String getDistributionStatus() { return distributionStatus; }
+
+
+ public static class Builder {
+ private final ResourceAuditData instance;
+
+ private Builder() {
+ instance = new ResourceAuditData();
+ }
+
+ public Builder artifactUuid(String artifactUuid) {
+ instance.artifactUuid = artifactUuid;
+ return this;
+ }
+
+ public Builder state(String state) {
+ instance.state = state;
+ return this;
+ }
+
+ public Builder version(String version) {
+ instance.version = version;
+ return this;
+ }
+
+ public Builder distributionStatus(String distributionStatus) {
+ instance.distributionStatus = distributionStatus;
+ return this;
+ }
+
+ public ResourceAuditData build() {
+ return instance;
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java
index d42eb78ed3..27f5674558 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/CategoryData.java
@@ -20,17 +20,16 @@
package org.openecomp.sdc.be.resources.data.category;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class CategoryData extends GraphNode {
private CategoryDataDefinition categoryDataDefinition;
@@ -61,7 +60,7 @@ public class CategoryData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return categoryDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java
index ca40ae986b..ba451cb930 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/GroupingData.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.resources.data.category;
-import java.util.HashMap;
-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.datatypes.category.GroupingDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import java.util.HashMap;
+import java.util.Map;
+
public class GroupingData extends GraphNode {
private GroupingDataDefinition groupingDataDefinition;
@@ -56,7 +56,7 @@ public class GroupingData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return groupingDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java
index 1112b4514d..5011992c61 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/category/SubCategoryData.java
@@ -20,17 +20,16 @@
package org.openecomp.sdc.be.resources.data.category;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class SubCategoryData extends GraphNode {
@@ -67,7 +66,7 @@ public class SubCategoryData extends GraphNode {
}
@Override
- public Object getUniqueId() {
+ public String getUniqueId() {
return subCategoryDataDefinition.getUniqueId();
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java
index a3c5218495..2c659ff527 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/impl/ResourceUploader.java
@@ -78,8 +78,6 @@ public class ResourceUploader implements IResourceUploader {
public ResourceUploadStatus saveArtifact(ESArtifactData artifactData, boolean isReload) {
ResourceUploadStatus status = ResourceUploadStatus.OK;
if (resourceDAO == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInitializationError,
- "Save Artifact - internal object not initialized");
BeEcompErrorManager.getInstance()
.logBeInitializationError("Save Artifact - internal object not initialized");
log.debug("update artifact failed - resourceDAO is null");
@@ -101,8 +99,6 @@ public class ResourceUploader implements IResourceUploader {
} catch (ResourceDAOException e) {
status = ResourceUploadStatus.ERROR;
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError,
- "Save Artifact to database");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Save Artifact to database");
log.debug("ResourceUploadStatus:saveArtifact failed with exception ", e);
}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java
deleted file mode 100644
index 0f6faaa02c..0000000000
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java
+++ /dev/null
@@ -1,291 +0,0 @@
-package org.openecomp.sdc.be.dao.jsongraph;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.Test;
-import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
-import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
-import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
-import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-
-import com.thinkaurelius.titan.core.TitanGraph;
-
-import fj.data.Either;
-
-
-public class TitanDaoTest {
-
- private TitanDao createTestSubject() {
- return new TitanDao(new TitanGraphClient());
- }
-
-
- @Test
- public void testCommit() throws Exception {
- TitanDao testSubject;
- TitanOperationStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.commit();
- }
-
-
- @Test
- public void testRollback() throws Exception {
- TitanDao testSubject;
- TitanOperationStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.rollback();
- }
-
-
- @Test
- public void testGetGraph() throws Exception {
- TitanDao testSubject;
- Either<TitanGraph, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getGraph();
- }
-
-
-
-
-
- @Test
- public void testGetVertexByPropertyAndLabel() throws Exception {
- TitanDao testSubject;
- GraphPropertyEnum name = null;
- Object value = null;
- VertexTypeEnum label = null;
- Either<GraphVertex, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getVertexByPropertyAndLabel(name, value, label);
- }
-
-
- @Test
- public void testGetVertexByPropertyAndLabel_1() throws Exception {
- TitanDao testSubject;
- GraphPropertyEnum name = null;
- Object value = null;
- VertexTypeEnum label = null;
- JsonParseFlagEnum parseFlag = null;
- Either<GraphVertex, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getVertexByPropertyAndLabel(name, value, label, parseFlag);
- }
-
-
- @Test
- public void testGetVertexById() throws Exception {
- TitanDao testSubject;
- String id = "";
- Either<GraphVertex, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getVertexById(id);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @Test
- public void testGetByCriteria() throws Exception {
- TitanDao testSubject;
- VertexTypeEnum type = null;
- Map<GraphPropertyEnum, Object> props = null;
- Either<List<GraphVertex>, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getByCriteria(type, props);
- }
-
-
- @Test
- public void testGetByCriteria_1() throws Exception {
- TitanDao testSubject;
- VertexTypeEnum type = null;
- Map<GraphPropertyEnum, Object> props = null;
- JsonParseFlagEnum parseFlag = null;
- Either<List<GraphVertex>, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getByCriteria(type, props, parseFlag);
- }
-
-
- @Test
- public void testGetByCriteria_2() throws Exception {
- TitanDao testSubject;
- VertexTypeEnum type = null;
- Map<GraphPropertyEnum, Object> props = null;
- Map<GraphPropertyEnum, Object> hasNotProps = null;
- JsonParseFlagEnum parseFlag = null;
- Either<List<GraphVertex>, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getByCriteria(type, props, hasNotProps, parseFlag);
- }
-
-
-
-
-
- @Test
- public void testGetChildVertex() throws Exception {
- TitanDao testSubject;
- GraphVertex parentVertex = null;
- EdgeLabelEnum edgeLabel = null;
- JsonParseFlagEnum parseFlag = null;
- Either<GraphVertex, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getChildVertex(parentVertex, edgeLabel, parseFlag);
- }
-
-
- @Test
- public void testGetParentVertex() throws Exception {
- TitanDao testSubject;
- GraphVertex parentVertex = null;
- EdgeLabelEnum edgeLabel = null;
- JsonParseFlagEnum parseFlag = null;
- Either<GraphVertex, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getParentVertex(parentVertex, edgeLabel, parseFlag);
- }
-
-
- @Test
- public void testGetChildrenVertecies() throws Exception {
- TitanDao testSubject;
- GraphVertex parentVertex = null;
- EdgeLabelEnum edgeLabel = null;
- JsonParseFlagEnum parseFlag = null;
- Either<List<GraphVertex>, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getChildrenVertecies(parentVertex, edgeLabel, parseFlag);
- }
-
-
- @Test
- public void testGetParentVertecies() throws Exception {
- TitanDao testSubject;
- GraphVertex parentVertex = null;
- EdgeLabelEnum edgeLabel = null;
- JsonParseFlagEnum parseFlag = null;
- Either<List<GraphVertex>, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getParentVertecies(parentVertex, edgeLabel, parseFlag);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @Test
- public void testUpdateVertexMetadataPropertiesWithJson() throws Exception {
- TitanDao testSubject;
- Vertex vertex = null;
- Map<GraphPropertyEnum, Object> properties = null;
- TitanOperationStatus result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.updateVertexMetadataPropertiesWithJson(vertex, properties);
- }
-
-
-
-
-
-
-
- @Test
- public void testGetProperty_1() throws Exception {
- TitanDao testSubject;
- Edge edge = null;
- EdgePropertyEnum key = null;
- Object result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getProperty(edge, key);
- }
-
-
-
-
- @Test
- public void testGetBelongingEdgeByCriteria_1() throws Exception {
- TitanDao testSubject;
- String parentId = "";
- EdgeLabelEnum label = null;
- Map<GraphPropertyEnum, Object> properties = null;
- Either<Edge, TitanOperationStatus> result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getBelongingEdgeByCriteria(parentId, label, properties);
- }
-} \ No newline at end of file
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfoTest.java
deleted file mode 100644
index 63091f4412..0000000000
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/rest/RestConfigurationInfoTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-package org.openecomp.sdc.be.dao.rest;
-
-import org.junit.Test;
-
-
-public class RestConfigurationInfoTest {
-
- private RestConfigurationInfo createTestSubject() {
- return new RestConfigurationInfo();
- }
-
-
- @Test
- public void testGetReadTimeoutInSec() throws Exception {
- RestConfigurationInfo testSubject;
- Integer result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getReadTimeoutInSec();
- }
-
-
- @Test
- public void testSetReadTimeoutInSec() throws Exception {
- RestConfigurationInfo testSubject;
- Integer readTimeoutInSec = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setReadTimeoutInSec(readTimeoutInSec);
- }
-
-
- @Test
- public void testGetIgnoreCertificate() throws Exception {
- RestConfigurationInfo testSubject;
- Boolean result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getIgnoreCertificate();
- }
-
-
- @Test
- public void testSetIgnoreCertificate() throws Exception {
- RestConfigurationInfo testSubject;
- Boolean ignoreCertificate = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setIgnoreCertificate(ignoreCertificate);
- }
-
-
- @Test
- public void testGetConnectionPoolSize() throws Exception {
- RestConfigurationInfo testSubject;
- Integer result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getConnectionPoolSize();
- }
-
-
- @Test
- public void testSetConnectionPoolSize() throws Exception {
- RestConfigurationInfo testSubject;
- Integer connectionPoolSize = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setConnectionPoolSize(connectionPoolSize);
- }
-
-
- @Test
- public void testGetConnectTimeoutInSec() throws Exception {
- RestConfigurationInfo testSubject;
- Integer result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getConnectTimeoutInSec();
- }
-
-
- @Test
- public void testSetConnectTimeoutInSec() throws Exception {
- RestConfigurationInfo testSubject;
- Integer connectTimeoutInSec = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setConnectTimeoutInSec(connectTimeoutInSec);
- }
-
-
- @Test
- public void testGetSocketTimeoutInSec() throws Exception {
- RestConfigurationInfo testSubject;
- Integer result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getSocketTimeoutInSec();
- }
-
-
- @Test
- public void testSetSocketTimeoutInSec() throws Exception {
- RestConfigurationInfo testSubject;
- Integer socketTimeoutInSec = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setSocketTimeoutInSec(socketTimeoutInSec);
- }
-
-
- @Test
- public void testToString() throws Exception {
- RestConfigurationInfo testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.toString();
- }
-} \ No newline at end of file
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java
index cac429c6fb..e02611a5a4 100644
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,54 +20,69 @@
package org.openecomp.sdc.be.resources;
-import java.io.IOException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.google.common.collect.ImmutableList;
+import org.junit.Test;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
+import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
-import org.codehaus.jackson.JsonGenerationException;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.junit.Test;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.openecomp.sdc.be.utils.FixtureHelpers.fixture;
+import static org.openecomp.sdc.be.utils.JsonTester.testJsonMap;
public class JsonParserUtilsTests {
- @Test
- public void testProperties() throws JsonGenerationException, JsonMappingException, IOException {
- PropertyDataDefinition dataDefinition = new PropertyDataDefinition();
- dataDefinition.setName("myName");
- dataDefinition.setDescription("description");
- dataDefinition.setDefaultValue("default11");
- SchemaDefinition entrySchema = new SchemaDefinition();
- PropertyDataDefinition property = new PropertyDataDefinition();
- property.setName("name12");
- property.setType("string");
- entrySchema.setProperty(property);
- Map<String, PropertyDataDefinition> properties = new HashMap<>();
- properties.put("key1", property);
- properties.put("key2", property);
-
- entrySchema.setProperties(properties );
- dataDefinition.setSchema(entrySchema);
-
- Map<String, PropertyDataDefinition> map = new HashMap<>();
- map.put("prop", dataDefinition);
-
-// String jsonstring = JsonParserUtils.jsonToString(map);
-
-// Map<String, PropertyDataDefinition> parseToJson = JsonParserUtils.parseToJson(jsonstring, PropertyDataDefinition.class);
-// Map<String, PropertyDataDefinition> parseToJson;
-// TypeReference<Map<String, PropertyDataDefinition>> typeRef = new TypeReference<Map<String, PropertyDataDefinition>>() {
-// };
-// ObjectMapper mapper = new ObjectMapper();
-// try {
-// parseToJson = mapper.readValue(jsonstring, typeRef);
-// } catch (Exception e) {
-//// logger.debug("Failed to parse json {}", json, e);
-// }
-
-// System.out.println(parseToJson);
-
- }
+ private static final String FIXTURE_PATH = "fixtures/ListCapabilityDataDefinition.json";
+
+ @Test
+ public void testToMap() {
+ String json = fixture(FIXTURE_PATH);
+ Map<String, ListCapabilityDataDefinition> actual = JsonParserUtils.toMap(json, ListCapabilityDataDefinition.class);
+ Map<String, ListCapabilityDataDefinition> expected = buildMap();
+ assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
+ }
+
+ @Test
+ public void testJacksonFasterXml() {
+ ObjectMapper mapper = new ObjectMapper()
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
+ assertThatCode(() -> testJsonMap(buildMap(), ListCapabilityDataDefinition.class, FIXTURE_PATH, mapper))
+ .doesNotThrowAnyException();
+ }
+
+ private Map<String, ListCapabilityDataDefinition> buildMap() {
+ Map<String, ListCapabilityDataDefinition> map = new HashMap<>();
+ map.put("org.openecomp.capabilities.Forwarder", buildListCapabilityDataDefinition());
+ return map;
+ }
+
+ private ListCapabilityDataDefinition buildListCapabilityDataDefinition() {
+ CapabilityDataDefinition dataDefinition = new CapabilityDataDefinition();
+ dataDefinition.setName("forwarder");
+ dataDefinition.setType("org.openecomp.capabilities.Forwarder");
+ dataDefinition.setUniqueId("capability.deb142fd-95eb-48f7-99ae-81ab09466b1e.forwarder");
+ dataDefinition.setOwnerId("deb142fd-95eb-48f7-99ae-81ab09466b1e");
+ dataDefinition.setMinOccurrences("1");
+ dataDefinition.setLeftOccurrences("UNBOUNDED");
+ dataDefinition.setMaxOccurrences("UNBOUNDED");
+ dataDefinition.setCapabilitySources(buildCapabilitySources());
+
+ return new ListCapabilityDataDefinition(ImmutableList.of(dataDefinition));
+ }
+ private List<String> buildCapabilitySources() {
+ return ImmutableList.of(
+ "org.openecomp.resource.cp.nodes.network.Port",
+ "org.openecomp.resource.cp.v2.extCP",
+ "org.openecomp.resource.cp.v2.extContrailCP");
+ }
}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java
index 6dede29977..97ccb43959 100644
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/TitanGenericDaoTest.java
@@ -23,6 +23,7 @@ package org.openecomp.sdc.be.resources;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -72,6 +73,8 @@ import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.TitanVertex;
import com.thinkaurelius.titan.core.attribute.Text;
+import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
+import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
import com.thinkaurelius.titan.core.schema.TitanManagement;
import fj.data.Either;
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/data/PolicyTypeDataTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/data/PolicyTypeDataTest.java
index 840a55b336..afd58c5994 100644
--- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/data/PolicyTypeDataTest.java
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/data/PolicyTypeDataTest.java
@@ -55,15 +55,4 @@ public class PolicyTypeDataTest {
testSubject = createTestSubject();
result = testSubject.getPolicyTypeDataDefinition();
}
-
-
- @Test
- public void testSetPolicyTypeDataDefinition() throws Exception {
- PolicyTypeData testSubject;
- PolicyTypeDataDefinition policyTypeDataDefinition = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setPolicyTypeDataDefinition(policyTypeDataDefinition);
- }
} \ No newline at end of file
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/utils/FixtureHelpers.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/utils/FixtureHelpers.java
new file mode 100644
index 0000000000..1992b8043c
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/utils/FixtureHelpers.java
@@ -0,0 +1,50 @@
+package org.openecomp.sdc.be.utils;
+
+import java.io.IOException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+
+import com.google.common.io.Resources;
+
+/**
+ * A set of helper method for fixture files.
+ */
+public class FixtureHelpers {
+
+ private FixtureHelpers() {
+ // singleton
+ }
+
+ /**
+ * Reads the given fixture file from the classpath (e. g. {@code src/test/resources})
+ * and returns its contents as a UTF-8 string.
+ *
+ * @param filename the filename of the fixture file
+ * @return the contents of {@code src/test/resources/{filename}}
+ * @throws IllegalArgumentException if an I/O error occurs.
+ */
+ public static String fixture(String filename) {
+ return fixture(filename, StandardCharsets.UTF_8);
+ }
+
+ /**
+ * Reads the given fixture file from the classpath (e. g. {@code src/test/resources})
+ * and returns its contents as a string.
+ *
+ * @param filename the filename of the fixture file
+ * @param charset the character set of {@code filename}
+ * @return the contents of {@code src/test/resources/{filename}}
+ * @throws IllegalArgumentException if an I/O error occurs.
+ */
+ private static String fixture(String filename, Charset charset) {
+ try {
+ URL url = Resources.getResource(filename);
+ String text = Resources.toString(url, charset);
+ return text.trim();
+ }
+ catch (IOException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+}
diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/utils/JsonTester.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/utils/JsonTester.java
new file mode 100644
index 0000000000..4f1b2f24bc
--- /dev/null
+++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/utils/JsonTester.java
@@ -0,0 +1,42 @@
+package org.openecomp.sdc.be.utils;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.MapType;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.openecomp.sdc.be.utils.FixtureHelpers.fixture;
+
+public class JsonTester {
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ public JsonTester() {
+
+ }
+
+ public static <T> void testJson(T object, String fixturePath) throws Exception {
+ testJson(object, fixturePath, MAPPER);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> void testJson(T object, String fixturePath, ObjectMapper mapper) throws Exception {
+ T expectedObject = (T) mapper.readValue(fixture(fixturePath), object.getClass());
+ String expectedJson = mapper.writeValueAsString(expectedObject);
+ String actualJson = mapper.writeValueAsString(object);
+
+ assertThat(actualJson).isEqualTo(expectedJson);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> void testJsonMap(Map<String, T> map, Class<T> valueClass, String fixturePath, ObjectMapper mapper) throws Exception {
+ MapType mapType = TypeFactory.defaultInstance().constructMapType(Map.class, String.class, valueClass);
+ Map<String, T> expectedObject = mapper.readValue(fixture(fixturePath), mapType);
+ String expectedJson = mapper.writeValueAsString(expectedObject);
+
+ String actualJson = mapper.writeValueAsString(map);
+
+ assertThat(actualJson).isEqualTo(expectedJson);
+ }
+} \ No newline at end of file
diff --git a/catalog-dao/src/test/resources/fixtures/ListCapabilityDataDefinition.json b/catalog-dao/src/test/resources/fixtures/ListCapabilityDataDefinition.json
new file mode 100644
index 0000000000..6a193ae0e7
--- /dev/null
+++ b/catalog-dao/src/test/resources/fixtures/ListCapabilityDataDefinition.json
@@ -0,0 +1,19 @@
+{
+ "org.openecomp.capabilities.Forwarder": [
+ {
+ "name": "forwarder",
+ "type": "org.openecomp.capabilities.Forwarder",
+ "uniqueId": "capability.deb142fd-95eb-48f7-99ae-81ab09466b1e.forwarder",
+ "ownerId": "deb142fd-95eb-48f7-99ae-81ab09466b1e",
+ "capabilitySources": [
+ "org.openecomp.resource.cp.nodes.network.Port",
+ "org.openecomp.resource.cp.v2.extCP",
+ "org.openecomp.resource.cp.v2.extContrailCP"
+ ],
+ "minOccurrences": "1",
+ "leftOccurrences": "UNBOUNDED",
+ "maxOccurrences": "UNBOUNDED",
+ "empty": false
+ }
+ ]
+}
diff --git a/catalog-fe/pom.xml b/catalog-fe/pom.xml
index 360d5b28ed..f0ecbbce37 100644
--- a/catalog-fe/pom.xml
+++ b/catalog-fe/pom.xml
@@ -35,13 +35,6 @@
<!-- File changes listener -->
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
@@ -49,13 +42,6 @@
</dependency>
<dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
@@ -126,6 +112,12 @@
</dependency>
<dependency>
+ <groupId>org.glassfish.jersey.inject</groupId>
+ <artifactId>jersey-hk2</artifactId>
+ <version>${jersey-bom.version}</version>
+ </dependency>
+
+ <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
@@ -294,7 +286,6 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
@@ -485,7 +476,7 @@
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
- <version>0.23.0</version>
+ <version>${fabric8.version}</version>
<configuration>
<verbose>true</verbose>
diff --git a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb
index ea2d9033ab..e4c36ca00b 100644
--- a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb
+++ b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb
@@ -53,6 +53,12 @@ dcae:
<% end -%>
healthCheckUri: "/dcae/healthCheck"
+dcae:
+ protocol: http
+ host: localhost
+ port: 8181
+ healthCheckUri: "/dcae/healthCheck"
+
identificationHeaderFields:
-
- &HTTP_IV_USER HTTP_IV_USER
@@ -100,3 +106,8 @@ systemMonitoring:
kibanaHost: <%= @kb_host_ip %>
kibanaPort: 5601
kibanaProtocol: http
+
+healthStatusExclude:
+ - DE
+ - ES
+ - DMAAP
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/client/BackendClient.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/client/BackendClient.java
deleted file mode 100644
index 92e497d278..0000000000
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/client/BackendClient.java
+++ /dev/null
@@ -1,179 +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.fe.client;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.ws.rs.container.AsyncResponse;
-import javax.ws.rs.core.Response;
-
-import org.apache.http.HttpStatus;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
-import org.apache.http.entity.InputStreamEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.ssl.SSLContextBuilder;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.api.ResponseInfo;
-import org.openecomp.sdc.common.api.ResponseInfo.ResponseStatusEnum;
-import org.openecomp.sdc.fe.impl.Audit;
-import org.openecomp.sdc.fe.impl.HttpRequestInfo;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class BackendClient {
-
- private static Logger log = LoggerFactory.getLogger(BackendClient.class.getName());
-
- private HostnameVerifier hostnameVerifier = null;
-
- private CloseableHttpClient backendHttpClient;
- private String backendHost;
- private String backendContext;
-
- public BackendClient(String protocol, String backendHost, String backendContext) {
-
- this.backendContext = backendContext;
- hostnameVerifier = new HostnameVerifier() {
-
- public boolean verify(String hostname, SSLSession session) {
-
- return true;
- }
- };
-
- if (protocol == null || protocol.isEmpty() || protocol.equals(Constants.HTTP)) {
- backendHttpClient = HttpClients.createDefault();
- this.backendHost = Constants.HTTP + "://" + backendHost;
- } else {
- // NULL can be returned in case of error
- backendHttpClient = getSslClient();
- this.backendHost = Constants.HTTPS + "://" + backendHost;
- }
-
- }
-
- public HostnameVerifier getHostnameVerifier() {
- return hostnameVerifier;
- }
-
- private CloseableHttpClient getSslClient() {
-
- CloseableHttpClient httpClient = null;
- try {
-
- // SSLContextBuilder is not thread safe
- SSLContextBuilder builder = new SSLContextBuilder();
- builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
- SSLContext sslContext = builder.build();
-
- httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(hostnameVerifier).setSslcontext(sslContext)
- .build();
-
- } catch (Exception e) {
- log.error("Failed to create https client", e);
- return null;
- }
-
- return httpClient;
-
- }
-
- public ResponseInfo forwardRequestToBackend(HttpRequestInfo requestInfo, List<String> requiredHeaders,
- AsyncResponse asyncResponse) {
-
- ResponseInfo responseInfo = null;
- log.debug("forwardRequestToBackend");
- if (backendHttpClient == null) {
- responseInfo = new ResponseInfo(ResponseStatusEnum.INTERNAL_ERROR, "Failed to create https client");
- Audit.error(log, requestInfo, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- asyncResponse.resume(
- Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(responseInfo.toString()).build());
- return responseInfo;
- }
-
- CloseableHttpResponse response = null;
- int status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
- HttpPost httpPost = new HttpPost(backendHost + backendContext);
- try {
-
- log.debug("Executing request {}", httpPost.getRequestLine());
- httpPost.setEntity(new InputStreamEntity(requestInfo.getRequestData()));
- boolean allHeadersAreSet = copyHeadersToRequest(requiredHeaders, requestInfo, httpPost);
- if (!allHeadersAreSet) {
- responseInfo = new ResponseInfo(ResponseStatusEnum.MISSING_HEADERS, "Required headers are missing");
- asyncResponse
- .resume(Response.status(HttpStatus.SC_BAD_REQUEST).entity(responseInfo.toString()).build());
- Audit.error(log, requestInfo, HttpStatus.SC_BAD_REQUEST);
- } else {
- response = backendHttpClient.execute(httpPost);
- status = response.getStatusLine().getStatusCode();
- asyncResponse.resume(Response.status(status).entity(response.getEntity()).build());
- }
- Audit.info(log, requestInfo, status);
-
- } catch (IOException e) {
- log.error("connection with backend failed with exception", e);
- responseInfo = new ResponseInfo(ResponseStatusEnum.INTERNAL_ERROR, e.getMessage());
- Audit.error(log, requestInfo, HttpStatus.SC_INTERNAL_SERVER_ERROR);
- asyncResponse.resume(
- Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(responseInfo.toString()).build());
- } finally {
- try {
- if (response != null) {
- response.close();
- }
- backendHttpClient.close();
- } catch (IOException e) {
- log.error("failed to close httpClient: {}", e.getMessage());
- }
-
- }
-
- return responseInfo;
-
- }
-
- private boolean copyHeadersToRequest(List<String> requiredHeaders, HttpRequestInfo requestInfo, HttpPost httpPost) {
- boolean allHeadersAreSet = false;
- Map<String, String> originalHeaders = requestInfo.getHeaders();
- for (String headerName : requiredHeaders) {
- String headerValue = originalHeaders.get(headerName);
- if (headerValue != null) {
- httpPost.setHeader(headerName, headerValue);
- } else {
- log.error("missing required header {}", headerName);
- return allHeadersAreSet;
- }
- }
- allHeadersAreSet = true;
- return allHeadersAreSet;
- }
-
-}
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java
index 1ed6ac5c07..563af73ebe 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeHealthCheckServlet.java
@@ -20,6 +20,9 @@
package org.openecomp.sdc.fe.servlets;
+import com.jcabi.aspects.Loggable;
+import org.openecomp.sdc.common.servlets.BasicServlet;
+
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
@@ -27,10 +30,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.servlets.BasicServlet;
-
-import com.jcabi.aspects.Loggable;
+import static org.openecomp.sdc.common.api.Constants.HEALTH_CHECK_SERVICE_ATTR;
@Loggable(prepend = true, value = Loggable.TRACE, trim = false)
@Path("/healthCheck")
@@ -38,8 +38,7 @@ public class FeHealthCheckServlet extends BasicServlet {
@GET
public Response getFEandBeHealthCheck(@Context final HttpServletRequest request) {
ServletContext context = request.getSession().getServletContext();
- HealthCheckService hcs = ((HealthCheckService) context.getAttribute(Constants.HEALTH_CHECK_SERVICE_ATTR));
+ HealthCheckService hcs = ((HealthCheckService) context.getAttribute(HEALTH_CHECK_SERVICE_ATTR));
return hcs.getFeHealth();
}
-
}
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java
index 11d4abf4af..f9ac666933 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java
@@ -50,7 +50,6 @@ public class FeProxyServlet extends SSLProxyServlet {
try {
logFeRequest(request);
} catch (Exception e) {
- FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHttpLoggingError, "FE Request");
FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Request");
log.error("Unexpected FE request logging error :", e);
}
@@ -67,7 +66,6 @@ public class FeProxyServlet extends SSLProxyServlet {
try {
logFeResponse(request, proxyResponse);
} catch (Exception e) {
- FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHttpLoggingError, "FE Response");
FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Response");
log.error("Unexpected FE response logging error :", e);
}
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java
index 7010034214..fce5d35d20 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,327 +20,326 @@
package org.openecomp.sdc.fe.servlets;
-import java.io.IOException;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-
-import javax.servlet.ServletContext;
-import javax.ws.rs.core.Response;
-
-import org.apache.http.HttpStatus;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.util.EntityUtils;
-import org.openecomp.sdc.common.api.Constants;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.reflect.TypeToken;
import org.openecomp.sdc.common.api.HealthCheckInfo;
-import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
import org.openecomp.sdc.common.api.HealthCheckWrapper;
-import org.openecomp.sdc.common.config.EcompErrorName;
-import org.openecomp.sdc.common.impl.ExternalConfiguration;
+import org.openecomp.sdc.common.config.EcompErrorEnum;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.openecomp.sdc.common.http.config.Timeouts;
import org.openecomp.sdc.common.util.HealthCheckUtil;
import org.openecomp.sdc.fe.config.Configuration;
import org.openecomp.sdc.fe.config.ConfigurationManager;
import org.openecomp.sdc.fe.config.FeEcompErrorManager;
import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonSyntaxException;
-import com.google.gson.reflect.TypeToken;
+import javax.servlet.ServletContext;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.Arrays.asList;
+import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
+import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
+import static org.apache.http.HttpStatus.SC_OK;
+import static org.openecomp.sdc.common.api.Constants.*;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.*;
+import static org.openecomp.sdc.common.http.client.api.HttpRequest.get;
+import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion;
+import static org.slf4j.LoggerFactory.getLogger;
public class HealthCheckService {
- private class HealthStatus {
- public String body;
- public int statusCode;
-
- public HealthStatus(int code, String body) {
- this.body = body;
- this.statusCode = code;
- }
- }
-
- private static final String URL = "%s://%s:%s/sdc2/rest/healthCheck";
- private static Logger healthLogger = LoggerFactory.getLogger("asdc.fe.healthcheck");
- private static Logger log = LoggerFactory.getLogger(HealthCheckService.class.getName());
-
- private HealthStatus lastHealthStatus = new HealthStatus(500, "{}");
- private final List<String> healthCheckFeComponents = Arrays.asList(Constants.HC_COMPONENT_ON_BOARDING, Constants.HC_COMPONENT_DCAE);
-
- private class HealthCheckScheduledTask implements Runnable {
- @Override
- public void run() {
- healthLogger.trace("Executing FE Health Check Task - Start");
- HealthStatus currentHealth = checkHealth();
- int currentHealthStatus = currentHealth.statusCode;
- healthLogger.trace("Executing FE Health Check Task - Status = {}", currentHealthStatus);
-
- // In case health status was changed, issue alarm/recovery
- if (currentHealthStatus != lastHealthStatus.statusCode) {
- log.trace("FE Health State Changed to {}. Issuing alarm / recovery alarm...", currentHealthStatus);
- logFeAlarm(currentHealthStatus);
- }
-
- // Anyway, update latest response
- lastHealthStatus = currentHealth;
- }
- }
-
- /**
- * This executor will execute the health check task.
- */
- ScheduledExecutorService healthCheckExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- return new Thread(r, "FE-Health-Check-Thread");
- }
- });
- private ServletContext context;
-
- public HealthCheckService(ServletContext context) {
- this.context = context;
- }
-
- public void start(int interval) {
- this.healthCheckExecutor.scheduleAtFixedRate(new HealthCheckScheduledTask(), 0, interval, TimeUnit.SECONDS);
- }
-
- /**
- * To be used by the HealthCheckServlet
- *
- * @return
- */
- public Response getFeHealth() {
- return this.buildResponse(lastHealthStatus.statusCode, lastHealthStatus.body);
- }
-
- private HealthStatus checkHealth() {
- CloseableHttpClient httpClient = null;
- try {
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
- .getConfiguration();
- String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(),
- config.getBeHttpPort());
- httpClient = getHttpClient(config);
- HttpGet httpGet = new HttpGet(redirectedUrl);
- CloseableHttpResponse beResponse;
- HealthCheckWrapper feAggHealthCheck;
- try {
- beResponse = httpClient.execute(httpGet);
- log.debug("HC call to BE - status code is {}", beResponse.getStatusLine().getStatusCode());
- String beJsonResponse = EntityUtils.toString(beResponse.getEntity());
- feAggHealthCheck = getFeHealthCheckInfos(gson, beJsonResponse);
- } catch (Exception e) {
- log.debug("Health Check error when trying to connect to BE or external FE. Error: {}", e.getMessage());
- log.error("Health Check error when trying to connect to BE or external FE.", e);
- String beDowneResponse = gson.toJson(getBeDownCheckInfos());
- return new HealthStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR, beDowneResponse);
- }
-
- //Getting aggregate FE status
- boolean aggregateFeStatus = HealthCheckUtil.getAggregateStatus(feAggHealthCheck.getComponentsInfo());
- return new HealthStatus(aggregateFeStatus ? HttpStatus.SC_OK : HttpStatus.SC_INTERNAL_SERVER_ERROR, gson.toJson(feAggHealthCheck));
- } catch (Exception e) {
- FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHealthCheckGeneralError, "Unexpected FE Health check error");
- FeEcompErrorManager.getInstance().logFeHealthCheckGeneralError("Unexpected FE Health check error");
- log.error("Unexpected FE health check error {}", e.getMessage());
- return new HealthStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
- } finally {
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- log.error("Couldn't close HC HTTP Client: ", e);
- }
- }
- }
- }
-
-
-
-
-
- private Response buildResponse(int status, String jsonResponse) {
- healthLogger.trace("FE and BE health check status: {}", jsonResponse);
- return Response.status(status).entity(jsonResponse).build();
- }
-
- private void logFeAlarm(int lastFeStatus) {
-
- switch (lastFeStatus) {
- case 200:
- FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHealthCheckRecovery,
- "FE Health Recovered");
- FeEcompErrorManager.getInstance().logFeHealthCheckRecovery("FE Health Recovered");
- break;
- case 500:
- FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHealthCheckConnectionError,
- "Connection with ASDC-BE is probably down");
- FeEcompErrorManager.getInstance().logFeHealthCheckError("Connection with ASDC-BE is probably down");
- break;
- default:
- break;
- }
-
- }
-
- private HealthCheckWrapper getFeHealthCheckInfos(Gson gson, String responseString) {
- Type wrapperType = new TypeToken<HealthCheckWrapper>() {
- }.getType();
- HealthCheckWrapper healthCheckWrapper = gson.fromJson(responseString, wrapperType);
- String appVersion = ExternalConfiguration.getAppVersion();
- String description = "OK";
- healthCheckWrapper.getComponentsInfo()
- .add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckStatus.UP, appVersion, description));
-
- //add hosted components fe component
- for (String component: healthCheckFeComponents) {
- List<HealthCheckInfo> feComponentsInfo = addHostedComponentsFeHealthCheck(component);
- HealthCheckInfo baseComponentHCInfo = healthCheckWrapper.getComponentsInfo().stream().filter(c -> c.getHealthCheckComponent().equals(component)).findFirst().orElse(null);
- if (baseComponentHCInfo != null) {
- if (baseComponentHCInfo.getComponentsInfo() == null) {
- baseComponentHCInfo.setComponentsInfo(new ArrayList<>());
- }
- baseComponentHCInfo.getComponentsInfo().addAll(feComponentsInfo);
- boolean status = HealthCheckUtil.getAggregateStatus(baseComponentHCInfo.getComponentsInfo());
- baseComponentHCInfo.setHealthCheckStatus(status ? HealthCheckStatus.UP : HealthCheckStatus.DOWN);
-
- String componentsDesc = HealthCheckUtil.getAggregateDescription(baseComponentHCInfo.getComponentsInfo(), baseComponentHCInfo.getDescription());
- if (componentsDesc.length() > 0) { //aggregated description contains all the internal components desc
- baseComponentHCInfo.setDescription(componentsDesc);
- }
- } else {
- log.error("{} not exists in HealthCheck info", component);
- }
- }
- return healthCheckWrapper;
- }
-
- private List<HealthCheckInfo> addHostedComponentsFeHealthCheck(String baseComponent) {
- Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
- .getConfiguration();
-
- String healthCheckUrl = null;
- switch(baseComponent) {
- case Constants.HC_COMPONENT_ON_BOARDING:
- healthCheckUrl = buildOnboardingHealthCheckUrl(config);
- break;
- case Constants.HC_COMPONENT_DCAE:
- healthCheckUrl = buildDcaeHealthCheckUrl(config);
- break;
- }
-
- String description;
-
- if (healthCheckUrl != null) {
- ObjectMapper mapper = new ObjectMapper();
- CloseableHttpClient httpClient = getHttpClient(config);
- HttpGet httpGet = new HttpGet(healthCheckUrl);
- CloseableHttpResponse beResponse;
-
- try {
- beResponse = httpClient.execute(httpGet);
- int beStatus = beResponse.getStatusLine().getStatusCode();
- if (beStatus == HttpStatus.SC_OK || beStatus == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
- try {
- String beJsonResponse = EntityUtils.toString(beResponse.getEntity());
-
- Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>(){});
- if (healthCheckMap.containsKey("componentsInfo")) {
- List<HealthCheckInfo> componentsInfo = mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {});
- return componentsInfo;
- } else {
- description = "Internal components are missing";
- }
- } catch (JsonSyntaxException e) {
- log.error("{} Unexpected response body ", baseComponent, e);
- description = baseComponent + " Unexpected response body. Response code: " + beStatus;
- }
- } else {
- description = "Response code: " + beStatus;
- log.trace("{} Health Check Response code: {}", baseComponent, beStatus);
- }
- } catch (Exception e) {
- log.error("{} Unexpected response ", baseComponent, e);
- description = baseComponent + " Unexpected response: " + e.getMessage();
- }
- } else {
- description = baseComponent + " health check Configuration is missing";
- }
-
- return Arrays.asList(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckStatus.DOWN, null, description));
- }
-
- private HealthCheckWrapper getBeDownCheckInfos() {
- List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>();
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_FE, HealthCheckStatus.UP,
- ExternalConfiguration.getAppVersion(), "OK"));
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_BE, HealthCheckStatus.DOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_TITAN, HealthCheckStatus.UNKNOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_CASSANDRA, HealthCheckStatus.UNKNOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UNKNOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_ON_BOARDING, HealthCheckStatus.UNKNOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(Constants.HC_COMPONENT_DCAE, HealthCheckStatus.UNKNOWN, null, null));
- HealthCheckWrapper hcWrapper = new HealthCheckWrapper(healthCheckInfos, "UNKNOWN", "UNKNOWN");
- return hcWrapper;
- }
-
- private CloseableHttpClient getHttpClient(Configuration config) {
- int timeout = 3000;
- int socketTimeout = config.getHealthCheckSocketTimeoutInMs(5000);
- RequestConfig.Builder requestBuilder = RequestConfig.custom();
- requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(socketTimeout);
-
- HttpClientBuilder builder = HttpClientBuilder.create();
- builder.setDefaultRequestConfig(requestBuilder.build());
- return builder.build();
- }
-
- private String buildOnboardingHealthCheckUrl(Configuration config) {
-
- Configuration.OnboardingConfig onboardingConfig = config.getOnboarding();
-
- if (onboardingConfig != null) {
- String protocol = onboardingConfig.getProtocol();
- String host = onboardingConfig.getHost();
- Integer port = onboardingConfig.getPort();
- String uri = onboardingConfig.getHealthCheckUri();
-
- return protocol + "://" + host + ":" + port + uri;
- }
-
- log.error("onboarding health check configuration is missing.");
- return null;
- }
-
- private String buildDcaeHealthCheckUrl(Configuration config) {
-
- Configuration.DcaeConfig dcaeConfig = config.getDcae();
-
- if (dcaeConfig != null) {
- String protocol = dcaeConfig.getProtocol();
- String host = dcaeConfig.getHost();
- Integer port = dcaeConfig.getPort();
- String uri = dcaeConfig.getHealthCheckUri();
-
- return protocol + "://" + host + ":" + port + uri;
- }
-
- log.error("dcae health check configuration is missing.");
- return null;
- }
+ private static final String URL = "%s://%s:%s/sdc2/rest/healthCheck";
+ private static Logger healthLogger = getLogger("asdc.fe.healthcheck");
+ private static Logger log = getLogger(HealthCheckService.class.getName());
+ private final List<String> healthCheckFeComponents = asList(HC_COMPONENT_ON_BOARDING, HC_COMPONENT_DCAE);
+ private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil();
+ private static final String DEBUG_CONTEXT = "HEALTH_FE";
+ /**
+ * This executor will execute the health check task.
+ */
+ ScheduledExecutorService healthCheckExecutor = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "FE-Health-Check-Thread"));
+
+ public void setTask(HealthCheckScheduledTask task) {
+ this.task = task;
+ }
+
+ private HealthCheckScheduledTask task ;
+ private HealthStatus lastHealthStatus = new HealthStatus(500, "{}");
+ private ServletContext context;
+
+ public HealthCheckService(ServletContext context) {
+ this.context = context;
+ this.task = new HealthCheckScheduledTask();
+ }
+
+ public void start(int interval) {
+ this.healthCheckExecutor.scheduleAtFixedRate( getTask() , 0, interval, TimeUnit.SECONDS);
+ }
+
+ /**
+ * To be used by the HealthCheckServlet
+ *
+ * @return
+ */
+ public Response getFeHealth() {
+ return this.buildResponse(lastHealthStatus.statusCode, lastHealthStatus.body);
+ }
+
+ private Response buildResponse(int status, String jsonResponse) {
+ healthLogger.trace("FE and BE health check status: {}", jsonResponse);
+ return Response.status(status).entity(jsonResponse).build();
+ }
+
+ public HealthStatus getLastHealthStatus() {
+ return lastHealthStatus;
+ }
+ public HealthCheckScheduledTask getTask() {
+ return task;
+ }
+
+ //immutable
+ protected static class HealthStatus {
+
+ private String body;
+ private int statusCode;
+
+ public HealthStatus(int code, String body) {
+ this.body = body;
+ this.statusCode = code;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public String getBody() {
+ return body;
+ }
+ }
+
+ protected class HealthCheckScheduledTask implements Runnable {
+ @Override
+ public void run() {
+ healthLogger.trace("Executing FE Health Check Task - Start");
+ HealthStatus currentHealth = checkHealth();
+ int currentHealthStatus = currentHealth.statusCode;
+ healthLogger.trace("Executing FE Health Check Task - Status = {}", currentHealthStatus);
+
+ // In case health status was changed, issue alarm/recovery
+ if (currentHealthStatus != lastHealthStatus.statusCode) {
+ log.trace("FE Health State Changed to {}. Issuing alarm / recovery alarm...", currentHealthStatus);
+ logFeAlarm(currentHealthStatus);
+ }
+
+ // Anyway, update latest response
+ lastHealthStatus = currentHealth;
+ }
+
+ private List<HealthCheckInfo> addHostedComponentsFeHealthCheck(String baseComponent) {
+ Configuration config = getConfig();
+
+ String healthCheckUrl = null;
+ switch (baseComponent) {
+ case HC_COMPONENT_ON_BOARDING:
+ healthCheckUrl = buildOnboardingHealthCheckUrl(config);
+ break;
+ case HC_COMPONENT_DCAE:
+ healthCheckUrl = buildDcaeHealthCheckUrl(config);
+ break;
+ default:
+ log.debug("Unsupported base component {}", baseComponent);
+ }
+
+ StringBuilder description = new StringBuilder("");
+ int connectTimeoutMs = 3000;
+ int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(5000);
+
+ if (healthCheckUrl != null) {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ HttpResponse<String> response = get(healthCheckUrl, new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs)));
+ int beStatus = response.getStatusCode();
+ if (beStatus == SC_OK || beStatus == SC_INTERNAL_SERVER_ERROR) {
+ String beJsonResponse = response.getResponse();
+ return convertResponse(beJsonResponse, mapper, baseComponent, description, beStatus);
+ } else {
+ description.append("Response code: " + beStatus);
+ log.trace("{} Health Check Response code: {}", baseComponent, beStatus);
+ }
+ } catch (Exception e) {
+ log.error("{} Unexpected response ", baseComponent, e);
+ description.append(baseComponent + " Unexpected response: " + e.getMessage());
+ }
+ } else {
+ description.append(baseComponent + " health check Configuration is missing");
+ }
+
+ return asList(new HealthCheckInfo(HC_COMPONENT_FE, DOWN, null, description.toString()));
+ }
+
+ private void logFeAlarm(int lastFeStatus) {
+ switch (lastFeStatus) {
+ case 200:
+ FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckRecovery, "FE Health Recovered");
+ FeEcompErrorManager.getInstance().logFeHealthCheckRecovery("FE Health Recovered");
+ break;
+ case 500:
+ FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT, EcompErrorEnum.FeHealthCheckError, "Connection with ASDC-BE is probably down");
+ FeEcompErrorManager.getInstance().logFeHealthCheckError("Connection with ASDC-BE is probably down");
+ break;
+ default:
+ break;
+ }
+ }
+
+ protected HealthStatus checkHealth() {
+ HttpResponse<String> response;
+ try {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ Configuration config = getConfig();
+ String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(),
+ HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort());
+
+ int connectTimeoutMs = 3000;
+ int readTimeoutMs = config.getHealthCheckSocketTimeoutInMs(5000);
+
+ HealthCheckWrapper feAggHealthCheck;
+ try {
+ response = get(redirectedUrl, new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs)));
+ log.debug("HC call to BE - status code is {}", response.getStatusCode());
+ String beJsonResponse = response.getResponse();
+ feAggHealthCheck = getFeHealthCheckInfos(gson, beJsonResponse);
+ } catch (Exception e) {
+ log.debug("Health Check error when trying to connect to BE or external FE. Error: {}", e.getMessage());
+ log.error("Health Check error when trying to connect to BE or external FE.", e);
+ String beDowneResponse = gson.toJson(getBeDownCheckInfos());
+ return new HealthStatus(SC_INTERNAL_SERVER_ERROR, beDowneResponse);
+ }
+
+ //Getting aggregate FE status
+ boolean aggregateFeStatus = (response != null && response.getStatusCode() == SC_INTERNAL_SERVER_ERROR) ? false : healthCheckUtil.getAggregateStatus(feAggHealthCheck.getComponentsInfo(), config.getHealthStatusExclude());
+ return new HealthStatus(aggregateFeStatus ? SC_OK : SC_INTERNAL_SERVER_ERROR, gson.toJson(feAggHealthCheck));
+ } catch (Exception e) {
+ FeEcompErrorManager.getInstance().processEcompError(DEBUG_CONTEXT,EcompErrorEnum.FeHealthCheckGeneralError, "Unexpected FE Health check error");
+ FeEcompErrorManager.getInstance().logFeHealthCheckGeneralError("Unexpected FE Health check error");
+ log.error("Unexpected FE health check error {}", e.getMessage());
+ return new HealthStatus(SC_INTERNAL_SERVER_ERROR, e.getMessage());
+ }
+ }
+
+ protected Configuration getConfig(){
+ return ((ConfigurationManager) context.getAttribute(CONFIGURATION_MANAGER_ATTR))
+ .getConfiguration();
+ }
+
+ protected HealthCheckWrapper getFeHealthCheckInfos(Gson gson, String responseString) {
+ Configuration config = getConfig();
+ Type wrapperType = new TypeToken<HealthCheckWrapper>() {
+ }.getType();
+ HealthCheckWrapper healthCheckWrapper = gson.fromJson(responseString, wrapperType);
+ String appVersion = getAppVersion();
+ String description = "OK";
+ healthCheckWrapper.getComponentsInfo()
+ .add(new HealthCheckInfo(HC_COMPONENT_FE, UP, appVersion, description));
+
+ //add hosted components fe component
+ for (String component : healthCheckFeComponents) {
+ List<HealthCheckInfo> feComponentsInfo = addHostedComponentsFeHealthCheck(component);
+ HealthCheckInfo baseComponentHCInfo = healthCheckWrapper.getComponentsInfo().stream().filter(c -> c.getHealthCheckComponent().equals(component)).findFirst().orElse(null);
+ if (baseComponentHCInfo != null) {
+ if (baseComponentHCInfo.getComponentsInfo() == null) {
+ baseComponentHCInfo.setComponentsInfo(new ArrayList<>());
+ }
+ baseComponentHCInfo.getComponentsInfo().addAll(feComponentsInfo);
+ boolean status = healthCheckUtil.getAggregateStatus(baseComponentHCInfo.getComponentsInfo() ,config.getHealthStatusExclude());
+ baseComponentHCInfo.setHealthCheckStatus(status ? UP : DOWN);
+
+ String componentsDesc = healthCheckUtil.getAggregateDescription(baseComponentHCInfo.getComponentsInfo(), baseComponentHCInfo.getDescription());
+ if (componentsDesc.length() > 0) { //aggregated description contains all the internal components desc
+ baseComponentHCInfo.setDescription(componentsDesc);
+ }
+ } else {
+ log.error("{} not exists in HealthCheck info", component);
+ }
+ }
+ return healthCheckWrapper;
+ }
+
+ private HealthCheckWrapper getBeDownCheckInfos() {
+ List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_FE, UP,
+ getAppVersion(), "OK"));
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, DOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_TITAN, UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_CASSANDRA, UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_DISTRIBUTION_ENGINE, UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_ON_BOARDING, UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_DCAE, UNKNOWN, null, null));
+ return new HealthCheckWrapper(healthCheckInfos, "UNKNOWN", "UNKNOWN");
+ }
+
+ private String buildOnboardingHealthCheckUrl(Configuration config) {
+
+ Configuration.OnboardingConfig onboardingConfig = config.getOnboarding();
+
+ if (onboardingConfig != null) {
+ String protocol = onboardingConfig.getProtocol();
+ String host = onboardingConfig.getHost();
+ Integer port = onboardingConfig.getPort();
+ String uri = onboardingConfig.getHealthCheckUri();
+
+ return protocol + "://" + host + ":" + port + uri;
+ }
+
+ log.error("onboarding health check configuration is missing.");
+ return null;
+ }
+
+ private String buildDcaeHealthCheckUrl(Configuration config) {
+
+ Configuration.DcaeConfig dcaeConfig = config.getDcae();
+
+ if (dcaeConfig != null) {
+ String protocol = dcaeConfig.getProtocol();
+ String host = dcaeConfig.getHost();
+ Integer port = dcaeConfig.getPort();
+ String uri = dcaeConfig.getHealthCheckUri();
+
+ return protocol + "://" + host + ":" + port + uri;
+ }
+
+ log.error("dcae health check configuration is missing.");
+ return null;
+ }
+
+ private List<HealthCheckInfo> convertResponse(String beJsonResponse, ObjectMapper mapper, String baseComponent, StringBuilder description, int beStatus) {
+ try {
+ Map<String, Object> healthCheckMap = mapper.readValue(beJsonResponse, new TypeReference<Map<String, Object>>() {
+ });
+ if (healthCheckMap.containsKey("componentsInfo")) {
+ return mapper.convertValue(healthCheckMap.get("componentsInfo"), new TypeReference<List<HealthCheckInfo>>() {
+ });
+ } else {
+ description.append("Internal components are missing");
+ }
+ } catch (JsonSyntaxException | IOException e) {
+ log.error("{} Unexpected response body ", baseComponent, e);
+ description.append(baseComponent + " Unexpected response body. Response code: " + beStatus);
+ }
+ return new ArrayList<>();
+ }
+ }
+
}
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 53fbd04a43..ad5d08e209 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
@@ -67,7 +67,6 @@ public class PortalServlet extends HttpServlet {
try {
addRequestHeadersUsingWebseal(request, response);
} catch (Exception e) {
- FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FePortalServletError, "Portal Servlet");
FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
log.error("Error during getting portal page", e);
}
diff --git a/catalog-fe/src/main/resources/config/configuration.yaml b/catalog-fe/src/main/resources/config/configuration.yaml
index 0636e701af..b2dc6da63d 100644
--- a/catalog-fe/src/main/resources/config/configuration.yaml
+++ b/catalog-fe/src/main/resources/config/configuration.yaml
@@ -88,3 +88,10 @@ systemMonitoring:
kibanaHost: localhost
kibanaPort: 5601
kibanaProtocol: http
+
+healthStatusExclude:
+ - DE
+ - ES
+ - DMAPP
+
+ \ No newline at end of file
diff --git a/catalog-fe/src/test/java/org/openecomp/sdc/fe/client/BackendClientTest.java b/catalog-fe/src/test/java/org/openecomp/sdc/fe/client/BackendClientTest.java
deleted file mode 100644
index 943385bb7f..0000000000
--- a/catalog-fe/src/test/java/org/openecomp/sdc/fe/client/BackendClientTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.openecomp.sdc.fe.client;
-
-import javax.net.ssl.HostnameVerifier;
-
-import org.junit.Test;
-
-
-public class BackendClientTest {
-
- private BackendClient createTestSubject() {
- return new BackendClient("", "", "");
- }
-
-
- @Test
- public void testGetHostnameVerifier() throws Exception {
- BackendClient testSubject;
- HostnameVerifier result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getHostnameVerifier();
- }
-
-
-} \ No newline at end of file
diff --git a/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/PortalServletTest.java b/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/PortalServletTest.java
deleted file mode 100644
index c400ba2da3..0000000000
--- a/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/PortalServletTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.openecomp.sdc.fe.servlets;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.junit.Test;
-
-
-public class PortalServletTest {
-
- private PortalServlet createTestSubject() {
- return new PortalServlet();
- }
-
-
- @Test
- public void testDoGet() throws Exception {
- PortalServlet testSubject;
- HttpServletRequest request = null;
- HttpServletResponse response = null;
-
- // default test
- testSubject = createTestSubject();
- testSubject.doGet(request, response);
- }
-
-
-
-} \ No newline at end of file
diff --git a/catalog-fe/src/test/java/org/openecomp/sdc/servlets/PortalServletTest.java b/catalog-fe/src/test/java/org/openecomp/sdc/servlets/PortalServletTest.java
index f2ff870a91..02f685302e 100644
--- a/catalog-fe/src/test/java/org/openecomp/sdc/servlets/PortalServletTest.java
+++ b/catalog-fe/src/test/java/org/openecomp/sdc/servlets/PortalServletTest.java
@@ -38,7 +38,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.Application;
-import org.glassfish.hk2.utilities.binding.AbstractBinder;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.BeforeClass;
diff --git a/catalog-model/pom.xml b/catalog-model/pom.xml
index 8b0786f71d..ef12ad6297 100644
--- a/catalog-model/pom.xml
+++ b/catalog-model/pom.xml
@@ -12,6 +12,9 @@
<version>1.2.0-SNAPSHOT</version>
</parent>
+ <properties>
+ <sonar.skip>true</sonar.skip>
+ </properties>
<dependencies>
<!-- Common of SDC -->
<dependency>
@@ -178,7 +181,12 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java b/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java
new file mode 100644
index 0000000000..1dcbfbf1e9
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/config/CatalogModelSpringConfig.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.config;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan({"org.openecomp.sdc.be.model.operations.impl",
+ "org.openecomp.sdc.be.model.cache",
+ "org.openecomp.sdc.be.model.jsontitan.operations"
+
+})
+public class CatalogModelSpringConfig {
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
index 5760e0b11b..d3bdfede42 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
@@ -20,23 +20,25 @@
package org.openecomp.sdc.be.model;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import org.codehaus.jackson.annotate.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+import java.util.stream.Collectors;
+import static java.util.Collections.emptyList;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+
+import java.io.Serializable;
+import java.util.*;
+import java.util.stream.Collectors;
+
public abstract class Component implements Serializable {
/**
@@ -48,27 +50,17 @@ public abstract class Component implements Serializable {
private Map<String, ArtifactDefinition> artifacts;
private Map<String, ArtifactDefinition> deploymentArtifacts;
private Map<String, ArtifactDefinition> toscaArtifacts;
-
private List<CategoryDefinition> categories;
-
private List<ComponentInstance> componentInstances;
-
private List<RequirementCapabilityRelDef> componentInstancesRelations;
-
private Map<String, List<ComponentInstanceInput>> componentInstancesInputs;
-
private Map<String, List<ComponentInstanceProperty>> componentInstancesProperties;
-
private Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes;
-
private Map<String, List<CapabilityDefinition>> capabilities;
-
private Map<String, List<RequirementDefinition>> requirements;
-
private List<InputDefinition> inputs;
-
private List<GroupDefinition> groups;
-
+ private Map<String, PolicyDefinition> policies;
private String derivedFromGenericType;
private String derivedFromGenericVersion;
private String toscaType;
@@ -344,16 +336,22 @@ public abstract class Component implements Serializable {
return componentInstances;
}
+ public Optional<ComponentInstance> fetchInstanceById(String instanceId) {
+ return Optional.ofNullable(MapUtil.toMap(componentInstances, ComponentInstance::getUniqueId).get(instanceId));
+ }
+
+ @SuppressWarnings("unchecked")
public Map<String, ArtifactDefinition> safeGetComponentInstanceDeploymentArtifacts(String componentInstanceId) {
Optional<ComponentInstance> componentInstanceById = getComponentInstanceById(componentInstanceId);
Map<String, ArtifactDefinition> instanceDeploymentArtifacts = componentInstanceById.get().safeGetDeploymentArtifacts();
- return instanceDeploymentArtifacts != null ? instanceDeploymentArtifacts : Collections.EMPTY_MAP;
+ return instanceDeploymentArtifacts != null ? instanceDeploymentArtifacts : Collections.emptyMap();
}
+ @SuppressWarnings("unchecked")
public Map<String, ArtifactDefinition> safeGetComponentInstanceInformationalArtifacts(String componentInstanceId) {
Optional<ComponentInstance> componentInstanceById = getComponentInstanceById(componentInstanceId);
Map<String, ArtifactDefinition> instanceInformationalArtifacts = componentInstanceById.get().safeGetInformationalArtifacts();
- return instanceInformationalArtifacts != null ? instanceInformationalArtifacts : Collections.EMPTY_MAP;
+ return instanceInformationalArtifacts != null ? instanceInformationalArtifacts : Collections.emptyMap();
}
public List<ArtifactDefinition> safeGetComponentInstanceHeatArtifacts(String componentInstanceId) {
@@ -362,7 +360,7 @@ public abstract class Component implements Serializable {
.stream()
.filter(artifact -> artifact.getArtifactType() != null && artifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.name()))
.collect(Collectors.toList());
- return instanceHeatEnvArtifacts == null ? Collections.EMPTY_LIST : instanceHeatEnvArtifacts;
+ return instanceHeatEnvArtifacts == null ? emptyList() : instanceHeatEnvArtifacts;
}
public void setComponentInstances(List<ComponentInstance> resourceInstances) {
@@ -443,16 +441,31 @@ public abstract class Component implements Serializable {
}
public Optional<ComponentInstance> getComponentInstanceById(String id) {
+ if (componentInstances == null) {
+ return Optional.empty();
+ }
return componentInstances.stream().filter(instance -> id.equals(instance.getUniqueId())).findFirst();
}
public List<GroupDefinition> getGroups() {
return groups;
}
+ public Optional<GroupDefinition> getGroupById(String id){
+ return groups.stream().filter(g -> g.getUniqueId().equals(id)).findAny();
+
+ }
public void setGroups(List<GroupDefinition> groups) {
this.groups = groups;
}
+
+ public Map<String, PolicyDefinition> getPolicies() {
+ return policies;
+ }
+
+ public void setPolicies(Map<String, PolicyDefinition> policies) {
+ this.policies = policies;
+ }
@Override
public int hashCode() {
@@ -476,6 +489,7 @@ public abstract class Component implements Serializable {
result = prime * result + ((componentInstancesInputs == null) ? 0 : componentInstancesInputs.hashCode());
result = prime * result + ((componentInstancesRelations == null) ? 0 : componentInstancesRelations.hashCode());
result = prime * result + ((groups == null) ? 0 : groups.hashCode());
+ result = prime * result + ((policies == null) ? 0 : policies.hashCode());
result = prime * result + ((derivedFromGenericType == null) ? 0 : derivedFromGenericType.hashCode());
result = prime * result + ((derivedFromGenericVersion == null) ? 0 : derivedFromGenericVersion.hashCode());
return result;
@@ -567,6 +581,11 @@ public abstract class Component implements Serializable {
return false;
} else if (!groups.equals(other.groups))
return false;
+ if (policies == null) {
+ if (other.policies != null)
+ return false;
+ } else if (!policies.equals(other.policies))
+ return false;
if (derivedFromGenericType == null) {
if (other.derivedFromGenericType != null)
return false;
@@ -668,7 +687,7 @@ public abstract class Component implements Serializable {
}
public List<ComponentInstanceInput> safeGetComponentInstanceInputsByName(String cmptInstanceName) {
- List<ComponentInstanceInput> emptyPropsList = Collections.emptyList();
+ List<ComponentInstanceInput> emptyPropsList = emptyList();
if (this.componentInstancesInputs == null) {
return emptyPropsList;
}
@@ -681,7 +700,7 @@ public abstract class Component implements Serializable {
}
private <T> List<T> safeGetComponentInstanceEntity(String cmptInstanceId, Map<String, List<T>> instanceEntities) {
- List<T> emptyPropsList = Collections.emptyList();
+ List<T> emptyPropsList = emptyList();
if (instanceEntities == null) {
return emptyPropsList;
}
@@ -728,6 +747,10 @@ public abstract class Component implements Serializable {
derivedFromGenericVersion = genericType.getVersion();
}
+ public boolean isTopologyTemplate() {
+ return ToscaElementTypeEnum.TopologyTemplate.getValue().equals(toscaType);
+ }
+
public String getToscaType() {
return toscaType;
}
@@ -735,6 +758,7 @@ public abstract class Component implements Serializable {
public void setToscaType(String toscaType) {
this.toscaType = toscaType;
}
+
public List<AdditionalInformationDefinition> getAdditionalInformation() {
return additionalInformation;
}
@@ -742,5 +766,34 @@ public abstract class Component implements Serializable {
public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
this.additionalInformation = additionalInformation;
}
-
+
+ public PolicyDefinition getPolicyById(String id) {
+ return policies != null ? policies.get(id) : null;
+ }
+
+ public List<PolicyDefinition> resolvePoliciesList() {
+ if (policies == null) {
+ return emptyList();
+ }
+ return new ArrayList<>(policies.values());
+ }
+
+ public List<PolicyDefinition> resolvePoliciesByComponentInstanceTarget(String instanceId) {
+ if (policies == null) {
+ return emptyList();
+ }
+ return policies.values().stream()
+ .filter(policy -> policy.containsCmptInstanceAsTarget(instanceId))
+ .collect(Collectors.toList());
+ }
+
+ public List<GroupDefinition> resolveGroupsByMember(String instanceId) {
+ if (groups == null) {
+ return emptyList();
+ }
+ return groups.stream()
+ .filter(group -> group.containsInstanceAsMember(instanceId))
+ .collect(Collectors.toList());
+ }
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java
index e436548f60..19653e3847 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,33 +20,63 @@
package org.openecomp.sdc.be.model;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang3.tuple.Pair;
+
import java.io.Serializable;
import java.util.List;
import java.util.Map;
-public class ComponentInstInputsMap implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 1136631343963488131L;
-
- Map<String, List<ComponentInstancePropInput>> componentInstanceInputsMap;
- Map<String, List<ComponentInstancePropInput>> componentInstanceProperties;
-
- public Map<String, List<ComponentInstancePropInput>> getComponentInstanceInputsMap() {
- return componentInstanceInputsMap;
- }
-
- public void setComponentInstanceInputsMap(Map<String, List<ComponentInstancePropInput>> componentInstanceInputsMap) {
- this.componentInstanceInputsMap = componentInstanceInputsMap;
- }
-
- public Map<String, List<ComponentInstancePropInput>> getComponentInstanceProperties() {
- return componentInstanceProperties;
- }
-
- public void setComponentInstancePropInput(Map<String, List<ComponentInstancePropInput>> componentInstanceProperties) {
- this.componentInstanceProperties = componentInstanceProperties;
- }
+public class ComponentInstInputsMap implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1136631343963488131L;
+
+ private Map<String, List<ComponentInstancePropInput>> componentInstanceInputsMap;
+ private Map<String, List<ComponentInstancePropInput>> componentInstanceProperties;
+ private Map<String, List<ComponentInstancePropInput>> policyProperties;
+
+ public Pair<String, List<ComponentInstancePropInput>> resolvePropertiesToDeclare() {
+ if (!MapUtils.isEmpty(componentInstanceInputsMap)) {
+ return singleMapEntry(componentInstanceInputsMap);
+ }
+ if (!MapUtils.isEmpty(componentInstanceProperties)) {
+ return singleMapEntry(componentInstanceProperties);
+ }
+ if (!MapUtils.isEmpty(policyProperties)) {
+ return singleMapEntry(policyProperties);
+ }
+ throw new IllegalStateException("there are no properties selected for deceleration");
+ }
+
+ private Pair<String, List<ComponentInstancePropInput>> singleMapEntry(Map<String, List<ComponentInstancePropInput>> propertiesMap) {
+ Map.Entry<String, List<ComponentInstancePropInput>> singleEntry = propertiesMap.entrySet().iterator().next();
+ return Pair.of(singleEntry.getKey(), singleEntry.getValue());
+ }
+
+ public Map<String, List<ComponentInstancePropInput>> getComponentInstanceInputsMap() {
+ return componentInstanceInputsMap;
+ }
+
+ public void setComponentInstanceInputsMap(Map<String, List<ComponentInstancePropInput>> componentInstanceInputsMap) {
+ this.componentInstanceInputsMap = componentInstanceInputsMap;
+ }
+
+ public Map<String, List<ComponentInstancePropInput>> getComponentInstanceProperties() {
+ return componentInstanceProperties;
+ }
+
+ public void setComponentInstancePropInput(Map<String, List<ComponentInstancePropInput>> componentInstanceProperties) {
+ this.componentInstanceProperties = componentInstanceProperties;
+ }
+
+ public Map<String, List<ComponentInstancePropInput>> getPolicyProperties() {
+ return policyProperties;
+ }
+
+ public void setPolicyProperties(Map<String, List<ComponentInstancePropInput>> policyProperties) {
+ this.policyProperties = policyProperties;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java
index 8ed256c555..a45e3d2bd7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,88 +20,96 @@
package org.openecomp.sdc.be.model;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-
-public class ComponentInstance extends ComponentInstanceDataDefinition implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 6721465693884621223L;
-
- private Map<String, List<CapabilityDefinition>> capabilities;
- private Map<String, List<RequirementDefinition>> requirements;
- private Map<String, ArtifactDefinition> deploymentArtifacts;
- private Map<String, ArtifactDefinition> artifacts;
- private List<GroupInstance> groupInstances;
-
- public ComponentInstance() {
- super();
- }
-
- public ComponentInstance(ComponentInstanceDataDefinition r) {
- super(r);
- }
-
- public Map<String, List<CapabilityDefinition>> getCapabilities() {
- return capabilities;
- }
-
- public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
- this.capabilities = capabilities;
- }
-
- public Map<String, List<RequirementDefinition>> getRequirements() {
- return requirements;
- }
-
- public void setRequirements(Map<String, List<RequirementDefinition>> requirements) {
- this.requirements = requirements;
- }
-
- public Map<String, ArtifactDefinition> getDeploymentArtifacts() {
- return deploymentArtifacts;
- }
-
- public Map<String, ArtifactDefinition> safeGetDeploymentArtifacts() {
- return deploymentArtifacts == null ? Collections.EMPTY_MAP : deploymentArtifacts;
- }
-
- public Map<String, ArtifactDefinition> safeGetInformationalArtifacts() {
- return artifacts == null ? Collections.EMPTY_MAP : deploymentArtifacts;
- }
-
- public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) {
- this.deploymentArtifacts = deploymentArtifacts;
- }
-
- public Map<String, ArtifactDefinition> getArtifacts() {
- return artifacts;
- }
-
- public Map<String, ArtifactDefinition> safeGetArtifacts() {
- return artifacts == null ? Collections.EMPTY_MAP : artifacts;
- }
-
- public void setArtifacts(Map<String, ArtifactDefinition> artifacts) {
- this.artifacts = artifacts;
- }
-
- public List<GroupInstance> getGroupInstances() {
- return groupInstances;
- }
-
- public void setGroupInstances(List<GroupInstance> groupInstances) {
- this.groupInstances = groupInstances;
- }
-
- public String getActualComponentUid() {
- return getIsProxy() ? getSourceModelUid() : getComponentUid();
- }
-
+public class ComponentInstance extends ComponentInstanceDataDefinition implements Serializable, PropertiesOwner {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 6721465693884621223L;
+
+ private Map<String, List<CapabilityDefinition>> capabilities;
+ private Map<String, List<RequirementDefinition>> requirements;
+ private Map<String, ArtifactDefinition> deploymentArtifacts;
+ private Map<String, ArtifactDefinition> artifacts;
+ private List<GroupInstance> groupInstances;
+
+ public ComponentInstance() {
+ super();
+ }
+
+ public ComponentInstance(ComponentInstanceDataDefinition r) {
+ super(r);
+ }
+
+ public Map<String, List<CapabilityDefinition>> getCapabilities() {
+ return capabilities;
+ }
+
+ public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
+ this.capabilities = capabilities;
+ }
+
+ public Map<String, List<RequirementDefinition>> getRequirements() {
+ return requirements;
+ }
+
+ public void setRequirements(Map<String, List<RequirementDefinition>> requirements) {
+ this.requirements = requirements;
+ }
+
+ public Map<String, ArtifactDefinition> getDeploymentArtifacts() {
+ return deploymentArtifacts;
+ }
+
+ public Map<String, ArtifactDefinition> safeGetDeploymentArtifacts() {
+ return deploymentArtifacts == null ? Collections.emptyMap() : deploymentArtifacts;
+ }
+
+ public Map<String, ArtifactDefinition> safeGetInformationalArtifacts() {
+ return artifacts == null ? Collections.emptyMap() : deploymentArtifacts;
+ }
+
+ public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) {
+ this.deploymentArtifacts = deploymentArtifacts;
+ }
+
+ public Map<String, ArtifactDefinition> getArtifacts() {
+ return artifacts;
+ }
+
+ public Map<String, ArtifactDefinition> safeGetArtifacts() {
+ return artifacts == null ? Collections.emptyMap() : artifacts;
+ }
+
+ public void setArtifacts(Map<String, ArtifactDefinition> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public List<GroupInstance> getGroupInstances() {
+ return groupInstances;
+ }
+
+ public void setGroupInstances(List<GroupInstance> groupInstances) {
+ this.groupInstances = groupInstances;
+ }
+
+ public String getActualComponentUid() {
+ return getIsProxy() ? getSourceModelUid() : getComponentUid();
+ }
+
+ public boolean isArtifactExists(ArtifactGroupTypeEnum groupType, String artifactLabel) {
+ if (ArtifactGroupTypeEnum.DEPLOYMENT == groupType) {
+ return safeGetDeploymentArtifacts().get(artifactLabel) != null;
+ }
+ return safeGetInformationalArtifacts().get(artifactLabel) != null;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java
index 4078a47f86..9bd66006e7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.model;
-import java.util.List;
-
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import java.util.List;
+
public class ComponentParametersView {
boolean ignoreUsers = false;
@@ -46,10 +46,12 @@ public class ComponentParametersView {
boolean ignoreInputs = false;
boolean ignoreComponentInstancesInputs = false;
boolean ignoreCapabiltyProperties = true;
-
+ boolean ignoreServicePath = true;
+ boolean ignorePolicies = false;
+
public ComponentParametersView() {
}
-
+
public ComponentParametersView(boolean setAllToIgnore) {
this();
if(setAllToIgnore){
@@ -59,9 +61,9 @@ public class ComponentParametersView {
public ComponentParametersView(List<String> filters) {
this(true);
-
+
for(String fieldName: filters) {
- switch (ComponentFieldsEnum.findByValue(fieldName)) {
+ switch (ComponentFieldsEnum.findByValue(fieldName)) {
case PROPERTIES:
this.setIgnoreProperties(false);
break;
@@ -89,11 +91,11 @@ public class ComponentParametersView {
this.setIgnoreRequirements(false);
break;
case COMPONENT_INSTANCES_PROPERTIES:
- this.setIgnoreComponentInstances(false); //we need this in order to get the calculate capabilities requirements
+ this.setIgnoreComponentInstances(false); //we need this in order to get the calculate capabilities requirements
this.setIgnoreComponentInstancesProperties(false);
break;
case CAPABILITIES:
- this.setIgnoreComponentInstances(false);//we need this in order to get the calculate capabilities requirements
+ this.setIgnoreComponentInstances(false);//we need this in order to get the calculate capabilities requirements
this.setIgnoreCapabilities(false);
break;
case REQUIREMENTS:
@@ -132,10 +134,16 @@ public class ComponentParametersView {
case INSTANCE_CAPABILTY_PROPERTIES:
this.setIgnoreCapabiltyProperties(false);
break;
+ case FORWARDING_PATHS:
+ this.setIgnoreForwardingPath(false);
+ break;
+ case POLICIES:
+ this.setIgnorePolicies(false);
+ break;
default:
break;
}
-
+
}
}
@@ -249,6 +257,16 @@ public class ComponentParametersView {
if (ignoreComponentInstancesInputs) {
component.setComponentInstancesInputs(null);
}
+
+ if (ignoreServicePath){
+ switch (componentType) {
+ case SERVICE:
+ ((Service) component).setForwardingPaths(null);
+ break;
+ default:
+ break;
+ }
+ }
return component;
}
@@ -272,6 +290,7 @@ public class ComponentParametersView {
ignoreComponentInstancesAttributesFrom = true;
ignoreComponentInstancesInputs = true;
ignoreCapabiltyProperties = true;
+ ignoreServicePath = true;
}
public boolean isIgnoreGroups() {
@@ -418,6 +437,22 @@ public class ComponentParametersView {
this.ignoreCapabiltyProperties = ignoreCapabiltyProperties;
}
+ public boolean isIgnoreForwardingPath() {
+ return ignoreServicePath;
+ }
+
+ public void setIgnoreForwardingPath(boolean ignoreServicePath) {
+ this.ignoreServicePath = ignoreServicePath;
+ }
+
+ public boolean isIgnorePolicies() {
+ return ignorePolicies;
+ }
+
+ public void setIgnorePolicies(boolean ignorePolicies) {
+ this.ignorePolicies = ignorePolicies;
+ }
+
public JsonParseFlagEnum detectParseFlag() {
JsonParseFlagEnum parseFlag;
if(isIgnoreComponentInstances()){
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java
index a9cc32d9b0..c5f4cf923c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DataTypeDefinition.java
@@ -26,8 +26,6 @@ import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition;
public class DataTypeDefinition extends DataTypeDataDefinition {
- // @JsonIgnore
- // @org.codehaus.jackson.annotate.JsonIgnore
private DataTypeDefinition derivedFrom;
private List<PropertyConstraint> constraints;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
index e7d7c69efc..4ffa843463 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java
@@ -21,11 +21,18 @@
package org.openecomp.sdc.be.model;
import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.stream.Collectors;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
public class GroupInstance extends GroupInstanceDataDefinition implements Serializable {
@@ -38,7 +45,10 @@ public class GroupInstance extends GroupInstanceDataDefinition implements Serial
public GroupInstance(GroupInstanceDataDefinition r) {
super(r);
}
-
+ /**
+ * Converts contained list of PropertyDataDefinitions to list of GroupInstanceProperties
+ * @return
+ */
public List<GroupInstanceProperty> convertToGroupInstancesProperties() {
List<GroupInstanceProperty> groupInstancesProperties = null;
List<PropertyDataDefinition> propertiesList = super.getProperties();
@@ -47,12 +57,77 @@ public class GroupInstance extends GroupInstanceDataDefinition implements Serial
}
return groupInstancesProperties;
}
-
+ /**
+ * Converts received list of GroupInstanceProperties to the list of PropertyDataDefinitions and sets It into the GroupInstanceDataDefinition as properties
+ * @param groupInstancesProperties
+ */
public void convertFromGroupInstancesProperties(List<GroupInstanceProperty> groupInstancesProperties) {
if(groupInstancesProperties != null && !groupInstancesProperties .isEmpty()){
List<PropertyDataDefinition> propList = groupInstancesProperties.stream().map(p -> new PropertyDataDefinition(p)).collect(Collectors.toList());
super.setProperties(propList);
}
}
+
+ private void removeArtifactsDuplicates() {
+ List<String> artifacts = getArtifacts();
+ Set<String> artifactsSet = new HashSet<>();
+ artifactsSet.addAll(artifacts);
+ artifacts.clear();
+ artifacts.addAll(artifactsSet);
+
+ List<String> giArtifacts = getGroupInstanceArtifacts();
+ Set<String> giArtifactsSet = new HashSet<>();
+ giArtifactsSet.addAll(giArtifacts);
+ giArtifacts.clear();
+ giArtifacts.addAll(giArtifactsSet);
+ }
+
+ private void clearArtifactsUuid() {
+ List<String> artifactsUuid = getArtifactsUuid();
+ if(CollectionUtils.isNotEmpty(artifactsUuid)){
+ artifactsUuid.clear();
+ } else if (artifactsUuid == null){
+ setArtifactsUuid(new ArrayList<>());
+ }
+
+ List<String> giartifactsUuid = this.getGroupInstanceArtifactsUuid();
+ if(CollectionUtils.isNotEmpty(giartifactsUuid)){
+ giartifactsUuid.clear();
+ } else if (giartifactsUuid == null){
+ setGroupInstanceArtifactsUuid(new ArrayList<>());
+ }
+ }
+
+ /**
+ * Aligns the list of artifacts UUIDs of group instance according to received deployment artifacts
+ * @param deploymentArtifacts
+ */
+ public void alignArtifactsUuid(Map<String, ArtifactDefinition> deploymentArtifacts) {
+ List<String> artifactIds = getArtifacts();
+ if(CollectionUtils.isNotEmpty(artifactIds)){
+ removeArtifactsDuplicates();
+ clearArtifactsUuid();
+ List<String> artifactUuids = getArtifactsUuid();
+ List<String> giArtifactUuids = getGroupInstanceArtifactsUuid();
+ for(String artifactId : artifactIds){
+ String label = artifactId.substring(artifactId.lastIndexOf('.') + 1);
+ ArtifactDefinition artifact = deploymentArtifacts.get(label);
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
+ if (artifactType != ArtifactTypeEnum.HEAT_ENV){
+ addArtifactsIdToCollection(artifactUuids, artifact);
+ }else{
+ addArtifactsIdToCollection(giArtifactUuids, artifact);
+ }
+ }
+
+ }
+ }
+
+ private void addArtifactsIdToCollection(List<String> artifactUuids, ArtifactDefinition artifact) {
+ if(!artifactUuids.contains(artifact.getArtifactUUID()) && StringUtils.isNotEmpty(artifact.getArtifactUUID())){
+ artifactUuids.add(artifact.getArtifactUUID());
+
+ }
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java
index cd7fd6401b..5263fcf96e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupTypeDefinition.java
@@ -36,6 +36,7 @@ public class GroupTypeDefinition extends GroupTypeDataDefinition implements Seri
private static final long serialVersionUID = -1597773317924162703L;
private List<PropertyDefinition> properties;
+ private List<CapabilityTypeDefinition> capabilityTypes;
public List<PropertyDefinition> getProperties() {
return properties;
@@ -53,9 +54,17 @@ public class GroupTypeDefinition extends GroupTypeDataDefinition implements Seri
super(p);
}
+ public List<CapabilityTypeDefinition> getCapabilityTypes() {
+ return capabilityTypes;
+ }
+
+ public void setCapabilityTypes(List<CapabilityTypeDefinition> capabilityTypes) {
+ this.capabilityTypes = capabilityTypes;
+ }
+
@Override
public String toString() {
- return super.toString() + " [ properties=" + properties + " ]";
+ return super.toString() + " [properties=" + properties + ", capabilityTypes=" + capabilityTypes + "]";
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java
index 5eb5e8c05c..78b5a82468 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,67 +20,74 @@
package org.openecomp.sdc.be.model;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
+
import java.io.Serializable;
import java.util.Map;
import java.util.stream.Collectors;
-import org.codehaus.jackson.annotate.JsonIgnore;
-import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
-
/**
* Definition of the operations that can be performed on (instances of) a Node
* Type.
- *
+ *
* @author esofer
*/
public class InterfaceDefinition extends InterfaceDataDefinition implements IOperationParameter, Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 8220887972866354746L;
-
-
-
- private boolean definition;
-
- public InterfaceDefinition() {
- super();
- }
-
- public InterfaceDefinition(String type, String description, Map<String, Operation> operations) {
- super(type, description);
- setOperationsMap(operations);
- }
-
- public InterfaceDefinition(InterfaceDataDefinition p) {
- super(p);
- }
-
- @Override
- public boolean isDefinition() {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void setDefinition(boolean definition) {
- this.definition = definition;
- }
- @JsonIgnore
- public Map<String, Operation> getOperationsMap() {
- Map<String, Operation> convertedOperation = getOperations().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new Operation(e.getValue())));
- return convertedOperation;
- }
- @JsonIgnore
- public void setOperationsMap(Map<String, Operation> operations) {
- Map<String, OperationDataDefinition> convertedOperation = operations.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new OperationDataDefinition(e.getValue())));
- setOperations(convertedOperation);
- }
-
- @Override
- public String toString() {
- return "InterfaceDefinition [definition=" + definition + "]";
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8220887972866354746L;
+
+
+ private boolean definition;
+
+ public InterfaceDefinition() {
+ super();
+ }
+
+ public InterfaceDefinition(String type, String description, Map<String, Operation> operations) {
+ super(type, description);
+ setOperationsMap(operations);
+ }
+
+ public InterfaceDefinition(InterfaceDataDefinition p) {
+ super(p);
+ }
+
+ @Override
+ public boolean isDefinition() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void setDefinition(boolean definition) {
+ this.definition = definition;
+ }
+
+ @JsonIgnore
+ public Map<String, Operation> getOperationsMap() {
+ Map<String, Operation> convertedOperation = getOperations().entrySet()
+ .stream()
+ .collect(Collectors.toMap(e -> e.getKey(), e -> new Operation(e
+ .getValue())));
+ return convertedOperation;
+ }
+
+ @JsonIgnore
+ public void setOperationsMap(Map<String, Operation> operations) {
+ Map<String, OperationDataDefinition> convertedOperation = operations.entrySet()
+ .stream()
+ .collect(Collectors.toMap(e -> e.getKey(), e -> new OperationDataDefinition(e
+ .getValue())));
+ setOperations(convertedOperation);
+ }
+
+ @Override
+ public String toString() {
+ return "InterfaceDefinition [definition=" + definition + "]";
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java
new file mode 100644
index 0000000000..dc742cb163
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyDefinition.java
@@ -0,0 +1,66 @@
+package org.openecomp.sdc.be.model;
+
+import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+/**
+ * public class representing the component policy
+ */
+public class PolicyDefinition extends PolicyDataDefinition implements Serializable, PropertiesOwner {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 8433981810801300209L;
+
+ /**
+ * public constructor by default
+ */
+ public PolicyDefinition() {
+ super();
+ }
+
+ /**
+ * public constructor from superclass
+ * @param policy
+ */
+ public PolicyDefinition(Map<String, Object> policy) {
+ super(policy);
+ }
+
+ /**
+ * public copy constructor
+ * @param other
+ */
+ public PolicyDefinition(PolicyDataDefinition other) {
+ super(other);
+ }
+
+ /**
+ * public converter constructor
+ * builds PolicyDefinition object based on received PolicyTypeDefinition object
+ * @param policyType
+ */
+ public PolicyDefinition(PolicyTypeDefinition policyType) {
+ this.setPolicyTypeName(policyType.getType());
+ this.setPolicyTypeUid(policyType.getUniqueId());
+ this.setDerivedFrom(policyType.getDerivedFrom());
+ this.setDescription(policyType.getDescription());
+ this.setVersion(policyType.getVersion());
+ if (policyType.getProperties() != null) {
+ this.setProperties(policyType.getProperties().stream().map(PropertyDataDefinition::new).collect(Collectors.toList()));
+ }
+ this.setTargets(new HashMap<>());
+
+ }
+
+ @Override
+ public String getNormalizedName() {
+ return getName();
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java
new file mode 100644
index 0000000000..33a32d2624
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTargetDTO.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.be.model;
+
+import java.util.List;
+
+public class PolicyTargetDTO {
+
+
+ private String type;
+ private List<String> uniqueIds;
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public List<String> getUniqueIds() {
+ return uniqueIds;
+ }
+
+ public void setUniqueIds(List<String> ids) {
+ this.uniqueIds = ids;
+ }
+
+
+
+
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java
index 9b3e72ccc6..0cfdf196e1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PolicyTypeDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,36 +20,35 @@
package org.openecomp.sdc.be.model;
-import java.util.List;
-
import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
+import java.util.List;
+
/**
* Specifies the policy type that the Node Type exposes.
*/
public class PolicyTypeDefinition extends PolicyTypeDataDefinition {
- private List<PropertyDefinition> properties;
-
- public List<PropertyDefinition> getProperties() {
- return properties;
- }
+ private List<PropertyDefinition> properties;
- public void setProperties(List<PropertyDefinition> properties) {
- this.properties = properties;
- }
+ public List<PropertyDefinition> getProperties() {
+ return properties;
+ }
- public PolicyTypeDefinition() {
- super();
- }
+ public void setProperties(List<PropertyDefinition> properties) {
+ this.properties = properties;
+ }
- public PolicyTypeDefinition(PolicyTypeDataDefinition p) {
- super(p);
- }
+ public PolicyTypeDefinition() {
+ super();
+ }
- @Override
- public String toString() {
- return super.toString() + " [ properties=" + properties + " ]";
- }
+ public PolicyTypeDefinition(PolicyTypeDataDefinition p) {
+ super(p);
+ }
+ @Override
+ public String toString() {
+ return super.toString() + " [ properties=" + properties + " ]";
+ }
}
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 786c11f636..5310d5a00c 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
@@ -28,8 +28,10 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.utils.MapUtil;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.datatypes.elements.WorkflowOperationDataDefinition;
+import static java.util.stream.Collectors.groupingBy;
public class Resource extends Component implements Serializable {
private static final long serialVersionUID = -6811540567661368482L;
@@ -306,7 +308,7 @@ public class Resource extends Component implements Serializable {
@Override
public boolean shouldGenerateInputs(){
//TODO add complex VFC condition when supported
- return ResourceTypeEnum.VF == this.getResourceType() || ResourceTypeEnum.CVFC == this.getResourceType() || ResourceTypeEnum.PNF == this.getResourceType();
+ return !(this.getResourceType().isAtomicType());
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
index 563030e147..c3852e060b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
@@ -20,9 +20,11 @@
package org.openecomp.sdc.be.model;
+import java.util.HashMap;
import java.util.Map;
import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
@@ -43,6 +45,7 @@ public class Service extends Component {
}
private Map<String, ArtifactDefinition> serviceApiArtifacts;
+ private Map<String, ForwardingPathDataDefinition> forwardingPaths;
public Map<String, ArtifactDefinition> getServiceApiArtifacts() {
@@ -57,6 +60,21 @@ public class Service extends Component {
return getServiceMetadataDefinition().getProjectCode();
}
+ public Map<String, ForwardingPathDataDefinition> getForwardingPaths() {
+ return forwardingPaths;
+ }
+
+ public void setForwardingPaths(Map<String, ForwardingPathDataDefinition> forwardingPaths) {
+ this.forwardingPaths = forwardingPaths;
+ }
+
+ public ForwardingPathDataDefinition addForwardingPath(ForwardingPathDataDefinition forwardingPathDataDefinition){
+ if(forwardingPaths == null){
+ forwardingPaths = new HashMap<>();
+ }
+ return forwardingPaths.put(forwardingPathDataDefinition.getUniqueId(),forwardingPathDataDefinition);
+ }
+
public void setProjectCode(String projectName) {
getServiceMetadataDefinition().setProjectCode(projectName);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java
index 6a1fcac7e8..8da4c113a2 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java
@@ -65,8 +65,7 @@ public class TargetCapabilityRelDef implements Serializable {
return relationships;
}
-
- public CapabilityRequirementRelationship getSingleRelationship() {//currently only single relationship is supported
+ public CapabilityRequirementRelationship resolveSingleRelationship() {//currently only single relationship is supported
return relationships == null || relationships.isEmpty() ? null : relationships.get(0);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java
index 385b15c728..36ac871cab 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadResourceInfo.java
@@ -29,13 +29,23 @@ import org.openecomp.sdc.common.api.UploadArtifactInfo;
public class UploadResourceInfo {
+ private String payloadData;
+ private String payloadName;
+ private String description;
+ private List<String> tags;
+ private List<CategoryDefinition> categories;
+
+ private List<UploadArtifactInfo> artifactList;
+ private String contactId, name, resourceIconPath, icon, vendorName, vendorRelease, resourceVendorModelNumber;
+
+ private String resourceType = "VFC";
+
public UploadResourceInfo(String payload, String payloadName, String description, String category,
- List<String> tags, List<UploadArtifactInfo> artifactsList) {
+ List<String> tags, List<UploadArtifactInfo> artifactsList) {
super();
this.payloadData = payload;
this.payloadName = payloadName;
this.description = description;
- // this.category = category;
this.tags = tags;
this.artifactList = artifactsList;
if (category != null) {
@@ -55,17 +65,6 @@ public class UploadResourceInfo {
public UploadResourceInfo() {
}
- private String payloadData;
- private String payloadName;
- private String description;
- // private String category;
- private List<String> tags;
- private List<CategoryDefinition> categories;
-
- private List<UploadArtifactInfo> artifactList;
- private String contactId, name, resourceIconPath, icon, vendorName, vendorRelease;
-
- private String resourceType = "VFC";
public String getPayloadData() {
return payloadData;
@@ -91,12 +90,6 @@ public class UploadResourceInfo {
this.description = description;
}
- // public String getCategory() {
- // return category;
- // }
- // public void setCategory(String category) {
- // this.category = category;
- // }
public List<String> getTags() {
return tags;
}
@@ -119,8 +112,6 @@ public class UploadResourceInfo {
int result = 1;
result = prime * result + ((artifactList == null) ? 0 : artifactList.hashCode());
result = prime * result + ((contactId == null) ? 0 : contactId.hashCode());
- // result = prime * result + ((category == null) ? 0 :
- // category.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((icon == null) ? 0 : icon.hashCode());
result = prime * result + ((payloadData == null) ? 0 : payloadData.hashCode());
@@ -130,78 +121,106 @@ public class UploadResourceInfo {
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
result = prime * result + ((vendorName == null) ? 0 : vendorName.hashCode());
result = prime * result + ((vendorRelease == null) ? 0 : vendorRelease.hashCode());
+ result = prime * result + ((resourceVendorModelNumber == null) ? 0 : resourceVendorModelNumber.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
UploadResourceInfo other = (UploadResourceInfo) obj;
if (artifactList == null) {
- if (other.artifactList != null)
+ if (other.artifactList != null) {
return false;
- } else if (!artifactList.equals(other.artifactList))
+ }
+ } else if (!artifactList.equals(other.artifactList)) {
return false;
+ }
if (contactId == null) {
- if (other.contactId != null)
+ if (other.contactId != null) {
return false;
- } else if (!contactId.equals(other.contactId))
+ }
+ } else if (!contactId.equals(other.contactId)) {
return false;
- // if (category == null) {
- // if (other.category != null)
- // return false;
- // } else if (!category.equals(other.category))
- // return false;
+ }
if (description == null) {
- if (other.description != null)
+ if (other.description != null) {
return false;
- } else if (!description.equals(other.description))
+ }
+ } else if (!description.equals(other.description)) {
return false;
+ }
if (icon == null) {
- if (other.icon != null)
+ if (other.icon != null) {
return false;
- } else if (!icon.equals(other.icon))
+ }
+ } else if (!icon.equals(other.icon)) {
return false;
+ }
if (payloadData == null) {
- if (other.payloadData != null)
+ if (other.payloadData != null) {
return false;
- } else if (!payloadData.equals(other.payloadData))
+ }
+ } else if (!payloadData.equals(other.payloadData)) {
return false;
+ }
if (payloadName == null) {
- if (other.payloadName != null)
+ if (other.payloadName != null) {
return false;
- } else if (!payloadName.equals(other.payloadName))
+ }
+ } else if (!payloadName.equals(other.payloadName)) {
return false;
+ }
if (resourceIconPath == null) {
- if (other.resourceIconPath != null)
+ if (other.resourceIconPath != null) {
return false;
- } else if (!resourceIconPath.equals(other.resourceIconPath))
+ }
+ } else if (!resourceIconPath.equals(other.resourceIconPath)) {
return false;
+ }
if (name == null) {
- if (other.name != null)
+ if (other.name != null) {
return false;
- } else if (!name.equals(other.name))
+ }
+ } else if (!name.equals(other.name)) {
return false;
+ }
if (tags == null) {
- if (other.tags != null)
+ if (other.tags != null) {
return false;
- } else if (!tags.equals(other.tags))
+ }
+ } else if (!tags.equals(other.tags)) {
return false;
+ }
if (vendorName == null) {
- if (other.vendorName != null)
+ if (other.vendorName != null) {
return false;
- } else if (!vendorName.equals(other.vendorName))
+ }
+ } else if (!vendorName.equals(other.vendorName)) {
return false;
+ }
+ if (resourceVendorModelNumber == null) {
+ if (other.resourceVendorModelNumber != null) {
+ return false;
+ }
+ } else if (!resourceVendorModelNumber.equals(other.resourceVendorModelNumber)) {
+ return false;
+ }
if (vendorRelease == null) {
- if (other.vendorRelease != null)
+ if (other.vendorRelease != null) {
return false;
- } else if (!vendorRelease.equals(other.vendorRelease))
+ }
+ } else if (!vendorRelease.equals(other.vendorRelease)) {
return false;
+ }
return true;
}
@@ -246,6 +265,14 @@ public class UploadResourceInfo {
this.vendorRelease = vendorRelease;
}
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
+
public void setIcon(String icon) {
this.icon = icon;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java
index 22b46a0458..f969bbd18f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java
@@ -20,22 +20,7 @@
package org.openecomp.sdc.be.model.cache;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import javax.annotation.PostConstruct;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -65,14 +50,27 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Function;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("component-cache")
public class ComponentCache {
private static Logger logger = LoggerFactory.getLogger(ComponentCache.class.getName());
- @javax.annotation.Resource
+ @Autowired
ComponentCassandraDao componentCassandraDao;
@Autowired
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java
new file mode 100644
index 0000000000..d051e0ae79
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java
@@ -0,0 +1,107 @@
+package org.openecomp.sdc.be.model.catalog;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+
+public class CatalogComponent {
+
+ private String version;
+ private ComponentTypeEnum componentType;
+ private String icon;
+ private String uniqueId;
+ private String lifecycleState;
+ private long lastUpdateDate;
+ private String name;
+ private String resourceType;
+ private String categoryNormalizedName;
+ private String subCategoryNormalizedName;
+ private String distributionStatus;
+
+ public String getCategoryNormalizedName() {
+ return categoryNormalizedName;
+ }
+
+ public void setCategoryNormalizedName(String categoryNormalizedName) {
+ this.categoryNormalizedName = categoryNormalizedName;
+ }
+
+ public String getSubCategoryNormalizedName() {
+ return subCategoryNormalizedName;
+ }
+
+ public void setSubCategoryNormalizedName(String subCategoryNormalizedName) {
+ this.subCategoryNormalizedName = subCategoryNormalizedName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public long getLastUpdateDate() {
+ return lastUpdateDate;
+ }
+
+ public void setLastUpdateDate(long lastUpdateDate) {
+ this.lastUpdateDate = lastUpdateDate;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public void setComponentType(ComponentTypeEnum componentType) {
+ this.componentType = componentType;
+ }
+
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public ComponentTypeEnum getComponentType() {
+ return componentType;
+ }
+
+ public String getIcon() {
+ return icon;
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public String getDistributionStatus() {
+ return distributionStatus;
+ }
+
+ public void setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ }
+
+}
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 663b5bf6df..6b5f1157fc 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
@@ -20,24 +20,14 @@
package org.openecomp.sdc.be.model.jsontitan.datamodel;
-import java.util.HashMap;
-import java.util.Map;
-
import org.apache.commons.collections.MapUtils;
-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.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.*;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+
+import java.util.HashMap;
+import java.util.Map;
public class TopologyTemplate extends ToscaElement{
@@ -50,8 +40,10 @@ public class TopologyTemplate extends ToscaElement{
private Map<String, MapPropertiesDataDefinition> instAttributes;
private Map<String, MapPropertiesDataDefinition> instProperties;
private Map<String, GroupDataDefinition> groups;
+ private Map<String, PolicyDataDefinition> policies;
private Map<String, MapGroupsDataDefinition> instGroups;
private Map<String, ArtifactDataDefinition> serviceApiArtifacts;
+ private Map<String, ForwardingPathDataDefinition> forwardingPaths;
private Map<String, CompositionDataDefinition> compositions;
private Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities;
@@ -64,7 +56,18 @@ public class TopologyTemplate extends ToscaElement{
private Map<String, MapArtifactDataDefinition> instDeploymentArtifacts;
private Map<String, MapArtifactDataDefinition> instanceArtifacts;
-
+ //Component Instances External References (instanceId -> ExternalRefsMap)
+ //-----------------------------------------------------------------------
+ private Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs;
+ public Map<String, MapComponentInstanceExternalRefs> getMapComponentInstancesExternalRefs() {
+ return this.mapComponentInstancesExternalRefs;
+ }
+ public void setComponentInstancesExternalRefs(Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs) {
+ this.mapComponentInstancesExternalRefs = mapComponentInstancesExternalRefs;
+ }
+ //-----------------------------------------------------------------------
+
+
public Map<String, PropertyDataDefinition> getInputs() {
return inputs;
}
@@ -101,6 +104,12 @@ public class TopologyTemplate extends ToscaElement{
public void setGroups(Map<String, GroupDataDefinition> groups) {
this.groups = groups;
}
+ public Map<String, PolicyDataDefinition> getPolicies() {
+ return policies;
+ }
+ public void setPolicies(Map<String, PolicyDataDefinition> policies) {
+ this.policies = policies;
+ }
public Map<String, MapGroupsDataDefinition> getInstGroups() {
return instGroups;
}
@@ -164,6 +173,15 @@ public class TopologyTemplate extends ToscaElement{
public void setInstanceArtifacts(Map<String, MapArtifactDataDefinition> instanceArtifacts) {
this.instanceArtifacts = instanceArtifacts;
}
+
+ public Map<String, ForwardingPathDataDefinition> getForwardingPaths() {
+ return forwardingPaths;
+ }
+
+ public void setForwardingPaths(Map<String, ForwardingPathDataDefinition> forwardingPaths) {
+ this.forwardingPaths = forwardingPaths;
+ }
+
/**
* Adds component instance to composition of topology template
* Note that component instance will be overrided in case if the topology template already contains a component instance with the same name
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 706007bdd7..cbd612d024 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
@@ -68,7 +68,7 @@ public class ArtifactsOperations extends BaseOperation {
public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) {
String artifactId = artifactInfo.getUniqueId();
- if (artifactId == null && artifactInfo.getEsId()!=null) {
+ if (artifactId == null && artifactInfo.getEsId() != null) {
artifactId = artifactInfo.getEsId();
}
Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false);
@@ -186,8 +186,7 @@ public class ArtifactsOperations extends BaseOperation {
}
/**
- *
- * @param parentId the id of the instance container
+ * @param parentId the id of the instance container
* @param instanceId the id of the instance of which to return its artifacts
* @return instance and instance deployment artifacts mapped by artifact label name
*/
@@ -267,27 +266,27 @@ public class ArtifactsOperations extends BaseOperation {
if (isUpdate) {
ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactData.getArtifactType());
switch (type) {
- case HEAT_ENV:
- if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) {
- generateUUID(artifactData, oldVesrion);
- } else {
- updateVersionAndDate(artifactData, oldVesrion);
- }
- break;
- case HEAT:
- case HEAT_NET:
- case HEAT_VOL:
- generateUUID(artifactData, oldVesrion);
- break;
- default:
- if (oldChecksum == null || oldChecksum.isEmpty()) {
- if (currentChecksum != null) {
+ case HEAT_ENV:
+ if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) {
generateUUID(artifactData, oldVesrion);
+ } else {
+ updateVersionAndDate(artifactData, oldVesrion);
}
- } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
+ break;
+ case HEAT:
+ case HEAT_NET:
+ case HEAT_VOL:
generateUUID(artifactData, oldVesrion);
- }
- break;
+ break;
+ default:
+ if (oldChecksum == null || oldChecksum.isEmpty()) {
+ if (currentChecksum != null) {
+ generateUUID(artifactData, oldVesrion);
+ }
+ } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
+ generateUUID(artifactData, oldVesrion);
+ }
+ break;
}
} else {
if (oldChecksum == null || oldChecksum.isEmpty()) {
@@ -315,11 +314,11 @@ public class ArtifactsOperations extends BaseOperation {
String id = heatEnv.getGeneratedFromId();
ComponentTypeEnum compType;
switch (parentType) {
- case ResourceInstance:
- compType = ComponentTypeEnum.RESOURCE_INSTANCE;
- break;
- default:
- compType = componentType;
+ case ResourceInstance:
+ compType = ComponentTypeEnum.RESOURCE_INSTANCE;
+ break;
+ default:
+ compType = componentType;
}
return getArtifactById(parentId, id, compType, containerId);
}
@@ -430,7 +429,7 @@ public class ArtifactsOperations extends BaseOperation {
return artMap;
}
- private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
if (resultEither.isRight()) {
log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
@@ -449,34 +448,34 @@ public class ArtifactsOperations extends BaseOperation {
* if (nodeType == NodeTypeEnum.ResourceInstance) { edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; isDeepElement = true; } else {
*/
switch (groupType) {
- case TOSCA:
- edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS;
- vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS;
- break;
- case DEPLOYMENT:
- if (nodeType == NodeTypeEnum.ResourceInstance) {
- edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS;
- vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS;
- isDeepElement = true;
- } else {
- edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS;
- vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS;
- }
- break;
- case SERVICE_API:
- edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS;
- vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS;
- break;
- default:
- if (nodeType == NodeTypeEnum.ResourceInstance) {
- edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS;
- vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS;
- isDeepElement = true;
- } else {
- edgeLabelEnum = EdgeLabelEnum.ARTIFACTS;
- vertexTypeEnum = VertexTypeEnum.ARTIFACTS;
- }
- break;
+ case TOSCA:
+ edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS;
+ break;
+ case DEPLOYMENT:
+ if (nodeType == NodeTypeEnum.ResourceInstance) {
+ edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS;
+ isDeepElement = true;
+ } else {
+ edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS;
+ }
+ break;
+ case SERVICE_API:
+ edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS;
+ break;
+ default:
+ if (nodeType == NodeTypeEnum.ResourceInstance) {
+ edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS;
+ isDeepElement = true;
+ } else {
+ edgeLabelEnum = EdgeLabelEnum.ARTIFACTS;
+ vertexTypeEnum = VertexTypeEnum.ARTIFACTS;
+ }
+ break;
}
// }
return new ImmutableTriple<EdgeLabelEnum, Boolean, VertexTypeEnum>(edgeLabelEnum, isDeepElement, vertexTypeEnum);
@@ -505,10 +504,10 @@ public class ArtifactsOperations extends BaseOperation {
if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel());
} else {
- uniqueId = UniqueIdBuilder.buildPropertyUniqueId(instanceId, artifactToUpdate.getArtifactLabel());
+ uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel());
}
artifactToUpdate.setUniqueId(uniqueId);
- if(!isDeletePlaceholder)
+ if (!isDeletePlaceholder)
artifactToUpdate.setEsId(uniqueId);
} else
artifactToUpdate.setUniqueId(artifactId);
@@ -547,15 +546,19 @@ public class ArtifactsOperations extends BaseOperation {
oldVersion = oldArtifactData.getArtifactVersion();
//duplicated flag didn't receive from UI, take from DB
artifactToUpdate.setDuplicated(oldArtifactData.getDuplicated());
-
+
if (isNeedToClone)
artifactToUpdate.setDuplicated(Boolean.FALSE);
else {
if (artifactToUpdate.getDuplicated()) {
- String id = type != NodeTypeEnum.ResourceInstance ? componentId : instanceId;
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactToUpdate.getArtifactLabel());
+ String uniqueId = "";
+ if(type != NodeTypeEnum.ResourceInstance)
+ uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel());
+ else
+ uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel());
+
artifactToUpdate.setUniqueId(uniqueId);
- if(!isDeletePlaceholder)
+ if (!isDeletePlaceholder)
artifactToUpdate.setEsId(uniqueId);
artifactToUpdate.setDuplicated(Boolean.FALSE);
}
@@ -594,12 +597,12 @@ public class ArtifactsOperations extends BaseOperation {
artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate);
}
- for ( Entry<String, MapArtifactDataDefinition> e : artifactInst.entrySet() ) {
+ for (Entry<String, MapArtifactDataDefinition> e : artifactInst.entrySet()) {
List<ArtifactDataDefinition> toscaDataListPerInst = e.getValue().getMapToscaDataDefinition().values().stream().collect(Collectors.toList());
List<String> pathKeysPerInst = new ArrayList<>();
pathKeysPerInst.add(e.getKey());
status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.ARTIFACT_LABEL);
- if ( status != StorageOperationStatus.OK) {
+ if (status != StorageOperationStatus.OK) {
log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId, componentId, edgeLabelEnum, status);
res = Either.right(status);
break;
@@ -637,14 +640,14 @@ public class ArtifactsOperations extends BaseOperation {
private boolean validateParentType(NodeTypeEnum type) {
boolean isValid = false;
switch (type) {
- case Resource:
- case InterfaceOperation:
- case Service:
- case ResourceInstance:
- isValid = true;
- break;
- default:
- log.debug("Not supported node type for artifact relation : {} ", type);
+ case Resource:
+ case InterfaceOperation:
+ case Service:
+ case ResourceInstance:
+ isValid = true;
+ break;
+ default:
+ log.debug("Not supported node type for artifact relation : {} ", type);
}
return isValid;
}
@@ -727,4 +730,5 @@ public class ArtifactsOperations extends BaseOperation {
}
return result;
}
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java
index 537198d395..3b64a6b208 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
@@ -21,6 +21,7 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -54,6 +55,8 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.PolicyDefinition;
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;
@@ -549,6 +552,27 @@ public abstract class BaseOperation {
return statusRes;
}
+ StorageOperationStatus overrideToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> toscaData) {
+ return titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse)
+ .left()
+ .bind(graphVertex -> overrideToscaElementData(graphVertex, toscaData, edgeLabel))
+ .either(graphVertex -> StorageOperationStatus.OK,
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private Either<GraphVertex, TitanOperationStatus> overrideToscaElementData(GraphVertex toscaElement, Map<String, ? extends ToscaDataDefinition> toscaData, EdgeLabelEnum edgeLabelEnum) {
+ return titanDao.getChildVertex(toscaElement, edgeLabelEnum, JsonParseFlagEnum.ParseJson)
+ .left()
+ .bind(dataVertex -> overrideToscaElementData(dataVertex, toscaElement, toscaData, edgeLabelEnum))
+ .right()
+ .map(err -> logAndReturn(err, "failed to override tosca data for element {} of type {}. status: {}", toscaElement.getUniqueId(), edgeLabelEnum, err));
+ }
+
+ private Either<GraphVertex, TitanOperationStatus> overrideToscaElementData(GraphVertex dataElement, GraphVertex toscaElement, Map<String, ? extends ToscaDataDefinition> toscaData, EdgeLabelEnum edgeLabelEnum) {
+ dataElement.setJson(toscaData);
+ return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabelEnum);
+ }
+
/**
* Adds list of tosca data deep elements to tosca element with specified uid according received labels
*
@@ -693,6 +717,36 @@ public abstract class BaseOperation {
}
/**
+ *
+ * @param toscaElementId the id of the tosca element data container
+ * @param edgeLabel the edge label of the data type to update
+ * @param toscaDataMap the data to update
+ * @param key the key in the json object where the map object block resides
+ * @return the status of the update operation
+ */
+ public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(String toscaElementId, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
+ return titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse)
+ .either(toscaElement -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, edgeLabel, toscaDataMap, key),
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
+ return titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson)
+ .left()
+ .bind(dataVertex -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, dataVertex, edgeLabel, toscaDataMap, key))
+ .either(updatedVertex -> StorageOperationStatus.OK,
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private <T extends ToscaDataDefinition> Either<GraphVertex, TitanOperationStatus> updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, GraphVertex dataElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) {
+ Map<String, T> mapToscaDataDefinition = toscaDataMap.getMapToscaDataDefinition();
+ updateDeepElements(dataElement, mapToscaDataDefinition, Collections.singletonList(key));
+ return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabel)
+ .right()
+ .map(err -> logAndReturn(err, "failed while trying to update data vertex from tosca element {}, of type {} . status {}", toscaElement.getUniqueId(), edgeLabel, err));
+ }
+
+ /**
* Updates tosca data element of tosca element by specified uid according received labels
*
* @param toscaElementUid
@@ -833,7 +887,7 @@ public abstract class BaseOperation {
existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson();
}
- validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate);
+ validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate);
if (validateRes.isRight()) {
result = validateRes.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
@@ -1389,7 +1443,7 @@ public abstract class BaseOperation {
protected String buildGroupInstanceName(String instanceName, String groupName) {
return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName;
}
-
+
protected String generateCustomizationUUID() {
return UUID.randomUUID().toString();
}
@@ -1398,4 +1452,9 @@ public abstract class BaseOperation {
properties.forEach(p -> p.convertPropertyDataToInstancePropertyData());
}
+ private TitanOperationStatus logAndReturn(TitanOperationStatus titanOperationStatus, String logMsg, Object ... logParams) {
+ logger.debug(logMsg, logParams);
+ return titanOperationStatus;
+ }
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java
new file mode 100644
index 0000000000..76fb0a9151
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java
@@ -0,0 +1,261 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs;
+import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.*;
+
+/**
+ * Created by yavivi on 26/01/2018.
+ */
+@Component
+public class ExternalReferencesOperation extends BaseOperation {
+
+ private static final Logger log = LoggerFactory.getLogger(ExternalReferencesOperation.class);
+
+ public IdMapper getIdMapper() {
+ return idMapper;
+ }
+
+ public void setIdMapper(IdMapper idMapper) {
+ this.idMapper = idMapper;
+ }
+
+ @Autowired
+ protected IdMapper idMapper;
+
+ /**
+ * Constructor
+ */
+ public ExternalReferencesOperation(TitanDao titanDao, NodeTypeOperation nto, TopologyTemplateOperation tto, IdMapper idMapper){
+ this.titanDao = titanDao;
+ this.topologyTemplateOperation = tto;
+ this.nodeTypeOperation = nto;
+ this.idMapper = idMapper;
+ }
+
+ public Either<String, ActionStatus> addExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) {
+ Either<String, ActionStatus> addResult = this.addExternalReference(serviceUuid, componentInstanceName, objectType, reference);
+ this.titanDao.commit();
+ return addResult;
+ }
+
+ public Either<String, ActionStatus> deleteExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) {
+ Either<String, ActionStatus> result = this.deleteExternalReference(serviceUuid, componentInstanceName, objectType, reference);
+ this.titanDao.commit();
+ return result;
+ }
+
+ public Either<String, ActionStatus> updateExternalReferenceWithCommit(String serviceVertexUuid, String componentInstanceName, String objectType, String oldRef, String newRef) {
+ Either<String, ActionStatus> updateResult = this.updateExternalReference(serviceVertexUuid, componentInstanceName, objectType, oldRef, newRef);
+ this.titanDao.commit();
+ return updateResult;
+ }
+
+ public Either<String, ActionStatus> addExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference) {
+
+ //Get Service vertex
+ Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid);
+ if (vertexById.isRight()){
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ GraphVertex serviceVertex = vertexById.left().value();
+
+ final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
+ if (compInstanceUniqueId == null) {
+ return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
+ }
+
+ //Get the external references map vertex
+ final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
+
+ //Check whether data vertex found
+ GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
+
+ //instanceId -> externalRefsMap
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = null;
+ if (externalRefsVertex == null) {
+ //External Refs vertext does not exist, create its map.
+ externalReferencesFullData = new HashMap<String, MapComponentInstanceExternalRefs>() {
+ {
+ MapComponentInstanceExternalRefs externalRefsMap = new MapComponentInstanceExternalRefs();
+ put(compInstanceUniqueId, externalRefsMap);
+ }
+ };
+ } else {
+ externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ if (externalReferencesFullData.get(compInstanceUniqueId) == null){
+ externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs());
+ }
+ }
+
+ boolean isAdded = this.addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference);
+ this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData);
+
+ return isAdded ? Either.left(reference) : Either.right(ActionStatus.EXT_REF_ALREADY_EXIST);
+ }
+
+ public Either<String, ActionStatus> deleteExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference){
+ //Get Service vertex
+ Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid);
+ if (vertexById.isRight()){
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+ GraphVertex serviceVertex = vertexById.left().value();
+
+ final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
+ if (compInstanceUniqueId == null) {
+ return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
+ }
+
+ //Get the external references map vertex
+ final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
+
+ //Check whether data vertex found
+ GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
+ boolean refDeleted = false;
+ if (externalRefsVertex != null) {
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ if (externalReferencesFullData != null) {
+ refDeleted = this.deleteExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference);
+ this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); //@ TODO if ref deleted
+ }
+ }
+
+ if (refDeleted) {
+ return Either.left(reference);
+ } else {
+ return Either.right(ActionStatus.EXT_REF_NOT_FOUND);
+ }
+ }
+
+ public Either<String, ActionStatus> updateExternalReference(String assetUuid, String componentInstanceName, String objectType, String oldRef, String newRef) {
+ //Get Service vertex
+ Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid);
+ if (vertexById.isRight()){
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ GraphVertex serviceVertex = vertexById.left().value();
+
+ //Map instance_name -> uuid
+ final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
+ if (compInstanceUniqueId == null) {
+ return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
+ }
+
+ //Get the external references map vertex
+ final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
+
+ //Check whether data vertex found
+ GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
+ boolean refReplaced = false;
+ if (externalRefsVertex != null) {
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ if (externalReferencesFullData != null) {
+ refReplaced = this.updateExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, oldRef, newRef);
+ this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData);
+ }
+ }
+ if (refReplaced) {
+ return Either.left(newRef);
+ } else {
+ return Either.right(ActionStatus.EXT_REF_NOT_FOUND);
+ }
+ }
+
+ public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String objectType) {
+ //Get Service vertex
+ Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid);
+ if (vertexById.isRight()){
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ GraphVertex serviceVertex = vertexById.left().value();
+
+ Map<String, List<String>> result = new HashMap();
+
+ //Get the external references map vertex
+ final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
+ //Check whether data vertex found
+ GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
+ if (externalRefsVertex != null) {
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ if (externalReferencesFullData != null) {
+ externalReferencesFullData.entrySet().forEach(
+ s -> {
+ List<String> externalRefsByObjectType = externalReferencesFullData.get(s.getKey()).getExternalRefsByObjectType(objectType);
+ List<String> refList = externalRefsByObjectType == null ? new ArrayList<>() : externalRefsByObjectType;
+ String key = idMapper.mapUniqueIdToComponentNameTo(s.getKey(), serviceVertex);
+ result.put(key, refList);
+ }
+ );
+ return Either.left(result);
+ }
+ }
+ //No external References Node found on this asset
+ return Either.left(new HashMap<>());
+ }
+
+ public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String componentInstanceName, String objectType) {
+ //Get Service vertex
+ Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid);
+ if (vertexById.isRight()){
+ return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
+ }
+
+ GraphVertex serviceVertex = vertexById.left().value();
+ final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex);
+ if (compInstanceUniqueId == null) {
+ return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
+ }
+
+ //Get the external references map vertex
+ final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS);
+
+ //Check whether data vertex found
+ GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null;
+ if (externalRefsVertex != null) {
+ Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson();
+ if (externalReferencesFullData != null) {
+ return Either.left(this.getExternalReferencesByObjectId(externalReferencesFullData, compInstanceUniqueId, objectType));
+ }
+ }
+
+ //No external References Node found on this asset
+ return Either.left(new LinkedList());
+ }
+
+ private List<String> getExternalReferencesByObjectId(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType) {
+ MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
+ List<String> externalRefsByObjectType = externalRefsMap.getExternalRefsByObjectType(objectType);
+ return externalRefsByObjectType != null ? externalRefsByObjectType : new LinkedList<String>();
+ }
+
+ private boolean updateExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String oldRef, String newRef) {
+ MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
+ return externalRefsMap.replaceExternalRef(objectType, oldRef, newRef);
+ }
+
+ private boolean deleteExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String reference) {
+ MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
+ return externalRefsMap.deleteExternalRef(objectType, reference);
+ }
+
+ private boolean addExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String reference) {
+ MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId);
+ return externalRefsMap.addExternalRef(objectType, reference);
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java
new file mode 100644
index 0000000000..ad4c1fb4f3
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.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.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+@org.springframework.stereotype.Component("forwarding-paths-operations")
+public class ForwardingPathOperation extends BaseOperation {
+ private static Logger logger = LoggerFactory.getLogger(ForwardingPathOperation.class.getName());
+
+
+ public Either<Set<String>, StorageOperationStatus> deleteForwardingPath(Service service, Set<String> forwardingPathsToDelete) {
+ Either<Set<String>, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getComponentVertex;
+ StorageOperationStatus status = null;
+
+ if (result == null) {
+ getComponentVertex = titanDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (getComponentVertex.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
+ }
+ }
+ if (result == null) {
+
+ status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.FORWARDING_PATH,new ArrayList<>(forwardingPathsToDelete));
+
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ }
+ }
+
+ if (result == null) {
+ result = Either.left(forwardingPathsToDelete);
+ }
+ return result;
+ }
+
+ public Either<ForwardingPathDataDefinition, StorageOperationStatus> addForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) {
+ return addOrUpdateForwardingPath(false, serviceId, currentPath);
+ }
+
+ public Either<ForwardingPathDataDefinition, StorageOperationStatus> updateForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) {
+ return addOrUpdateForwardingPath(true, serviceId, currentPath);
+ }
+
+ private Either<ForwardingPathDataDefinition, StorageOperationStatus> addOrUpdateForwardingPath(boolean isUpdateAction, String serviceId, ForwardingPathDataDefinition currentPath) {
+
+ StorageOperationStatus statusRes;
+ Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
+
+ getToscaElementRes = titanDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse);
+ if (getToscaElementRes.isRight()) {
+ TitanOperationStatus status = getToscaElementRes.right().value();
+ CommonUtility.addRecordToLog(logger, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status);
+ statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ return Either.right(statusRes);
+ }
+ GraphVertex serviceVertex = getToscaElementRes.left().value();
+ if (!isUpdateAction){
+ currentPath.setUniqueId(UUID.randomUUID().toString());
+ }
+ statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, Arrays.asList(currentPath), JsonPresentationFields.FORWARDING_PATH);
+ {
+ if (!statusRes.equals(StorageOperationStatus.OK)) {
+ logger.error("Failed to find the parent capability of capability type {}. status is {}", serviceId, statusRes);
+ return Either.right(statusRes);
+ }
+ return Either.left(currentPath);
+ }
+
+ }
+
+
+ private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, List<ForwardingPathDataDefinition> toscaDataList, JsonPresentationFields mapKeyField) {
+ if (isUpdate) {
+ return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ } else {
+ return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID);
+ }
+ }
+
+}
+
+
+
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
index 87053ff454..668a6d973a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
@@ -34,14 +34,12 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
@@ -56,9 +54,9 @@ import fj.data.Either;
@org.springframework.stereotype.Component("groups-operation")
public class GroupsOperation extends BaseOperation {
- private static Logger logger = LoggerFactory.getLogger(GroupsOperation.class.getName());
+ private static final Logger log = LoggerFactory.getLogger(GroupsOperation.class);
- public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, User user, ComponentTypeEnum componentType, Map<String, GroupDataDefinition> groups) {
+ public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, Map<String, GroupDataDefinition> groups) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
@@ -76,20 +74,13 @@ public class GroupsOperation extends BaseOperation {
result = Either.right(status);
}
}
- /* if (result == null) {
- status = topologyTemplateOperation.associateGroupsPropertiesToComponent(getComponentVertex.left().value(), groupsProperties);
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- }
- }*/
if (result == null) {
result = Either.left(ModelConverter.convertToGroupDefinitions(groups));
}
return result;
}
- public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) {
- // TODO Auto-generated method stub
+ public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(Component component, List<GroupDataDefinition> groups) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
StorageOperationStatus status = null;
@@ -115,8 +106,7 @@ public class GroupsOperation extends BaseOperation {
return result;
}
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) {
- // TODO Auto-generated method stub
+ public Either<List<GroupDefinition>, StorageOperationStatus> deleteGroups(Component component, List<GroupDataDefinition> groups) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
StorageOperationStatus status = null;
@@ -143,8 +133,7 @@ public class GroupsOperation extends BaseOperation {
return result;
}
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) {
- // TODO Auto-generated method stub
+ public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups) {
Either<List<GroupDefinition>, StorageOperationStatus> result = null;
Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
StorageOperationStatus status = null;
@@ -184,12 +173,11 @@ public class GroupsOperation extends BaseOperation {
Either<List<GroupProperty>,StorageOperationStatus> result = null;
Either<GraphVertex, TitanOperationStatus> getComponentVertex = null;
GraphVertex componentVertex = null;
- StorageOperationStatus status = null;
if (result == null) {
getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
if (getComponentVertex.isRight()) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
}
}
@@ -206,7 +194,7 @@ public class GroupsOperation extends BaseOperation {
StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME);
if ( updateDataRes != StorageOperationStatus.OK ){
- logger.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes);
+ log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes);
result = Either.right(updateDataRes);
}
}
@@ -214,7 +202,7 @@ public class GroupsOperation extends BaseOperation {
componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(componentVertex);
if (updateRes.isRight()) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
}
}
@@ -241,7 +229,7 @@ public class GroupsOperation extends BaseOperation {
}
- public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) {
Either<List<GroupInstance>, StorageOperationStatus> result = null;
StorageOperationStatus status = null;
@@ -267,7 +255,7 @@ public class GroupsOperation extends BaseOperation {
public Either<GroupDefinition, StorageOperationStatus> updateGroup(Component component, GroupDefinition currentGroup) {
StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME);
if(status != StorageOperationStatus.OK){
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status);
return Either.right(status);
}
return Either.left(currentGroup);
@@ -276,7 +264,7 @@ public class GroupsOperation extends BaseOperation {
public StorageOperationStatus deleteGroup(Component component, String currentGroupName) {
StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.NAME);
if(status != StorageOperationStatus.OK){
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status);
}
return status;
}
@@ -284,7 +272,7 @@ public class GroupsOperation extends BaseOperation {
public Either<GroupDefinition, StorageOperationStatus> addGroup(Component component, GroupDefinition currentGroup) {
StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME);
if(status != StorageOperationStatus.OK){
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status);
return Either.right(status);
}
return Either.left(currentGroup);
@@ -294,7 +282,7 @@ public class GroupsOperation extends BaseOperation {
Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
if (getComponentVertex.isRight()) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value()));
}
@@ -310,7 +298,7 @@ public class GroupsOperation extends BaseOperation {
pathKeys.add(instanceId);
StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME);
if (updateDataRes != StorageOperationStatus.OK) {
- logger.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes);
+ log.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes);
return Either.right(updateDataRes);
}
return Either.left(oldGroupInstance);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java
index f59f097bdb..3dc39b3a99 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
@@ -28,11 +28,11 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.function.BiConsumer;
+import java.util.function.BiPredicate;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
-import java.util.function.BiConsumer;
-import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
@@ -69,22 +69,7 @@ import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityRequirementRelationship;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.RelationshipImpl;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
@@ -539,6 +524,7 @@ public class NodeTemplateOperation extends BaseOperation {
}
}
}
+ return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult);
}
}
return StorageOperationStatus.OK;
@@ -1000,35 +986,7 @@ public class NodeTemplateOperation extends BaseOperation {
dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
if (dataDefinition.getOriginType() == null && originToscaElement != null) {
ResourceTypeEnum resourceType = originToscaElement.getResourceType();
- OriginTypeEnum originType = null;
- switch (resourceType) {
- case VF:
- originType = OriginTypeEnum.VF;
- break;
- case VFC:
- originType = OriginTypeEnum.VFC;
- break;
- case CVFC:
- originType = OriginTypeEnum.CVFC;
- break;
- case VL:
- originType = OriginTypeEnum.VL;
- break;
- case CP:
- originType = OriginTypeEnum.CP;
- break;
- case PNF:
- originType = OriginTypeEnum.PNF;
- break;
- case ServiceProxy:
- originType = OriginTypeEnum.ServiceProxy;
- break;
- case Configuration:
- originType = OriginTypeEnum.Configuration;
- break;
- default:
- break;
- }
+ OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name());
dataDefinition.setOriginType(originType);
}
if(dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy)
@@ -1340,7 +1298,7 @@ public class NodeTemplateOperation extends BaseOperation {
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null;
MapListRequirementDataDefinition reqMapOfLists = null;
Optional<RequirementDataDefinition> foundRequirement;
- RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation();
+ RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
TitanOperationStatus error = containerVEither.right().value();
@@ -1387,7 +1345,7 @@ public class NodeTemplateOperation extends BaseOperation {
MapListCapabiltyDataDefinition capMapOfLists = null;
Optional<CapabilityDataDefinition> foundRequirement;
- RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation();
+ RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
TitanOperationStatus error = containerVEither.right().value();
@@ -1526,7 +1484,8 @@ public class NodeTemplateOperation extends BaseOperation {
mapListCapaDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(cap);
- relationship.setCapability(cap);
+ if(relationship!= null)
+ relationship.setCapability(cap);
break;
}
}
@@ -1574,7 +1533,8 @@ public class NodeTemplateOperation extends BaseOperation {
mapListReqDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(req);
- relationship.setRequirement(req);
+ if(relationship!= null)
+ relationship.setRequirement(req);
break;
}
}
@@ -1770,8 +1730,12 @@ public class NodeTemplateOperation extends BaseOperation {
}
}
}
+ if (requirementForRelation == null) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId, containerId);
+ return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
+ }
if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId,
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId,
toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
@@ -1985,6 +1949,10 @@ public class NodeTemplateOperation extends BaseOperation {
return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
}
+ public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map<String, MapCapabiltyProperty> capabilityPropertyMap) {
+ return overrideToscaDataOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilityPropertyMap);
+ }
+
public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
List<String> 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 d46743cfa9..59f4745537 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
@@ -41,6 +41,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java
new file mode 100644
index 0000000000..06770318aa
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java
@@ -0,0 +1,63 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+@org.springframework.stereotype.Component
+public class PolicyOperation {
+
+ private static final Logger log = LoggerFactory.getLogger(PolicyOperation.class);
+ private TopologyTemplateOperation topologyTemplateOperation;
+ private TitanDao titanDao;
+
+ public PolicyOperation(TopologyTemplateOperation topologyTemplateOperation, TitanDao titanDao) {
+ this.topologyTemplateOperation = topologyTemplateOperation;
+ this.titanDao = titanDao;
+ }
+
+ /**
+ * updates a list of policy properties by overriding the existing ones with the same name
+ * @param containerComponent the container of the policy of which its properties are to be updated
+ * @param policyId the id of the policy of which its properties are to be updated
+ * @param propertiesToUpdate the policy properties to update
+ * @return the update operation status
+ */
+ public StorageOperationStatus updatePolicyProperties(Component containerComponent, String policyId, List<PropertyDataDefinition> propertiesToUpdate) {
+ log.debug("#updatePolicyProperties - updating the properties of policy {} in component {}", policyId, containerComponent.getUniqueId());
+ PolicyDefinition policy = containerComponent.getPolicyById(policyId);
+ return titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse)
+ .either(containerVertex -> updatePolicyProperties(containerVertex, policy, propertiesToUpdate),
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private StorageOperationStatus updatePolicyProperties(GraphVertex container, PolicyDefinition policy, List<PropertyDataDefinition> propertiesToUpdate) {
+ List<PropertyDataDefinition> policyProperties = policy.getProperties();
+ List<PropertyDataDefinition> updatedPolicyProperties = updatePolicyProperties(policyProperties, propertiesToUpdate);
+ policy.setProperties(updatedPolicyProperties);
+ return topologyTemplateOperation.updatePolicyOfToscaElement(container, policy);
+ }
+
+ private List<PropertyDataDefinition> updatePolicyProperties(List<PropertyDataDefinition> currentPolicyProperties, List<PropertyDataDefinition> toBeUpdatedProperties) {
+ Map<String, PropertyDataDefinition> currPropsByName = MapUtil.toMap(currentPolicyProperties, PropertyDataDefinition::getName);
+ overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties);
+ return new ArrayList<>(currPropsByName.values());
+ }
+
+ private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName, List<PropertyDataDefinition> toBeUpdatedProperties) {
+ toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop));
+ }
+
+}
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 b1d4f151d8..9ad3053d66 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
@@ -20,15 +20,8 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
import org.apache.commons.collections.MapUtils;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -37,24 +30,15 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.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.MapCapabiltyProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.*;
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.Component;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.PolicyDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
@@ -65,19 +49,31 @@ import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("topology-template-operation")
public class TopologyTemplateOperation extends ToscaElementOperation {
+
private static Logger log = LoggerFactory.getLogger(TopologyTemplateOperation.class.getName());
+ @Override
+ public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) {
+ return super.getToscaElement(uniqueId);
+ }
+
public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) {
Either<TopologyTemplate, StorageOperationStatus> result = null;
@@ -125,6 +121,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
result = Either.right(associateGroups);
return result;
}
+ StorageOperationStatus associatePolicies = associatePoliciesToComponent(topologyTemplateVertex, topologyTemplate);
+ if (associatePolicies != StorageOperationStatus.OK) {
+ result = Either.right(associatePolicies);
+ return result;
+ }
StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate);
if (associateInstAttr != StorageOperationStatus.OK) {
result = Either.right(associateInstAttr);
@@ -174,10 +175,40 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
result = Either.right(associateCapProperties);
return result;
}
+ StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate);
+ if (associateCapProperties != StorageOperationStatus.OK) {
+ result = Either.right(associatePathProperties);
+ return result;
+ }
+
+
return Either.left(topologyTemplate);
}
+ private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) {
+ return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies());
+ }
+
+ private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) {
+ if (policies != null && !policies.isEmpty()) {
+ policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
+ Map<String, ForwardingPathDataDefinition> forwardingPaths = topologyTemplate.getForwardingPaths();
+ return associateForwardingPathToComponent(topologyTemplateVertex,forwardingPaths);
+ }
+
private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) {
Map<String, MapCapabiltyProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties();
if (calculatedCapProperties != null && !calculatedCapProperties.isEmpty()) {
@@ -405,6 +436,16 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return associateInstAttributeToComponent(nodeTypeVertex, instAttr);
}
+ public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map<String, ForwardingPathDataDefinition> forwardingPathMap) {
+ if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instAttr) {
if (instAttr != null && !instAttr.isEmpty()) {
Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr);
@@ -509,8 +550,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
TopologyTemplate toscaElement;
toscaElement = convertToTopologyTemplate(componentV);
- TitanOperationStatus status = null;
- if (false == componentParametersView.isIgnoreUsers()) {
+ TitanOperationStatus status;
+ if (!componentParametersView.isIgnoreUsers()) {
status = setCreatorFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -521,72 +562,79 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreCategories()) {
+ if (!componentParametersView.isIgnoreCategories()) {
status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreArtifacts()) {
+ if (!componentParametersView.isIgnoreArtifacts()) {
TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement);
if (storageStatus != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus));
}
}
- if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
+ if (!componentParametersView.isIgnoreComponentInstancesProperties()) {
status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreCapabilities()) {
+ if (!componentParametersView.isIgnoreCapabilities()) {
status = setCapabilitiesFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreRequirements()) {
+ if (!componentParametersView.isIgnoreRequirements()) {
status = setRequirementsFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreAllVersions()) {
+ if (!componentParametersView.isIgnoreAllVersions()) {
status = setAllVersions(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreAdditionalInformation()) {
+ if (!componentParametersView.isIgnoreAdditionalInformation()) {
status = setAdditionalInformationFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreGroups()) {
+ if (!componentParametersView.isIgnoreGroups()) {
status = setGroupsFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreComponentInstances()) {
+ if (!componentParametersView.isIgnorePolicies()) {
+ status = setPoliciesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ }
+ if (!componentParametersView.isIgnoreComponentInstances()) {
status = setInstGroupsFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreInputs()) {
+ if (!componentParametersView.isIgnoreInputs()) {
status = setInputsFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
- if (false == componentParametersView.isIgnoreProperties()) {
+ if (!componentParametersView.isIgnoreProperties()) {
status = setPropertiesFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -594,7 +642,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
- if (false == componentParametersView.isIgnoreComponentInstancesInputs()) {
+ if (!componentParametersView.isIgnoreComponentInstancesInputs()) {
status = setComponentInstancesInputsFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
@@ -602,16 +650,49 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
}
- if (false == componentParametersView.isIgnoreCapabiltyProperties()) {
+ if (!componentParametersView.isIgnoreCapabiltyProperties()) {
status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement);
if (status != TitanOperationStatus.OK) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
+
+ if (!componentParametersView.isIgnoreForwardingPath()) {
+ status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+
+ }
+ }
return Either.left(toscaElement);
}
+ private TitanOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) {
+ Either<Map<String, PolicyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES);
+ if (result.isLeft()) {
+ toscaElement.setPolicies(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ private TitanOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
+ Either<Map<String, ForwardingPathDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH);
+ if (result.isLeft()) {
+ topologyTemplate.setForwardingPaths(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+
private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) {
Either<Map<String, MapCapabiltyProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES);
if (result.isLeft()) {
@@ -808,6 +889,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return TitanOperationStatus.OK;
}
+ @SuppressWarnings("unchecked")
private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) {
TopologyTemplate topologyTemplate = super.convertToComponent(componentV);
@@ -901,6 +983,12 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status);
+ Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS);
toscaElementVertex.getVertex().remove();
log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId());
@@ -984,6 +1072,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return Either.left(byCriteria.left().value());
}
+ @SuppressWarnings("unchecked")
public boolean isInUse(GraphVertex elementV, List<GraphVertex> allNonDeleted) {
for (GraphVertex containerV : allNonDeleted) {
Map<String, CompositionDataDefinition> composition = (Map<String, CompositionDataDefinition>) containerV.getJson();
@@ -1004,6 +1093,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return false;
}
+ @SuppressWarnings("unchecked")
public boolean isInUse(String componentId, List<GraphVertex> allNonDeleted) {
for (GraphVertex containerV : allNonDeleted) {
Map<String, CompositionDataDefinition> composition = (Map<String, CompositionDataDefinition>) containerV.getJson();
@@ -1074,14 +1164,15 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result;
}
/**
- * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type
+ * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
* @param componentId
* @param instanceId
* @param capabilityName
* @param capabilityType
+ * @param ownerId
* @return
*/
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType) {
+ public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null;
Map<String, MapCapabiltyProperty> mapPropertiesDataDefinition = null;
@@ -1098,21 +1189,26 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
}
}
if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){
- result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
+ result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()));
}
- return result;
+ return result;
+ }
+
+ public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabiltyProperty instanceProperties) {
+ return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId);
}
+
private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabiltyProperty> mapPropertiesDataDefinition) {
return MapUtils.isNotEmpty(mapPropertiesDataDefinition) &&
mapPropertiesDataDefinition.get(instanceId) != null &&
MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition());
}
- private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, Map<String, MapPropertiesDataDefinition> propertiesMap) {
+ private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) {
List<ComponentInstanceProperty> capPropsList = null;
for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){
- if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, capProp)) {
+ if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) {
Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition();
if (capMap != null && !capMap.isEmpty()) {
capPropsList = capMap.values().stream().map(o -> new ComponentInstanceProperty(o)).collect(Collectors.toList());
@@ -1126,16 +1222,48 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return capPropsList;
}
- private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, Entry<String, MapPropertiesDataDefinition> capProp) {
+ private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) {
if (capProp != null) {
String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM );
if (path.length < 4) {
log.debug("wrong key format for capabilty, key {}", capProp);
return false;
}
- return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[0].equals(instanceId);
+ return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId);
}
return false;
}
+ public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
+ fillPolicyDefinition(componentV, policyDefinition, counter);
+ return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) {
+ return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) {
+ return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) {
+ return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID);
+ }
+
+ private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) {
+ String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter);
+ policyDefinition.setName(policyName);
+ policyDefinition.setInvariantName(policyName);
+ policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME));
+ policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName));
+ policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+ policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID());
+ }
+
+ public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) {
+ String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length());
+ return componentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter;
+ }
+
}
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 f34975b073..86415de635 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
@@ -76,6 +76,8 @@ import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.thinkaurelius.titan.core.TitanVertex;
+
import fj.data.Either;
@org.springframework.stereotype.Component("tosca-element-lifecycle-operation")
@@ -223,29 +225,43 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Either<GraphVertex, TitanOperationStatus> getToscaElementRes = null;
Iterator<Edge> nextVersionComponentIter = null;
ToscaElementOperation operation;
+ Vertex preVersionVertex = null;
try {
getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata);
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())) {
+ GraphVertex currVersionV = getToscaElementRes.left().value();
+ if (result == null && hasPreviousVersion(currVersionV)) {
// find previous version
- nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name());
+ nextVersionComponentIter = currVersionV.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());
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", currVersionV.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString());
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
if (result == null) {
- StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex());
+ preVersionVertex = nextVersionComponentIter.next().outVertex();
+ StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex);
if (updateOldResourceResult != StorageOperationStatus.OK) {
result = Either.right(updateOldResourceResult);
}
}
}
if (result == null) {
- operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel());
- result = operation.deleteToscaElement(getToscaElementRes.left().value());
+ GraphVertex prevVersionV = null;
+ if (preVersionVertex != null) {
+ prevVersionV = new GraphVertex();
+ prevVersionV.setVertex((TitanVertex) preVersionVertex);
+ String uniqueIdPreVer = (String) titanDao.getProperty((TitanVertex) preVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty());
+ prevVersionV.setUniqueId(uniqueIdPreVer);
+ }
+ StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRoot(prevVersionV, currVersionV);
+ if (updateCatalogRes != StorageOperationStatus.OK) {
+ return Either.right(updateCatalogRes);
+ }
+ operation = getToscaElementOperation(currVersionV.getLabel());
+ result = operation.deleteToscaElement(currVersionV);
}
} catch (Exception e) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage());
@@ -539,11 +555,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
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);
+ 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){
+ if (result == null) {
while (certReqUserEdgeIter.hasNext()) {
Edge edge = certReqUserEdgeIter.next();
@@ -698,6 +715,14 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
+ // remove previous certified version from the catalog
+ GraphVertex lastCertifiedV = new GraphVertex();
+ lastCertifiedV.setVertex((TitanVertex) lastCertifiedVertex);
+ lastCertifiedV.setUniqueId((String) titanDao.getProperty((TitanVertex) lastCertifiedVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()));
+ StorageOperationStatus res = updateEdgeToCatalogRoot(null, lastCertifiedV);
+ if (res != StorageOperationStatus.OK) {
+ return res;
+ }
}
}
if (result == null) {
@@ -811,9 +836,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Map<String, Object> propertiesToUpdate = new HashMap<>();
propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
- Map<String, Object> jsonMetadataMap = JsonParserUtils.parseToJson((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value());
+ Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value());
jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true);
- propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap));
+ propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap));
titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate);
@@ -832,6 +857,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes);
}
}
+
}
} catch (Exception e) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage());
@@ -888,9 +914,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
// check if component with the next version doesn't exist.
Iterator<Edge> nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name());
if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) {
- Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex();
+ Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex();
String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value();
- String fetchedName = (String)nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value();
+ String fetchedName = (String) nextVersionVertex.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);
@@ -912,16 +938,22 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
}
if (result == null) {
+ Boolean isHighest = (Boolean) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
+ GraphVertex prevVersionInCatalog = (isHighest != null && isHighest) ? null : toscaElementVertex;
+ StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRoot(clonedVertex, prevVersionInCatalog);
+ if (updateCatalogRes != StorageOperationStatus.OK) {
+ return Either.right(updateCatalogRes);
+ }
result = operation.getToscaElement(cloneResult.left().value().getUniqueId());
if (result.isRight()) {
return result;
}
-
ToscaElement toscaElement = result.left().value();
if (toscaElement.getToscaType() == ToscaElementTypeEnum.TopologyTemplate) {
result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement);
}
}
+
return result;
}
@@ -952,7 +984,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex);
}
needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap);
- if(needUpdateComposition){
+ if (needUpdateComposition) {
instancesMap.put(vfInst.getUniqueId(), vfInst);
}
}
@@ -1010,8 +1042,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
return result;
}
-
- //TODO remove after jsonModelMigration
+
+ // TODO remove after jsonModelMigration
public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
return fixToscaComponentName(vfInst, origCompMap);
}
@@ -1026,7 +1058,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
Either<ToscaElement, StorageOperationStatus> origCompEither;
if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) {
origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
- }else{
+ } else {
origCompEither = nodeTypeOperation.getToscaElement(origCompUid);
}
if (origCompEither.isRight()) {
@@ -1088,7 +1120,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before create group instance. ");
List<GroupDataDefinition> 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());
@@ -1097,39 +1128,38 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
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<String, ArtifactDataDefinition> deploymentArtifacts = origComp.getDeploymentArtifacts();
-
-
- instArifacts = new MapArtifactDataDefinition(deploymentArtifacts);
- addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid);
-
- instArtifactsMap.put(ciUid, instArifacts);
-
- }else{
+ if (!instArtifactsMap.containsKey(ciUid)) {
+
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "istance artifacts not found ");
+
+ Map<String, ArtifactDataDefinition> 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){
+
+ if (instArifacts != null) {
Map<String, ArtifactDataDefinition> instDeplArtifMap = instArifacts.getMapToscaDataDefinition();
-
+
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size());
Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
- for(GroupDataDefinition group:filteredGroups){
+ for (GroupDataDefinition group : filteredGroups) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName());
GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst, instDeplArtifMap);
List<String> artifactsUid = new ArrayList<>();
List<String> artifactsId = new ArrayList<>();
for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) {
- //CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", artifact.getA);
+ // CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", artifact.getA);
Optional<String> 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);
@@ -1138,7 +1168,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate));
-
+
}
}
}
@@ -1195,6 +1225,10 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value());
} else {
clonedToscaElement = result.left().value();
+ StorageOperationStatus updateEdgeToCatalog = updateEdgeToCatalogRoot(clonedToscaElement, toscaElementVertex);
+ if (updateEdgeToCatalog != StorageOperationStatus.OK) {
+ return Either.right(updateEdgeToCatalog);
+ }
deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex);
if (deleteResult.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value());
@@ -1229,6 +1263,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
}
+
}
if (result == null) {
result = Either.left(clonedToscaElement);
@@ -1436,13 +1471,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return verticesToGetParameters;
}
-
private String getNextCertifiedVersion(String version) {
String[] versionParts = version.split(VERSION_DELIMETER_REGEXP);
Integer nextMajorVersion = Integer.parseInt(versionParts[0]) + 1;
return nextMajorVersion + VERSION_DELIMETER + "0";
}
-
+
private String getNextVersion(String currVersion) {
String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP);
Integer minorVersion = Integer.parseInt(versionParts[1]) + 1;
@@ -1466,7 +1500,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
return false;
}
- public Either<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) {
+ public Either<ToscaElement, StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) {
Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
Either<ToscaElement, StorageOperationStatus> result = null;
GraphVertex toscaElement = null;
@@ -1514,23 +1548,55 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
- StorageOperationStatus result = null;
- TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
+ StorageOperationStatus result = null;
+ TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
+ if (status != TitanOperationStatus.OK) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
+ properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
+ status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
- if (result == null) {
- Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
- properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
- status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
- if (status != TitanOperationStatus.OK) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ result = StorageOperationStatus.OK;
+ }
+ return result;
+ }
+
+ private StorageOperationStatus updateEdgeToCatalogRoot(GraphVertex newVersionV, GraphVertex prevVersionV) {
+ Either<GraphVertex, TitanOperationStatus> catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT);
+ if (catalog.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch catalog vertex. error {}", catalog.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value());
+ }
+ GraphVertex catalogV = catalog.left().value();
+ if (newVersionV != null) {
+ Boolean isAbstract = (Boolean) newVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
+ if (isAbstract == null || !isAbstract) {
+ // no new vertex, only delete previous
+ TitanOperationStatus result = titanDao.createEdge(catalogV, newVersionV, EdgeLabelEnum.CATALOG_ELEMENT, null);
+ if (result != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}", newVersionV.getUniqueId(), result);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
}
}
- if (result == null) {
- result = StorageOperationStatus.OK;
+ }
+ if (prevVersionV != null) {
+ Boolean isAbstract = (Boolean) prevVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
+ if (isAbstract == null || !isAbstract) {
+ // if prev == null -> new resource was added
+ Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteEdge(catalogV, prevVersionV, EdgeLabelEnum.CATALOG_ELEMENT);
+ if (deleteResult.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}", prevVersionV.getUniqueId(), deleteResult.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteResult.right().value());
+ }
}
- return result;
+ }
+ return StorageOperationStatus.OK;
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java
index ec55ddaf3b..0cb71eeab3 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
@@ -33,12 +33,15 @@ import java.util.Set;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
@@ -50,6 +53,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
@@ -65,6 +69,7 @@ import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.StopWatch;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
@@ -72,1143 +77,1244 @@ import com.google.gson.reflect.TypeToken;
import fj.data.Either;
public abstract class ToscaElementOperation extends BaseOperation {
- private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName());
-
- private static final Gson gson = new Gson();
-
- protected Gson getGson() {
- return gson;
- }
-
- @Autowired
- protected CategoryOperation categoryOperation;
-
- protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) {
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>();
- propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId);
-
- VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType);
- Either<List<GraphVertex>, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag);
- if (getResponse.isRight()) {
- log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()));
-
- }
- List<GraphVertex> componentList = getResponse.left().value();
- if (componentList.isEmpty()) {
- log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- GraphVertex vertexG = componentList.get(0);
- return Either.left(vertexG);
- }
-
- public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) {
- return getToscaElement(uniqueId, new ComponentParametersView());
- }
-
- public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) {
- Either<GraphVertex, StorageOperationStatus> result = null;
-
- Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
- if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) {
- // component already marked for delete
- result = Either.left(componentToDelete);
- return result;
- } else {
-
- componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE);
- componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
-
- Either<GraphVertex, TitanOperationStatus> updateNode = titanDao.updateVertex(componentToDelete);
-
- StorageOperationStatus updateComponent;
- if (updateNode.isRight()) {
- log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value());
- updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value());
- result = Either.right(updateComponent);
- return result;
- }
-
- result = Either.left(componentToDelete);
- return result;
- }
- }
-
- /**
- * Performs a shadow clone of previousToscaElement
- *
- * @param previousToscaElement
- * @param nextToscaElement
- * @param user
- * @return
- */
- public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) {
-
- Either<GraphVertex, StorageOperationStatus> result = null;
- GraphVertex createdToscaElementVertex = null;
- TitanOperationStatus status;
-
- Either<GraphVertex, TitanOperationStatus> createNextVersionRes = titanDao.createVertex(nextToscaElement);
- if (createNextVersionRes.isRight()) {
- status = createNextVersionRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
- previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- createdToscaElementVertex = createNextVersionRes.left().value();
- Map<EdgePropertyEnum, Object> properties = new HashMap<EdgePropertyEnum, Object>();
- properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE));
- status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
- if (status != TitanOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.STATE, user.getUniqueId(),
- previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (result == null) {
- status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
- if (status != TitanOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(),
- nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (result == null) {
- status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>());
- if (status != TitanOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.CREATOR, user.getUniqueId(),
- nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (result == null) {
- Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT);
- while (edgesToCopyIter.hasNext()) {
- Edge currEdge = edgesToCopyIter.next();
- Vertex currVertex = currEdge.inVertex();
- // if(EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()).equals(EdgeLabelEnum.VERSION)){
- // continue;
- // }
- status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge);
- if (status != TitanOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(),
- currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- break;
- }
- }
- }
-
- if (result == null) {
- result = Either.left(createdToscaElementVertex);
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
- }
- return result;
- }
-
- protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
- Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
- if (parentVertex.isRight()) {
- log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
- return parentVertex.right().value();
- }
- GraphVertex userV = parentVertex.left().value();
- String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
- toscaElement.setLastUpdaterUserId(userId);
- toscaElement.setLastUpdaterFullName(buildFullName(userV));
- return TitanOperationStatus.OK;
- }
-
- public String buildFullName(GraphVertex userV) {
-
- String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME);
- if (fullName == null) {
- fullName = "";
- } else {
- fullName = fullName + " ";
- }
- String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME);
- if (lastName != null) {
- fullName += lastName;
- }
- return fullName;
- }
-
- protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
- Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
- if (parentVertex.isRight()) {
- log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
- return parentVertex.right().value();
- }
- GraphVertex userV = parentVertex.left().value();
- String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
- toscaElement.setCreatorUserId(creatorUserId);
- toscaElement.setCreatorFullName(buildFullName(userV));
-
- return TitanOperationStatus.OK;
- }
-
- protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) {
- if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) {
- toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName()));
- }
- if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) {
- toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName()));
- }
-
- LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState();
- if (lifecycleStateEnum == null) {
- toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- }
- long currentDate = System.currentTimeMillis();
- if (toscaElement.getCreationDate() == null) {
- toscaElement.setCreationDate(currentDate);
- }
- toscaElement.setLastUpdateDate(currentDate);
-
- return toscaElement;
- }
-
- protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
- if (toscaElement.isHighestVersion() == null) {
- toscaElement.setHighestVersion(true);
- }
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME));
- nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
- toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue()));
-
- nodeTypeVertex.setUniqueId(toscaElement.getUniqueId());
- nodeTypeVertex.setType(toscaElement.getComponentType());
-
- }
-
- protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
- // handle user
- String userId = toscaElement.getCreatorUserId();
-
- Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(userId);
-
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
-
- }
- GraphVertex creatorVertex = findUser.left().value();
- GraphVertex updaterVertex = creatorVertex;
- String updaterId = toscaElement.getLastUpdaterUserId();
- if (updaterId != null && !updaterId.equals(userId)) {
- findUser = findUserVertex(updaterId);
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- } else {
- updaterVertex = findUser.left().value();
- }
- }
- Map<EdgePropertyEnum, Object> props = new HashMap<EdgePropertyEnum, Object>();
- props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
-
- TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
- log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE);
- if (TitanOperationStatus.OK != result) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
- }
- result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
- log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
- if (!result.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
- }
-
- toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId());
- toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName());
-
- result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null);
- log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
- if (!result.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
- }
- return StorageOperationStatus.OK;
- }
-
- protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
- String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName();
- String categoryName = nodeType.getCategories().get(0).getName();
- Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName);
-
- if (getCategoryVertex.isRight()) {
- return getCategoryVertex.right().value();
- }
-
- GraphVertex subCategoryV = getCategoryVertex.left().value();
-
- TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
- if (createEdge != TitanOperationStatus.OK) {
- log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
- }
- return StorageOperationStatus.OK;
- }
-
- protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) {
- Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY);
- if (category.isRight()) {
- log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value());
- return Either.right(category.right().value());
- }
- GraphVertex categoryV = category.left().value();
-
- if (subcategoryName != null) {
- Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName);
- if (subCategory.isRight()) {
- log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value());
- return Either.right(subCategory.right().value());
- }
-
- GraphVertex subCategoryV = subCategory.left().value();
- return Either.left(subCategoryV);
- }
- return Either.left(categoryV);
- }
-
- private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
- Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts();
- Either<GraphVertex, StorageOperationStatus> status;
- if (artifacts != null) {
- artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
- a.setUniqueId(uniqueId);
- });
- status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts);
- if (status.isRight()) {
- return status.right().value();
- }
- }
- Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
- if (toscaArtifacts != null) {
- toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
- a.setUniqueId(uniqueId);
- });
- status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts);
- if (status.isRight()) {
- return status.right().value();
- }
- }
- Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
- if (deploymentArtifacts != null) {
- deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
- String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
- a.setUniqueId(uniqueId);
- });
- status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts);
- if (status.isRight()) {
- return status.right().value();
- }
- }
- return StorageOperationStatus.OK;
- }
-
- protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) {
- TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
- return status;
- }
- return TitanOperationStatus.OK;
- }
-
- protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) {
-
- StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement);
- if (associateUsers != StorageOperationStatus.OK) {
- return associateUsers;
- }
- StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement);
- if (associateArtifacts != StorageOperationStatus.OK) {
- return associateArtifacts;
- }
- StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources);
- if (associateProperties != StorageOperationStatus.OK) {
- return associateProperties;
- }
- StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement);
- if (associateAdditionaInfo != StorageOperationStatus.OK) {
- return associateAdditionaInfo;
- }
-
- return StorageOperationStatus.OK;
- }
-
- protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) {
- // Note : currently only one derived supported!!!!
- Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES);
- if (dataFromDerived.isRight()) {
- return dataFromDerived.right().value();
- }
- Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value();
-
- Map<String, PropertyDataDefinition> properties = nodeType.getProperties();
-
- if (properties != null) {
- properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
- String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName());
- p.setUniqueId(uid);
- });
-
- Either<Map<String, PropertyDataDefinition>, 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<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll);
- if (assosiateElementToData.isRight()) {
- return assosiateElementToData.right().value();
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
- Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation();
- if (additionalInformation != null) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
- if (assosiateElementToData.isRight()) {
- return assosiateElementToData.right().value();
- }
- }
- return StorageOperationStatus.OK;
- }
-
- protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, EdgeLabelEnum edge) {
- Map<String, T> propertiesAll = new HashMap<>();
-
- if (derivedResources != null && !derivedResources.isEmpty()) {
- for (GraphVertex derived : derivedResources) {
- Either<List<GraphVertex>, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson);
- if (derivedProperties.isRight()) {
- if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value()));
- } else {
- continue;
- }
- }
- List<GraphVertex> propList = derivedProperties.left().value();
- for (GraphVertex propV : propList) {
- Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson();
- if (propertiesFromDerived != null) {
- propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId()));
- propertiesAll.putAll(propertiesFromDerived);
- }
- }
- }
- }
- return Either.left(propertiesAll);
- }
-
- protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
- Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS);
- if (result.isLeft()) {
- toscaElement.setArtifacts(result.left().value());
- } else {
- if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
- return result.right().value();
- }
- }
- result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
- if (result.isLeft()) {
- toscaElement.setDeploymentArtifacts(result.left().value());
- } else {
- if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
- return result.right().value();
- }
- }
- result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS);
- if (result.isLeft()) {
- toscaElement.setToscaArtifacts(result.left().value());
- } else {
- if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
- return result.right().value();
- }
- }
- return TitanOperationStatus.OK;
- }
-
- protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) {
- Map<String, String> allVersion = new HashMap<>();
-
- allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId());
- ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<GraphVertex>();
- Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
- while (childResourceRes.isLeft()) {
- GraphVertex child = childResourceRes.left().value();
- allChildrenAndParants.add(child);
- childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
- }
- TitanOperationStatus operationStatus = childResourceRes.right().value();
-
- if (operationStatus != TitanOperationStatus.NOT_FOUND) {
- return operationStatus;
- } else {
- Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
- while (parentResourceRes.isLeft()) {
- GraphVertex parent = parentResourceRes.left().value();
- allChildrenAndParants.add(parent);
- parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
- }
- operationStatus = parentResourceRes.right().value();
- if (operationStatus != TitanOperationStatus.NOT_FOUND) {
- return operationStatus;
- } else {
- allChildrenAndParants.stream().filter(vertex -> {
- Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
- return (isDeleted == null || isDeleted == false);
- }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId()));
-
- toscaElement.setAllVersions(allVersion);
- return TitanOperationStatus.OK;
- }
- }
- }
-
- protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) {
-
- Either<List<T>, StorageOperationStatus> result = null;
-
- Map<GraphPropertyEnum, Object> props = null;
-
- if (userId != null) {
- props = new HashMap<>();
- // for Designer retrieve specific user
- props.put(GraphPropertyEnum.USERID, userId);
- }
- // in case of user id == null -> get all users by label
- // for Tester and Admin retrieve all users
- Either<List<GraphVertex>, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse);
- if (usersByCriteria.isRight()) {
- log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value()));
- }
- List<GraphVertex> users = usersByCriteria.left().value();
-
- List<T> components = new ArrayList<>();
- List<T> componentsPerUser;
- for (GraphVertex userV : users) {
-
- HashSet<String> ids = new HashSet<String>();
- Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
- if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value()));
- }
-
- // get all resource with current state
- if (childrenVertecies.isLeft()) {
- componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE);
-
- if (componentsPerUser != null) {
- for (T comp : componentsPerUser) {
- ids.add(comp.getUniqueId());
- components.add(comp);
- }
- }
- }
- if (lastStateStates != null && !lastStateStates.isEmpty()) {
- // get all resource with last state
- childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse);
- if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value()));
- }
- if (childrenVertecies.isLeft()) {
- boolean isFirst;
- componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE);
- if (componentsPerUser != null) {
- for (T comp : componentsPerUser) {
- isFirst = true;
-
- if (ids.contains(comp.getUniqueId())) {
- isFirst = false;
- }
- if (isFirst == true) {
- components.add(comp);
- }
-
- }
- }
- }
- }
-
- } // whlile users
- ;
- result = Either.left(components);
- return result;
-
- }
-
- private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
- List<T> components = new ArrayList<>();
- for (GraphVertex node : vertices) {
-
- Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name());
- while (edges.hasNext()) {
- Edge edge = edges.next();
- String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE);
-
- LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr);
- if (nodeState == null) {
- log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId());
- continue;
- }
- if (lifecycleStates != null && lifecycleStates.contains(nodeState)) {
-
- Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
- if (isDeleted != null && isDeleted) {
- log.trace("Deleted element {}, discard", node.getUniqueId());
- continue;
- }
-
- Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
- if (isHighest) {
-
- ComponentTypeEnum componentType = node.getType();
- // get only latest versions
-
- if (componentType == null) {
- log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId());
- continue;
- }
- if (neededType == componentType) {
- switch (componentType) {
- case SERVICE:
- case PRODUCT:
- handleNode(components, node, componentType);
- break;
- case RESOURCE:
- Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
- if (isAbtract == null || false == isAbtract) {
- handleNode(components, node, componentType);
- } // if not abstract
- break;
- default:
- log.debug("not supported node type {}", componentType);
- break;
- }// case
- } // needed type
- }
- } // if
- } // while edges
- } // while resources
- return components;
- }
-
- protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) {
-
- Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true));
- if (component.isRight()) {
- log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value());
- } else {
- components.add(component.left().value());
- }
- }
-
- protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
- Either<GraphVertex, TitanOperationStatus> getVertexRes = titanDao.getVertexById(componentUid);
- if (getVertexRes.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value()));
- }
- return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter);
- }
-
- protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
-
- log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
-
- titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
-
- T toscaElement = convertToComponent(vertexComponent);
-
- TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- status = setLastModifierFromGraph(vertexComponent, toscaElement);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- status = setCategoriesFromGraph(vertexComponent, toscaElement);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (!parametersFilter.isIgnoreAllVersions()) {
- status = setAllVersions(vertexComponent, toscaElement);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (!parametersFilter.isIgnoreCapabilities()) {
- status = setCapabilitiesFromGraph(vertexComponent, toscaElement);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (!parametersFilter.isIgnoreRequirements()) {
- status = setRequirementsFromGraph(vertexComponent, toscaElement);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
- return Either.left(toscaElement);
- }
-
- @SuppressWarnings("unchecked")
- protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) {
- ToscaElement toscaElement = null;
- VertexTypeEnum label = componentV.getLabel();
- switch (label) {
- case NODE_TYPE:
- toscaElement = new NodeType();
- break;
- case TOPOLOGY_TEMPLATE:
- toscaElement = new TopologyTemplate();
- break;
- default:
- log.debug("Not supported tosca type {}", label);
- break;
- }
-
- Map<String, Object> jsonMetada = componentV.getMetadataJson();
- if (toscaElement != null) {
- toscaElement.setMetadata(jsonMetada);
- }
- return (T) toscaElement;
- }
-
- protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
- List<CategoryDefinition> categories = new ArrayList<>();
- SubCategoryDefinition subcategory;
-
- Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
- if (childVertex.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
- return childVertex.right().value();
- }
- GraphVertex subCategoryV = childVertex.left().value();
- Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
- subcategory = new SubCategoryDefinition();
- subcategory.setUniqueId(subCategoryV.getUniqueId());
- subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
- subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
-
- Type listTypeSubcat = new TypeToken<List<String>>() {
- }.getType();
- List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
- subcategory.setIcons(iconsfromJsonSubcat);
-
- Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
- if (parentVertex.isRight()) {
- log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value());
- return childVertex.right().value();
- }
- GraphVertex categoryV = parentVertex.left().value();
- metadataProperties = categoryV.getMetadataProperties();
-
- CategoryDefinition category = new CategoryDefinition();
- category.setUniqueId(categoryV.getUniqueId());
- category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
- category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
-
- Type listTypeCat = new TypeToken<List<String>>() {
- }.getType();
- List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
- category.setIcons(iconsfromJsonCat);
-
- category.addSubCategory(subcategory);
- categories.add(category);
- toscaElement.setCategories(categories);
-
- return TitanOperationStatus.OK;
- }
-
- public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) {
- Either<T, StorageOperationStatus> result = null;
-
- log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
- if (toscaElementToUpdate == null) {
- log.error("Service object is null");
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
- if (modifierUserId == null || modifierUserId.isEmpty()) {
- log.error("UserId is missing in the request.");
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
- Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(modifierUserId);
-
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status);
- return result;
- }
-
- GraphVertex modifierV = findUser.left().value();
- // UserData modifierUserData = findUser.left().value();
- String toscaElementId = toscaElementToUpdate.getUniqueId();
-
- Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
- if (parentVertex.isRight()) {
- log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value()));
- }
- GraphVertex userV = parentVertex.left().value();
- String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
-
- String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
-
- if (currentModifier.equals(modifierUserId)) {
- log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
- } else {
- log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
- StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV);
- log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- return result;
- }
- }
-
- final long currentTimeMillis = System.currentTimeMillis();
- log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
- elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
-
- StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
- if (checkCategories != StorageOperationStatus.OK) {
- result = Either.right(checkCategories);
- return result;
- }
-
- // update all data on vertex
- fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
-
- Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(elementV);
-
- if (updateElement.isRight()) {
- log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
- return result;
- }
- GraphVertex updateElementV = updateElement.left().value();
-
- // DE230195 in case resource name changed update TOSCA artifacts
- // file names accordingly
- String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
- if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
- Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS);
- if (resultToscaArt.isRight()) {
- log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value()));
- }
-
- Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
- if (toscaArtifacts != null) {
- for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
- generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
- }
- // TODO call to new Artifact operation in order to update list of artifacts
-
- }
- // US833308 VLI in service - specific network_role property value logic
- if (ComponentTypeEnum.SERVICE == toscaElementToUpdate.getComponentType()) {
- // update method logs success/error and returns boolean (true if nothing fails)
- // TODO!!!!
- // updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName);
- }
- }
-
- if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
- StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
- if (resultDerived != StorageOperationStatus.OK) {
- log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived);
- return Either.right(resultDerived);
- }
- }
-
- Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
- if (updatedResource.isRight()) {
- log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- T updatedResourceValue = updatedResource.left().value();
- result = Either.left(updatedResourceValue);
-
- return result;
- }
-
- protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
- }
-
- protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
- }
-
- private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
- Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
- .findAny().get().getValue();
- artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
- }
-
- protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) {
- StorageOperationStatus status = StorageOperationStatus.OK;
- List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
- CategoryDefinition newCategory = newCategoryList.get(0);
-
- Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
- if (childVertex.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value());
- }
- GraphVertex subCategoryV = childVertex.left().value();
- Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
- String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
-
- Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
- if (parentVertex.isRight()) {
- log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value());
- }
- GraphVertex categoryV = parentVertex.left().value();
- metadataProperties = categoryV.getMetadataProperties();
- String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
-
- boolean categoryWasChanged = false;
-
- String newCategoryName = newCategory.getName();
- SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
- String newSubCategoryName = newSubcategory.getName();
- if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) {
- // the category was changed
- categoryWasChanged = true;
- } else {
- // the sub-category was changed
- if (newSubCategoryName != null && false == newSubCategoryName.equals(subCategoryNameCurrent)) {
- log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory);
- categoryWasChanged = true;
- }
- }
- if (categoryWasChanged) {
- Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName);
-
- if (getCategoryVertex.isRight()) {
- return getCategoryVertex.right().value();
- }
- GraphVertex newCategoryV = getCategoryVertex.left().value();
- status = moveCategoryEdge(elementV, newCategoryV);
- log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
- }
- return status;
- }
-
- public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) {
- Either<List<GraphVertex>, TitanOperationStatus> listOfComponents;
- if (isHighestVersions) {
- listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
- }
- else {
- listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
- }
-
- if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value()));
- }
- List<T> result = new ArrayList<>();
- if (listOfComponents.isLeft()) {
- List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
- if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) {
- for (GraphVertex vertexComponent : highestAndAllCertified) {
- Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true));
- if (component.isRight()) {
- log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
- return Either.right(component.right().value());
- } else {
- result.add(component.left().value());
- }
- }
- }
- }
- return Either.left(result);
- }
-
- private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) {
- Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
- if (componentType == ComponentTypeEnum.RESOURCE) {
- propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
- propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
- }
- propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
- }
-
- // highest + (certified && !highest)
- public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
- long startFetchAllStates = System.currentTimeMillis();
- Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata);
-
- Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>();
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
- propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- if (componentType == ComponentTypeEnum.RESOURCE) {
- propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
- propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
- }
-
- propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
- propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified,
- JsonParseFlagEnum.ParseMetadata);
- if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(certifiedNotHighestNodes.right().value());
- }
-
- long endFetchAllStates = System.currentTimeMillis();
-
- List<GraphVertex> allNodes = new ArrayList<>();
-
- if (certifiedNotHighestNodes.isLeft()) {
- allNodes.addAll(certifiedNotHighestNodes.left().value());
- }
- if (highestNodes.isLeft()) {
- allNodes.addAll(highestNodes.left().value());
- }
-
- log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
- return Either.left(allNodes);
- }
-
- protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
-
- // get all components marked for delete
- Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
- props.put(GraphPropertyEnum.IS_DELETED, true);
- props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
- Either<List<GraphVertex>, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
-
- if (componentsToDelete.isRight()) {
- TitanOperationStatus error = componentsToDelete.right().value();
- if (error.equals(TitanOperationStatus.NOT_FOUND)) {
- log.trace("no components to delete");
- return Either.left(new ArrayList<>());
- } else {
- log.info("failed to find components to delete. error : {}", error.name());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
- }
- }
- return Either.left(componentsToDelete.left().value());
- }
-
- protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
- Either<Map<String, AdditionalInfoParameterDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION);
- if (result.isLeft()) {
- toscaElement.setAdditionalInformation(result.left().value());
- } else {
- if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
- return result.right().value();
- }
- }
- return TitanOperationStatus.OK;
- }
-
- // --------------------------------------------
- public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView);
-
- public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView);
-
- public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
-
- public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
-
- protected abstract <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
-
- protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
-
- protected abstract <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
-
- protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
-
- protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
+ private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName());
+
+ private static final Gson gson = new Gson();
+
+ protected Gson getGson() {
+ return gson;
+ }
+
+ @Autowired
+ protected CategoryOperation categoryOperation;
+
+ protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) {
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>();
+ propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId);
+
+ VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType);
+ Either<List<GraphVertex>, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag);
+ if (getResponse.isRight()) {
+ log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()));
+
+ }
+ List<GraphVertex> componentList = getResponse.left().value();
+ if (componentList.isEmpty()) {
+ log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ GraphVertex vertexG = componentList.get(0);
+ return Either.left(vertexG);
+ }
+
+ public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) {
+ return getToscaElement(uniqueId, new ComponentParametersView());
+ }
+
+ public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) {
+ Either<GraphVertex, StorageOperationStatus> result = null;
+
+ Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
+ if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) {
+ // component already marked for delete
+ result = Either.left(componentToDelete);
+ return result;
+ } else {
+
+ componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE);
+ componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
+
+ Either<GraphVertex, TitanOperationStatus> updateNode = titanDao.updateVertex(componentToDelete);
+
+ StorageOperationStatus updateComponent;
+ if (updateNode.isRight()) {
+ log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value());
+ updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value());
+ result = Either.right(updateComponent);
+ return result;
+ }
+
+ result = Either.left(componentToDelete);
+ return result;
+ }
+ }
+
+ /**
+ * Performs a shadow clone of previousToscaElement
+ *
+ * @param previousToscaElement
+ * @param nextToscaElement
+ * @param user
+ * @return
+ */
+ public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) {
+
+ Either<GraphVertex, StorageOperationStatus> result = null;
+ GraphVertex createdToscaElementVertex = null;
+ TitanOperationStatus status;
+
+ Either<GraphVertex, TitanOperationStatus> createNextVersionRes = titanDao.createVertex(nextToscaElement);
+ if (createNextVersionRes.isRight()) {
+ status = createNextVersionRes.right().value();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME),
+ previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ createdToscaElementVertex = createNextVersionRes.left().value();
+ Map<EdgePropertyEnum, Object> properties = new HashMap<EdgePropertyEnum, Object>();
+ properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE));
+ status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.STATE, user.getUniqueId(),
+ previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (result == null) {
+ status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>());
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(),
+ nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (result == null) {
+ status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>());
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.CREATOR, user.getUniqueId(),
+ nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (result == null) {
+ Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT);
+ while (edgesToCopyIter.hasNext()) {
+ Edge currEdge = edgesToCopyIter.next();
+ Vertex currVertex = currEdge.inVertex();
+ // if(EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()).equals(EdgeLabelEnum.VERSION)){
+ // continue;
+ // }
+ status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(),
+ currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ break;
+ }
+ }
+ }
+
+ if (result == null) {
+ result = Either.left(createdToscaElementVertex);
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME));
+ }
+ return result;
+ }
+
+ protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
+ if (parentVertex.isRight()) {
+ log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
+ return parentVertex.right().value();
+ }
+ GraphVertex userV = parentVertex.left().value();
+ String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
+ toscaElement.setLastUpdaterUserId(userId);
+ toscaElement.setLastUpdaterFullName(buildFullName(userV));
+ return TitanOperationStatus.OK;
+ }
+
+ public String buildFullName(GraphVertex userV) {
+
+ String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME);
+ if (fullName == null) {
+ fullName = "";
+ } else {
+ fullName = fullName + " ";
+ }
+ String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME);
+ if (lastName != null) {
+ fullName += lastName;
+ }
+ return fullName;
+ }
+
+ protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse);
+ if (parentVertex.isRight()) {
+ log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value());
+ return parentVertex.right().value();
+ }
+ GraphVertex userV = parentVertex.left().value();
+ String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
+ toscaElement.setCreatorUserId(creatorUserId);
+ toscaElement.setCreatorFullName(buildFullName(userV));
+
+ return TitanOperationStatus.OK;
+ }
+
+ protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) {
+ if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) {
+ toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName()));
+ }
+ if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) {
+ toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName()));
+ }
+
+ LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState();
+ if (lifecycleStateEnum == null) {
+ toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+ long currentDate = System.currentTimeMillis();
+ if (toscaElement.getCreationDate() == null) {
+ toscaElement.setCreationDate(currentDate);
+ }
+ toscaElement.setLastUpdateDate(currentDate);
+
+ return toscaElement;
+ }
+
+ protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
+ if (toscaElement.isHighestVersion() == null) {
+ toscaElement.setHighestVersion(true);
+ }
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME));
+ nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME));
+ toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue()));
+
+ nodeTypeVertex.setUniqueId(toscaElement.getUniqueId());
+ nodeTypeVertex.setType(toscaElement.getComponentType());
+
+ }
+
+ protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
+ // handle user
+ String userId = toscaElement.getCreatorUserId();
+
+ Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(userId);
+
+ if (findUser.isRight()) {
+ TitanOperationStatus status = findUser.right().value();
+ log.error("Cannot find user {} in the graph. status is {}", userId, status);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+
+ }
+ GraphVertex creatorVertex = findUser.left().value();
+ GraphVertex updaterVertex = creatorVertex;
+ String updaterId = toscaElement.getLastUpdaterUserId();
+ if (updaterId != null && !updaterId.equals(userId)) {
+ findUser = findUserVertex(updaterId);
+ if (findUser.isRight()) {
+ TitanOperationStatus status = findUser.right().value();
+ log.error("Cannot find user {} in the graph. status is {}", userId, status);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ } else {
+ updaterVertex = findUser.left().value();
+ }
+ }
+ Map<EdgePropertyEnum, Object> props = new HashMap<EdgePropertyEnum, Object>();
+ props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE));
+
+ TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props);
+ log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE);
+ if (TitanOperationStatus.OK != result) {
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
+ }
+ result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null);
+ log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ if (!result.equals(TitanOperationStatus.OK)) {
+ log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
+ }
+
+ toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId());
+ toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName());
+
+ result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null);
+ log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
+ if (!result.equals(TitanOperationStatus.OK)) {
+ log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR);
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(result);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
+ String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName();
+ String categoryName = nodeType.getCategories().get(0).getName();
+ Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName);
+
+ if (getCategoryVertex.isRight()) {
+ return getCategoryVertex.right().value();
+ }
+
+ GraphVertex subCategoryV = getCategoryVertex.left().value();
+
+ TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>());
+ if (createEdge != TitanOperationStatus.OK) {
+ log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) {
+ Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY);
+ if (category.isRight()) {
+ log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value());
+ return Either.right(category.right().value());
+ }
+ GraphVertex categoryV = category.left().value();
+
+ if (subcategoryName != null) {
+ Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName);
+ if (subCategory.isRight()) {
+ log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value());
+ return Either.right(subCategory.right().value());
+ }
+
+ GraphVertex subCategoryV = subCategory.left().value();
+ return Either.left(subCategoryV);
+ }
+ return Either.left(categoryV);
+ }
+
+ private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) {
+ Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts();
+ Either<GraphVertex, StorageOperationStatus> status;
+ if (artifacts != null) {
+ artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ a.setUniqueId(uniqueId);
+ });
+ status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts);
+ if (status.isRight()) {
+ return status.right().value();
+ }
+ }
+ Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts();
+ if (toscaArtifacts != null) {
+ toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ a.setUniqueId(uniqueId);
+ });
+ status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts);
+ if (status.isRight()) {
+ return status.right().value();
+ }
+ }
+ Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts();
+ if (deploymentArtifacts != null) {
+ deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> {
+ String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase());
+ a.setUniqueId(uniqueId);
+ });
+ status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts);
+ if (status.isRight()) {
+ return status.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) {
+ TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH);
+ if (status != TitanOperationStatus.OK) {
+ log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status);
+ return status;
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) {
+
+ StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement);
+ if (associateUsers != StorageOperationStatus.OK) {
+ return associateUsers;
+ }
+ StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement);
+ if (associateArtifacts != StorageOperationStatus.OK) {
+ return associateArtifacts;
+ }
+ StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources);
+ if (associateProperties != StorageOperationStatus.OK) {
+ return associateProperties;
+ }
+ StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement);
+ if (associateAdditionaInfo != StorageOperationStatus.OK) {
+ return associateAdditionaInfo;
+ }
+ if (needConnectToCatalog(toscaElement)) {
+ StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex);
+ if (associateToCatalog != StorageOperationStatus.OK) {
+ return associateToCatalog;
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private boolean needConnectToCatalog(ToscaElement toscaElement) {
+ Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT);
+ if (isAbstract != null && isAbstract) {
+ return false;
+ }
+ return toscaElement.isHighestVersion();
+ }
+
+ private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) {
+ Either<GraphVertex, TitanOperationStatus> catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT);
+ if (catalog.isRight()) {
+ log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value());
+ }
+ TitanOperationStatus createEdge = titanDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null);
+
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge);
+ }
+
+ protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) {
+ // Note : currently only one derived supported!!!!
+ Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES);
+ if (dataFromDerived.isRight()) {
+ return dataFromDerived.right().value();
+ }
+ Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value();
+
+ Map<String, PropertyDataDefinition> properties = nodeType.getProperties();
+
+ if (properties != null) {
+ properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> {
+ String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName());
+ p.setUniqueId(uid);
+ });
+
+ Either<Map<String, PropertyDataDefinition>, 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<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) {
+ Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation();
+ if (additionalInformation != null) {
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation);
+ if (assosiateElementToData.isRight()) {
+ return assosiateElementToData.right().value();
+ }
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, EdgeLabelEnum edge) {
+ Map<String, T> propertiesAll = new HashMap<>();
+
+ if (derivedResources != null && !derivedResources.isEmpty()) {
+ for (GraphVertex derived : derivedResources) {
+ Either<List<GraphVertex>, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson);
+ if (derivedProperties.isRight()) {
+ if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value()));
+ } else {
+ continue;
+ }
+ }
+ List<GraphVertex> propList = derivedProperties.left().value();
+ for (GraphVertex propV : propList) {
+ Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson();
+ if (propertiesFromDerived != null) {
+ propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId()));
+ propertiesAll.putAll(propertiesFromDerived);
+ }
+ }
+ }
+ }
+ return Either.left(propertiesAll);
+ }
+
+ protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS);
+ if (result.isLeft()) {
+ toscaElement.setArtifacts(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
+ if (result.isLeft()) {
+ toscaElement.setDeploymentArtifacts(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ if (result.isLeft()) {
+ toscaElement.setToscaArtifacts(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) {
+ Map<String, String> allVersion = new HashMap<>();
+
+ allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId());
+ ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<GraphVertex>();
+ Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ while (childResourceRes.isLeft()) {
+ GraphVertex child = childResourceRes.left().value();
+ allChildrenAndParants.add(child);
+ childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ }
+ TitanOperationStatus operationStatus = childResourceRes.right().value();
+
+ if (operationStatus != TitanOperationStatus.NOT_FOUND) {
+ return operationStatus;
+ } else {
+ Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ while (parentResourceRes.isLeft()) {
+ GraphVertex parent = parentResourceRes.left().value();
+ allChildrenAndParants.add(parent);
+ parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ }
+ operationStatus = parentResourceRes.right().value();
+ if (operationStatus != TitanOperationStatus.NOT_FOUND) {
+ return operationStatus;
+ } else {
+ allChildrenAndParants.stream().filter(vertex -> {
+ Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
+ return (isDeleted == null || isDeleted == false);
+ }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId()));
+
+ toscaElement.setAllVersions(allVersion);
+ return TitanOperationStatus.OK;
+ }
+ }
+ }
+
+ protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) {
+
+ Either<List<T>, StorageOperationStatus> result = null;
+
+ Map<GraphPropertyEnum, Object> props = null;
+
+ if (userId != null) {
+ props = new HashMap<>();
+ // for Designer retrieve specific user
+ props.put(GraphPropertyEnum.USERID, userId);
+ }
+ // in case of user id == null -> get all users by label
+ // for Tester and Admin retrieve all users
+ Either<List<GraphVertex>, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse);
+ if (usersByCriteria.isRight()) {
+ log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value()));
+ }
+ List<GraphVertex> users = usersByCriteria.left().value();
+
+ List<T> components = new ArrayList<>();
+ List<T> componentsPerUser;
+ for (GraphVertex userV : users) {
+
+ HashSet<String> ids = new HashSet<String>();
+ Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse);
+ if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value()));
+ }
+
+ // get all resource with current state
+ if (childrenVertecies.isLeft()) {
+ componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE);
+
+ if (componentsPerUser != null) {
+ for (T comp : componentsPerUser) {
+ ids.add(comp.getUniqueId());
+ components.add(comp);
+ }
+ }
+ }
+ if (lastStateStates != null && !lastStateStates.isEmpty()) {
+ // get all resource with last state
+ childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse);
+ if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value()));
+ }
+ if (childrenVertecies.isLeft()) {
+ boolean isFirst;
+ componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE);
+ if (componentsPerUser != null) {
+ for (T comp : componentsPerUser) {
+ isFirst = true;
+
+ if (ids.contains(comp.getUniqueId())) {
+ isFirst = false;
+ }
+ if (isFirst == true) {
+ components.add(comp);
+ }
+
+ }
+ }
+ }
+ }
+
+ } // whlile users
+ ;
+ result = Either.left(components);
+ return result;
+
+ }
+
+ private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) {
+ List<T> components = new ArrayList<>();
+ for (GraphVertex node : vertices) {
+
+ Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name());
+ while (edges.hasNext()) {
+ Edge edge = edges.next();
+ String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE);
+
+ LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr);
+ if (nodeState == null) {
+ log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId());
+ continue;
+ }
+ if (lifecycleStates != null && lifecycleStates.contains(nodeState)) {
+
+ Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED);
+ if (isDeleted != null && isDeleted) {
+ log.trace("Deleted element {}, discard", node.getUniqueId());
+ continue;
+ }
+
+ Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
+ if (isHighest) {
+
+ ComponentTypeEnum componentType = node.getType();
+ // get only latest versions
+
+ if (componentType == null) {
+ log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId());
+ continue;
+ }
+ if (neededType == componentType) {
+ switch (componentType) {
+ case SERVICE:
+ case PRODUCT:
+ handleNode(components, node, componentType);
+ break;
+ case RESOURCE:
+ Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT);
+ if (isAbtract == null || false == isAbtract) {
+ handleNode(components, node, componentType);
+ } // if not abstract
+ break;
+ default:
+ log.debug("not supported node type {}", componentType);
+ break;
+ }// case
+ } // needed type
+ }
+ } // if
+ } // while edges
+ } // while resources
+ return components;
+ }
+
+ protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) {
+
+ Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true));
+ if (component.isRight()) {
+ log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value());
+ } else {
+ components.add(component.left().value());
+ }
+ }
+
+ protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
+ Either<GraphVertex, TitanOperationStatus> getVertexRes = titanDao.getVertexById(componentUid);
+ if (getVertexRes.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value()));
+ }
+ return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter);
+ }
+
+ protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
+
+ log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
+
+ titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
+
+ T toscaElement = convertToComponent(vertexComponent);
+
+ TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+
+ status = setLastModifierFromGraph(vertexComponent, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ status = setCategoriesFromGraph(vertexComponent, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (!parametersFilter.isIgnoreAllVersions()) {
+ status = setAllVersions(vertexComponent, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (!parametersFilter.isIgnoreCapabilities()) {
+ status = setCapabilitiesFromGraph(vertexComponent, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ if (!parametersFilter.isIgnoreRequirements()) {
+ status = setRequirementsFromGraph(vertexComponent, toscaElement);
+ if (status != TitanOperationStatus.OK) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ }
+ log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId());
+ return Either.left(toscaElement);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) {
+ ToscaElement toscaElement = null;
+ VertexTypeEnum label = componentV.getLabel();
+ switch (label) {
+ case NODE_TYPE:
+ toscaElement = new NodeType();
+ break;
+ case TOPOLOGY_TEMPLATE:
+ toscaElement = new TopologyTemplate();
+ break;
+ default:
+ log.debug("Not supported tosca type {}", label);
+ break;
+ }
+
+ Map<String, Object> jsonMetada = componentV.getMetadataJson();
+ if (toscaElement != null) {
+ toscaElement.setMetadata(jsonMetada);
+ }
+ return (T) toscaElement;
+ }
+
+ protected TitanOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
+ Either<Vertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ if (childVertex.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value());
+ return childVertex.right().value();
+ }
+ Vertex categoryV = childVertex.left().value();
+ catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value());
+
+ return TitanOperationStatus.OK;
+ }
+
+ protected TitanOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) {
+
+ Either<Vertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ if (childVertex.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value());
+ return childVertex.right().value();
+ }
+ Vertex subCategoryV = childVertex.left().value();
+ catalogComponent.setSubCategoryNormalizedName((String) subCategoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value());
+ Either<Vertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
+ Vertex categoryV = parentVertex.left().value();
+ catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value());
+
+ return TitanOperationStatus.OK;
+ }
+
+ protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ List<CategoryDefinition> categories = new ArrayList<>();
+ SubCategoryDefinition subcategory;
+
+ Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ if (childVertex.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value());
+ return childVertex.right().value();
+ }
+ GraphVertex subCategoryV = childVertex.left().value();
+ Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
+ subcategory = new SubCategoryDefinition();
+ subcategory.setUniqueId(subCategoryV.getUniqueId());
+ subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
+ subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
+
+ Type listTypeSubcat = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat);
+ subcategory.setIcons(iconsfromJsonSubcat);
+
+ Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
+ if (parentVertex.isRight()) {
+ log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value());
+ return childVertex.right().value();
+ }
+ GraphVertex categoryV = parentVertex.left().value();
+ metadataProperties = categoryV.getMetadataProperties();
+
+ CategoryDefinition category = new CategoryDefinition();
+ category.setUniqueId(categoryV.getUniqueId());
+ category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
+ category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
+
+ Type listTypeCat = new TypeToken<List<String>>() {
+ }.getType();
+ List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat);
+ category.setIcons(iconsfromJsonCat);
+
+ category.addSubCategory(subcategory);
+ categories.add(category);
+ toscaElement.setCategories(categories);
+
+ return TitanOperationStatus.OK;
+ }
+
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) {
+ Either<T, StorageOperationStatus> result = null;
+
+ log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId()));
+ if (toscaElementToUpdate == null) {
+ log.error("Service object is null");
+ result = Either.right(StorageOperationStatus.BAD_REQUEST);
+ return result;
+ }
+
+ String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId();
+ if (modifierUserId == null || modifierUserId.isEmpty()) {
+ log.error("UserId is missing in the request.");
+ result = Either.right(StorageOperationStatus.BAD_REQUEST);
+ return result;
+ }
+ Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(modifierUserId);
+
+ if (findUser.isRight()) {
+ TitanOperationStatus status = findUser.right().value();
+ log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status);
+ return result;
+ }
+
+ GraphVertex modifierV = findUser.left().value();
+ // UserData modifierUserData = findUser.left().value();
+ String toscaElementId = toscaElementToUpdate.getUniqueId();
+
+ Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse);
+ if (parentVertex.isRight()) {
+ log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value()));
+ }
+ GraphVertex userV = parentVertex.left().value();
+ String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID);
+
+ String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
+
+ if (currentModifier.equals(modifierUserId)) {
+ log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
+ } else {
+ log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
+ StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV);
+ log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
+ if (status != StorageOperationStatus.OK) {
+ result = Either.right(status);
+ return result;
+ }
+ }
+
+ final long currentTimeMillis = System.currentTimeMillis();
+ log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis);
+ elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis);
+
+ StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV);
+ if (checkCategories != StorageOperationStatus.OK) {
+ result = Either.right(checkCategories);
+ return result;
+ }
+
+ // update all data on vertex
+ fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata);
+
+ Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(elementV);
+
+ if (updateElement.isRight()) {
+ log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
+ return result;
+ }
+ GraphVertex updateElementV = updateElement.left().value();
+
+ // DE230195 in case resource name changed update TOSCA artifacts
+ // file names accordingly
+ String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME);
+ if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS);
+ if (resultToscaArt.isRight()) {
+ log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value()));
+ }
+
+ Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value();
+ if (toscaArtifacts != null) {
+ for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) {
+ generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue());
+ }
+ // TODO call to new Artifact operation in order to update list of artifacts
+
+ }
+ // US833308 VLI in service - specific network_role property value logic
+ if (ComponentTypeEnum.SERVICE == toscaElementToUpdate.getComponentType()) {
+ // update method logs success/error and returns boolean (true if nothing fails)
+ // TODO!!!!
+ // updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName);
+ }
+ }
+
+ if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) {
+ StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV);
+ if (resultDerived != StorageOperationStatus.OK) {
+ log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived);
+ return Either.right(resultDerived);
+ }
+ }
+
+ Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult);
+ if (updatedResource.isRight()) {
+ log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value());
+ result = Either.right(StorageOperationStatus.BAD_REQUEST);
+ return result;
+ }
+
+ T updatedResourceValue = updatedResource.left().value();
+ result = Either.left(updatedResourceValue);
+
+ return result;
+ }
+
+ protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) {
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN));
+ }
+
+ protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) {
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT));
+ }
+
+ private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) {
+ Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
+ .findAny().get().getValue();
+ artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
+ }
+
+ protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) {
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories();
+ CategoryDefinition newCategory = newCategoryList.get(0);
+
+ Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse);
+ if (childVertex.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value());
+ }
+ GraphVertex subCategoryV = childVertex.left().value();
+ Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties();
+ String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
+
+ Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse);
+ if (parentVertex.isRight()) {
+ log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value());
+ }
+ GraphVertex categoryV = parentVertex.left().value();
+ metadataProperties = categoryV.getMetadataProperties();
+ String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME);
+
+ boolean categoryWasChanged = false;
+
+ String newCategoryName = newCategory.getName();
+ SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
+ String newSubCategoryName = newSubcategory.getName();
+ if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) {
+ // the category was changed
+ categoryWasChanged = true;
+ } else {
+ // the sub-category was changed
+ if (newSubCategoryName != null && false == newSubCategoryName.equals(subCategoryNameCurrent)) {
+ log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory);
+ categoryWasChanged = true;
+ }
+ }
+ if (categoryWasChanged) {
+ Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName);
+
+ if (getCategoryVertex.isRight()) {
+ return getCategoryVertex.right().value();
+ }
+ GraphVertex newCategoryV = getCategoryVertex.left().value();
+ status = moveCategoryEdge(elementV, newCategoryV);
+ log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status);
+ }
+ return status;
+ }
+
+ public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) {
+ Either<List<GraphVertex>, TitanOperationStatus> listOfComponents;
+ if (isHighestVersions) {
+ listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
+ } else {
+ listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
+ }
+
+ if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value()));
+ }
+ List<T> result = new ArrayList<>();
+ if (listOfComponents.isLeft()) {
+ List<GraphVertex> highestAndAllCertified = listOfComponents.left().value();
+ if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) {
+ for (GraphVertex vertexComponent : highestAndAllCertified) {
+ Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true));
+ if (component.isRight()) {
+ log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
+ return Either.right(component.right().value());
+ } else {
+ result.add(component.left().value());
+ }
+ }
+ }
+ }
+ return Either.left(result);
+ }
+
+ public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData() {
+ List<CatalogComponent> results = new ArrayList<>();
+ StopWatch stopWatch = new StopWatch();
+ stopWatch.start();
+
+ Either<Iterator<Vertex>, TitanOperationStatus> verticesEither = titanDao.getCatalogVerticies();
+ if (verticesEither.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(verticesEither.right().value()));
+ }
+ Iterator<Vertex> vertices = verticesEither.left().value();
+ while (vertices.hasNext()) {
+ Vertex vertex = vertices.next();
+ VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty());
+ String json = (String) property.value();
+
+ CatalogComponent catalogComponent = new CatalogComponent();
+ Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
+
+ catalogComponent.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation())));
+ catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation()));
+ catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation()));
+ catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation()));
+ catalogComponent.setUniqueId((String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation()));
+ catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation()));
+ catalogComponent.setLastUpdateDate((Long) metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation()));
+ catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation()));
+ Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation());
+ if (resourceType != null) {
+ catalogComponent.setResourceType((String) resourceType);
+ }
+
+ if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
+ setServiceCategoryFromGraphV(vertex, catalogComponent);
+
+ } else {
+ setResourceCategoryFromGraphV(vertex, catalogComponent);
+ }
+ results.add(catalogComponent);
+
+ }
+ stopWatch.stop();
+ String timeToFetchElements = stopWatch.prettyPrint();
+ log.info("time to fetch all catalog elements: {}", timeToFetchElements);
+ return Either.left(results);
+ }
+
+ public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ if (componentType == ComponentTypeEnum.RESOURCE) {
+ propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
+ }
+ propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
+ }
+
+ // highest + (certified && !highest)
+ public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
+ long startFetchAllStates = System.currentTimeMillis();
+ Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata);
+
+ Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
+ propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ if (componentType == ComponentTypeEnum.RESOURCE) {
+ propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
+ }
+
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata);
+ if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(certifiedNotHighestNodes.right().value());
+ }
+
+ long endFetchAllStates = System.currentTimeMillis();
+
+ List<GraphVertex> allNodes = new ArrayList<>();
+
+ if (certifiedNotHighestNodes.isLeft()) {
+ allNodes.addAll(certifiedNotHighestNodes.left().value());
+ }
+ if (highestNodes.isLeft()) {
+ allNodes.addAll(highestNodes.left().value());
+ }
+
+ log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
+ return Either.left(allNodes);
+ }
+
+ protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
+
+ // get all components marked for delete
+ Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
+ props.put(GraphPropertyEnum.IS_DELETED, true);
+ props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ Either<List<GraphVertex>, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse);
+
+ if (componentsToDelete.isRight()) {
+ TitanOperationStatus error = componentsToDelete.right().value();
+ if (error.equals(TitanOperationStatus.NOT_FOUND)) {
+ log.trace("no components to delete");
+ return Either.left(new ArrayList<>());
+ } else {
+ log.info("failed to find components to delete. error : {}", error.name());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
+ }
+ }
+ return Either.left(componentsToDelete.left().value());
+ }
+
+ protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) {
+ Either<Map<String, AdditionalInfoParameterDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION);
+ if (result.isLeft()) {
+ toscaElement.setAdditionalInformation(result.left().value());
+ } else {
+ if (result.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return result.right().value();
+ }
+ }
+ return TitanOperationStatus.OK;
+ }
+
+ // --------------------------------------------
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView);
+
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView);
+
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex);
+
+ public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement);
+
+ protected abstract <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement);
+
+ protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement);
+
+ protected abstract <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement);
+
+ protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV);
+
+ protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV);
- public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);
+ public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java
index 15fb63f14c..647234d892 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
@@ -20,21 +20,7 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.BiPredicate;
-import java.util.stream.Collectors;
-
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
@@ -45,43 +31,14 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.*;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RelationshipInfo;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
@@ -96,7 +53,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.function.BiPredicate;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("tosca-operation-facade")
public class ToscaOperationFacade {
@@ -128,7 +88,7 @@ public class ToscaOperationFacade {
public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
ComponentParametersView filters = new ComponentParametersView();
filters.setIgnoreCapabiltyProperties(false);
-
+ filters.setIgnoreForwardingPath(false);
return getToscaElement(componentId, filters);
}
@@ -202,7 +162,7 @@ public class ToscaOperationFacade {
String componentId = componentV.getUniqueId();
if (toscaOperation != null) {
log.debug("Need to fetch tosca element for id {}", componentId);
- toscaElement = toscaOperation.getToscaElement(componentV, filters);
+ toscaElement = toscaOperation.getToscaElement(componentV, filters);
} else {
log.debug("not supported tosca type {} for id {}", label, componentId);
toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
@@ -328,7 +288,10 @@ public class ToscaOperationFacade {
}
public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
- return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll);
+ ComponentParametersView fetchAllFilter = new ComponentParametersView();
+ fetchAllFilter.setIgnoreForwardingPath(true);
+ fetchAllFilter.setIgnoreCapabiltyProperties(false);
+ return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
}
public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
@@ -448,7 +411,7 @@ public class ToscaOperationFacade {
public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate);
}
-
+
public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
if (status.isRight()) {
@@ -495,7 +458,7 @@ public class ToscaOperationFacade {
*
* @param newComponent
* @param oldComponent
- * @return
+ * @return vendor
*/
public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) {
@@ -504,8 +467,6 @@ public class ToscaOperationFacade {
newComponent.setArtifacts(oldComponent.getArtifacts());
newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
newComponent.setGroups(oldComponent.getGroups());
- List<InputDefinition> newInputs = getNewInputsByResourceType(oldComponent);
- newComponent.setInputs(newInputs);
newComponent.setLastUpdateDate(null);
newComponent.setHighestVersion(true);
@@ -584,6 +545,10 @@ public class ToscaOperationFacade {
}
private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) {
+ return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
Either<T, StorageOperationStatus> result;
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
@@ -613,7 +578,7 @@ public class ToscaOperationFacade {
highestResource = vertex;
}
}
- return getToscaElementByOperation(highestResource);
+ return getToscaElementByOperation(highestResource, filter);
}
// endregion
@@ -688,6 +653,9 @@ public class ToscaOperationFacade {
}
return getToscaElementByOperation(getResourceRes.left().value().get(0));
}
+ public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogComponents() {
+ return topologyTemplateOperation.getElementCatalogData();
+ }
// endregion
public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
@@ -804,7 +772,7 @@ public class ToscaOperationFacade {
if (StringUtils.isEmpty(componentInstance.getIcon())) {
componentInstance.setIcon(origComponent.getIcon());
}
- String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? PROXY_SUFFIX : origComponent.getName();
+ String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName();
String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter);
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user);
@@ -1413,8 +1381,6 @@ public class ToscaOperationFacade {
// exclude props
states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- states.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- states.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
hasNotProps.put(GraphPropertyEnum.STATE, states);
hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
return fetchServicesByCriteria(services, hasProps, hasNotProps);
@@ -1611,6 +1577,7 @@ public class ToscaOperationFacade {
break;
case "service":
case "pnf":
+ case "cr":
hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
break;
case "vl":
@@ -1685,13 +1652,37 @@ public class ToscaOperationFacade {
}
- public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
+ private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ if (additionalPropertiesToMatch != null) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
return componentListByUuid;
}
+ public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
+ propertiesToMatch.put(GraphPropertyEnum.VERSION, version);
+
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+ Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (vertexEither.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+ if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) {
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+
+ return getToscaElementByOperation(vertexList.get(0));
+ }
+
public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
@@ -1743,9 +1734,19 @@ public class ToscaOperationFacade {
return Either.left(latestComponents);
}
+ public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ return getLatestComponentByUuid(serviceUuid, propertiesToMatch);
+ }
+
public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
+ return getLatestComponentByUuid(componentUuid, null);
+ }
+
+ public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) {
- Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
+ Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch);
if (latestVersionListEither.isRight()) {
return Either.right(latestVersionListEither.right().value());
@@ -1927,7 +1928,9 @@ public class ToscaOperationFacade {
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
+ Map<GraphPropertyEnum, Object> propsHasNotToMatch = new HashMap<>();
+ propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+ Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
if (resourcesByTypeEither.isRight()) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
@@ -2311,12 +2314,12 @@ public class ToscaOperationFacade {
return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
}
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
- return groupsOperation.updateGroups(component, componentType, updatedGroups);
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) {
+ return groupsOperation.updateGroups(component, updatedGroups);
}
public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
- return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
+ return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances);
}
public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
@@ -2368,6 +2371,17 @@ public class ToscaOperationFacade {
return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property);
}
+ public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) {
+ return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId)
+ .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps))
+ .orElse(StorageOperationStatus.NOT_FOUND);
+ }
+
+ public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) {
+ Map<String, MapCapabiltyProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent);
+ return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap);
+ }
+
public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) {
StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES);
if (status == StorageOperationStatus.OK) {
@@ -2402,15 +2416,94 @@ public class ToscaOperationFacade {
return Either.left(clonedResource);
}
/**
- * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type
+ * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
* @param componentId
* @param instanceId
* @param capabilityName
* @param capabilityType
+ * @param ownerId
* @return
*/
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType) {
- return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType);
+ public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) {
+ return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId);
+ }
+
+ private Map<String, MapCapabiltyProperty> convertComponentCapabilitiesProperties(Component currComponent) {
+ return currComponent.getComponentInstances()
+ .stream()
+ .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId,
+ ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), true)));
+ }
+
+ private Optional<MapCapabiltyProperty> convertComponentInstanceProperties(Component component, String instanceId) {
+ return component.fetchInstanceById(instanceId)
+ .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(),instanceId));
}
+ public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) {
+ Either<PolicyDefinition, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getVertexEither;
+ getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ if (getVertexEither.isRight()) {
+ log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ } else {
+ if(getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE){
+ log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel());
+ result = Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ }
+ if(result == null){
+ StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter);
+ if(status != StorageOperationStatus.OK){
+ return Either.right(status);
+ }
+ }
+ if(result == null){
+ result = Either.left(policyDefinition);
+ }
+ return result;
+ }
+
+ public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) {
+ Either<PolicyDefinition, StorageOperationStatus> result = null;
+ Either<GraphVertex, TitanOperationStatus> getVertexEither;
+ getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ if(result == null){
+ StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition);
+ if(status != StorageOperationStatus.OK){
+ return Either.right(status);
+ }
+ }
+ if(result == null){
+ result = Either.left(policyDefinition);
+ }
+ return result;
+ }
+
+ public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) {
+ log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId);
+ return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse)
+ .right()
+ .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
+ .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition),
+ err -> err);
+ }
+
+ public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) {
+ StorageOperationStatus status = null;
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value());
+ status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
+ }
+ if(status == null){
+ status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId);
+ }
+ return status;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java
new file mode 100644
index 0000000000..8c9d025a7b
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java
@@ -0,0 +1,54 @@
+package org.openecomp.sdc.be.model.jsontitan.utils;
+
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
+import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
+import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Created by yavivi on 12/02/2018.
+ */
+@Component
+public class IdMapper {
+
+ private static final Logger log = LoggerFactory.getLogger(ExternalReferencesOperation.class);
+
+ public String mapComponentNameToUniqueId(String componentInstanceName, GraphVertex serviceVertex) {
+ return map(componentInstanceName, serviceVertex, true);
+ }
+
+ public String mapUniqueIdToComponentNameTo(String compUniqueId, GraphVertex serviceVertex) {
+ return map(compUniqueId, serviceVertex, false);
+ }
+
+ private String map(String componentUniqueIdOrName, GraphVertex serviceVertex, boolean fromCompName) {
+ String result = null;
+ try {
+ Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) serviceVertex.getJson();
+ CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
+
+ Optional<ComponentInstanceDataDefinition> componentInstanceDataDefinitionOptional = null;
+ if (fromCompName) {
+ componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream().filter(c -> c.getNormalizedName().equals(componentUniqueIdOrName)).findAny();
+ result = componentInstanceDataDefinitionOptional.get().getUniqueId();
+ log.debug("Compponent Instance Unique Id = {}", result);
+ } else {
+ componentInstanceDataDefinitionOptional = compositionDataDefinition.getComponentInstances().values().stream().filter(c -> c.getUniqueId().equals(componentUniqueIdOrName)).findAny();
+ result = componentInstanceDataDefinitionOptional.get().getNormalizedName();
+ log.debug("Compponent Instance Normalized Name = {}", result);
+ }
+
+ } catch (Exception e) {
+ log.error("Failed to map UUID or Normalized name of " + componentUniqueIdOrName, e);
+ }
+ return result;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java
index e89f63b12f..71f0b77902 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
@@ -40,6 +40,7 @@ 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.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
@@ -51,11 +52,13 @@ import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -70,6 +73,7 @@ import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
+import org.openecomp.sdc.be.model.PolicyDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RelationshipInfo;
@@ -82,6 +86,7 @@ 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.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.ProductMetadataData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
@@ -125,9 +130,10 @@ public class ModelConverter {
}
public static boolean isAtomicComponent(ResourceTypeEnum resourceType) {
- if (resourceType == null || resourceType == ResourceTypeEnum.VF || resourceType == ResourceTypeEnum.PNF || resourceType == ResourceTypeEnum.CVFC)
+ if (resourceType == null) {
return false;
- return true;
+ }
+ return resourceType.isAtomicType();
}
// **********************************************************
@@ -165,6 +171,16 @@ public class ModelConverter {
convertComponentInstances(topologyTemplate, service);
convertInputs(topologyTemplate, service);
+
+ convertPolicies(topologyTemplate, service);
+
+ convertGroups(topologyTemplate, service);
+
+ convertPolicies(topologyTemplate, service);
+
+ convertGroups(topologyTemplate, service);
+
+ convertPolicies(topologyTemplate, service);
convertRelations(topologyTemplate, service);
@@ -172,6 +188,8 @@ public class ModelConverter {
convertServiceApiArtifacts(topologyTemplate, service);
+ convertServicePaths(topologyTemplate, service);
+
return service;
}
@@ -210,6 +228,7 @@ public class ModelConverter {
convertRelations(topologyTemplate, resource);
convertInputs(topologyTemplate, resource);
convertGroups(topologyTemplate, resource);
+ convertPolicies(topologyTemplate, resource);
}
convertArtifacts(toscaElement, resource);
convertAdditionalInformation(toscaElement, resource);
@@ -505,19 +524,19 @@ public class ModelConverter {
resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE));
// field isn't mandatory , but shouldn't be null(should be an empty string instead)
if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){
- resource.setResourceVendorModelNumber(((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)));
+ resource.setResourceVendorModelNumber((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER));
} else {
resource.setResourceVendorModelNumber("");
}
} else if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
Service service = (Service) component;
if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){
- service.setServiceType(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)));
+ service.setServiceType((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE));
} else {
service.setServiceType("");
}
if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){
- service.setServiceRole(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)));
+ service.setServiceRole((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE));
} else {
service.setServiceRole("");
}
@@ -633,6 +652,17 @@ public class ModelConverter {
}
service.setServiceApiArtifacts(copy);
}
+ private static void convertServicePaths(TopologyTemplate topologyTemplate, Service service) {
+ Map<String, ForwardingPathDataDefinition> servicePaths = topologyTemplate.getForwardingPaths();
+ Map<String, ForwardingPathDataDefinition> copy;
+ if (servicePaths != null) {
+ copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue())));
+
+ } else {
+ copy = new HashMap<>();
+ }
+ service.setForwardingPaths(copy);
+ }
private static void convertArtifacts(Component component, ToscaElement toscaElement) {
Map<String, ArtifactDefinition> artifacts = component.getArtifacts();
@@ -801,16 +831,33 @@ public class ModelConverter {
}
component.setGroups(groupDefinitions);
}
+
+ private static void convertPolicies(TopologyTemplate toscaElement, Component component) {
+ Map<String, PolicyDataDefinition> policies = toscaElement.getPolicies();
+ Map<String, PolicyDefinition> policyDefinitions = null;
+ if (MapUtils.isNotEmpty(policies)) {
+ policyDefinitions = policies.values().stream().map(p -> new PolicyDefinition(p)).collect(Collectors.toMap(p->p.getUniqueId(), p->p));
+ }
+ component.setPolicies(policyDefinitions);
+ }
private static void convertGroups(Component component, TopologyTemplate toscaElement) {
List<GroupDefinition> groupDefinitions = component.getGroups();
Map<String, GroupDataDefinition> groups = new HashMap<>();
if (groupDefinitions != null && groups.isEmpty()) {
- groups = groupDefinitions.stream().collect((Collectors.toMap(pr -> pr.getName(), pr -> new GroupDataDefinition(pr))));
+ groups = groupDefinitions.stream().collect(Collectors.toMap(pr -> pr.getName(), pr -> new GroupDataDefinition(pr)));
}
toscaElement.setGroups(groups);
-
+ }
+
+ private static void convertPolicies(Component component, TopologyTemplate toscaElement) {
+ Map<String, PolicyDefinition> policyDefinitions = component.getPolicies();
+ Map<String, PolicyDataDefinition> policies = new HashMap<>();
+ if (MapUtils.isNotEmpty(policyDefinitions)) {
+ policies = policyDefinitions.values().stream().collect((Collectors.toMap(p -> p.getUniqueId(), p -> new PolicyDataDefinition(p))));
+ }
+ toscaElement.setPolicies(policies);
}
private static void convertRequirements(NodeType toscaElement, Component component) {
@@ -863,6 +910,7 @@ public class ModelConverter {
convertInputs(component, topologyTemplate);
convertCapabilities(component, topologyTemplate);
convertGroups(component, topologyTemplate);
+ convertPolicies(component, topologyTemplate);
convertRequirements(component, topologyTemplate);
convertRelationsToComposition(component, topologyTemplate);
@@ -872,6 +920,15 @@ public class ModelConverter {
private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) {
convertServiceMetaData(service, topologyTemplate);
convertServiceApiArtifacts(service, topologyTemplate);
+ convertServicePaths(service,topologyTemplate);
+ }
+
+ private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) {
+ Map<String, ForwardingPathDataDefinition> servicePaths = service.getForwardingPaths();
+ if (servicePaths != null && !servicePaths.isEmpty()) {
+ Map<String, ForwardingPathDataDefinition> copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue())));
+ topologyTemplate.setForwardingPaths(copy);
+ }
}
private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java
new file mode 100644
index 0000000000..de52101ec1
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java
@@ -0,0 +1,17 @@
+package org.openecomp.sdc.be.model.operations;
+
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+public class StorageException extends RuntimeException{
+
+ private final StorageOperationStatus storageOperationStatus;
+
+ public StorageException(StorageOperationStatus storageOperationStatus) {
+ super();
+ this.storageOperationStatus = storageOperationStatus;
+ }
+
+ public StorageOperationStatus getStorageOperationStatus() {
+ return storageOperationStatus;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java
new file mode 100644
index 0000000000..0dc03ad363
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/DerivedFromOperation.java
@@ -0,0 +1,36 @@
+package org.openecomp.sdc.be.model.operations.api;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public interface DerivedFromOperation {
+
+ /**
+ *
+ * @param parentUniqueId the unique id of the object which is the parent of the derived from object
+ * @param derivedFromUniqueId the unique id of the derived from object
+ * @param nodeType the type of the derived from and its parent objects
+ * @return the status of the operation
+ */
+ Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType);
+
+ /**
+ *
+ * @param uniqueId the id of the entity of which to fetch its derived from object
+ * @param nodeType the type of the derived from object
+ * @param clazz the class which represent the derived from object
+ * @return the derived from object or error status of operation failed
+ */
+ <T extends GraphNode> Either<T, StorageOperationStatus> getDerivedFromChild(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz);
+
+ /**
+ *
+ * @param uniqueId the id of the entity of which to remove its derived from object
+ * @param derivedFromUniqueId the unique id of the derived from object
+ * @param nodeType the type of the derived from and its parent objects
+ * @return the status of the remove operation. if no derived from relation exists the operation is successful.
+ */
+ StorageOperationStatus removeDerivedFromRelation(String uniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType);
+}
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 90e01c3980..d4e5939173 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
@@ -20,12 +20,26 @@
package org.openecomp.sdc.be.model.operations.api;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+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.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.RelationshipInfo;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.AttributeValueData;
+import org.openecomp.sdc.be.resources.data.CapabilityData;
import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
+import org.openecomp.sdc.be.resources.data.RequirementData;
+import org.openecomp.sdc.exception.ResponseFormat;
import fj.data.Either;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
index 87a0dccfab..0fe50ff17a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java
@@ -35,6 +35,10 @@ public interface IGroupTypeOperation {
public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition);
public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction);
+
+ public Either<GroupTypeDefinition, StorageOperationStatus> upgradeGroupType(GroupTypeDefinition groupTypeDefinitionNew, GroupTypeDefinition groupTypeDefinitionOld);
+
+ public Either<GroupTypeDefinition, StorageOperationStatus> upgradeGroupType(GroupTypeDefinition groupTypeDefinitionNew, GroupTypeDefinition groupTypeDefinitionOld, boolean inTransaction);
/**
* @param uniqueId
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
index d25d11331d..526cbd282d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,18 +20,20 @@
package org.openecomp.sdc.be.model.operations.api;
+import fj.data.Either;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import fj.data.Either;
+import java.util.List;
+import java.util.Set;
public interface IPolicyTypeOperation {
- Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String policyTypeName);
+ Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String policyTypeName);
- Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType);
+ Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType);
- Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction);
+ Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType);
- Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType, boolean inTransaction);
+ Either<List<PolicyTypeDefinition>, StorageOperationStatus> getAllPolicyTypes(Set<String> excludedPolicyTypes);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
index 3dd49f1aee..d1a51677fe 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
@@ -20,15 +20,14 @@
package org.openecomp.sdc.be.model.operations.api;
-import java.util.Map;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.PropertyDefinition;
-import fj.data.Either;
+import java.util.Map;
public interface IPropertyOperation {
@@ -41,6 +40,14 @@ public interface IPropertyOperation {
*/
public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
+ /**
+ * same as deleteAllPropertiesAssociatedToNode but returns empty map if node has no properties
+ * @param nodeType
+ * @param uniqueId
+ * @return
+ */
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> deletePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
+
public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
public boolean isPropertyTypeValid(IComplexDefaultValue propertyDefinition);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
index b9a67e5dc6..24e4b48793 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java
@@ -116,7 +116,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (updateNode.isRight()) {
TitanOperationStatus status = updateNode.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "UpdateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
return Either.right(status);
}
@@ -168,7 +167,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (updateNode.isRight()) {
TitanOperationStatus status = updateNode.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status));
return Either.right(status);
}
@@ -213,7 +211,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (updateNode.isRight()) {
TitanOperationStatus status = updateNode.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "DeleteAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
return Either.right(status);
}
@@ -266,7 +263,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
Either<AdditionalInfoParameterData, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData, AdditionalInfoParameterData.class);
if (createNode.isRight()) {
TitanOperationStatus status = createNode.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, "AddAdditionalInformationNode", "additional information to " + nodeType.getName() + " " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status));
return Either.right(status);
}
@@ -294,7 +290,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
Either<TitanVertex, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData);
if (createNode.isRight()) {
TitanOperationStatus status = createNode.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, "AddAdditionalInformationNode", "additional information to " + nodeType.getName() + " " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status));
return Either.right(status);
}
@@ -498,7 +493,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (either.isRight()) {
TitanOperationStatus status = either.right().value();
log.debug("Failed to add additional information property {} to component {}. Status is {}", key, resourceId, status);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
} else {
@@ -654,7 +648,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (updateNode.isRight()) {
TitanOperationStatus status = updateNode.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedRetrieveNodeError, "GetAdditionnalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
}
return Either.right(status);
@@ -682,7 +675,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (getResult.isRight()) {
TitanOperationStatus status = getResult.right().value();
if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedRetrieveNodeError, "GetAdditionnalInformationParameters", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status));
}
return Either.right(status);
@@ -789,7 +781,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
if (status == TitanOperationStatus.NOT_FOUND) {
return Either.right(StorageOperationStatus.OK);
} else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, "DeleteAdditionalInformationNode", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
@@ -802,7 +793,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe
Either<AdditionalInfoParameterData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(parameterData, AdditionalInfoParameterData.class);
if (deleteNodeRes.isRight()) {
TitanOperationStatus status = getResult.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, "DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status));
BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status));
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
return result;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
index 9ef116d0c9..10cd30cbe5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
@@ -165,8 +165,6 @@ public class ArtifactOperation implements IArtifactOperation {
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, "Failed to add artifact " + artifactData.getArtifactDataDefinition().getArtifactName() + " to graph. status is " + operationStatus,
- artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus);
}
@@ -229,8 +227,6 @@ public class ArtifactOperation implements IArtifactOperation {
if (createNodeResult.isRight()) {
TitanOperationStatus operationStatus = createNodeResult.right().value();
log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, "Failed to add artifact " + artifactData.getArtifactDataDefinition().getArtifactName() + " to graph. status is " + operationStatus,
- artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus));
}
@@ -309,8 +305,6 @@ public class ArtifactOperation implements IArtifactOperation {
titanGenericDao.rollback();
}
log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value());
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId,
- String.valueOf(status.right().value()));
BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value()));
return Either.right(status.right().value());
} else {
@@ -335,7 +329,6 @@ public class ArtifactOperation implements IArtifactOperation {
}
log.debug("Failed to delete artifact {} of resource {}", artifactId, id);
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, "Failed to delete artifact " + artifactId + " of resource " + id, artifactId, String.valueOf(status.right().value()));
BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value()));
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
} else {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
index 203135b31e..9b31c71787 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
@@ -32,6 +32,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
@@ -253,6 +254,21 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
}
}
}
+
+
+ public Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeByType(String capabilityType) {
+ Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityType, CapabilityTypeData.class);
+
+ if (capabilityTypesRes.isRight()) {
+ TitanOperationStatus status = capabilityTypesRes.right().value();
+ log.debug("Capability type {} cannot be found in graph. status is {}", capabilityType, status);
+
+ return Either.right(status);
+ }
+
+ CapabilityTypeData ctData = capabilityTypesRes.left().value();
+ return Either.left(ctData);
+ }
/**
* Build Capability type object from graph by unique id
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java
index 88edb1fd9e..e81264ab59 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java
@@ -25,9 +25,9 @@ import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Map;
+import java.util.Map.Entry;
import javax.annotation.PostConstruct;
-
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -38,6 +38,7 @@ 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;
import fj.data.Either;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java
new file mode 100644
index 0000000000..fc78ada054
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java
@@ -0,0 +1,67 @@
+package org.openecomp.sdc.be.model.operations.impl;
+
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.Pair;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+@Component
+public class DefaultDerivedFromOperation implements DerivedFromOperation {
+
+ private static final Logger log = LoggerFactory.getLogger(DefaultDerivedFromOperation.class);
+ private TitanGenericDao titanGenericDao;
+
+ public DefaultDerivedFromOperation(TitanGenericDao titanGenericDao) {
+ this.titanGenericDao = titanGenericDao;
+ }
+
+ @Override
+ public Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) {
+ UniqueIdData from = new UniqueIdData(NodeTypeEnum.PolicyType, parentUniqueId);
+ UniqueIdData to = new UniqueIdData(NodeTypeEnum.PolicyType, derivedFromUniqueId);
+ return titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null)
+ .right()
+ .map(DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ @Override
+ public <T extends GraphNode> Either<T, StorageOperationStatus> getDerivedFromChild(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz) {
+ log.debug("#getDerivedFromChild - fetching derived from entity for node type {} with id {}", nodeType, uniqueId);
+ return titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz)
+ .bimap(Pair::getKey,
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ @Override
+ public StorageOperationStatus removeDerivedFromRelation(String uniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) {
+ UniqueIdData from = new UniqueIdData(NodeTypeEnum.PolicyType, uniqueId);
+ UniqueIdData to = new UniqueIdData(NodeTypeEnum.PolicyType, derivedFromUniqueId);
+ return isDerivedFromExists(from, to)
+ .either(isRelationExist -> isRelationExist ? deleteDerivedFrom(from, to) : StorageOperationStatus.OK,
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+
+
+ }
+
+ private StorageOperationStatus deleteDerivedFrom(UniqueIdData from, UniqueIdData to) {
+ return titanGenericDao.deleteRelation(from, to, GraphEdgeLabels.DERIVED_FROM)
+ .either(deletedRelation -> StorageOperationStatus.OK,
+ DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private Either<Boolean, TitanOperationStatus> isDerivedFromExists(UniqueIdData from, UniqueIdData to) {
+ return titanGenericDao.isRelationExist(from, to, GraphEdgeLabels.DERIVED_FROM);
+ }
+
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
index 413ce4c2fa..e9236fc9af 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,15 +20,15 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import com.google.common.base.Strings;
+import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
+import fj.data.Either;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
@@ -38,318 +38,450 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.StorageException;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
import org.openecomp.sdc.be.resources.data.GroupTypeData;
import org.openecomp.sdc.be.resources.data.PropertyData;
+import org.openecomp.sdc.be.resources.data.UniqueIdData;
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 javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate;
@Component("group-type-operation")
public class GroupTypeOperation extends AbstractOperation implements IGroupTypeOperation {
+ @Resource
+ private CapabilityTypeOperation capabilityTypeOperation;
+
+ private static final Logger log = LoggerFactory.getLogger(GroupTypeOperation.class);
- String CREATE_FLOW_CONTEXT = "CreateGroupType";
- String GET_FLOW_CONTEXT = "GetGroupType";
+ private static final String CREATE_FLOW_CONTEXT = "CreateGroupType";
+ private static final String GET_FLOW_CONTEXT = "GetGroupType";
- private PropertyOperation propertyOperation;
-
- private TitanGenericDao titanGenericDao;
+ private PropertyOperation propertyOperation;
- public GroupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation")PropertyOperation propertyOperation) {
- super();
- this.propertyOperation = propertyOperation;
- this.titanGenericDao = titanGenericDao;
- }
+ private TitanGenericDao titanGenericDao;
- private static Logger log = LoggerFactory.getLogger(GroupTypeOperation.class.getName());
+ public GroupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation") PropertyOperation propertyOperation) {
+ super();
+ this.propertyOperation = propertyOperation;
+ this.titanGenericDao = titanGenericDao;
+ }
- /**
- * FOR TEST ONLY
- *
- * @param titanGenericDao
- */
- public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
- }
+ /**
+ * FOR TEST ONLY
+ *
+ * @param titanGenericDao
+ */
+ public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
+ this.titanGenericDao = titanGenericDao;
+ }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition) {
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition) {
- return addGroupType(groupTypeDefinition, false);
- }
+ return addGroupType(groupTypeDefinition, false);
+ }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction) {
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction) {
- Either<GroupTypeDefinition, StorageOperationStatus> result = null;
+ Either<GroupTypeDefinition, StorageOperationStatus> result = null;
- try {
+ try {
- Either<GroupTypeData, TitanOperationStatus> eitherStatus = addGroupTypeToGraph(groupTypeDefinition);
+ Either<GroupTypeData, TitanOperationStatus> eitherStatus = addGroupTypeToGraph(groupTypeDefinition);
- if (eitherStatus.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
+ if (eitherStatus.isRight()) {
+ BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
- } else {
- GroupTypeData groupTypeData = eitherStatus.left().value();
+ } else {
+ GroupTypeData groupTypeData = eitherStatus.left().value();
- String uniqueId = groupTypeData.getUniqueId();
- Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = this.getGroupType(uniqueId, true);
+ String uniqueId = groupTypeData.getUniqueId();
+ Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = this.getGroupType(uniqueId, true);
- if (groupTypeRes.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
- }
+ if (groupTypeRes.isRight()) {
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name());
+ } else {
+ List<CapabilityTypeDefinition> groupCapTypes = groupTypeDefinition.getCapabilityTypes();
+ if (!CollectionUtils.isEmpty(groupCapTypes)) {
+ Optional<TitanOperationStatus> firstFailure = connectToCapabilityType(groupTypeData, groupCapTypes);
+ if (firstFailure.isPresent()) {
+ groupTypeRes = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(firstFailure.get()));
+ }
+ }
+ }
- result = groupTypeRes;
+ result = groupTypeRes;
- }
+ }
- return result;
+ return result;
- } finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
+ } finally {
+ handleTransactionCommitRollback(inTransaction, result);
+ }
- }
+ }
- public Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeByUid(String uniqueId) {
- Either<GroupTypeDefinition, TitanOperationStatus> result = null;
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> upgradeGroupType(GroupTypeDefinition groupTypeDefinitionNew, GroupTypeDefinition groupTypeDefinitionOld) {
+ return upgradeGroupType(groupTypeDefinitionOld, groupTypeDefinitionNew, false);
+ }
- Either<GroupTypeData, TitanOperationStatus> groupTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class);
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> upgradeGroupType(GroupTypeDefinition groupTypeDefinitionNew, GroupTypeDefinition groupTypeDefinitionOld, boolean inTransaction) {
+ Either<GroupTypeDefinition, StorageOperationStatus> result = Either.left(groupTypeDefinitionNew);
- if (groupTypesRes.isRight()) {
- TitanOperationStatus status = groupTypesRes.right().value();
- log.debug("Group type {} cannot be found in graph. status is {}", uniqueId, status);
- return Either.right(status);
- }
+ try {
+ // dr2032:
+ // Right now upgrade Group is used only to ensure that already existing group type is connected by DERRIVED_FROM edge with it's parent
+ // We don't need to use for a while new node definition since following group type upgrade is not supported.
+ if (!Strings.isNullOrEmpty(groupTypeDefinitionOld.getDerivedFrom())) {
+ result = ensureExsitanceDerivedFromEdge(groupTypeDefinitionOld);
+ }
+ } finally {
+ handleTransactionCommitRollback(inTransaction, result);
+ }
- GroupTypeData gtData = groupTypesRes.left().value();
- GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(gtData.getGroupTypeDataDefinition());
+ return result;
+ }
- TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, properList -> groupTypeDefinition.setProperties(properList));
+ private Optional<TitanOperationStatus> connectToCapabilityType(GroupTypeData groupTypeData, List<CapabilityTypeDefinition> groupCapTypes) {
+ return groupCapTypes.stream()
+ .map(groupCapTypeDef -> connectTo(groupTypeData, groupCapTypeDef))
+ .filter(Either::isRight)
+ .findFirst()
+ .map(either -> either.right().value());
+ }
- if (propertiesStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of capability type {}", uniqueId);
- return Either.right(propertiesStatus);
- }
+ private Either<GraphRelation, TitanOperationStatus> connectTo(GroupTypeData groupTypeData, CapabilityTypeDefinition groupCapTypeDef) {
+ Either<CapabilityTypeData, TitanOperationStatus> eitherCapData = capabilityTypeOperation.getCapabilityTypeByType(groupCapTypeDef.getType());
+ if (eitherCapData.isLeft()) {
+ return titanGenericDao.createRelation(groupTypeData, eitherCapData.left().value(), GraphEdgeLabels.GROUP_TYPE_CAPABILITY_TYPE, null);
+ }
- result = Either.left(groupTypeDefinition);
+ return Either.right(eitherCapData.right().value());
+ }
- return result;
- }
+ public List<GroupTypeDefinition> getAllGroupTypes(Set<String> excludedGroupTypes) {
+ Map<String, Map.Entry<TitanPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedGroupTypes);
+ List<GroupTypeData> groupTypes = titanGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.GroupType, predicateCriteria, GroupTypeData.class)
+ .left()
+ .on(this::onTitanAccessError);
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId) {
+ return convertGroupTypesToDefinition(groupTypes);
+ }
- return getGroupType(uniqueId, false);
- }
+ private List<GroupTypeDefinition> convertGroupTypesToDefinition(List<GroupTypeData> groupTypes) {
+ return groupTypes.stream()
+ .map(type -> new GroupTypeDefinition(type.getGroupTypeDataDefinition()))
+ .collect(Collectors.toList());
+ }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) {
- return getElementType(this::getGroupTypeByUid, uniqueId, inTransaction);
- }
+ private List<GroupTypeData> onTitanAccessError(TitanOperationStatus toe) {
+ throw new StorageException(
+ DaoStatusConverter.convertTitanStatusToStorageStatus(toe));
+ }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type) {
- return getLatestGroupTypeByType(type, false);
- }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type, boolean inTransaction) {
- Map<String, Object> mapCriteria = new HashMap<>();
- mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
- mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+ public Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeByUid(String uniqueId) {
+
+ Either<GroupTypeDefinition, TitanOperationStatus> result = null;
+
+ Either<GroupTypeData, TitanOperationStatus> groupTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class);
+
+ if (groupTypesRes.isRight()) {
+ TitanOperationStatus status = groupTypesRes.right().value();
+ log.debug("Group type {} cannot be found in graph. status is {}", uniqueId, status);
+ return Either.right(status);
+ }
+
+ GroupTypeData gtData = groupTypesRes.left().value();
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(gtData.getGroupTypeDataDefinition());
+
+ TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, NodeTypeEnum.GroupType, properList -> groupTypeDefinition.setProperties(properList));
+
+ if (propertiesStatus != TitanOperationStatus.OK) {
+ log.error("Failed to fetch properties of capability type {}", uniqueId);
+ return Either.right(propertiesStatus);
+ }
- return getGroupTypeByCriteria(type, mapCriteria, inTransaction);
+ result = Either.left(groupTypeDefinition);
- }
+ return result;
+ }
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) {
- Either<GroupTypeDefinition, StorageOperationStatus> result = null;
- try {
- if (type == null || type.isEmpty()) {
- log.error("type is empty");
- result = Either.right(StorageOperationStatus.INVALID_ID);
- return result;
- }
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId) {
+
+ return getGroupType(uniqueId, false);
+
+ }
+
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) {
+ return getElementType(this::getGroupTypeByUid, uniqueId, inTransaction);
+ }
+
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type) {
+ return getLatestGroupTypeByType(type, false);
+ }
+
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type, boolean inTransaction) {
+ Map<String, Object> mapCriteria = new HashMap<>();
+ mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
+ mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+
+ return getGroupTypeByCriteria(type, mapCriteria, inTransaction);
+
+ }
- Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class);
- if (groupTypeEither.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value()));
- } else {
- GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream().map(e -> e.getGroupTypeDataDefinition()).findFirst().get();
- result = getGroupType(dataDefinition.getUniqueId(), inTransaction);
- }
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) {
+ Either<GroupTypeDefinition, StorageOperationStatus> result = null;
+ try {
+ if (type == null || type.isEmpty()) {
+ log.error("type is empty");
+ result = Either.right(StorageOperationStatus.INVALID_ID);
+ return result;
+ }
+
+ Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class);
+ if (groupTypeEither.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value()));
+ } else {
+ GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream().map(e -> e.getGroupTypeDataDefinition()).findFirst().get();
+ result = getGroupType(dataDefinition.getUniqueId(), inTransaction);
+ }
- return result;
+ return result;
- } finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
- }
+ } finally {
+ handleTransactionCommitRollback(inTransaction, result);
+ }
+ }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version) {
- return getGroupTypeByTypeAndVersion(type, version, false);
- }
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version) {
+ return getGroupTypeByTypeAndVersion(type, version, false);
+ }
- @Override
- public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version, boolean inTransaction) {
- Map<String, Object> mapCriteria = new HashMap<>();
- mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
- mapCriteria.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
-
- return getGroupTypeByCriteria(type, mapCriteria, inTransaction);
- }
-
- /**
- *
- * Add group type to graph.
- *
- * 1. Add group type node
- *
- * 2. Add edge between the former node to its parent(if exists)
- *
- * 3. Add property node and associate it to the node created at #1. (per property & if exists)
- *
- * @param groupTypeDefinition
- * @return
- */
- private Either<GroupTypeData, TitanOperationStatus> addGroupTypeToGraph(GroupTypeDefinition groupTypeDefinition) {
-
- log.debug("Got group type {}", groupTypeDefinition);
-
- String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), groupTypeDefinition.getVersion());
- // capabilityTypeDefinition.setUniqueId(ctUniqueId);
-
- GroupTypeData groupTypeData = buildGroupTypeData(groupTypeDefinition, ctUniqueId);
-
- log.debug("Before adding group type to graph. groupTypeData = {}", groupTypeData);
-
- Either<GroupTypeData, TitanOperationStatus> createGTResult = titanGenericDao.createNode(groupTypeData, GroupTypeData.class);
- log.debug("After adding group type to graph. status is = {}", createGTResult);
-
- if (createGTResult.isRight()) {
- TitanOperationStatus operationStatus = createGTResult.right().value();
- log.error("Failed to add group type {} to graph. status is {}", groupTypeDefinition.getType(), operationStatus);
- return Either.right(operationStatus);
- }
-
- GroupTypeData resultCTD = createGTResult.left().value();
- List<PropertyDefinition> properties = groupTypeDefinition.getProperties();
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties);
- if (addPropertiesToCapablityType.isRight()) {
- log.error("Failed add properties {} to capability {}", properties, groupTypeDefinition.getType());
- return Either.right(addPropertiesToCapablityType.right().value());
- }
-
- String derivedFrom = groupTypeDefinition.getDerivedFrom();
- if (derivedFrom != null) {
-
- // TODO: Need to find the parent. need to take the latest one since
- // we may have many versions of the same type
- /*
- * log.debug("Before creating relation between group type {} to its parent {}", ctUniqueId, derivedFrom); UniqueIdData from = new UniqueIdData(NodeTypeEnum.CapabilityType, ctUniqueId); UniqueIdData to = new
- * UniqueIdData(NodeTypeEnum.CapabilityType, derivedFrom); Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
- * log.debug("After create relation between capability type {} to its parent {}. status is {}", ctUniqueId, derivedFrom, createRelation); if (createRelation.isRight()) { return Either.right(createRelation.right().value()); }
- *
- */
- }
-
- return Either.left(createGTResult.left().value());
-
- }
-
- /**
- *
- * convert between graph Node object to Java object
- *
- * @param capabilityTypeData
- * @return
- */
- protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) {
- log.debug("The object returned after create capability is {}", capabilityTypeData);
-
- CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition());
-
- return capabilityTypeDefResult;
- }
-
- private GroupTypeData buildGroupTypeData(GroupTypeDefinition groupTypeDefinition, String ctUniqueId) {
-
- GroupTypeData groupTypeData = new GroupTypeData(groupTypeDefinition);
-
- groupTypeData.getGroupTypeDataDefinition().setUniqueId(ctUniqueId);
- Long creationDate = groupTypeData.getGroupTypeDataDefinition().getCreationTime();
- if (creationDate == null) {
- creationDate = System.currentTimeMillis();
- }
- groupTypeData.getGroupTypeDataDefinition().setCreationTime(creationDate);
- groupTypeData.getGroupTypeDataDefinition().setModificationTime(creationDate);
-
- return groupTypeData;
- }
-
- public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) {
- Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType);
- Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class);
- if (getResponse.isRight()) {
- TitanOperationStatus titanOperationStatus = getResponse.right().value();
- log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, titanOperationStatus);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus));
- }
- String childUniqueId = getResponse.left().value().get(0).getUniqueId();
- Set<String> travelledTypes = new HashSet<>();
- do {
- travelledTypes.add(childUniqueId);
- Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
- if (childrenNodes.isRight()) {
- if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- TitanOperationStatus titanOperationStatus = getResponse.right().value();
- log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus));
- } else {
- log.debug("Derived from node is not found for type {} - this is OK for root capability.");
- return Either.left(false);
- }
- }
- String derivedFromUniqueId = childrenNodes.left().value().get(0).getLeft().getUniqueId();
- if (derivedFromUniqueId.equals(parentCandidateType)) {
- log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType);
- return Either.left(true);
- }
- childUniqueId = derivedFromUniqueId;
- } while (!travelledTypes.contains(childUniqueId));
- // this stop condition should never be used, if we use it, we have an
- // illegal cycle in graph - "derived from" hierarchy cannot be cycled.
- // It's here just to avoid infinite loop in case we have such cycle.
- log.error("Detected a cycle of \"derived from\" edges starting at capability type node {}", childUniqueId);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
-
- /**
- * FOR TEST ONLY
- *
- * @param propertyOperation
- */
- public void setPropertyOperation(PropertyOperation propertyOperation) {
- this.propertyOperation = propertyOperation;
- }
-
- @Override
- public Either<GroupTypeData, TitanOperationStatus> getLatestGroupTypeByNameFromGraph(String name) {
-
- return null;
- }
+ @Override
+ public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version, boolean inTransaction) {
+ Map<String, Object> mapCriteria = new HashMap<>();
+ mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
+ mapCriteria.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
+
+ return getGroupTypeByCriteria(type, mapCriteria, inTransaction);
+ }
+
+ /**
+ * Add group type to graph.
+ * <p>
+ * 1. Add group type node
+ * <p>
+ * 2. Add edge between the former node to its parent(if exists)
+ * <p>
+ * 3. Add property node and associate it to the node created at #1. (per property & if exists)
+ *
+ * @param groupTypeDefinition
+ * @return
+ */
+ private Either<GroupTypeData, TitanOperationStatus> addGroupTypeToGraph(GroupTypeDefinition groupTypeDefinition) {
+
+ log.debug("Got group type {}", groupTypeDefinition);
+
+ String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), groupTypeDefinition.getVersion());
+
+ GroupTypeData groupTypeData = buildGroupTypeData(groupTypeDefinition, ctUniqueId);
+
+ log.debug("Before adding group type to graph. groupTypeData = {}", groupTypeData);
+
+ Either<GroupTypeData, TitanOperationStatus> createGTResult = titanGenericDao.createNode(groupTypeData, GroupTypeData.class);
+ log.debug("After adding group type to graph. status is = {}", createGTResult);
+
+ if (createGTResult.isRight()) {
+ TitanOperationStatus operationStatus = createGTResult.right().value();
+ log.error("Failed to add group type {} to graph. status is {}", groupTypeDefinition.getType(), operationStatus);
+ return Either.right(operationStatus);
+ }
+
+ GroupTypeData resultCTD = createGTResult.left().value();
+ List<PropertyDefinition> properties = groupTypeDefinition.getProperties();
+ Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties);
+ if (addPropertiesToCapablityType.isRight()) {
+ log.error("Failed add properties {} to capability {}", properties, groupTypeDefinition.getType());
+ return Either.right(addPropertiesToCapablityType.right().value());
+ }
+
+ String derivedFrom = groupTypeDefinition.getDerivedFrom();
+ if (derivedFrom != null) {
+ Either<GraphRelation, TitanOperationStatus> createRelation = connectToDerivedFrom(ctUniqueId, derivedFrom);
+ if (createRelation.isRight()) {
+ return Either.right(createRelation.right().value());
+ }
+ }
+
+ return Either.left(createGTResult.left().value());
+
+ }
+
+
+ private Either<GraphRelation, TitanOperationStatus> connectToDerivedFrom(String ctUniqueId, String derivedFrom) {
+ log.debug("Before creating relation between Group Type with id {} to its parent {}", ctUniqueId, derivedFrom);
+
+ Either<GroupTypeData, TitanOperationStatus> derivedFromGroupTypeResult =
+ titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), derivedFrom, GroupTypeData.class);
+
+ if (derivedFromGroupTypeResult.isLeft()) {
+ UniqueIdData from = new UniqueIdData(NodeTypeEnum.GroupType, ctUniqueId);
+ GroupTypeData to = derivedFromGroupTypeResult.left().value();
+
+ Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null);
+ log.debug("After create relation between Group Type with id {} to its parent {}, status is {}.", ctUniqueId, derivedFrom, createRelation);
+ return createRelation;
+ } else {
+ TitanOperationStatus status = derivedFromGroupTypeResult.right().value();
+ log.debug("Failed to found parent Group Type {}, stauts is {}.", derivedFrom, status);
+ return Either.right(status);
+ }
+ }
+
+
+ private Either<GroupTypeDefinition, StorageOperationStatus> ensureExsitanceDerivedFromEdge(GroupTypeDefinition groupTypeDefinition) {
+ Either<GroupTypeDefinition, StorageOperationStatus> result = Either.left(groupTypeDefinition);
+
+ GroupTypeData childGroupType = null;
+ GroupTypeData parentGroupType = null;
+
+ Either<GroupTypeData, TitanOperationStatus> childGroupTypeResult =
+ titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class);
+ if (childGroupTypeResult.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childGroupTypeResult.right().value()));
+ log.debug("Filed to find GroupType with type {}, status is {}.", groupTypeDefinition.getType(), childGroupTypeResult);
+ } else {
+ childGroupType = childGroupTypeResult.left().value();
+ }
+
+
+ if (result.isLeft()) {
+ Either<GroupTypeData, TitanOperationStatus> parentGroupTypeResult =
+ titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getDerivedFrom(), GroupTypeData.class);
+ if (parentGroupTypeResult.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentGroupTypeResult.right().value()));
+ log.debug("Filed to find GroupType with type {}, status is {}.", groupTypeDefinition.getDerivedFrom(), parentGroupTypeResult);
+ } else {
+ parentGroupType = parentGroupTypeResult.left().value();
+ }
+ }
+
+
+ if (childGroupType != null && parentGroupType != null) {
+ Either<Edge, TitanOperationStatus> edgeDerivedFromResult = titanGenericDao.getEdgeByNodes(childGroupType, parentGroupType, GraphEdgeLabels.DERIVED_FROM);
+ if (edgeDerivedFromResult.isLeft()) {
+ log.debug("It was found relation {}. Don't need to create the edge.", edgeDerivedFromResult.left().value());
+ } else {
+ Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(childGroupType, parentGroupType, GraphEdgeLabels.DERIVED_FROM, null);
+ log.debug("After create relation between Group Type with id {} to its parent with id {}, status is {}.",
+ childGroupType.getKeyValueId().getValue(), parentGroupType.getKeyValueId().getValue(), createRelationResult);
+ if (createRelationResult.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationResult.right().value()));
+ }
+ }
+
+ }
+
+
+ return result;
+ }
+
+
+ private GroupTypeData buildGroupTypeData(GroupTypeDefinition groupTypeDefinition, String ctUniqueId) {
+
+ GroupTypeData groupTypeData = new GroupTypeData(groupTypeDefinition);
+
+ groupTypeData.getGroupTypeDataDefinition().setUniqueId(ctUniqueId);
+ Long creationDate = groupTypeData.getGroupTypeDataDefinition().getCreationTime();
+ if (creationDate == null) {
+ creationDate = System.currentTimeMillis();
+ }
+ groupTypeData.getGroupTypeDataDefinition().setCreationTime(creationDate);
+ groupTypeData.getGroupTypeDataDefinition().setModificationTime(creationDate);
+
+ return groupTypeData;
+ }
+
+ public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) {
+ Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
+ propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType);
+ Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class);
+ if (getResponse.isRight()) {
+ TitanOperationStatus titanOperationStatus = getResponse.right().value();
+ log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, titanOperationStatus);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus));
+ }
+ String childUniqueId = getResponse.left().value().get(0).getUniqueId();
+ Set<String> travelledTypes = new HashSet<>();
+ do {
+ travelledTypes.add(childUniqueId);
+ Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM,
+ NodeTypeEnum.CapabilityType, CapabilityTypeData.class);
+ if (childrenNodes.isRight()) {
+ if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ TitanOperationStatus titanOperationStatus = getResponse.right().value();
+ log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus));
+ } else {
+ log.debug("Derived from node is not found for type {} - this is OK for root capability.");
+ return Either.left(false);
+ }
+ }
+ String derivedFromUniqueId = childrenNodes.left().value().get(0).getLeft().getUniqueId();
+ if (derivedFromUniqueId.equals(parentCandidateType)) {
+ log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType);
+ return Either.left(true);
+ }
+ childUniqueId = derivedFromUniqueId;
+ } while (!travelledTypes.contains(childUniqueId));
+ // this stop condition should never be used, if we use it, we have an
+ // illegal cycle in graph - "derived from" hierarchy cannot be cycled.
+ // It's here just to avoid infinite loop in case we have such cycle.
+ log.error("Detected a cycle of \"derived from\" edges starting at capability type node {}", childUniqueId);
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+
+ /**
+ * FOR TEST ONLY
+ *
+ * @param propertyOperation
+ */
+ public void setPropertyOperation(PropertyOperation propertyOperation) {
+ this.propertyOperation = propertyOperation;
+ }
+
+ @Override
+ public Either<GroupTypeData, TitanOperationStatus> getLatestGroupTypeByNameFromGraph(String name) {
+
+ return null;
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java
index 9b6591ec08..7d299c85d1 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java
@@ -27,20 +27,14 @@ import java.nio.file.Files;
import java.util.Map;
import java.util.Properties;
-import javax.annotation.PostConstruct;
-
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.config.Configuration.OnboardingConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.rest.HttpRestClient;
-import org.openecomp.sdc.be.dao.rest.RestConfigurationInfo;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.rest.api.RestResponse;
-import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
import org.openecomp.sdc.common.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,8 +46,6 @@ public class OnboardingClient {
private static Logger log = LoggerFactory.getLogger(OnboardingClient.class.getName());
- private HttpRestClient httpRestClient = null;
-
private static Properties downloadCsarHeaders = new Properties();
static {
@@ -67,7 +59,6 @@ public class OnboardingClient {
public static void main(String[] args) {
OnboardingClient csarOperation = new OnboardingClient();
- csarOperation.init();
String csarUuid = "70025CF6081B489CA7B1CBA583D5278D";
Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null);
@@ -75,23 +66,6 @@ public class OnboardingClient {
}
- @PostConstruct
- public void init() {
-
- // TODO: read connection configuration from OnboardingConfig
- // onboardingConfig =
- // ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
-
- RestConfigurationInfo restConfigurationInfo = new RestConfigurationInfo();
- httpRestClient = new HttpRestClient(restConfigurationInfo);
-
- if (false == httpRestClient.isInitialized()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("InitializeRestClient", "Failed to initialize rest client", ErrorSeverity.FATAL);
- httpRestClient = null;
- }
-
- }
-
public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) {
File dir = new File("/var/tmp/mockCsar");
FileFilter fileFilter = new WildcardFileFilter("*.csar");
@@ -116,12 +90,6 @@ public class OnboardingClient {
}
public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) {
-
- if (httpRestClient == null) {
- BeEcompErrorManager.getInstance().logInternalFlowError("RestClient", "Rest Client could not be initialized", ErrorSeverity.ERROR);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
-
String url = buildDownloadCsarUrl() + "/" + csarUuid;
Properties headers = new Properties();
@@ -135,36 +103,35 @@ public class OnboardingClient {
log.debug("Url for downloading csar is {}. Headers are {}", url, headers);
- RestResponseAsByteArray restResponse = httpRestClient.doGetAsByteArray(url, headers);
- log.debug("After fetching csar {}. Http return code is {}", csarUuid, restResponse.getHttpStatusCode());
-
- switch (restResponse.getHttpStatusCode()) {
- case HttpStatus.SC_OK:
- byte[] data = restResponse.getResponse();
- if (data != null && data.length > 0) {
- Map<String, byte[]> readZip = ZipUtil.readZip(data);
- return Either.left(readZip);
- } else {
- log.debug("Data received from rest is null or empty");
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- case HttpStatus.SC_NOT_FOUND:
- return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
-
- default:
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ try {
+ HttpResponse<byte []> httpResponse = HttpRequest.getAsByteArray(url, headers);
+ log.debug("After fetching csar {}. Http return code is {}", csarUuid, httpResponse.getStatusCode());
+
+ switch (httpResponse.getStatusCode()) {
+ case HttpStatus.SC_OK:
+ byte[] data = httpResponse.getResponse();
+ if (data != null && data.length > 0) {
+ Map<String, byte[]> readZip = ZipUtil.readZip(data);
+ return Either.left(readZip);
+ } else {
+ log.debug("Data received from rest is null or empty");
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+
+ case HttpStatus.SC_NOT_FOUND:
+ return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
+
+ default:
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ }
+ catch(Exception e) {
+ log.debug("Request failed with exception {}", e);
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
}
public Either<String, StorageOperationStatus> getPackages(String userId) {
-
- if (httpRestClient == null) {
- BeEcompErrorManager.getInstance().logInternalFlowError("RestClient", "Rest Client could not be initialized", ErrorSeverity.ERROR);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
-
String url = buildDownloadCsarUrl();
Properties headers = new Properties();
@@ -176,29 +143,26 @@ public class OnboardingClient {
log.debug("Url for downloading packages is {}. Headers are {}", url, headers);
- RestResponse restResponse = httpRestClient.doGET(url, headers);
- log.debug("After fetching packages. Http return code is {}", restResponse.getHttpStatusCode());
-
- switch (restResponse.getHttpStatusCode()) {
- case HttpStatus.SC_OK:
- String data = restResponse.getResponse();
- return Either.left(data);
-
- case HttpStatus.SC_NOT_FOUND:
- return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
-
- default:
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ try {
+ HttpResponse<String> httpResposne = HttpRequest.get(url, headers);
+ log.debug("After fetching packages. Http return code is {}", httpResposne.getStatusCode());
+
+ switch (httpResposne.getStatusCode()) {
+ case HttpStatus.SC_OK:
+ String data = httpResposne.getResponse();
+ return Either.left(data);
+
+ case HttpStatus.SC_NOT_FOUND:
+ return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
+
+ default:
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ }
+ catch(Exception e) {
+ log.debug("Request failed with exception {}", e);
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
}
-
- }
-
- public HttpRestClient getHttpRestClient() {
- return httpRestClient;
- }
-
- public void setHttpRestClient(HttpRestClient httpRestClient) {
- this.httpRestClient = httpRestClient;
}
/**
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
index 70efe12b86..799c01692d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,193 +20,288 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Resource;
-
+import com.thinkaurelius.titan.graphdb.query.TitanPredicate;
+import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation;
import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.PolicyTypeData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate;
@Component("policy-type-operation")
public class PolicyTypeOperation extends AbstractOperation implements IPolicyTypeOperation {
- private static final String CREATE_FLOW_CONTEXT = "CreatePolicyType";
- private static final String GET_FLOW_CONTEXT = "GetPolicyType";
-
- @Resource
- private PropertyOperation propertyOperation;
-
- public PolicyTypeOperation() {
- super();
- }
-
- private static Logger log = LoggerFactory.getLogger(PolicyTypeOperation.class.getName());
-
- @Override
- public Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String policyTypeName) {
- return getLatestPolicyTypeByType(policyTypeName, false);
- }
-
- private Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String type, boolean inTransaction) {
- Map<String, Object> mapCriteria = new HashMap<>();
- mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
- mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- return getPolicyTypeByCriteria(type, mapCriteria, inTransaction);
- }
-
- @Override
- public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType) {
- return addPolicyType(policyType, false);
- }
-
- @Override
- public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyTypeDef, boolean inTransaction) {
-
- Either<PolicyTypeDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<PolicyTypeData, TitanOperationStatus> eitherStatus = addPolicyTypeToGraph(policyTypeDef);
-
- if (eitherStatus.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
-
- } else {
- PolicyTypeData policyTypeData = eitherStatus.left().value();
-
- String uniqueId = policyTypeData.getUniqueId();
- Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeRes = this.getPolicyType(uniqueId, true);
-
- if (policyTypeRes.isRight()) {
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
- }
-
- result = policyTypeRes;
-
- }
-
- return result;
-
- } finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
-
- }
-
- private Either<PolicyTypeData, TitanOperationStatus> addPolicyTypeToGraph(PolicyTypeDefinition policyTypeDef) {
- log.debug("Got policy type {}", policyTypeDef);
-
- String ptUniqueId = UniqueIdBuilder.buildPolicyTypeUid(policyTypeDef.getType(), policyTypeDef.getVersion());
-
- PolicyTypeData policyTypeData = buildPolicyTypeData(policyTypeDef, ptUniqueId);
-
- log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData);
-
- Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData, PolicyTypeData.class);
- log.debug("After adding policy type to graph. status is = {}", eitherPolicyTypeData);
-
- if (eitherPolicyTypeData.isRight()) {
- TitanOperationStatus operationStatus = eitherPolicyTypeData.right().value();
- log.error("Failed to add policy type {} to graph. status is {}", policyTypeDef.getType(), operationStatus);
- return Either.right(operationStatus);
- }
-
- PolicyTypeData resultCTD = eitherPolicyTypeData.left().value();
- List<PropertyDefinition> properties = policyTypeDef.getProperties();
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToPolicyType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.PolicyType, properties);
- if (addPropertiesToPolicyType.isRight()) {
- log.error("Failed add properties {} to policy {}", properties, policyTypeDef.getType());
- return Either.right(addPropertiesToPolicyType.right().value());
- }
-
- return Either.left(eitherPolicyTypeData.left().value());
- }
-
- public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) {
- Either<PolicyTypeDefinition, StorageOperationStatus> result = null;
- try {
- if (type == null || type.isEmpty()) {
- log.error("type is empty");
- result = Either.right(StorageOperationStatus.INVALID_ID);
- return result;
- }
-
- Either<List<PolicyTypeData>, TitanOperationStatus> eitherPolicyData = titanGenericDao.getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class);
- if (eitherPolicyData.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value()));
- } else {
- PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(e -> e.getPolicyTypeDataDefinition()).findFirst().get();
- result = getPolicyType(dataDefinition.getUniqueId(), inTransaction);
- }
-
- return result;
-
- } finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
- }
-
- @Override
- public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction) {
- return getElementType(this::getPolicyTypeByUid, uniqueId, inTransaction);
- }
-
- private Either<PolicyTypeDefinition, TitanOperationStatus> getPolicyTypeByUid(String uniqueId) {
- Either<PolicyTypeDefinition, TitanOperationStatus> result = null;
-
- Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class);
-
- if (eitherPolicyTypeData.isRight()) {
- TitanOperationStatus status = eitherPolicyTypeData.right().value();
- log.debug("Policy type {} cannot be found in graph. status is {}", uniqueId, status);
- return Either.right(status);
- }
-
- PolicyTypeData policyTypeData = eitherPolicyTypeData.left().value();
- PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeData.getPolicyTypeDataDefinition());
-
- TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, propList -> policyTypeDefinition.setProperties(propList));
- if (propertiesStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of policy type {}", uniqueId);
- return Either.right(propertiesStatus);
- }
-
- result = Either.left(policyTypeDefinition);
-
- return result;
- }
-
- private PolicyTypeData buildPolicyTypeData(PolicyTypeDefinition policyTypeDefinition, String ptUniqueId) {
-
- PolicyTypeData policyTypeData = new PolicyTypeData(policyTypeDefinition);
-
- policyTypeData.getPolicyTypeDataDefinition().setUniqueId(ptUniqueId);
- Long creationDate = policyTypeData.getPolicyTypeDataDefinition().getCreationTime();
- if (creationDate == null) {
- creationDate = System.currentTimeMillis();
- }
-
- policyTypeData.getPolicyTypeDataDefinition().setCreationTime(creationDate);
- policyTypeData.getPolicyTypeDataDefinition().setModificationTime(creationDate);
- return policyTypeData;
- }
+ private static final Logger log = LoggerFactory.getLogger(PolicyTypeOperation.class.getName());
+ private static final String CREATE_FLOW_CONTEXT = "CreatePolicyType";
+ private static final String GET_FLOW_CONTEXT = "GetPolicyType";
+
+ @Autowired
+ private PropertyOperation propertyOperation;
+ @Autowired
+ private DerivedFromOperation derivedFromOperation;
+
+ @Override
+ public Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String type) {
+ Map<String, Object> mapCriteria = new HashMap<>();
+ mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type);
+ mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+ return getPolicyTypeByCriteria(type, mapCriteria);
+ }
+
+ @Override
+ public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyTypeDef) {
+ Either<PolicyTypeDefinition, StorageOperationStatus> result;
+ Either<PolicyTypeData, StorageOperationStatus> eitherStatus = addPolicyTypeToGraph(policyTypeDef);
+ if (eitherStatus.isRight()) {
+ BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
+ result = Either.right(eitherStatus.right().value());
+ } else {
+ PolicyTypeData policyTypeData = eitherStatus.left().value();
+ String uniqueId = policyTypeData.getUniqueId();
+ Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeRes = this.getPolicyTypeByUid(uniqueId);
+
+ if (policyTypeRes.isRight()) {
+ BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name());
+ }
+ result = policyTypeRes;
+ }
+ return result;
+ }
+
+ @Override
+ public Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType) {
+ log.debug("updating policy type {}", updatedPolicyType.getType());
+ updatePolicyTypeData(updatedPolicyType, currPolicyType);
+ return updatePolicyTypeOnGraph(updatedPolicyType, currPolicyType);
+ }
+
+ @Override
+ public Either<List<PolicyTypeDefinition>, StorageOperationStatus> getAllPolicyTypes(Set<String> excludedPolicyTypes) {
+ Map<String, Map.Entry<TitanPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedPolicyTypes);
+ return titanGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.PolicyType, predicateCriteria, PolicyTypeData.class)
+ .left()
+ .map(this::convertPolicyTypesToDefinition)
+ .right()
+ .map(DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private List<PolicyTypeDefinition> convertPolicyTypesToDefinition(List<PolicyTypeData> policiesTypes) {
+ return policiesTypes.stream().map(type -> new PolicyTypeDefinition(type.getPolicyTypeDataDefinition())).collect(Collectors.toList());
+ }
+
+
+ private Either<PolicyTypeData, StorageOperationStatus> addPolicyTypeToGraph(PolicyTypeDefinition policyTypeDef) {
+ log.debug("Got policy type {}", policyTypeDef);
+
+ String ptUniqueId = UniqueIdBuilder.buildPolicyTypeUid(policyTypeDef.getType(), policyTypeDef.getVersion());
+ PolicyTypeData policyTypeData = buildPolicyTypeData(policyTypeDef, ptUniqueId);
+ log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData);
+ Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData, PolicyTypeData.class);
+ log.debug("After adding policy type to graph. status is = {}", eitherPolicyTypeData);
+ if (eitherPolicyTypeData.isRight()) {
+ TitanOperationStatus operationStatus = eitherPolicyTypeData.right().value();
+ log.error("Failed to add policy type {} to graph. status is {}", policyTypeDef.getType(), operationStatus);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus));
+ }
+ List<PropertyDefinition> properties = policyTypeDef.getProperties();
+ Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToPolicyType = propertyOperation.addPropertiesToElementType(ptUniqueId, NodeTypeEnum.PolicyType, properties);
+ if (addPropertiesToPolicyType.isRight()) {
+ log.error("Failed add properties {} to policy {}", properties, policyTypeDef.getType());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToPolicyType.right().value()));
+ }
+ return addDerivedFromRelation(policyTypeDef, ptUniqueId)
+ .left()
+ .map(updatedDerivedFrom -> eitherPolicyTypeData.left().value());
+ }
+
+ private Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type, Map<String, Object> properties) {
+ Either<PolicyTypeDefinition, StorageOperationStatus> result;
+ if (type == null || type.isEmpty()) {
+ log.error("type is empty");
+ result = Either.right(StorageOperationStatus.INVALID_ID);
+ return result;
+ }
+
+ Either<List<PolicyTypeData>, TitanOperationStatus> eitherPolicyData = titanGenericDao.getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class);
+ if (eitherPolicyData.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value()));
+ } else {
+ PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(PolicyTypeData::getPolicyTypeDataDefinition).findFirst().get();
+ result = getPolicyTypeByUid(dataDefinition.getUniqueId());
+ }
+ return result;
+
+ }
+
+ private Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByUid(String uniqueId) {
+ log.debug("#getPolicyTypeByUid - fetching policy type with id {}", uniqueId);
+ return titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class)
+ .right()
+ .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
+ .left()
+ .bind(policyType -> createPolicyTypeDefinition(uniqueId, policyType));
+ }
+
+ private Either<PolicyTypeDefinition, StorageOperationStatus> createPolicyTypeDefinition(String uniqueId, PolicyTypeData policyTypeNode) {
+ PolicyTypeDefinition policyType = new PolicyTypeDefinition(policyTypeNode.getPolicyTypeDataDefinition());
+ return fillDerivedFrom(uniqueId, policyType)
+ .left()
+ .map(derivedFrom -> fillProperties(uniqueId, policyType, derivedFrom))
+ .left()
+ .map(props -> policyType);
+ }
+
+ private Either<List<PropertyDefinition>, StorageOperationStatus> fillProperties(String uniqueId, PolicyTypeDefinition policyType, PolicyTypeData derivedFromNode) {
+ log.debug("#fillProperties - fetching all properties for policy type {}", policyType.getType());
+ return propertyOperation.findPropertiesOfNode(NodeTypeEnum.PolicyType, uniqueId)
+ .right()
+ .bind(this::handlePolicyTypeHasNoProperties)
+ .left()
+ .bind(propsMap -> fillDerivedFromProperties(policyType, derivedFromNode, new ArrayList<>(propsMap.values())));
+ }
+
+ private Either<List<PropertyDefinition>, StorageOperationStatus> fillDerivedFromProperties(PolicyTypeDefinition policyType, PolicyTypeData derivedFromNode, List<PropertyDefinition> policyTypeDirectProperties) {
+ if (derivedFromNode == null) {
+ policyType.setProperties(policyTypeDirectProperties);
+ return Either.left(policyTypeDirectProperties);
+ }
+ log.debug("#fillDerivedFromProperties - fetching all properties of derived from chain for policy type {}", policyType.getType());
+ return propertyOperation.getAllPropertiesRec(derivedFromNode.getUniqueId(), NodeTypeEnum.PolicyType, PolicyTypeData.class)
+ .left()
+ .map(derivedFromProps -> {policyTypeDirectProperties.addAll(derivedFromProps); return policyTypeDirectProperties;})
+ .left()
+ .map(allProps -> {policyType.setProperties(allProps);return allProps;});
+ }
+
+ private Either<PolicyTypeData, StorageOperationStatus> fillDerivedFrom(String uniqueId, PolicyTypeDefinition policyType) {
+ log.debug("#fillDerivedFrom - fetching policy type {} derived node", policyType.getType());
+ return derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.PolicyType, PolicyTypeData.class)
+ .right()
+ .bind(this::handleDerivedFromNotExist)
+ .left()
+ .map(derivedFrom -> setDerivedFrom(policyType, derivedFrom));
+
+ }
+
+ private Either<PolicyTypeData, StorageOperationStatus> handleDerivedFromNotExist(StorageOperationStatus err) {
+ if (err == StorageOperationStatus.NOT_FOUND) {
+ return Either.left(null);
+ }
+ return Either.right(err);
+ }
+
+ Either<Map<String, PropertyDefinition>, StorageOperationStatus> handlePolicyTypeHasNoProperties(TitanOperationStatus err) {
+ if (err == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(new HashMap<>());
+ }
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(err));
+ }
+
+ private PolicyTypeData setDerivedFrom(PolicyTypeDefinition policyTypeDefinition, PolicyTypeData derivedFrom) {
+ if (derivedFrom != null) {
+ policyTypeDefinition.setDerivedFrom(derivedFrom.getPolicyTypeDataDefinition().getType());
+ }
+ return derivedFrom;
+ }
+
+ private PolicyTypeData buildPolicyTypeData(PolicyTypeDefinition policyTypeDefinition, String ptUniqueId) {
+
+ PolicyTypeData policyTypeData = new PolicyTypeData(policyTypeDefinition);
+
+ policyTypeData.getPolicyTypeDataDefinition().setUniqueId(ptUniqueId);
+ Long creationDate = policyTypeData.getPolicyTypeDataDefinition().getCreationTime();
+ if (creationDate == null) {
+ creationDate = System.currentTimeMillis();
+ }
+
+ policyTypeData.getPolicyTypeDataDefinition().setCreationTime(creationDate);
+ policyTypeData.getPolicyTypeDataDefinition().setModificationTime(creationDate);
+ return policyTypeData;
+ }
+
+ private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyTypeOnGraph(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType) {
+ updatePolicyTypeData(updatedPolicyType, currPolicyType);
+ return titanGenericDao.updateNode(new PolicyTypeData(updatedPolicyType), PolicyTypeData.class)
+ .right()
+ .map(DaoStatusConverter::convertTitanStatusToStorageStatus)
+ .left()
+ .bind(updatedNode -> updatePolicyProperties(updatedPolicyType.getUniqueId(), updatedPolicyType.getProperties()))
+ .left()
+ .bind(updatedProperties -> updatePolicyDerivedFrom(updatedPolicyType, currPolicyType.getDerivedFrom()))
+ .left()
+ .map(updatedDerivedFrom -> updatedPolicyType);
+ }
+
+ private Either<Map<String, PropertyData>, StorageOperationStatus> updatePolicyProperties(String policyId, List<PropertyDefinition> properties) {
+ log.debug("#updatePolicyProperties - updating policy type properties for policy type with id {}", policyId);
+ return propertyOperation.deletePropertiesAssociatedToNode(NodeTypeEnum.PolicyType, policyId)
+ .left()
+ .bind(deleteProps -> addPropertiesToPolicy(policyId, properties));
+ }
+
+ private Either<GraphRelation, StorageOperationStatus> updatePolicyDerivedFrom(PolicyTypeDefinition updatedPolicyType, String currDerivedFromPolicyType) {
+ String policyTypeId = updatedPolicyType.getUniqueId();
+ log.debug("#updatePolicyDerivedFrom - updating policy derived from relation for policy type with id {}. old derived type {}. new derived type {}", policyTypeId, currDerivedFromPolicyType, updatedPolicyType.getDerivedFrom());
+ StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromPolicyType(policyTypeId, currDerivedFromPolicyType);
+ if (deleteDerivedRelationStatus != StorageOperationStatus.OK) {
+ return Either.right(deleteDerivedRelationStatus);
+ }
+ return addDerivedFromRelation(updatedPolicyType, policyTypeId);
+ }
+
+ private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(PolicyTypeDataDefinition policyTypeDef, String ptUniqueId) {
+ String derivedFrom = policyTypeDef.getDerivedFrom();
+ if (derivedFrom == null) {
+ return Either.left(null);
+ }
+ log.debug("#addDerivedFromRelationBefore - adding derived from relation between policy type {} to its parent {}", policyTypeDef.getType(), derivedFrom);
+ return this.getLatestPolicyTypeByType(derivedFrom)
+ .left()
+ .bind(derivedFromPolicy -> derivedFromOperation.addDerivedFromRelation(ptUniqueId, derivedFromPolicy.getUniqueId(), NodeTypeEnum.PolicyType));
+ }
+
+ private StorageOperationStatus deleteDerivedFromPolicyType(String policyTypeId, String derivedFromType) {
+ if (derivedFromType == null) {
+ return StorageOperationStatus.OK;
+ }
+ log.debug("#deleteDerivedFromPolicyType - deleting derivedFrom relation for policy type with id {} and its derived type {}", policyTypeId, derivedFromType);
+ return getLatestPolicyTypeByType(derivedFromType)
+ .either(derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(policyTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.PolicyType),
+ err -> err);
+ }
+
+ private Either<Map<String, PropertyData>, StorageOperationStatus> addPropertiesToPolicy(String policyTypeId, List<PropertyDefinition> properties) {
+ log.debug("#addPropertiesToPolicy - adding policy type properties for policy type with id {}", policyTypeId);
+ return propertyOperation.addPropertiesToElementType(policyTypeId, NodeTypeEnum.PolicyType, properties)
+ .right()
+ .map(DaoStatusConverter::convertTitanStatusToStorageStatus);
+ }
+
+ private void updatePolicyTypeData(PolicyTypeDefinition updatedTypeDefinition, PolicyTypeDefinition currTypeDefinition) {
+ updatedTypeDefinition.setUniqueId(currTypeDefinition.getUniqueId());
+ updatedTypeDefinition.setCreationTime(currTypeDefinition.getCreationTime());
+ updatedTypeDefinition.setModificationTime(System.currentTimeMillis());
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
index 6835e813ee..99e95e6653 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
@@ -20,34 +20,29 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.io.IOException;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.StringJoiner;
-import java.util.function.Consumer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
+import com.fasterxml.jackson.core.ObjectCodec;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.codehaus.jackson.JsonNode;
-import org.codehaus.jackson.JsonProcessingException;
-import org.codehaus.jackson.ObjectCodec;
-import org.codehaus.jackson.map.DeserializationContext;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
@@ -62,6 +57,7 @@ import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -83,26 +79,30 @@ import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSerializationContext;
-import com.google.gson.JsonSerializer;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+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.Set;
+import java.util.StringJoiner;
+import java.util.function.Consumer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
@Component("property-operation")
public class PropertyOperation extends AbstractOperation implements IPropertyOperation {
private TitanGenericDao titanGenericDao;
+ private DerivedFromOperation derivedFromOperation;
public static void main(String[] args) {
@@ -119,9 +119,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
- public PropertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- super();
+ public PropertyOperation(TitanGenericDao titanGenericDao, DerivedFromOperation derivedFromOperation) {
this.titanGenericDao = titanGenericDao;
+ this.derivedFromOperation = derivedFromOperation;
}
private static Logger log = LoggerFactory.getLogger(PropertyOperation.class.getName());
@@ -790,6 +790,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return Either.left(resourceProps);
}
+ public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deletePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
+ return deleteAllPropertiesAssociatedToNode(nodeType, uniqueId)
+ .right()
+ .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err));
+ }
+
public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesOfNodeRes = findPropertiesOfNode(nodeType, uniqueId);
@@ -823,18 +829,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
/**
- * fetch all properties under a given resource(includes its parents' resources)
- *
- * @param resourceId
- * @param properties
- * @return
- */
- public TitanOperationStatus findAllResourcePropertiesRecursively(String resourceId, List<PropertyDefinition> properties) {
- final NodeElementFetcher<PropertyDefinition> singleNodeFetcher = (resourceIdParam, attributesParam) -> findPropertiesOfNode(NodeTypeEnum.Resource, resourceIdParam, attributesParam);
- return findAllResourceElementsDefinitionRecursively(resourceId, properties, singleNodeFetcher);
- }
-
- /**
*
*
* @param nodeType
@@ -1323,11 +1317,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return instanceProperty;
}
- public static class PropertyConstraintJacksonDeserialiser extends org.codehaus.jackson.map.JsonDeserializer<PropertyConstraint> {
- @Override
- public PropertyConstraint deserialize(org.codehaus.jackson.JsonParser json, DeserializationContext context) throws IOException, JsonProcessingException {
+ public static class PropertyConstraintJacksonDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<PropertyConstraint> {
+ @Override
+ public PropertyConstraint deserialize(com.fasterxml.jackson.core.JsonParser json, DeserializationContext context) throws IOException {
ObjectCodec oc = json.getCodec();
JsonNode node = oc.readTree(json);
return null;
@@ -2147,13 +2141,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return Either.left(dataTypeDefinition);
}
- public Either<DataTypeDefinition, TitanOperationStatus> getDataTypeByNameWithoutDerivedDataTypes(String name) {
-
- String uid = UniqueIdBuilder.buildDataTypeUid(name);
- return getDataTypeByUidWithoutDerivedDataTypes(uid);
-
- }
-
/**
*
* convert between graph Node object to Java object
@@ -2271,7 +2258,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
* @param uniqueId
* @return
*/
- public Either<DataTypeDefinition, TitanOperationStatus> getAndAddDataTypeByUid(String uniqueId, Map<String, DataTypeDefinition> allDataTypes) {
+ private Either<DataTypeDefinition, TitanOperationStatus> getAndAddDataTypeByUid(String uniqueId, Map<String, DataTypeDefinition> allDataTypes) {
Either<DataTypeDefinition, TitanOperationStatus> result = null;
@@ -2339,13 +2326,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return result;
}
- public Either<DataTypeDefinition, TitanOperationStatus> getDataTypeUsingName(String name) {
-
+ private Either<DataTypeDefinition, TitanOperationStatus> getDataTypeUsingName(String name) {
String uid = UniqueIdBuilder.buildDataTypeUid(name);
-
- Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = getDataTypeByUid(uid);
-
- return dataTypeByUid;
+ return getDataTypeByUid(uid);
}
public Either<String, TitanOperationStatus> checkInnerType(PropertyDataDefinition propDataDef) {
@@ -2354,9 +2337,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- Either<String, TitanOperationStatus> result = getInnerType(type, () -> propDataDef.getSchema());
-
- return result;
+ return getInnerType(type, () -> propDataDef.getSchema());
}
public Either<List<DataTypeData>, TitanOperationStatus> getAllDataTypeNodes() {
@@ -2380,7 +2361,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
if (type == null) {
DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
- if (validateResult.right.booleanValue() == false) {
+ if (Boolean.FALSE.equals(validateResult.right)) {
log.debug("The value {} of property from type {} is invalid", value, propertyType);
return Either.right(false);
}
@@ -2390,13 +2371,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
log.trace("before validating property type {}", propertyType);
boolean isValidProperty = isValidValue(type, value, innerType, dataTypes);
- if (false == isValidProperty) {
+ if (!isValidProperty) {
log.debug("The value {} of property from type {} is invalid", value, type);
return Either.right(false);
}
}
Object convertedValue = value;
- if (false == isEmptyValue(value) && isValidate) {
+ if (!isEmptyValue(value) && isValidate) {
PropertyValueConverter converter = type.getConverter();
convertedValue = converter.convert(value, innerType, dataTypes);
}
@@ -2407,11 +2388,46 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return validateAndUpdatePropertyValue(propertyType, value, true, innerType, dataTypes);
}
+ public <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllPropertiesRec(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz) {
+ return this.findPropertiesOfNode(nodeType, uniqueId)
+ .right()
+ .bind(this::handleNotFoundProperties)
+ .left()
+ .bind(props -> getAllDerivedFromChainProperties(uniqueId, nodeType, clazz, props.values()));
+ }
+
+ private Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleNotFoundProperties(TitanOperationStatus titanOperationStatus) {
+ if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(new HashMap<>());
+ }
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus));
+ }
+
+ private <T extends GraphNode> Either<List<PropertyDefinition>, StorageOperationStatus> getAllDerivedFromChainProperties(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz, Collection<PropertyDefinition> nodeProps) {
+ List<PropertyDefinition> accumulatedProps = new ArrayList<>(nodeProps);
+ String currentNodeUid = uniqueId;
+ Either<T, StorageOperationStatus> derivedFrom;
+ while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) {
+ currentNodeUid = derivedFrom.left().value().getUniqueId();
+ TitanOperationStatus titanOperationStatus = fillProperties(currentNodeUid, nodeType, accumulatedProps::addAll);
+ if (titanOperationStatus != TitanOperationStatus.OK) {
+ log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus));
+ }
+ }
+ StorageOperationStatus getDerivedResult = derivedFrom.right().value();
+ return isReachedEndOfDerivedFromChain(getDerivedResult) ? Either.left(accumulatedProps) : Either.right(getDerivedResult);
+ }
+
+ private boolean isReachedEndOfDerivedFromChain(StorageOperationStatus getDerivedResult) {
+ return getDerivedResult == StorageOperationStatus.NOT_FOUND;
+ }
+
/*
* @Override public PropertyOperation getPropertyOperation() { return this; }
*/
- protected TitanOperationStatus fillProperties(String uniqueId, Consumer<List<PropertyDefinition>> propertySetter) {
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.GroupType, uniqueId);
+ protected TitanOperationStatus fillProperties(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) {
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId);
if (findPropertiesOfNode.isRight()) {
TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value();
log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus);
@@ -2498,17 +2514,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return addPropertiesToElementType(uniqueId, elementType, propMap);
}
- public TitanOperationStatus addPropertiesToElementType(TitanVertex elementVertex, String uniqueId, NodeTypeEnum elementType, List<PropertyDefinition> properties) {
-
- Map<String, PropertyDefinition> propMap;
- if (properties == null) {
- propMap = null;
- } else {
- propMap = properties.stream().collect(Collectors.toMap(propDef -> propDef.getName(), propDef -> propDef));
- }
- return addPropertiesToElementType(uniqueId, elementType, propMap, elementVertex);
- }
-
@Override
public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition) {
return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
index eb5d8f6797..4cdb21a908 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java
@@ -31,6 +31,7 @@ import org.openecomp.sdc.be.resources.data.ResourceCategoryData;
import org.openecomp.sdc.be.resources.data.ServiceCategoryData;
import org.openecomp.sdc.be.resources.data.TagData;
import org.openecomp.sdc.be.resources.data.UserData;
+import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.util.ValidationUtils;
public class UniqueIdBuilder {
@@ -134,6 +135,11 @@ public class UniqueIdBuilder {
return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel;
}
+
+ public static String buildInstanceArtifactUniqueId(String parentId, String instanceId, String artifactLabel) {
+
+ return parentId + DOT + instanceId + DOT + artifactLabel;
+ }
// public static String
// buildArtifactByInterfaceUniqueIdAndRsrcNameVersion(String
@@ -240,6 +246,10 @@ public class UniqueIdBuilder {
public static String buildGroupUniqueId(String componentId, String name) {
return componentId + DOT + name + DOT + "group";
}
+
+ public static String buildPolicyUniqueId(String componentId, String name) {
+ return componentId + DOT + name + Constants.POLICY_UID_POSTFIX;
+ }
public static String buildGroupPropertyValueUid(String groupUniqueId, Integer index) {
return groupUniqueId + DOT + "property" + DOT + index;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java
index 5d7f98e438..ba765c92a0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverter.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,28 +23,29 @@ package org.openecomp.sdc.be.model.tosca.converters;
import java.math.BigDecimal;
import java.util.Map;
+import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.model.DataTypeDefinition;
public class ToscaFloatConverter implements PropertyValueConverter {
- private static ToscaFloatConverter numberConverter = new ToscaFloatConverter();
-
- public static ToscaFloatConverter getInstance() {
- return numberConverter;
- }
-
- private ToscaFloatConverter() {
-
- }
-
- @Override
- public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- if (original == null) {
- return null;
- }
- if (original.contains("f") || original.contains("F"))
- original = original.toLowerCase().replaceFirst("f", "");
- return new BigDecimal(original).toPlainString();
- }
+ private static ToscaFloatConverter numberConverter = new ToscaFloatConverter();
+
+ private ToscaFloatConverter() {}
+
+ public static ToscaFloatConverter getInstance() {
+ return numberConverter;
+ }
+
+ @Override
+ public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ if (StringUtils.isEmpty(original)) {
+ return null;
+ }
+ String convertedValue = original;
+ if (original.endsWith("f") || original.endsWith("F")) {
+ convertedValue = StringUtils.removeEndIgnoreCase(original, "f");
+ }
+ return new BigDecimal(convertedValue).toPlainString();
+ }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java
index 7c86b6da1b..862766b6fa 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,6 +24,7 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import org.apache.commons.lang.StringUtils;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -31,7 +32,6 @@ import org.openecomp.sdc.common.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@@ -50,16 +50,14 @@ when written line by line :
key1 : val1
key2 : val2
key1 and val does not need " " , even if val1 is a string.
-
when written as one line : {"key1":val1 , "key2":val2}
Keys always need " " around them.
- */
+*/
public class MapValidator implements PropertyTypeValidator {
private static MapValidator mapValidator = new MapValidator();
- private static Logger log = LoggerFactory.getLogger(MapValidator.class.getName());
- Gson gson = new Gson();
+ private static final Logger LOGGER = LoggerFactory.getLogger(MapValidator.class.getName());
private static DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
@@ -72,7 +70,7 @@ public class MapValidator implements PropertyTypeValidator {
@Override
public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
- if (value == null || value == "") {
+ if (StringUtils.isEmpty(value)) {
return true;
}
if (innerType == null) {
@@ -101,39 +99,28 @@ public class MapValidator implements PropertyTypeValidator {
innerValidator = ToscaPropertyType.JSON.getValidator();
break;
default:
- log.debug("inner Tosca Type is unknown. {}", innerToscaType);
+ LOGGER.debug("inner Tosca Type is unknown. {}", innerToscaType);
return false;
}
} else {
- log.debug("inner Tosca Type is: {}", innerType);
+ LOGGER.debug("inner Tosca Type is: {}", innerType);
boolean isValid = validateComplexInnerType(value, innerType, allDataTypes);
- log.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid);
+ LOGGER.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid);
return isValid;
}
try {
JsonElement jsonObject = jsonParser.parse(value);
- JsonObject asJsonObject = jsonObject.getAsJsonObject();
- Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
- for (Entry<String, JsonElement> entry : entrySet) {
- String currentKey = entry.getKey();
- JsonElement jsonValue = entry.getValue();
-
- String element = JsonUtils.toString(jsonValue);
-
- if (!innerValidator.isValid(element, null, allDataTypes)
- || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) {
- log.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue());
- return false;
- }
- }
-
- return true;
+ if (!jsonObject.isJsonObject()) {
+ return false;
+ }
+ JsonObject valueAsJson = jsonObject.getAsJsonObject();
+ return validateJsonObject(allDataTypes, innerValidator, keyValidator, valueAsJson);
} catch (JsonSyntaxException e) {
- log.debug("Failed to parse json : {}", value, e);
+ LOGGER.debug("Failed to parse json : {}", value, e);
BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator");
}
@@ -141,12 +128,30 @@ public class MapValidator implements PropertyTypeValidator {
}
+ private boolean validateJsonObject(Map<String, DataTypeDefinition> allDataTypes, PropertyTypeValidator innerValidator, PropertyTypeValidator keyValidator, JsonObject asJsonObject) {
+ Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
+ for (Entry<String, JsonElement> entry : entrySet) {
+ String currentKey = entry.getKey();
+ JsonElement jsonValue = entry.getValue();
+
+ String element = JsonUtils.toString(jsonValue);
+
+ if (!innerValidator.isValid(element, null, allDataTypes)
+ || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) {
+ LOGGER.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
private boolean validateComplexInnerType(String value, String innerType,
Map<String, DataTypeDefinition> allDataTypes) {
DataTypeDefinition innerDataTypeDefinition = allDataTypes.get(innerType);
if (innerDataTypeDefinition == null) {
- log.debug("Data type {} cannot be found in our data types.", innerType);
+ LOGGER.debug("Data type {} cannot be found in our data types.", innerType);
return false;
}
@@ -163,14 +168,14 @@ public class MapValidator implements PropertyTypeValidator {
boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition,
allDataTypes);
if (!isValid) {
- log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey);
+ LOGGER.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey);
return false;
}
}
}
} catch (Exception e) {
- log.debug("Cannot parse value {} of map from inner type {}", value, innerType, e);
+ LOGGER.debug("Cannot parse value {} of map from inner type {}", value, innerType, e);
return false;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java
new file mode 100644
index 0000000000..36777f0982
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/SerializedHashMap.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.be.ui.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+public class SerializedHashMap<T,R> extends java.util.HashMap<T,R> {
+
+ @JsonIgnore
+ @Override
+ public boolean isEmpty() {
+ return super.isEmpty();
+ }
+}
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 d699f28d07..f324cf83ad 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,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,251 +20,251 @@
package org.openecomp.sdc.be.ui.model;
-import java.util.List;
-import java.util.Map;
-
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.CapabilityDefinition;
-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.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import java.util.List;
+import java.util.Map;
+
public class UiComponentDataTransfer {
+ private Map<String, ArtifactDefinition> artifacts;
+ private Map<String, ArtifactDefinition> deploymentArtifacts;
+ private Map<String, ArtifactDefinition> toscaArtifacts;
+
+ private List<CategoryDefinition> categories;
+
+ // User
+ private String creatorUserId;
+ private String creatorFullName;
+ private String lastUpdaterUserId;
+ private String lastUpdaterFullName;
+
+ protected ComponentTypeEnum componentType;
+ private List<ComponentInstance> componentInstances;
- private Map<String, ArtifactDefinition> artifacts;
- private Map<String, ArtifactDefinition> deploymentArtifacts;
- private Map<String, ArtifactDefinition> toscaArtifacts;
+ private List<RequirementCapabilityRelDef> componentInstancesRelations;
- private List<CategoryDefinition> categories;
+ private Map<String, List<ComponentInstanceInput>> componentInstancesInputs;
- // User
- private String creatorUserId;
- private String creatorFullName;
- private String lastUpdaterUserId;
- private String lastUpdaterFullName;
+ private Map<String, List<ComponentInstanceProperty>> componentInstancesProperties;
- protected ComponentTypeEnum componentType;
+ private Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes;
- private List<ComponentInstance> componentInstances;
+ private Map<String, List<CapabilityDefinition>> capabilities;
- private List<RequirementCapabilityRelDef> componentInstancesRelations;
+ private List<PolicyDefinition> policies;
- private Map<String, List<ComponentInstanceInput>> componentInstancesInputs;
+ private Map<String, List<RequirementDefinition>> requirements;
- private Map<String, List<ComponentInstanceProperty>> componentInstancesProperties;
+ private List<InputDefinition> inputs;
- private Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes;
+ private List<GroupDefinition> groups;
- private Map<String, List<CapabilityDefinition>> capabilities;
+ protected List<AdditionalInformationDefinition> additionalInformation;
- private Map<String, List<RequirementDefinition>> requirements;
+ public UiComponentDataTransfer() {
+ }
- private List<InputDefinition> inputs;
+ public Map<String, ArtifactDefinition> getArtifacts() {
+ return artifacts;
+ }
- private List<GroupDefinition> groups;
-
- protected List<AdditionalInformationDefinition> additionalInformation;
- public UiComponentDataTransfer(){}
+ public void setArtifacts(Map<String, ArtifactDefinition> artifacts) {
+ this.artifacts = artifacts;
+ }
- public Map<String, ArtifactDefinition> getArtifacts() {
- return artifacts;
- }
+ public Map<String, ArtifactDefinition> getDeploymentArtifacts() {
+ return deploymentArtifacts;
+ }
- public void setArtifacts(Map<String, ArtifactDefinition> artifacts) {
- this.artifacts = artifacts;
- }
+ public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) {
+ this.deploymentArtifacts = deploymentArtifacts;
+ }
- public Map<String, ArtifactDefinition> getDeploymentArtifacts() {
- return deploymentArtifacts;
- }
+ public Map<String, ArtifactDefinition> getToscaArtifacts() {
+ return toscaArtifacts;
+ }
- public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) {
- this.deploymentArtifacts = deploymentArtifacts;
- }
+ public void setToscaArtifacts(Map<String, ArtifactDefinition> toscaArtifacts) {
+ this.toscaArtifacts = toscaArtifacts;
+ }
- public Map<String, ArtifactDefinition> getToscaArtifacts() {
- return toscaArtifacts;
- }
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
- public void setToscaArtifacts(Map<String, ArtifactDefinition> toscaArtifacts) {
- this.toscaArtifacts = toscaArtifacts;
- }
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
- public List<CategoryDefinition> getCategories() {
- return categories;
- }
+ public String getCreatorUserId() {
+ return creatorUserId;
+ }
- public void setCategories(List<CategoryDefinition> categories) {
- this.categories = categories;
- }
+ public void setCreatorUserId(String creatorUserId) {
+ this.creatorUserId = creatorUserId;
+ }
- public String getCreatorUserId() {
- return creatorUserId;
- }
+ public String getCreatorFullName() {
+ return creatorFullName;
+ }
- public void setCreatorUserId(String creatorUserId) {
- this.creatorUserId = creatorUserId;
- }
+ public void setCreatorFullName(String creatorFullName) {
+ this.creatorFullName = creatorFullName;
+ }
- public String getCreatorFullName() {
- return creatorFullName;
- }
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
- public void setCreatorFullName(String creatorFullName) {
- this.creatorFullName = creatorFullName;
- }
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
- public String getLastUpdaterUserId() {
- return lastUpdaterUserId;
- }
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
- public void setLastUpdaterUserId(String lastUpdaterUserId) {
- this.lastUpdaterUserId = lastUpdaterUserId;
- }
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
- public String getLastUpdaterFullName() {
- return lastUpdaterFullName;
- }
+ public ComponentTypeEnum getComponentType() {
+ return componentType;
+ }
- public void setLastUpdaterFullName(String lastUpdaterFullName) {
- this.lastUpdaterFullName = lastUpdaterFullName;
- }
+ public void setComponentType(ComponentTypeEnum componentType) {
+ this.componentType = componentType;
+ }
- public ComponentTypeEnum getComponentType() {
- return componentType;
- }
+ public List<ComponentInstance> getComponentInstances() {
+ return componentInstances;
+ }
- public void setComponentType(ComponentTypeEnum componentType) {
- this.componentType = componentType;
- }
+ public void setComponentInstances(List<ComponentInstance> componentInstances) {
+ this.componentInstances = componentInstances;
+ }
- public List<ComponentInstance> getComponentInstances() {
- return componentInstances;
- }
+ public List<RequirementCapabilityRelDef> getComponentInstancesRelations() {
+ return componentInstancesRelations;
+ }
- public void setComponentInstances(List<ComponentInstance> componentInstances) {
- this.componentInstances = componentInstances;
- }
+ public void setComponentInstancesRelations(List<RequirementCapabilityRelDef> componentInstancesRelations) {
+ this.componentInstancesRelations = componentInstancesRelations;
+ }
- public List<RequirementCapabilityRelDef> getComponentInstancesRelations() {
- return componentInstancesRelations;
- }
+ public Map<String, List<ComponentInstanceInput>> getComponentInstancesInputs() {
+ return componentInstancesInputs;
+ }
- public void setComponentInstancesRelations(List<RequirementCapabilityRelDef> componentInstancesRelations) {
- this.componentInstancesRelations = componentInstancesRelations;
- }
+ public void setComponentInstancesInputs(Map<String, List<ComponentInstanceInput>> componentInstancesInputs) {
+ this.componentInstancesInputs = componentInstancesInputs;
+ }
- public Map<String, List<ComponentInstanceInput>> getComponentInstancesInputs() {
- return componentInstancesInputs;
- }
+ public Map<String, List<ComponentInstanceProperty>> getComponentInstancesProperties() {
+ return componentInstancesProperties;
+ }
- public void setComponentInstancesInputs(Map<String, List<ComponentInstanceInput>> componentInstancesInputs) {
- this.componentInstancesInputs = componentInstancesInputs;
- }
+ public void setComponentInstancesProperties(Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) {
+ this.componentInstancesProperties = componentInstancesProperties;
+ }
- public Map<String, List<ComponentInstanceProperty>> getComponentInstancesProperties() {
- return componentInstancesProperties;
- }
+ public Map<String, List<ComponentInstanceProperty>> getComponentInstancesAttributes() {
+ return componentInstancesAttributes;
+ }
- public void setComponentInstancesProperties(Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) {
- this.componentInstancesProperties = componentInstancesProperties;
- }
+ public void setComponentInstancesAttributes(
+ Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes) {
+ this.componentInstancesAttributes = componentInstancesAttributes;
+ }
- public Map<String, List<ComponentInstanceProperty>> getComponentInstancesAttributes() {
- return componentInstancesAttributes;
- }
+ public Map<String, List<CapabilityDefinition>> getCapabilities() {
+ return capabilities;
+ }
- public void setComponentInstancesAttributes(
- Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes) {
- this.componentInstancesAttributes = componentInstancesAttributes;
- }
+ public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
+ this.capabilities = capabilities;
+ }
- public Map<String, List<CapabilityDefinition>> getCapabilities() {
- return capabilities;
- }
+ public Map<String, List<RequirementDefinition>> getRequirements() {
+ return requirements;
+ }
- public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) {
- this.capabilities = capabilities;
- }
+ public void setRequirements(Map<String, List<RequirementDefinition>> requirements) {
+ this.requirements = requirements;
+ }
- public Map<String, List<RequirementDefinition>> getRequirements() {
- return requirements;
- }
+ public List<InputDefinition> getInputs() {
+ return inputs;
+ }
- public void setRequirements(Map<String, List<RequirementDefinition>> requirements) {
- this.requirements = requirements;
- }
+ public void setInputs(List<InputDefinition> inputs) {
+ this.inputs = inputs;
+ }
- public List<InputDefinition> getInputs() {
- return inputs;
- }
+ public List<GroupDefinition> getGroups() {
+ return groups;
+ }
- public void setInputs(List<InputDefinition> inputs) {
- this.inputs = inputs;
- }
+ public void setGroups(List<GroupDefinition> groups) {
+ this.groups = groups;
+ }
- public List<GroupDefinition> getGroups() {
- return groups;
- }
+ public List<AdditionalInformationDefinition> getAdditionalInformation() {
+ return additionalInformation;
+ }
- public void setGroups(List<GroupDefinition> groups) {
- this.groups = groups;
- }
+ public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
+ this.additionalInformation = additionalInformation;
+ }
- public List<AdditionalInformationDefinition> getAdditionalInformation() {
- return additionalInformation;
- }
+ public List<PolicyDefinition> getPolicies() {
+ return policies;
+ }
+ public void setPolicies(List<PolicyDefinition> policies) {
+ this.policies = policies;
+ }
- public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) {
- this.additionalInformation = additionalInformation;
- }
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
index 757dccf5d9..c784a598ab 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java
@@ -20,15 +20,15 @@
package org.openecomp.sdc.be.ui.model;
-import java.util.Map;
-
+import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
+import java.util.Map;
public class UiServiceDataTransfer extends UiComponentDataTransfer {
private Map<String, ArtifactDefinition> serviceApiArtifacts;
-
+ private Map<String, ForwardingPathDataDefinition> forwardingPaths;
private UiServiceMetadata metadata;
public UiServiceMetadata getMetadata() {
@@ -46,4 +46,12 @@ public class UiServiceDataTransfer extends UiComponentDataTransfer {
public void setServiceApiArtifacts(Map<String, ArtifactDefinition> serviceApiArtifacts) {
this.serviceApiArtifacts = serviceApiArtifacts;
}
+
+ public java.util.Map<String, org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition> getForwardingPaths() {
+ return forwardingPaths;
+ }
+
+ public void setForwardingPaths(java.util.Map<String, org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition> forwardingPaths) {
+ this.forwardingPaths = forwardingPaths;
+ }
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java
new file mode 100644
index 0000000000..1215b5fc6f
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/config/ModelOperationsSpringConfig.java
@@ -0,0 +1,9 @@
+package org.openecomp.sdc.be.model.config;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan({"org.openecomp.sdc.be.model.jsontitan.operations","org.openecomp.sdc.be.model.jsontitan.utils"})
+public class ModelOperationsSpringConfig {
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java
new file mode 100644
index 0000000000..c0ba256957
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperationTest.java
@@ -0,0 +1,178 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils;
+import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+/**
+ * Created by yavivi on 26/01/2018.
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+public class ExternalReferencesOperationTest extends ModelTestBase {
+
+ @Resource
+ private ExternalReferencesOperation externalReferenceOperation;
+
+ @Resource
+ private TitanDao titanDao;
+
+ private boolean isInitialized;
+
+ private GraphVertex serviceVertex;
+
+ private String serviceVertexUuid;
+ private static final String COMPONENT_ID = "ci-MyComponentName";
+
+ private static final String MONITORING_OBJECT_TYPE = "monitoring";
+ private static final String WORKFLOW_OBJECT_TYPE = "workflow";
+ private static final String REF_1 = "ref1";
+ private static final String REF_2 = "ref2";
+ private static final String REF_3 = "ref3";
+ private static final String REF_4 = "ref4";
+ private static final String REF_5 = "ref5";
+
+ //workflow
+ private static final String REF_6 = "ref6";
+
+ private IdMapper idMapper;
+
+ @BeforeClass
+ public static void initTest(){
+ ModelTestBase.init();
+ }
+
+ @Before
+ public void beforeTest() {
+ idMapper = Mockito.mock(IdMapper.class);
+ this.externalReferenceOperation.setIdMapper(idMapper);
+ when(idMapper.mapComponentNameToUniqueId(Mockito.anyString(), Mockito.any(GraphVertex.class))).thenReturn(COMPONENT_ID);
+ if (!isInitialized) {
+ GraphTestUtils.clearGraph(titanDao);
+ initGraphForTest();
+ isInitialized = true;
+ }
+ }
+
+ @Test
+ public void testAddComponentInstanceExternalRef(){
+ Either<String, ActionStatus> addResult = externalReferenceOperation.addExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_4);
+ assertThat(addResult.isLeft()).isEqualTo(true);
+
+ //commit changes to titan
+ final TitanOperationStatus commit = this.titanDao.commit();
+ assertThat(commit).isEqualTo(TitanOperationStatus.OK);
+
+ assertThat(getServiceExternalRefs()).contains(REF_1, REF_2, REF_3, REF_4);
+ }
+
+ @Test
+ public void testGetComponentInstanceExternalRef(){
+ assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5);
+ assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE).left().value()).containsExactly(REF_6);
+ }
+
+ @Test
+ public void testGetComponentInstanceExternalRefForNonExistingObjectId(){
+ assertThat(externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE).left().value()).contains(REF_1, REF_2, REF_3, REF_5);
+ Either<List<String>, ActionStatus> getResult = externalReferenceOperation.getExternalReferences(this.serviceVertexUuid, COMPONENT_ID, "FAKE_OBJECT_TYPE");
+ assertThat(getResult.left().value()).isEmpty();
+ }
+
+ @Test
+ public void testDeleteComponentInstanceExternalRef(){
+ //Test the precondition
+ assertThat(getServiceExternalRefs()).contains(REF_5);
+
+ //Remove REF 5
+ Either<String, ActionStatus> deleteStatus = externalReferenceOperation.deleteExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+ assertThat(deleteStatus.isLeft()).isEqualTo(true);
+
+ //commit changes to titan
+ final TitanOperationStatus commit = this.titanDao.commit();
+ assertThat(commit).isEqualTo(TitanOperationStatus.OK);
+
+ //Check that ref does not exist anymore
+ assertThat(getServiceExternalRefs()).doesNotContain(REF_5).contains(REF_1, REF_2, REF_3);
+ }
+
+ @Test
+ public void testUpdateComponentInstanceExternalRef(){
+ //Test the precondition
+ assertThat(getServiceExternalRefs()).contains(REF_5).doesNotContain(REF_4);
+
+ //Update REF 5 with REF_4
+ Either<String, ActionStatus> updateResult = externalReferenceOperation.updateExternalReference(this.serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5, REF_4);
+
+ assertThat(updateResult.isLeft()).isEqualTo(true);
+
+ //commit changes to titan
+ final TitanOperationStatus commit = this.titanDao.commit();
+ assertThat(commit).isEqualTo(TitanOperationStatus.OK);
+
+ //Check that ref does not exist anymore
+ assertThat(getServiceExternalRefs()).doesNotContain(REF_5).contains(REF_1, REF_2, REF_3, REF_4);
+ }
+
+ private List<String> getServiceExternalRefs(){
+ //Get service vertex
+ final Either<GraphVertex, TitanOperationStatus> externalRefsVertexResult = this.titanDao.getChildVertex(this.serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, JsonParseFlagEnum.ParseJson);
+ assertThat(externalRefsVertexResult.isLeft()).isEqualTo(true);
+
+ GraphVertex externalRefVertex = externalRefsVertexResult.left().value();
+
+ //Get the full map
+ Map<String, MapComponentInstanceExternalRefs> componentInstancesMap = (Map<String, MapComponentInstanceExternalRefs>) externalRefVertex.getJson();
+ assertThat(componentInstancesMap).isNotNull();
+
+ //Get Map of external refs by object type
+ final MapComponentInstanceExternalRefs mapComponentInstanceExternalRefs = componentInstancesMap.get(COMPONENT_ID);
+
+ //Get List of references
+ //final List<String> externalRefsByObjectType = mapComponentInstanceExternalRefs.externalRefsByObjectType(objectType);
+ final List<String> externalRefsByObjectType = mapComponentInstanceExternalRefs.getExternalRefsByObjectType(MONITORING_OBJECT_TYPE);
+
+ return externalRefsByObjectType;
+ }
+
+ private void initGraphForTest() {
+ //create a service and add 1 ref
+ this.serviceVertex = GraphTestUtils.createServiceVertex(titanDao, new HashMap<>());
+ this.serviceVertexUuid = this.serviceVertex.getUniqueId();
+
+ //monitoring references
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_1);
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_2);
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_3);
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, MONITORING_OBJECT_TYPE, REF_5);
+
+ //workflow references
+ externalReferenceOperation.addExternalReference(serviceVertexUuid, COMPONENT_ID, WORKFLOW_OBJECT_TYPE, REF_6);
+
+ final TitanOperationStatus commit = this.titanDao.commit();
+ assertThat(commit).isEqualTo(TitanOperationStatus.OK);
+ }
+} \ No newline at end of file
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java
index a1a257b893..71d54bca73 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperationTest.java
@@ -25,7 +25,6 @@ import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RelationshipInfo;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-
import com.google.common.collect.Lists;
import fj.data.Either;
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java
new file mode 100644
index 0000000000..d4188744d8
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationIntegrationTest.java
@@ -0,0 +1,133 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.config.TitanSpringConfig;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.commons.collections.ListUtils.union;
+import static org.assertj.core.api.Assertions.assertThat;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class})
+public class PolicyOperationIntegrationTest extends ModelTestBase {
+
+ private static final String CONTAINER_ID = "container";
+ public static final String POLICY_ID = "policy";
+ @Resource
+ private TopologyTemplateOperation topologyTemplateOperation;
+ @Resource
+ private TitanDao titanDao;
+ @Resource
+ private PolicyOperation policyOperation;
+ private PropertyDataDefinition prop1, prop2;
+ private PolicyDefinition policy;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+
+ ModelTestBase.init();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ prop1 = new PropertyDataDefinition();
+ prop1.setUniqueId("prop1");
+ prop1.setName("prop1");
+ prop1.setValue("prop1");
+
+ prop2 = new PropertyDataDefinition();
+ prop2.setUniqueId("prop2");
+ prop2.setName("prop2");
+ prop2.setValue("prop2");
+
+ policy = new PolicyDefinition();
+ policy.setUniqueId(POLICY_ID);
+
+ policy.setProperties(Arrays.asList(prop1, prop2));
+
+ GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID);
+ titanDao.createVertex(resource);
+ GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value();
+ topologyTemplateOperation.addToscaDataToToscaElement(loadedResource, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policy, JsonPresentationFields.UNIQUE_ID);
+ titanDao.commit();
+ }
+
+ @After
+ public void tearDown() {
+ titanDao.rollback();
+ }
+
+ @Test
+ public void testUpdatePolicyProperties_singleProperty() {
+ PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1);
+ prop1Copy.setValue("prop1NewValue");
+ testUpdatePolicyProperties(Collections.singletonList(prop1Copy), Collections.singletonList(prop2));
+ }
+
+ @Test
+ public void testUpdatePolicyProperties_multipleProperties() {
+ PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1);
+ prop1Copy.setValue("prop1NewValue");
+
+ PropertyDataDefinition prop2Copy = new PropertyDataDefinition(prop2);
+ prop2Copy.setValue("prop2NewValue");
+
+ testUpdatePolicyProperties(Arrays.asList(prop1Copy, prop2Copy), Collections.emptyList());
+ }
+
+ private void testUpdatePolicyProperties(List<PropertyDataDefinition> updatedProperties, List<PropertyDataDefinition> nonUpdatedPropeties) {
+ Component cmpt = new org.openecomp.sdc.be.model.Resource();
+ cmpt.setUniqueId(CONTAINER_ID);
+ cmpt.setPolicies(Collections.singletonMap(POLICY_ID, policy));
+ StorageOperationStatus storageOperationStatus = policyOperation.updatePolicyProperties(cmpt, POLICY_ID, updatedProperties);
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnorePolicies(false);
+ Either<ToscaElement, StorageOperationStatus> loadedCmptEither = topologyTemplateOperation.getToscaElement(CONTAINER_ID, componentParametersView);
+
+ assertThat(loadedCmptEither.isLeft());
+ ToscaElement loadedCmpt = loadedCmptEither.left().value();
+ assertThat(loadedCmpt).isInstanceOf(TopologyTemplate.class);
+ @SuppressWarnings("unchecked") List<PropertyDataDefinition> allProperties = union(updatedProperties, nonUpdatedPropeties);
+ verifyPolicyPropertiesValuesUpdated((TopologyTemplate) loadedCmpt, allProperties);
+ }
+
+ private void verifyPolicyPropertiesValuesUpdated(TopologyTemplate toscaElement, List<PropertyDataDefinition> expectedUpdatedProperties) {
+ Map<String, PolicyDataDefinition> policies = toscaElement.getPolicies();
+ PolicyDataDefinition policy = policies.get(POLICY_ID);
+ List<PropertyDataDefinition> policyProperties = policy.getProperties();
+ assertThat(policyProperties).usingElementComparatorOnFields("value")
+ .containsAll(expectedUpdatedProperties);
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java
new file mode 100644
index 0000000000..136f95b987
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperationTest.java
@@ -0,0 +1,93 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class PolicyOperationTest {
+
+ private static final String CONTAINER_ID = "containerId";
+ private static final String POLICY_ID = "policyId";
+ @InjectMocks
+ private PolicyOperation testInstance;
+ @Mock
+ private TitanDao titanDao;
+ @Mock
+ private TopologyTemplateOperation topologyTemplateOperation;
+ @Captor
+ private ArgumentCaptor<PolicyDefinition> policyDefCaptor;
+ private Component component;
+ private PolicyDefinition policyDefinition;
+ private PropertyDataDefinition prop1, prop2;
+
+ @Before
+ public void setUp() throws Exception {
+ component = new Resource();
+ component.setUniqueId(CONTAINER_ID);
+ policyDefinition = new PolicyDefinition();
+ policyDefinition.setUniqueId(POLICY_ID);
+ prop1 = new PropertyDataDefinition();
+ prop1.setName("prop1");
+ prop1.setValue("prop1");
+
+ prop2 = new PropertyDataDefinition();
+ prop2.setName("prop2");
+ prop2.setValue("prop2");
+ policyDefinition.setProperties(Arrays.asList(prop1, prop2));
+ component.setPolicies(Collections.singletonMap(POLICY_ID, policyDefinition));
+ }
+
+ @Test
+ public void updatePolicyProperties_failedToFetchContainer() {
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND));
+ StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.emptyList());
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ verifyZeroInteractions(topologyTemplateOperation);
+ }
+
+ @Test
+ public void updatePolicyProperties_updateFailed() {
+ GraphVertex cmptVertex = new GraphVertex();
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(cmptVertex));
+ when(topologyTemplateOperation.updatePolicyOfToscaElement(cmptVertex, policyDefinition)).thenReturn(StorageOperationStatus.GENERAL_ERROR);
+ StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.emptyList());
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.GENERAL_ERROR);
+ }
+
+ @Test
+ public void updatePolicyProperties() {
+ GraphVertex cmptVertex = new GraphVertex();
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(cmptVertex));
+ when(topologyTemplateOperation.updatePolicyOfToscaElement(eq(cmptVertex), policyDefCaptor.capture())).thenReturn(StorageOperationStatus.OK);
+ PropertyDataDefinition prop1Copy = new PropertyDataDefinition(prop1);
+ prop1Copy.setValue("prop1Copy");
+ StorageOperationStatus storageOperationStatus = testInstance.updatePolicyProperties(component, POLICY_ID, Collections.singletonList(prop1Copy));
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ assertThat(policyDefCaptor.getValue().getProperties()).usingElementComparatorOnFields("value")
+ .containsExactlyInAnyOrder(prop1Copy, prop2);
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java
new file mode 100644
index 0000000000..103b27d3e6
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationCapabilityIntegrationTest.java
@@ -0,0 +1,199 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.config.TitanSpringConfig;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.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.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class})
+public class TopologyTemplateOperationCapabilityIntegrationTest extends ModelTestBase {
+
+ private static final String CONTAINER_ID = "id";
+ private Map<String, MapCapabiltyProperty> capabilitiesPropsMap;
+ private List<CapabilityPropertyDataObject> capabilitiesProperties;
+
+ @Resource
+ private TopologyTemplateOperation topologyTemplateOperation;
+
+ @Resource
+ private TitanDao titanDao;
+ private CapabilityPropertyDataObject capabilityProperty1;
+ private CapabilityPropertyDataObject capabilityProperty2;
+ private CapabilityPropertyDataObject capabilityProperty3;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+
+ ModelTestBase.init();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+
+ capabilitiesPropsMap = new HashMap<>();
+ capabilityProperty1 = new CapabilityPropertyDataObject("instance1", "capability1", "prop1", "val1");
+ capabilityProperty2 = new CapabilityPropertyDataObject("instance1", "capability2", "prop2", "val2");
+ capabilityProperty3 = new CapabilityPropertyDataObject("instance2", "capability3", "prop3", "val3");
+ capabilitiesProperties = Arrays.asList(capabilityProperty1, capabilityProperty2, capabilityProperty3);
+
+
+ //capablities props == Map<instance id, Map<capability id, Map<prop id, property>>>
+ capabilitiesProperties.forEach(capabilitiesProperty -> {
+ capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabiltyProperty(new HashMap<>()))
+ .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getCapabilityId(), k -> new MapPropertiesDataDefinition(new HashMap<>()))
+ .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getPropName(), k -> new PropertyDefinition(createPropWithValue(capabilitiesProperty.getPropValue())));
+ });
+
+ GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID);
+ titanDao.createVertex(resource);
+ GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value();
+ topologyTemplateOperation.assosiateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value();
+ titanDao.commit();
+
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ titanDao.rollback();
+ }
+
+ @Test
+ public void overrideCalculatedCapabilityProperties() {
+ Map<String, MapCapabiltyProperty> loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID);
+ compareCapabilitiesProperties(capabilitiesProperties, loadedCapPropsMap);
+ capabilityProperty1.setPropValue("newVal1");
+ capabilityProperty3.setPropValue("newVal3");
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty1);
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty3);
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap);
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ Map<String, MapCapabiltyProperty> updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID);
+ compareCapabilitiesProperties(capabilitiesProperties, updatedCapPropsMap);
+ }
+
+ @Test
+ public void updateToscaDataDeepElementsBlockToToscaElement() {
+ assertCapabilityPropValue(capabilityProperty1, "val1");
+ assertCapabilityPropValue(capabilityProperty2, "val2");
+ assertCapabilityPropValue(capabilityProperty3, "val3");
+
+ MapCapabiltyProperty instance1Props = capabilitiesPropsMap.get("instance1");
+ capabilityProperty1.setPropValue("newVal1");
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty1);
+
+ capabilityProperty3.setPropValue("newVal3");
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty3);
+
+ Component component = new org.openecomp.sdc.be.model.Resource();
+ component.setUniqueId(CONTAINER_ID);
+ StorageOperationStatus updateStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instance1Props, "instance1");
+
+ assertThat(updateStatus).isEqualTo(StorageOperationStatus.OK);
+ assertCapabilityPropValue(capabilityProperty1, "newVal1");
+ assertCapabilityPropValue(capabilityProperty2, "val2");
+ assertCapabilityPropValue(capabilityProperty3, "val3");//only instance1 props should be updated
+ }
+
+ private Map<String, MapCapabiltyProperty> fetchCapabilitiesProps(String containerId) {
+ ComponentParametersView capabilityPropsFilter = new ComponentParametersView(true);
+ capabilityPropsFilter.setIgnoreCapabiltyProperties(false);
+ return ((TopologyTemplate) topologyTemplateOperation.getToscaElement(containerId, capabilityPropsFilter).left().value()).getCalculatedCapabilitiesProperties();
+ }
+
+ private void compareCapabilitiesProperties(List<CapabilityPropertyDataObject> expected, Map<String, MapCapabiltyProperty> actual) {
+ expected.forEach(expectedCapabilityProp -> {
+ assertThat(getPropertyValue(actual, expectedCapabilityProp.instanceId, expectedCapabilityProp.capabilityId, expectedCapabilityProp.propName))
+ .isEqualTo(expectedCapabilityProp.propValue);
+ });
+ }
+
+ private String getPropertyValue(Map<String, MapCapabiltyProperty> capabilityPropertyMap, String instance, String capability, String prop) {
+ return capabilityPropertyMap.get(instance).getMapToscaDataDefinition().get(capability).getMapToscaDataDefinition().get(prop).getValue();
+ }
+
+ private void setPropertyValue(Map<String, MapCapabiltyProperty> capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) {
+ setPropertyValue(capabilityPropertyMap.get(capabilityProperty.getInstanceId()), capabilityProperty);
+
+ }
+
+ private void setPropertyValue(MapCapabiltyProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) {
+ capabilitiesInstanceProperties.getMapToscaDataDefinition().get(capabilityProperty.getCapabilityId())
+ .getMapToscaDataDefinition().get(capabilityProperty.getPropName())
+ .setValue(capabilityProperty.getPropValue());
+ }
+
+ private void assertCapabilityPropValue(CapabilityPropertyDataObject prop, String expectedValue) {
+ Map<String, MapCapabiltyProperty> loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID);
+ String propertyValue = getPropertyValue(loadedCapPropsMap, prop.getInstanceId(), prop.getCapabilityId(), prop.getPropName());
+ assertThat(propertyValue).isEqualTo(expectedValue);
+ }
+
+
+ private PropertyDefinition createPropWithValue(String val) {
+ PropertyDefinition propertyDefinition = new PropertyDefinition();
+ propertyDefinition.setValue(val);
+ return propertyDefinition;
+ }
+
+ private static class CapabilityPropertyDataObject {
+ private String instanceId;
+ private String capabilityId;
+ private String propName;
+ private String propValue;
+
+ CapabilityPropertyDataObject(String instanceId, String capabilityId, String propName, String propValue) {
+ this.instanceId = instanceId;
+ this.capabilityId = capabilityId;
+ this.propName = propName;
+ this.propValue = propValue;
+ }
+
+ String getInstanceId() {
+ return instanceId;
+ }
+
+ String getCapabilityId() {
+ return capabilityId;
+ }
+
+ String getPropName() {
+ return propName;
+ }
+
+ String getPropValue() {
+ return propValue;
+ }
+
+ void setPropValue(String propValue) {
+ this.propValue = propValue;
+ }
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java
new file mode 100644
index 0000000000..d104cd3d42
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationIntegrationTest.java
@@ -0,0 +1,199 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.config.TitanSpringConfig;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.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.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.annotation.Resource;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class})
+public class TopologyTemplateOperationIntegrationTest extends ModelTestBase {
+
+ private static final String CONTAINER_ID = "id";
+ private Map<String, MapCapabiltyProperty> capabilitiesPropsMap;
+ private List<CapabilityPropertyDataObject> capabilitiesProperties;
+
+ @Resource
+ private TopologyTemplateOperation topologyTemplateOperation;
+
+ @Resource
+ private TitanDao titanDao;
+ private CapabilityPropertyDataObject capabilityProperty1;
+ private CapabilityPropertyDataObject capabilityProperty2;
+ private CapabilityPropertyDataObject capabilityProperty3;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+
+ ModelTestBase.init();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+
+ capabilitiesPropsMap = new HashMap<>();
+ capabilityProperty1 = new CapabilityPropertyDataObject("instance1", "capability1", "prop1", "val1");
+ capabilityProperty2 = new CapabilityPropertyDataObject("instance1", "capability2", "prop2", "val2");
+ capabilityProperty3 = new CapabilityPropertyDataObject("instance2", "capability3", "prop3", "val3");
+ capabilitiesProperties = Arrays.asList(capabilityProperty1, capabilityProperty2, capabilityProperty3);
+
+
+ //capablities props == Map<instance id, Map<capability id, Map<prop id, property>>>
+ capabilitiesProperties.forEach(capabilitiesProperty -> {
+ capabilitiesPropsMap.computeIfAbsent(capabilitiesProperty.getInstanceId(), k -> new MapCapabiltyProperty(new HashMap<>()))
+ .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getCapabilityId(), k -> new MapPropertiesDataDefinition(new HashMap<>()))
+ .getMapToscaDataDefinition().computeIfAbsent(capabilitiesProperty.getPropName(), k -> new PropertyDefinition(createPropWithValue(capabilitiesProperty.getPropValue())));
+ });
+
+ GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID);
+ titanDao.createVertex(resource);
+ GraphVertex loadedResource = titanDao.getVertexById(CONTAINER_ID).left().value();
+ topologyTemplateOperation.assosiateElementToData(loadedResource, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap).left().value();
+ titanDao.commit();
+
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ titanDao.rollback();
+ }
+
+ @Test
+ public void overrideCalculatedCapabilityProperties() {
+ Map<String, MapCapabiltyProperty> loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID);
+ compareCapabilitiesProperties(capabilitiesProperties, loadedCapPropsMap);
+ capabilityProperty1.setPropValue("newVal1");
+ capabilityProperty3.setPropValue("newVal3");
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty1);
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty3);
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilitiesPropsMap);
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ Map<String, MapCapabiltyProperty> updatedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID);
+ compareCapabilitiesProperties(capabilitiesProperties, updatedCapPropsMap);
+ }
+
+ @Test
+ public void updateToscaDataDeepElementsBlockToToscaElement() {
+ assertCapabilityPropValue(capabilityProperty1, "val1");
+ assertCapabilityPropValue(capabilityProperty2, "val2");
+ assertCapabilityPropValue(capabilityProperty3, "val3");
+
+ MapCapabiltyProperty instance1Props = capabilitiesPropsMap.get("instance1");
+ capabilityProperty1.setPropValue("newVal1");
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty1);
+
+ capabilityProperty3.setPropValue("newVal3");
+ setPropertyValue(capabilitiesPropsMap, capabilityProperty3);
+
+ Component component = new org.openecomp.sdc.be.model.Resource();
+ component.setUniqueId(CONTAINER_ID);
+ StorageOperationStatus updateStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instance1Props, "instance1");
+
+ assertThat(updateStatus).isEqualTo(StorageOperationStatus.OK);
+ assertCapabilityPropValue(capabilityProperty1, "newVal1");
+ assertCapabilityPropValue(capabilityProperty2, "val2");
+ assertCapabilityPropValue(capabilityProperty3, "val3");//only instance1 props should be updated
+ }
+
+ private Map<String, MapCapabiltyProperty> fetchCapabilitiesProps(String containerId) {
+ ComponentParametersView capabilityPropsFilter = new ComponentParametersView(true);
+ capabilityPropsFilter.setIgnoreCapabiltyProperties(false);
+ return ((TopologyTemplate) topologyTemplateOperation.getToscaElement(containerId, capabilityPropsFilter).left().value()).getCalculatedCapabilitiesProperties();
+ }
+
+ private void compareCapabilitiesProperties(List<CapabilityPropertyDataObject> expected, Map<String, MapCapabiltyProperty> actual) {
+ expected.forEach(expectedCapabilityProp -> {
+ assertThat(getPropertyValue(actual, expectedCapabilityProp.instanceId, expectedCapabilityProp.capabilityId, expectedCapabilityProp.propName))
+ .isEqualTo(expectedCapabilityProp.propValue);
+ });
+ }
+
+ private String getPropertyValue(Map<String, MapCapabiltyProperty> capabilityPropertyMap, String instance, String capability, String prop) {
+ return capabilityPropertyMap.get(instance).getMapToscaDataDefinition().get(capability).getMapToscaDataDefinition().get(prop).getValue();
+ }
+
+ private void setPropertyValue(Map<String, MapCapabiltyProperty> capabilityPropertyMap, CapabilityPropertyDataObject capabilityProperty) {
+ setPropertyValue(capabilityPropertyMap.get(capabilityProperty.getInstanceId()), capabilityProperty);
+
+ }
+
+ private void setPropertyValue(MapCapabiltyProperty capabilitiesInstanceProperties, CapabilityPropertyDataObject capabilityProperty) {
+ capabilitiesInstanceProperties.getMapToscaDataDefinition().get(capabilityProperty.getCapabilityId())
+ .getMapToscaDataDefinition().get(capabilityProperty.getPropName())
+ .setValue(capabilityProperty.getPropValue());
+ }
+
+ private void assertCapabilityPropValue(CapabilityPropertyDataObject prop, String expectedValue) {
+ Map<String, MapCapabiltyProperty> loadedCapPropsMap = fetchCapabilitiesProps(CONTAINER_ID);
+ String propertyValue = getPropertyValue(loadedCapPropsMap, prop.getInstanceId(), prop.getCapabilityId(), prop.getPropName());
+ assertThat(propertyValue).isEqualTo(expectedValue);
+ }
+
+
+ private PropertyDefinition createPropWithValue(String val) {
+ PropertyDefinition propertyDefinition = new PropertyDefinition();
+ propertyDefinition.setValue(val);
+ return propertyDefinition;
+ }
+
+ private static class CapabilityPropertyDataObject {
+ private String instanceId;
+ private String capabilityId;
+ private String propName;
+ private String propValue;
+
+ CapabilityPropertyDataObject(String instanceId, String capabilityId, String propName, String propValue) {
+ this.instanceId = instanceId;
+ this.capabilityId = capabilityId;
+ this.propName = propName;
+ this.propValue = propValue;
+ }
+
+ String getInstanceId() {
+ return instanceId;
+ }
+
+ String getCapabilityId() {
+ return capabilityId;
+ }
+
+ String getPropName() {
+ return propName;
+ }
+
+ String getPropValue() {
+ return propValue;
+ }
+
+ void setPropValue(String propValue) {
+ this.propValue = propValue;
+ }
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java
new file mode 100644
index 0000000000..7756a08cc1
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperationTest.java
@@ -0,0 +1,125 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Property;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.VertexProperty.Cardinality;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
+import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+
+import com.thinkaurelius.titan.core.PropertyKey;
+import com.thinkaurelius.titan.core.TitanEdge;
+import com.thinkaurelius.titan.core.TitanTransaction;
+import com.thinkaurelius.titan.core.TitanVertex;
+import com.thinkaurelius.titan.core.TitanVertexProperty;
+import com.thinkaurelius.titan.core.TitanVertexQuery;
+import com.thinkaurelius.titan.core.VertexLabel;
+import com.thinkaurelius.titan.diskstorage.EntryMetaData.Map;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+//error scenarios
+public class TopologyTemplateOperationTest {
+
+ private static final String CONTAINER_ID = "containerId";
+ @InjectMocks
+ private TopologyTemplateOperation topologyTemplateOperation;
+ @Mock
+ private TitanDao titanDao;
+
+ @Test
+ public void overrideToscaDataOfToscaElement_failedToFetchContainerVertex() {
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.INVALID_ID));
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, Collections.emptyMap());
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID);
+ }
+
+ @Test
+ public void overrideToscaDataOfToscaElement_failedToFetchDataVertex() {
+ GraphVertex containerVertex = new GraphVertex();
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex));
+ when(titanDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND));
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation.overrideToscaDataOfToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, Collections.emptyMap());
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ }
+
+ @Test
+ public void updateToscaDataDeepElements_failedToFetchContainerVertex() {
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.right(TitanOperationStatus.INVALID_ID));
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabiltyProperty(), "");
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.INVALID_ID);
+ }
+
+ @Test
+ public void updateToscaDataDeepElements_failedToFetchDataVertex() {
+ GraphVertex containerVertex = new GraphVertex();
+ when(titanDao.getVertexById(CONTAINER_ID, JsonParseFlagEnum.NoParse)).thenReturn(Either.left(containerVertex));
+ when(titanDao.getChildVertex(containerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, JsonParseFlagEnum.ParseJson)).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND));
+ StorageOperationStatus storageOperationStatus = topologyTemplateOperation.updateToscaDataDeepElementsBlockToToscaElement(CONTAINER_ID, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, new MapCapabiltyProperty(), "");
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ }
+
+ @Test
+ public void addPolicyToToscaElementSuccessTest(){
+ TitanOperationStatus status = TitanOperationStatus.OK;
+ StorageOperationStatus result = addPolicyToToscaElementWithStatus(status);
+ assertThat(result).isEqualTo(StorageOperationStatus.OK);
+ }
+
+ @Test
+ public void addPolicyToToscaElementFailureTest(){
+ TitanOperationStatus status = TitanOperationStatus.ALREADY_EXIST;
+ StorageOperationStatus result = addPolicyToToscaElementWithStatus(status);
+ assertThat(result).isEqualTo(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
+ }
+
+ @SuppressWarnings("unchecked")
+ private StorageOperationStatus addPolicyToToscaElementWithStatus(TitanOperationStatus status) {
+ GraphVertex componentV = new GraphVertex();
+ componentV.setVertex(Mockito.mock(TitanVertex.class));
+ GraphVertex dataV = new GraphVertex();
+ dataV.setVertex(Mockito.mock(TitanVertex.class));
+ String componentName = "componentName";
+ String componentId = UniqueIdBuilder.buildResourceUniqueId();
+ String policyTypeName = "org.openecomp.policies.placement.valet.Affinity";
+ componentV.setJsonMetadataField(JsonPresentationFields.NAME, componentName);
+ componentV.setUniqueId(componentId);
+ PolicyDefinition policy = new PolicyDefinition();
+ policy.setPolicyTypeName(policyTypeName);
+ int counter = 0;
+ Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = Either.right(TitanOperationStatus.NOT_FOUND);
+ when(titanDao.getChildVertex(eq(componentV), eq(EdgeLabelEnum.POLICIES), eq(JsonParseFlagEnum.ParseJson))).thenReturn(toscaDataVertexRes);
+ Either<GraphVertex, TitanOperationStatus> createVertex = Either.left(dataV);
+ when(titanDao.createVertex(any(GraphVertex.class))).thenReturn(createVertex);
+ when(titanDao.createEdge(any(TitanVertex.class), any(TitanVertex.class), any(EdgeLabelEnum.class), any(HashMap.class))).thenReturn(status);
+ return topologyTemplateOperation.addPolicyToToscaElement(componentV, policy, counter);
+ }
+
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java
index 806c22a8fb..d9148a18e1 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java
@@ -22,6 +22,7 @@ import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -81,6 +82,9 @@ public class ToscaElementOperationTest extends ModelTestBase{
}, null);
assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
}
+
+
+
@Test
public void testGetAllResourcesCertifiedNoFilter() {
@@ -268,6 +272,8 @@ public class ToscaElementOperationTest extends ModelTestBase{
}
private void initGraphForTest() {
+ GraphTestUtils.createRootCatalogVertex(titanDao);
+
Map<GraphPropertyEnum, Object> highstVerticesProps = new HashMap<GraphPropertyEnum, Object>() {
{
put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java
new file mode 100644
index 0000000000..6a4a117360
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadePoliciesTest.java
@@ -0,0 +1,144 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.config.TitanSpringConfig;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
+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.Component;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.PolicyDefinition;
+import org.openecomp.sdc.be.model.config.ModelOperationsSpringConfig;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(classes = {TitanSpringConfig.class, ModelOperationsSpringConfig.class})
+public class ToscaOperationFacadePoliciesTest extends ModelTestBase {
+
+ private static final String CONTAINER_ID = "containerId";
+ private static final String CONTAINER_NAME = "containerName";
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
+ @Autowired
+ private TitanDao titanDao;
+
+ private PolicyDefinition policy1, policy2;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+ ModelTestBase.init();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ policy1 = createPolicyDefinition("type1");
+ policy2 = createPolicyDefinition("type2");
+ createContainerVertexInDB();
+ createPoliciesOnGraph(policy1, policy2);
+ }
+
+ private void createPoliciesOnGraph(PolicyDefinition ... policies) {
+ for (int i = 0; i < policies.length; i++) {
+ PolicyDefinition policy = policies[i];
+ Either<PolicyDefinition, StorageOperationStatus> createdPolicy = toscaOperationFacade.associatePolicyToComponent(CONTAINER_ID, policy, i);
+ assertTrue(createdPolicy.isLeft());
+ }
+ }
+
+ @After
+ public void tearDown() {
+ titanDao.rollback();
+ }
+
+ @Test
+ public void updatePoliciesTargetsOfComponent_updateSinglePolicy() {
+ List<String> updatedTargetIds = asList("instance1new", "instance2");
+ PolicyDefinition originalPolicy2 = clonePolicyWithTargets(policy2);
+ updatePolicyTypeTargetsIds(policy1, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds);
+ updatePolicyTypeTargetsIds(policy2, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds);
+
+ StorageOperationStatus storageOperationStatus = toscaOperationFacade.updatePoliciesOfComponent(CONTAINER_ID, singletonList(policy1));
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ Component updatedComponent = fetchComponentFromDB();
+ verifyPolicyTargets(updatedComponent.getPolicyById(policy1.getUniqueId()), policy1);
+ verifyPolicyTargets(updatedComponent.getPolicyById(policy2.getUniqueId()), originalPolicy2);
+ }
+
+ @Test
+ public void updatePoliciesTargetsOfComponent_updateMultiplePolicies() {
+ List<String> updatedTargetIds = asList("instance1new", "instance2");
+ updatePolicyTypeTargetsIds(policy1, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds);
+ updatePolicyTypeTargetsIds(policy2, PolicyTargetType.COMPONENT_INSTANCES, updatedTargetIds);
+ StorageOperationStatus storageOperationStatus = toscaOperationFacade.updatePoliciesOfComponent(CONTAINER_ID, asList(policy1, policy2));
+ assertThat(storageOperationStatus).isEqualTo(StorageOperationStatus.OK);
+ Component updatedComponent = fetchComponentFromDB();
+ verifyPolicyTargets(updatedComponent.getPolicyById(policy1.getUniqueId()), policy1);
+ verifyPolicyTargets(updatedComponent.getPolicyById(policy2.getUniqueId()), policy2);
+ }
+
+ private PolicyDefinition clonePolicyWithTargets(PolicyDefinition policy) {
+ PolicyDefinition originalPolicy = new PolicyDefinition(policy);
+ Map<PolicyTargetType, List<String>> clonedTargetMap = policy.getTargets().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new ArrayList<>(entry.getValue())));
+ originalPolicy.setTargets(clonedTargetMap);
+ return originalPolicy;
+ }
+
+ private void verifyPolicyTargets(PolicyDefinition updatedPolicy, PolicyDefinition expectedPolicy) {
+ assertThat(updatedPolicy.getTargets())
+ .isEqualTo(expectedPolicy.getTargets());
+ }
+
+ private void updatePolicyTypeTargetsIds(PolicyDefinition policy, PolicyTargetType targetType, List<String> updatedTargetIds) {
+ policy.getTargets().put(targetType, updatedTargetIds);
+ }
+
+ private Component fetchComponentFromDB() {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnorePolicies(false);
+ return toscaOperationFacade.getToscaElement(CONTAINER_ID, componentParametersView).left().value();
+ }
+
+ private void createContainerVertexInDB() {
+ GraphVertex resource = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ resource.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, CONTAINER_ID);
+ resource.addMetadataProperty(GraphPropertyEnum.NAME, CONTAINER_NAME);
+ resource.setJsonMetadataField(JsonPresentationFields.NAME, CONTAINER_NAME);
+ resource.setJsonMetadataField(JsonPresentationFields.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ Either<GraphVertex, TitanOperationStatus> container = titanDao.createVertex(resource);
+ assertTrue(container.isLeft());
+ }
+
+ private PolicyDefinition createPolicyDefinition(String type) {
+ PolicyDefinition policy = new PolicyDefinition();
+ policy.setPolicyTypeName(type);
+ policy.setTargets(new HashMap<>());
+ policy.getTargets().put(PolicyTargetType.COMPONENT_INSTANCES, asList("instance1", "instance2"));
+ return policy;
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java
index 4a7d27812d..37d466c648 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacadeTest.java
@@ -1,15 +1,6 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -29,11 +20,24 @@ import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.PolicyDefinition;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ToscaOperationFacadeTest {
@@ -58,16 +62,18 @@ public class ToscaOperationFacadeTest {
@Test
public void fetchMetaDataByResourceType() throws Exception {
ArgumentCaptor<Map> criteriaCapture = ArgumentCaptor.forClass(Map.class);
+ ArgumentCaptor<Map> criteriaNotCapture = ArgumentCaptor.forClass(Map.class);
ComponentParametersView dataFilter = new ComponentParametersView();
List<GraphVertex> mockVertices = getMockVertices(2);
Either<List<GraphVertex>, TitanOperationStatus> returnedVertices = Either.left(mockVertices);
- when(titanDaoMock.getByCriteria(Mockito.eq(null), criteriaCapture.capture(), Mockito.eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(returnedVertices);
+ when(titanDaoMock.getByCriteria(eq(null), criteriaCapture.capture(), criteriaNotCapture.capture(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(returnedVertices);
when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(0), dataFilter)).thenReturn(Either.left(getResourceToscaElement("0")));
when(topologyTemplateOperationMock.getToscaElement(mockVertices.get(1), dataFilter)).thenReturn(Either.left(getResourceToscaElement("1")));
Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), dataFilter);
verifyCriteriaForHighestVersionAndVfResourceType(criteriaCapture);
+ verifyCriteriaNotIsDeleted(criteriaNotCapture);
assertTrue(fetchedComponents.isLeft());
List<Component> cmpts = fetchedComponents.left().value();
@@ -83,17 +89,93 @@ public class ToscaOperationFacadeTest {
assertEquals(criteria.get(GraphPropertyEnum.IS_HIGHEST_VERSION), true);
}
+ private void verifyCriteriaNotIsDeleted(ArgumentCaptor<Map> criteriaNotCapture) {
+ Map<GraphPropertyEnum, Object> notCriteria = (Map<GraphPropertyEnum, Object>)criteriaNotCapture.getValue();
+ assertEquals(1, notCriteria.size());
+ assertEquals(notCriteria.get(GraphPropertyEnum.IS_DELETED), true);
+ }
+
@SuppressWarnings("unchecked")
@Test
public void fetchMetaDataByResourceType_failedToGetData() throws Exception {
- when(titanDaoMock.getByCriteria(Mockito.eq(null), Mockito.anyMap(), Mockito.eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR));
+ when(titanDaoMock.getByCriteria(eq(null), anyMap(), anyMap(), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR));
Either<List<Component>, StorageOperationStatus> fetchedComponents = testInstance.fetchMetaDataByResourceType(ResourceTypeEnum.VF.getValue(), new ComponentParametersView());
assertTrue(fetchedComponents.isRight());
assertEquals(StorageOperationStatus.GENERAL_ERROR, fetchedComponents.right().value());
}
+
+ @Test
+ public void associatePolicyToComponentSuccessTest(){
+ Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.OK);
+ assertTrue(result.isLeft());
+ }
+
+ @Test
+ public void associatePolicyToComponentFailureTest(){
+ Either<PolicyDefinition, StorageOperationStatus> result = associatePolicyToComponentWithStatus(StorageOperationStatus.BAD_REQUEST);
+ assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.BAD_REQUEST);
+ }
+
+ @Test
+ public void updatePolicyOfComponentSuccessTest(){
+ Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.OK);
+ assertTrue(result.isLeft());
+ }
+
+ @Test
+ public void updatePolicyOfComponentFailureTest(){
+ Either<PolicyDefinition, StorageOperationStatus> result = updatePolicyOfComponentWithStatus(StorageOperationStatus.NOT_FOUND);
+ assertTrue(result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND);
+ }
+
+ @Test
+ public void removePolicyFromComponentSuccessTest(){
+ removePolicyFromComponentWithStatus(StorageOperationStatus.OK);
+ }
+
+ @Test
+ public void removePolicyFromComponentFailureTest(){
+ removePolicyFromComponentWithStatus(StorageOperationStatus.NOT_FOUND);
+ }
+
+ private Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponentWithStatus(StorageOperationStatus status) {
+ PolicyDefinition policy = new PolicyDefinition();
+ String componentId = "componentId";
+ int counter = 0;
+ GraphVertex vertex;
+ if(status == StorageOperationStatus.OK){
+ vertex = getTopologyTemplateVertex();
+ } else {
+ vertex = getNodeTypeVertex();
+ }
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = Either.left(vertex);
+ when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.ParseMetadata))).thenReturn(getVertexEither);
+ when(topologyTemplateOperationMock.addPolicyToToscaElement(eq(vertex), any(PolicyDefinition.class), anyInt())).thenReturn(status);
+ return testInstance.associatePolicyToComponent(componentId, policy, counter);
+ }
+
+ private Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponentWithStatus(StorageOperationStatus status) {
+ PolicyDefinition policy = new PolicyDefinition();
+ String componentId = "componentId";
+ GraphVertex vertex = getTopologyTemplateVertex();
+ when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(Either.left(vertex));
+ when(topologyTemplateOperationMock.updatePolicyOfToscaElement(eq(vertex), any(PolicyDefinition.class))).thenReturn(status);
+ return testInstance.updatePolicyOfComponent(componentId, policy);
+ }
+ private void removePolicyFromComponentWithStatus(StorageOperationStatus status) {
+ String componentId = "componentId";
+ String policyId = "policyId";
+ GraphVertex vertex = getTopologyTemplateVertex();
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = Either.left(vertex);
+ when(titanDaoMock.getVertexById(eq(componentId), eq(JsonParseFlagEnum.NoParse))).thenReturn(getVertexEither);
+ when(topologyTemplateOperationMock.removePolicyFromToscaElement(eq(vertex), eq(policyId))).thenReturn(status);
+ StorageOperationStatus result = testInstance.removePolicyFromComponent(componentId, policyId);
+ assertTrue(result == status);
+ }
+
private List<GraphVertex> getMockVertices(int numOfVertices) {
- return IntStream.range(0, numOfVertices).mapToObj(i -> getMockVertex()).collect(Collectors.toList());
+ return IntStream.range(0, numOfVertices).mapToObj(i -> getTopologyTemplateVertex()).collect(Collectors.toList());
}
private ToscaElement getResourceToscaElement(String id) {
@@ -104,9 +186,15 @@ public class ToscaOperationFacadeTest {
return toscaElement;
}
- private GraphVertex getMockVertex() {
+ private GraphVertex getTopologyTemplateVertex() {
GraphVertex graphVertex = new GraphVertex();
graphVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
return graphVertex;
}
+
+ private GraphVertex getNodeTypeVertex() {
+ GraphVertex graphVertex = new GraphVertex();
+ graphVertex.setLabel(VertexTypeEnum.NODE_TYPE);
+ return graphVertex;
+ }
} \ No newline at end of file
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java
index 862515c58e..72919b6136 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java
@@ -32,6 +32,7 @@ import org.apache.tinkerpop.gremlin.structure.io.IoCore;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
@@ -44,6 +45,12 @@ import fj.data.Either;
public final class GraphTestUtils {
+ public static void createRootCatalogVertex(TitanDao titanDao) {
+ GraphVertex catalogRootVertex = new GraphVertex(VertexTypeEnum.CATALOG_ROOT);
+ catalogRootVertex.setUniqueId(IdBuilderUtils.generateUniqueId());
+ titanDao.createVertex(catalogRootVertex);
+ }
+
public static GraphVertex createResourceVertex(TitanDao titanDao, Map<GraphPropertyEnum,Object> metadataProps, ResourceTypeEnum type) {
GraphVertex vertex = new GraphVertex();
if (type == ResourceTypeEnum.VF) {
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java
new file mode 100644
index 0000000000..809134ecb6
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperationTest.java
@@ -0,0 +1,346 @@
+package org.openecomp.sdc.be.model.operations.impl;
+
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.junit.After;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
+import org.openecomp.sdc.be.model.GroupTypeDefinition;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.tosca.ToscaType;
+import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
+import org.openecomp.sdc.be.resources.data.GroupTypeData;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static com.google.common.collect.Sets.newHashSet;
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.*;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+public class GroupTypeOperationTest extends ModelTestBase {
+ private static final String TOSCA_GROUPS_ROOT = "tosca.groups.Root";
+
+ @Resource(name = "titan-generic-dao")
+ private TitanGenericDao titanDao;
+
+ @Resource(name = "capability-type-operation")
+ private CapabilityTypeOperation capabilityTypeOperation;
+
+ @Resource(name = "group-type-operation")
+ private GroupTypeOperation groupTypeOperation;
+
+ @BeforeClass
+ public static void setupBeforeClass() {
+ ModelTestBase.init();
+ }
+
+ @After
+ public void tearDown() {
+ titanDao.rollback();
+ }
+
+ @Test
+ public void getAllGroupTypes() {
+ GroupTypeDefinition rootGroupDefinition = createRootGroupDefinition();
+ GroupTypeDefinition type1 = createGroupType("type1");
+ GroupTypeDefinition type2 = createGroupType("type2");
+ groupTypeOperation.addGroupType(rootGroupDefinition);
+ groupTypeOperation.addGroupType(type1);
+ groupTypeOperation.addGroupType(type2);
+
+ List<GroupTypeDefinition> allGroupTypesNoExclusion = groupTypeOperation.getAllGroupTypes(null);
+ assertThat(allGroupTypesNoExclusion)
+ .usingElementComparatorOnFields("type")
+ .containsExactlyInAnyOrder(rootGroupDefinition, type1, type2);
+ }
+
+ @Test
+ public void getAllGroupTypes_whenPassingExclusionList_doNotReturnExcludedTypes() {
+ GroupTypeDefinition rootGroupDefinition = createRootGroupDefinition();
+ GroupTypeDefinition type1 = createGroupType("type1");
+ GroupTypeDefinition type2 = createGroupType("type2");
+ groupTypeOperation.addGroupType(rootGroupDefinition);
+ groupTypeOperation.addGroupType(type1);
+ groupTypeOperation.addGroupType(type2);
+
+ List<GroupTypeDefinition> allGroupTypes = groupTypeOperation.getAllGroupTypes(newHashSet("type1", "type2"));
+ assertThat(allGroupTypes)
+ .usingElementComparatorOnFields("type")
+ .containsExactly(rootGroupDefinition);
+ }
+
+ @Test
+ public void groupTypeWithoutCapabilityTypeCreated() {
+ GroupTypeData rootNode = getOrCreateRootGroupTypeNode();
+
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT);
+ groupTypeDefinition.setDescription("groups l3-networks in network collection");
+ groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection");
+ groupTypeDefinition.setVersion("1.0");
+
+ List<PropertyDefinition> properties = asList(
+ buildProperty("network_collection_type", "l3-network", "network collection type, defined with default value"),
+ buildProperty("network_collection_subtype", "sub-interface", "network collection subtype, defined with default value"),
+ buildProperty("network_collection_role", null, "network collection role"),
+ buildProperty("network_collection_description", null, "network collection description, free format text"));
+
+ groupTypeDefinition.setProperties(properties );
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, false);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ addGroupTypeResult = groupTypeOperation.getGroupTypeByTypeAndVersion("org.openecomp.groups.NetworkCollection", "1.0");
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ Either<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class);
+ GroupTypeData groupTypeNode = extractVal(groupTypeResult);
+
+ Either<Edge, TitanOperationStatus> edgeResult = titanDao.getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM);
+ validate(edgeResult);
+ }
+
+ @Test
+ public void groupTypeWithCapabilityTypeAndEdgeCreated() {
+ GroupTypeData rootNode = getOrCreateRootGroupTypeNode();
+
+ CapabilityTypeDefinition capabilityTypeDef = createCapabilityType();
+ Either<CapabilityTypeData, TitanOperationStatus> capabilityTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityTypeDef.getType(), CapabilityTypeData.class);
+ CapabilityTypeData capabilityTypeNode = extractVal(capabilityTypeResult);
+
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT);
+ groupTypeDefinition.setDescription("groups l3-networks in network collection");
+ groupTypeDefinition.setType("org.openecomp.groups.NetworkCollection");
+ groupTypeDefinition.setCapabilityTypes(asList(capabilityTypeDef));
+
+ List<PropertyDefinition> properties = asList(
+ buildProperty("vfc_instance_group_role", null, "role of this VFC group"),
+ buildProperty("vfc_parent_port_role", null, "common role of parent ports of VFCs in this group"),
+ buildProperty("network_collection_role", null, "network collection role assigned to this group"),
+ buildProperty("subinterface_role", null, "common role of subinterfaces of VFCs in this group, criteria the group is created"));
+
+ groupTypeDefinition.setProperties(properties );
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ Either<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class);
+ GroupTypeData groupTypeNode = extractVal(groupTypeResult);
+
+ Either<Edge, TitanOperationStatus> edgeCapTypeResult = titanDao.getEdgeByNodes(groupTypeNode, capabilityTypeNode, GraphEdgeLabels.GROUP_TYPE_CAPABILITY_TYPE);
+ validate(edgeCapTypeResult);
+
+ Either<Edge, TitanOperationStatus> edgeDerivedFromResult = titanDao.getEdgeByNodes(groupTypeNode, rootNode, GraphEdgeLabels.DERIVED_FROM);
+ validate(edgeDerivedFromResult);
+ }
+
+ @Test
+ public void testUpgradeGroupTypeWithDerrivedFromEdge() {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT);
+ groupTypeDefinition.setDescription("groups l2-networks in network collection");
+ groupTypeDefinition.setType("org.openecomp.groups.PrivateCollection");
+ groupTypeDefinition.setVersion("1.0");
+
+ List<PropertyDefinition> properties = singletonList(
+ buildProperty("network_collection_type", "l2-network", "network collection type, defined with default value"));
+
+ groupTypeDefinition.setProperties(properties );
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ addGroupTypeResult = groupTypeOperation.getGroupTypeByTypeAndVersion("org.openecomp.groups.PrivateCollection", "1.0");
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ Either<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true);
+ assertNotNull(upgradeResult);
+ assertTrue(upgradeResult.isLeft());
+ }
+
+ @Test
+ public void testUpgradeNonExistingGroupType() {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDerivedFrom(TOSCA_GROUPS_ROOT);
+ groupTypeDefinition.setDescription("groups l2-networks in network collection");
+ groupTypeDefinition.setType("org.openecomp.groups.MyCollection");
+ groupTypeDefinition.setVersion("1.0");
+
+ Either<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true);
+ assertNotNull(upgradeResult);
+ assertTrue(upgradeResult.isRight());
+ }
+
+ @Test
+ public void testUpgradeNotDerivedGroupType() {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDescription("groups social-networks in school");
+ groupTypeDefinition.setType("org.openecomp.groups.Teachers");
+ groupTypeDefinition.setVersion("1.0");
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ Either<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true);
+ assertNotNull(upgradeResult);
+ assertTrue(upgradeResult.isLeft());
+ assertEquals(groupTypeDefinition, upgradeResult.left().value());
+ }
+
+ @Test
+ public void testUpgradeGroupTypeWithNonExistingParent() {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDescription("groups social-networks in work");
+ groupTypeDefinition.setType("org.openecomp.groups.Cowokers");
+ groupTypeDefinition.setVersion("1.0");
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ groupTypeDefinition.setDerivedFrom("Non.existing.parent");
+ Either<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true);
+ assertNotNull(upgradeResult);
+ assertTrue(upgradeResult.isRight());
+ }
+
+ @Test
+ public void testUpgradeGroupType() {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDescription("groups social-networks in university");
+ groupTypeDefinition.setType("org.openecomp.groups.Students");
+ groupTypeDefinition.setVersion("1.0");
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(groupTypeDefinition, true);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(groupTypeDefinition, addGroupTypeResult.left().value());
+
+ GroupTypeDefinition parentGroupTypeDefinition = new GroupTypeDefinition();
+ parentGroupTypeDefinition.setDescription("groups social-networks in university");
+ parentGroupTypeDefinition.setType("org.openecomp.groups.Parents");
+ parentGroupTypeDefinition.setVersion("1.0");
+
+ Either<GroupTypeDefinition, StorageOperationStatus> addParentGroupTypeResult = groupTypeOperation.addGroupType(parentGroupTypeDefinition, true);
+ assertEquals("check group type added", true, addParentGroupTypeResult.isLeft());
+ compareBetweenCreatedToSent(parentGroupTypeDefinition, addParentGroupTypeResult.left().value());
+
+ groupTypeDefinition.setDerivedFrom("org.openecomp.groups.Parents");
+ Either<GroupTypeDefinition, StorageOperationStatus> upgradeResult = groupTypeOperation.upgradeGroupType(groupTypeDefinition, groupTypeDefinition, true);
+ assertNotNull(upgradeResult);
+ assertTrue(upgradeResult.isLeft());
+ assertEquals(groupTypeDefinition, upgradeResult.left().value());
+ }
+
+
+ private GroupTypeData getOrCreateRootGroupTypeNode() {
+ Either<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), TOSCA_GROUPS_ROOT, GroupTypeData.class);
+ if(groupTypeResult.isLeft()) {
+ return groupTypeResult.left().value();
+ }
+
+ return createRootGroupTypeNode();
+ }
+
+ private GroupTypeData createRootGroupTypeNode() {
+ GroupTypeDefinition rootGroupDefinition = createRootGroupDefinition();
+ Either<GroupTypeDefinition, StorageOperationStatus> addGroupTypeResult = groupTypeOperation.addGroupType(rootGroupDefinition, true);
+ assertEquals("check group type added", true, addGroupTypeResult.isLeft());
+
+ Either<GroupTypeData, TitanOperationStatus> groupTypeResult = titanDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), rootGroupDefinition.getType(), GroupTypeData.class);
+ return extractVal(groupTypeResult);
+ }
+
+ private GroupTypeDefinition createRootGroupDefinition() {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDescription("The TOSCA Group Type all other TOSCA Group Types derive from");
+ groupTypeDefinition.setType(TOSCA_GROUPS_ROOT);
+ return groupTypeDefinition;
+ }
+
+ private GroupTypeDefinition createGroupType(String type) {
+ GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition();
+ groupTypeDefinition.setDescription("description for type " + type);
+ groupTypeDefinition.setType(type);
+ return groupTypeDefinition;
+ }
+
+ private CapabilityTypeDefinition createCapabilityType() {
+ CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition();
+ capabilityTypeDefinition.setDescription("ability to expose routing information of the internal network");
+ capabilityTypeDefinition.setType("org.openecomp.capabilities.VLANAssignment");
+ capabilityTypeDefinition.setVersion("1.0");
+
+ Map<String, PropertyDefinition> properties = new HashMap<>();
+ properties.put("vfc_instance_group_reference",
+ buildProperty("vfc_instance_group_reference", null, "Ability to recognize capability per vfc instance group on vnf instance"));
+
+ capabilityTypeDefinition.setProperties(properties);
+
+ Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityTypeResult = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition, true);
+ assertEquals("check capability type added", true, addCapabilityTypeResult.isLeft());
+
+ CapabilityTypeDefinition capabilityTypeAdded = addCapabilityTypeResult.left().value();
+ compareBetweenCreatedToSent(capabilityTypeDefinition, capabilityTypeAdded);
+
+ return capabilityTypeDefinition;
+ }
+
+ private PropertyDefinition buildProperty(String name, String defaultValue, String description) {
+ PropertyDefinition property = new PropertyDefinition();
+ property.setName(name);
+ property.setDefaultValue(defaultValue);
+ property.setRequired(true);
+ property.setDescription(description);
+ property.setType(ToscaType.STRING.name().toLowerCase());
+
+ return property;
+ }
+
+ private void compareBetweenCreatedToSent(CapabilityTypeDefinition expected, CapabilityTypeDefinition actual) {
+ assertEquals(expected.getDerivedFrom(), actual.getDerivedFrom());
+ assertEquals(expected.getType(), actual.getType());
+ assertEquals(expected.getDescription(), actual.getDescription());
+ }
+
+ private void compareBetweenCreatedToSent(GroupTypeDefinition expected, GroupTypeDefinition actual) {
+ assertEquals(expected.getType(), actual.getType());
+ assertEquals(expected.getDescription(), actual.getDescription());
+ }
+
+ private <T> void validate(Either<T, TitanOperationStatus> result) {
+ extractVal(result);
+ }
+
+ private <T> T extractVal(Either<T, TitanOperationStatus> result) {
+ assertTrue(result.isLeft());
+ T t = result.left().value();
+ assertNotNull(t);
+
+ return t;
+ }
+
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java
index 8b4ebbdaf8..05b9ec1b89 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperationTest.java
@@ -20,13 +20,12 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyMap;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Matchers.anyMap;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
@@ -45,6 +44,7 @@ import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation;
import org.openecomp.sdc.be.resources.data.HeatParameterData;
import org.openecomp.sdc.be.resources.data.HeatParameterValueData;
@@ -103,7 +103,7 @@ public class HeatParametersOperationTest extends ModelTestBase {
Either<GraphRelation, TitanOperationStatus> relationResult = Either.left(graphRelation);
when(titanGenericDao.createNode(any(HeatParameterData.class), eq(HeatParameterData.class))).thenReturn(either);
- when(titanGenericDao.createRelation(any(GraphNode.class), any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult);
+ when(titanGenericDao.createRelation(any(GraphNode.class), (GraphNode) any(GraphNode.class), eq(GraphEdgeLabels.HEAT_PARAMETER), anyMap())).thenReturn(relationResult);
StorageOperationStatus result = heatParametersOperation.addPropertiesToGraph(parameters, "resourceId.artifactId", NodeTypeEnum.ArtifactRef);
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java
index 516ee51bab..c7e59006cf 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperationTest.java
@@ -20,40 +20,51 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Iterator;
-
-import javax.annotation.Resource;
-
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PolicyTypeDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.openecomp.sdc.be.resources.data.PolicyTypeData;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
+import java.util.Iterator;
+import java.util.List;
+import java.util.stream.Stream;
-import fj.data.Either;
+import static com.google.common.collect.Sets.newHashSet;
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
-
public class PolicyTypeOperationTest extends ModelTestBase {
- @Resource(name = "policy-type-operation")
+ private static final String NULL_STRING = null;
+ @Autowired
private PolicyTypeOperation policyTypeOperation;
+ @Autowired
+ private TitanGenericDao titanGenericDao;
+
@BeforeClass
public static void setupBeforeClass() {
ModelTestBase.init();
@@ -99,17 +110,269 @@ public class PolicyTypeOperationTest extends ModelTestBase {
assertTrue(eitherPolicyTypeFetched.isLeft());
PolicyTypeDefinition policyTypeFetched = eitherPolicyTypeFetched.left().value();
assertEquals(policyTypeFetched.toString(), policyTypeCreated.toString());
+ }
+
+ @Test
+ public void testGetLatestPolicyTypeByType_derivedFromFetchedCorrectly() {
+ PolicyTypeDefinition rootPolicyType = createRootPolicyTypeOnGraph();
+ String derivedFromRootType = rootPolicyType.getType();
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", derivedFromRootType);
+ policyTypeOperation.addPolicyType(policyType1);
+ Either<PolicyTypeDefinition, StorageOperationStatus> eitherPolicyTypeFetched = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType());
+ assertThat(eitherPolicyTypeFetched.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType());
+ }
+
+ @Test
+ public void testGetLatestPolicyTypeByType_whenGettingTypeGetPropertiesFromAllDerivedFromChain_policyTypeHasNoDirectProps() {
+ PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string");
+ PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string");
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", null, prop1, prop2);
+ PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.type2", "desc3", policyType1.getType(), null);
+ addPolicyTypesToDB(policyType1, policyType2);
+ Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyType2 = policyTypeOperation.getLatestPolicyTypeByType(policyType2.getType());
+ assertThat(latestPolicyType2.isLeft());
+ assertThat(latestPolicyType2.left().value().getProperties())
+ .usingElementComparatorOnFields("defaultValue", "name", "type")
+ .containsExactlyInAnyOrder(prop1, prop2);
+ }
+
+ @Test
+ public void testGetLatestPolicyTypeByType_whenGettingTypeGetPropertiesFromAllDerivedFromChain() {
+ PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string");
+ PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string");
+ PropertyDefinition prop3 = createSimpleProperty("val3", "prop3", "string");
+
+ PolicyTypeDefinition rootPolicyType = createPolicyTypeDef(prop1);
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", rootPolicyType.getType(), null);
+ PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.type2", "desc2", policyType1.getType(), prop2);
+ PolicyTypeDefinition policyType3 = createPolicyTypeDef("tosca.policies.type3", "desc3", policyType2.getType(), null);
+ PolicyTypeDefinition policyType4 = createPolicyTypeDef("tosca.policies.type4", "desc4", policyType3.getType(), prop3);
+
+ addPolicyTypesToDB(rootPolicyType, policyType1, policyType2, policyType3, policyType4);
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyType3 = policyTypeOperation.getLatestPolicyTypeByType(policyType4.getType());
+ assertThat(latestPolicyType3.isLeft());
+ assertThat(latestPolicyType3.left().value().getProperties())
+ .usingElementComparatorOnFields("defaultValue", "name", "type")
+ .containsExactlyInAnyOrder(prop1, prop2, prop3);
+ }
+
+ @Test
+ public void getAllPolicyTypes_noPolicies() {
+ Either<List<PolicyTypeDefinition>, StorageOperationStatus> allPolicyTypes = policyTypeOperation.getAllPolicyTypes(null);
+ assertThat(allPolicyTypes.isRight());
+ assertThat(allPolicyTypes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ }
+
+ @Test
+ public void getAllPolicyTypes() {
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef();
+ PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.test1", "desc1", "tosca.policies.Root");
+ addPolicyTypesToDB(policyType1, policyType2);
+ Either<List<PolicyTypeDefinition>, StorageOperationStatus> allPolicyTypesWithNoExcluded = policyTypeOperation.getAllPolicyTypes(null);
+ assertThat(allPolicyTypesWithNoExcluded.left().value()).hasSize(2);
+ assertThat(allPolicyTypesWithNoExcluded.left().value()).usingElementComparatorOnFields("uniqueId", "description", "version", "type")
+ .containsExactlyInAnyOrder(policyType1, policyType2);
+ }
+
+ @Test
+ public void getAllPolicyTypes_whenPassingExcludedTypeList_dontReturnExcludedTypes() {
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef();
+ PolicyTypeDefinition policyType2 = createPolicyTypeDef("tosca.policies.test1", "desc1", "tosca.policies.Root");
+ PolicyTypeDefinition policyType3 = createPolicyTypeDef("tosca.policies.test2", "desc2", "tosca.policies.Root");
+ policyTypeOperation.addPolicyType(policyType1);
+ policyTypeOperation.addPolicyType(policyType2);
+ policyTypeOperation.addPolicyType(policyType3);
+ Either<List<PolicyTypeDefinition>, StorageOperationStatus> allPolicyTypes = policyTypeOperation.getAllPolicyTypes(newHashSet("tosca.policies.test1", "tosca.policies.test2"));
+ assertThat(allPolicyTypes.left().value()).hasSize(1);
+ assertThat(allPolicyTypes.left().value()).usingElementComparatorOnFields("type")
+ .containsExactly(policyType1);
+ }
+
+ @Test
+ public void addPolicyType_whenDerivedFromNodeNotExist_returnNotFound() {
+ PolicyTypeDefinition type1 = createPolicyTypeDef("tosca.policies.type1", "desc1", "derivedFrom");
+ Either<PolicyTypeDefinition, StorageOperationStatus> addedPolicyTypeResult = policyTypeOperation.addPolicyType(type1);
+ assertThat(addedPolicyTypeResult.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ }
+
+ @Test//bug379696
+ public void addPolicyType_derivedFromAddedCorrectly() {
+ PolicyTypeDefinition rootPolicyType = createRootPolicyTypeOnGraph();
+ String derivedFromRootType = rootPolicyType.getType();
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("tosca.policies.type1", "desc1", derivedFromRootType);
+ Either<PolicyTypeDefinition, StorageOperationStatus> addedPolicyTypeResult = policyTypeOperation.addPolicyType(policyType1);
+ assertThat(addedPolicyTypeResult.isLeft()).isTrue();
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> fetchedPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType());
+ PolicyTypeDefinition fetchedPolicyTypeVal = fetchedPolicyType.left().value();
+ assertThat(fetchedPolicyTypeVal.getDerivedFrom()).isEqualTo(derivedFromRootType);
+ verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, fetchedPolicyTypeVal.getUniqueId());
+
+ }
+
+ @Test
+ public void updatePolicyType_returnNotFoundErrorIfTryingToUpdateANonExistingType() {
+ PolicyTypeDefinition currType = createPolicyTypeDef();
+ PolicyTypeDefinition updatedType = createPolicyTypeDef();
+ Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyTypeRes = policyTypeOperation.updatePolicyType(updatedType, currType);
+ assertThat(updatePolicyTypeRes.right().value()).isEqualTo(StorageOperationStatus.NOT_FOUND);
+ }
+ @Test
+ public void updatePolicyType_basicFields() {
+ PolicyTypeDefinition createdType = createPolicyTypeDef("type1", "description1", NULL_STRING);
+ Either<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(createdType);
+
+ PolicyTypeDefinition updatedType = createPolicyTypeDef("type1", "description2", NULL_STRING);
+ policyTypeOperation.updatePolicyType(updatedType, currPolicyType.left().value());
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> fetchedUpdatedType = policyTypeOperation.getLatestPolicyTypeByType(createdType.getType());
+ PolicyTypeDefinition fetchedPolicyType = fetchedUpdatedType.left().value();
+ assertThat(fetchedPolicyType.getProperties()).isEmpty();
+ assertThat(fetchedPolicyType)
+ .isEqualToIgnoringGivenFields(updatedType, "properties");
+
+ }
+
+ @Test
+ public void updatePolicyType_updateProperties() {
+ PropertyDefinition prop1 = createSimpleProperty("val1", "prop1", "string");
+ PolicyTypeDefinition policyType = createPolicyTypeDef(prop1);
+ Either<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType);
+
+ PropertyDefinition updatedProp1 = duplicateProperty(prop1, "newVal1", "int");
+ PropertyDefinition prop2 = createSimpleProperty("val2", "prop2", "string");
+ PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef(updatedProp1, prop2);
+
+ policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value());
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> fetchedUpdatedType = policyTypeOperation.getLatestPolicyTypeByType(policyType.getType());
+ assertThat(fetchedUpdatedType.left().value().getProperties())
+ .usingElementComparatorOnFields("name", "defaultValue", "type")
+ .containsExactlyInAnyOrder(updatedProp1, prop2);
+
+ }
+
+ @Test
+ public void updatePolicyType_derivedFrom_whenNoPrevDerivedFrom_updateToNewDerivedFrom() {
+ PolicyTypeDefinition rootPolicyType = createPolicyTypeDef();
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", NULL_STRING);
+ PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", rootPolicyType.getType());
+ policyTypeOperation.addPolicyType(rootPolicyType);
+ Either<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1);
+ policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value());
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType());
+ assertThat(latestPolicyType.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType());
+ verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, latestPolicyType.left().value().getUniqueId());
+ }
+
+ @Test
+ public void updatePolicyType_derivedFrom_updateToNullDerivedFrom_derivedFromDeleted() {
+ PolicyTypeDefinition rootPolicyType = createPolicyTypeDef();
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", rootPolicyType.getType());
+ PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", null, new PropertyDefinition[]{});
+ policyTypeOperation.addPolicyType(rootPolicyType);
+ Either<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1);
+
+ policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value());
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType());
+ assertThat(latestPolicyType.left().value().getDerivedFrom()).isNull();
+ verifyDerivedFromRelationDoesntExist(latestPolicyType.left().value().getUniqueId());
+ }
+
+ @Test
+ public void updatePolicyType_updateDerivedFrom() {
+ PolicyTypeDefinition rootPolicyType = createPolicyTypeDef();
+ PolicyTypeDefinition derivedType1 = createPolicyTypeDef("derivedType1", "descr", NULL_STRING);
+ PolicyTypeDefinition policyType1 = createPolicyTypeDef("type1", "descr", derivedType1.getType());
+ PolicyTypeDefinition updatedPolicyType = createPolicyTypeDef("type1", "descr", rootPolicyType.getType());
+
+ policyTypeOperation.addPolicyType(rootPolicyType);
+ policyTypeOperation.addPolicyType(derivedType1);
+ Either<PolicyTypeDefinition, StorageOperationStatus> currPolicyType = policyTypeOperation.addPolicyType(policyType1);
+
+ policyTypeOperation.updatePolicyType(updatedPolicyType, currPolicyType.left().value());
+
+ Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyType = policyTypeOperation.getLatestPolicyTypeByType(policyType1.getType());
+ assertThat(latestPolicyType.left().value().getDerivedFrom()).isEqualTo(rootPolicyType.getType());
+ verifyDerivedFromNodeEqualsToRootPolicyType(rootPolicyType, latestPolicyType.left().value().getUniqueId());
+ }
+
+ private PropertyDefinition duplicateProperty(PropertyDefinition prop1, String updatedValue, String updatedType) {
+ PropertyDefinition updatedProp1 = new PropertyDefinition(prop1);
+ updatedProp1.setUniqueId(null);
+ updatedProp1.setDefaultValue(updatedValue);
+ updatedProp1.setType(updatedType);
+ return updatedProp1;
+ }
+
+ private PropertyDefinition createSimpleProperty(String defaultValue, String name, String type) {
+ PropertyDefinition prop1 = new PropertyDefinition();
+ prop1.setDefaultValue(defaultValue);
+ prop1.setName(name);
+ prop1.setType(type);
+ return prop1;
}
+ private void verifyDerivedFromNodeEqualsToRootPolicyType(PolicyTypeDefinition rootPolicyType, String parentPolicyId) {
+ Either<ImmutablePair<PolicyTypeData, GraphEdge>, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM,
+ NodeTypeEnum.PolicyType, PolicyTypeData.class);
+ assertThat(derivedFromRelation.left().value().getLeft().getPolicyTypeDataDefinition())
+ .isEqualToComparingFieldByField(rootPolicyType);
+ }
+
+ private void verifyDerivedFromRelationDoesntExist(String parentPolicyId) {
+ Either<ImmutablePair<PolicyTypeData, GraphEdge>, TitanOperationStatus> derivedFromRelation = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), parentPolicyId, GraphEdgeLabels.DERIVED_FROM,
+ NodeTypeEnum.PolicyType, PolicyTypeData.class);
+ assertThat(derivedFromRelation.right().value())
+ .isEqualTo(TitanOperationStatus.NOT_FOUND);
+ }
+
+ private PolicyTypeDefinition createRootPolicyTypeOnGraph() {
+ PolicyTypeDefinition rootPolicyType = createPolicyTypeDef();
+ policyTypeOperation.addPolicyType(rootPolicyType);
+ return rootPolicyType;
+
+ }
+
private PolicyTypeDefinition createPolicyTypeDef() {
+ return createPolicyTypeDef("tosca.policies.Root", "description: The TOSCA Policy Type all other TOSCA Policy Types derive from", null, new PropertyDefinition[]{});
+ }
+
+ private PolicyTypeDefinition createPolicyTypeDef(PropertyDefinition ... props) {
+ return createPolicyTypeDef("tosca.policies.Root", null, props);
+ }
+
+ private PolicyTypeDefinition createPolicyTypeDef(String type, String derivedFrom, PropertyDefinition ... props) {
+ PolicyTypeDefinition policyType = createPolicyTypeDef(type, "description: The TOSCA Policy Type all other TOSCA Policy Types derive from", derivedFrom);
+ policyType.setProperties(asList(props));
+ return policyType;
+ }
+
+ private PolicyTypeDefinition createPolicyTypeDef(String type, String description, String derivedFrom) {
+ return createPolicyTypeDef(type, description, derivedFrom, null);
+ }
+
+ private PolicyTypeDefinition createPolicyTypeDef(String type, String description, String derivedFrom, PropertyDefinition ... props) {
PolicyTypeDataDefinition policyTypeDataDefinition = new PolicyTypeDataDefinition();
- policyTypeDataDefinition.setDescription("description: The TOSCA Policy Type all other TOSCA Policy Types derive from");
- policyTypeDataDefinition.setType("tosca.policies.Root");
+ policyTypeDataDefinition.setDescription(description);
+ policyTypeDataDefinition.setType(type);
+ policyTypeDataDefinition.setDerivedFrom(derivedFrom);
PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeDataDefinition);
policyTypeDefinition.setHighestVersion(true);
policyTypeDefinition.setVersion("1.0");
+ if (props != null) {
+ policyTypeDefinition.setProperties(asList(props));
+ }
return policyTypeDefinition;
}
+ private void addPolicyTypesToDB(PolicyTypeDefinition ... policyTypeDefinitions) {
+ Stream.of(policyTypeDefinitions).forEach(policyTypeOperation::addPolicyType);
+ }
+
+
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java
index d862c56790..88f3a24b5d 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperationTest.java
@@ -20,19 +20,6 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -48,11 +35,21 @@ import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
public class PropertyOperationTest extends ModelTestBase {
TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
- PropertyOperation propertyOperation = new PropertyOperation(titanGenericDao);
+ PropertyOperation propertyOperation = new PropertyOperation(titanGenericDao, null);
@Before
public void setup() {
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java
index 53bd753fa3..6e9fdc2928 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaElementLifecycleOperationTest.java
@@ -45,6 +45,7 @@ import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
@@ -57,6 +58,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.catalog.CatalogComponent;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
@@ -65,6 +67,7 @@ import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
+import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.springframework.test.context.ContextConfiguration;
@@ -78,23 +81,23 @@ import fj.data.Either;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
public class ToscaElementLifecycleOperationTest extends ModelTestBase {
-
+
@javax.annotation.Resource
protected TitanDao titanDao;
@javax.annotation.Resource
private NodeTypeOperation nodeTypeOperation;
-
+
@javax.annotation.Resource
private TopologyTemplateOperation topologyTemplateOperation;
-
+
@javax.annotation.Resource
private ToscaElementLifecycleOperation lifecycleOperation;
-
+
String categoryName = "category";
String subcategory = "mycategory";
String outputDirectory = "C:\\Output";
-
+
@Rule
public TestName name = new TestName();
@@ -102,11 +105,12 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
public static void initLifecycleOperation() {
ModelTestBase.init();
}
-
+
private GraphVertex ownerVertex;
private GraphVertex modifierVertex;
private GraphVertex vfVertex;
private GraphVertex serviceVertex;
+ private GraphVertex rootVertex;
@Before
public void setupBefore() {
@@ -114,222 +118,271 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
createUsers();
createResourceCategory();
createServiceCategory();
- createRootNodeType();
+ GraphTestUtils.createRootCatalogVertex(titanDao);
+ rootVertex = createRootNodeType();
createNodeType("firstVf");
- createTopologyTemplate("firstService");
+ serviceVertex = createTopologyTemplate("firstService");
}
-
@Test
public void lifecycleTest() {
- Either<ToscaElement, StorageOperationStatus> res = lifecycleOperation
- .checkinToscaELement(LifecycleStateEnum.findState((String) vfVertex.getMetadataProperty(GraphPropertyEnum.STATE)),
- vfVertex.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
+ Either<ToscaElement, StorageOperationStatus> res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) vfVertex.getMetadataProperty(GraphPropertyEnum.STATE)), vfVertex.getUniqueId(), modifierVertex.getUniqueId(),
+ ownerVertex.getUniqueId());
StorageOperationStatus status;
-
+
assertTrue(res.isLeft());
+ // 1-node type
+ // 2-vf
+ // 3- service
+ verifyInCatalogData(3, null);
+
String id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
+ verifyInCatalogData(3, null);
+
PropertyDataDefinition prop55 = new PropertyDataDefinition();
prop55.setName("prop55");
prop55.setDefaultValue("def55");
-
+
status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop55, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
CapabilityDataDefinition cap1 = new CapabilityDataDefinition();
cap1.setName("cap1");
cap1.setDescription("create");
cap1.setUniqueId(UniqueIdBuilder.buildCapabilityUid(id, "cap1"));
-
+
status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILTIES, cap1, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
prop55.setDefaultValue("AAAAAAAA");
status = nodeTypeOperation.updateToscaDataOfToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop55, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
cap1.setDescription("update");
-
+
status = nodeTypeOperation.updateToscaDataOfToscaElement(id, EdgeLabelEnum.CAPABILITIES, VertexTypeEnum.CAPABILTIES, cap1, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
PropertyDataDefinition prop66 = new PropertyDataDefinition();
prop66.setName("prop66");
prop66.setDefaultValue("def66");
-
+
status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop66, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.certifyToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
+
+ verifyInCatalogData(3, null);
res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
+
+ verifyInCatalogData(4, null);
PropertyDataDefinition prop77 = new PropertyDataDefinition();
prop77.setName("prop77");
prop77.setDefaultValue("def77");
-
+
status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop77, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
PropertyDataDefinition prop88 = new PropertyDataDefinition();
prop88.setName("prop88");
prop88.setDefaultValue("def88");
-
+
status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop88, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.certifyToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
+ verifyInCatalogData(3, null);
res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
+
+ verifyInCatalogData(4, null);
PropertyDataDefinition prop99 = new PropertyDataDefinition();
prop99.setName("prop99");
prop99.setDefaultValue("def99");
-
+
status = nodeTypeOperation.addToscaDataToToscaElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop99, JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
+
res = lifecycleOperation.requestCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
status = nodeTypeOperation.deleteToscaDataElement(id, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, "prop99", JsonPresentationFields.NAME);
assertTrue(status == StorageOperationStatus.OK);
-
- //cancel certification
+
+ // cancel certification
res = lifecycleOperation.cancelOrFailCertification(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.startCertificationToscaElement(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
- //fail certification
+
+ // fail certification
res = lifecycleOperation.cancelOrFailCertification(id, modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
assertTrue(res.isLeft());
id = res.left().value().getUniqueId();
-
- //exportGraphMl(titanDao.getGraph().left().value());
-
+ verifyInCatalogData(4, null);
+ // exportGraphMl(titanDao.getGraph().left().value());
+
}
@Test
public void serviceConformanceLevelTest() {
- Either<ToscaElement, StorageOperationStatus> res = lifecycleOperation
- .checkinToscaELement(LifecycleStateEnum.findState((String) serviceVertex.getMetadataProperty(GraphPropertyEnum.STATE)),
- serviceVertex.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
-
+ Either<ToscaElement, StorageOperationStatus> res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) serviceVertex.getMetadataProperty(GraphPropertyEnum.STATE)), serviceVertex.getUniqueId(),
+ modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
+
assertTrue(res.isLeft());
String id = res.left().value().getUniqueId();
-
+
res = lifecycleOperation.checkoutToscaElement(id, ownerVertex.getUniqueId(), modifierVertex.getUniqueId());
assertTrue(res.isLeft());
-
+
String conformanceLevel = res.left().value().getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL).toString();
assertEquals(conformanceLevel, ModelTestBase.configurationManager.getConfiguration().getToscaConformanceLevel());
}
-
- private void createResourceCategory() {
+
+ @Test
+ public void catalogTest() {
+ // start position - 3 in catalog
+ List<String> expectedIds = new ArrayList<String>();
+ expectedIds.add(rootVertex.getUniqueId());
+ expectedIds.add(vfVertex.getUniqueId());
+ expectedIds.add(serviceVertex.getUniqueId());
+
+ verifyInCatalogData(3, expectedIds);
+ GraphVertex vertex4 = createTopologyTemplate("topTemp4");
+ expectedIds.add(vertex4.getUniqueId());
+ verifyInCatalogData(4, expectedIds);
+
+ Either<ToscaElement, StorageOperationStatus> res = lifecycleOperation.undoCheckout(vertex4.getUniqueId());
+ expectedIds.remove(vertex4.getUniqueId());
+ verifyInCatalogData(3, expectedIds);
+
+ vertex4 = createTopologyTemplate("topTemp4");
+ expectedIds.add(vertex4.getUniqueId());
+ verifyInCatalogData(4, expectedIds);
+
+ res = lifecycleOperation.checkinToscaELement(LifecycleStateEnum.findState((String) vertex4.getMetadataProperty(GraphPropertyEnum.STATE)), vertex4.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
+ Either<ToscaElement, StorageOperationStatus> certifyToscaElement = lifecycleOperation.certifyToscaElement(vertex4.getUniqueId(), modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
+ assertTrue(certifyToscaElement.isLeft());
+ expectedIds.remove(vertex4.getUniqueId());
+ String certifiedId = certifyToscaElement.left().value().getUniqueId();
+ expectedIds.add(certifiedId);
+ verifyInCatalogData(4, expectedIds);
+
+ res = lifecycleOperation.checkoutToscaElement(certifiedId, modifierVertex.getUniqueId(), ownerVertex.getUniqueId());
+ assertTrue(certifyToscaElement.isLeft());
+ expectedIds.add(res.left().value().getUniqueId());
+ verifyInCatalogData(5, expectedIds);
+ }
+
+ private void createResourceCategory() {
+
GraphVertex cat = new GraphVertex(VertexTypeEnum.RESOURCE_CATEGORY);
Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>();
String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.RESOURCE_CATEGORY);
cat.setUniqueId(catId);
- metadataProperties.put(GraphPropertyEnum.UNIQUE_ID,catId);
+ metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId);
metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName());
- metadataProperties.put(GraphPropertyEnum.NAME,categoryName);
+ metadataProperties.put(GraphPropertyEnum.NAME, categoryName);
metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
cat.setMetadataProperties(metadataProperties);
cat.updateMetadataJsonWithCurrentMetadataProperties();
-
+
GraphVertex subCat = new GraphVertex(VertexTypeEnum.RESOURCE_SUBCATEGORY);
metadataProperties = new HashMap<>();
String subCatId = UniqueIdBuilder.buildSubCategoryUid(cat.getUniqueId(), subcategory);
subCat.setUniqueId(subCatId);
- metadataProperties.put(GraphPropertyEnum.UNIQUE_ID,subCatId);
+ metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, subCatId);
metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName());
- metadataProperties.put(GraphPropertyEnum.NAME,subcategory);
+ metadataProperties.put(GraphPropertyEnum.NAME, subcategory);
+ metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory));
subCat.setMetadataProperties(metadataProperties);
subCat.updateMetadataJsonWithCurrentMetadataProperties();
-
+
Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat);
-
+
Either<GraphVertex, TitanOperationStatus> subCatRes = titanDao.createVertex(subCat);
-
+
TitanOperationStatus status = titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), EdgeLabelEnum.SUB_CATEGORY, new HashMap<>());
assertEquals(TitanOperationStatus.OK, status);
}
-
+
private void createServiceCategory() {
-
+
GraphVertex cat = new GraphVertex(VertexTypeEnum.SERVICE_CATEGORY);
Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>();
String catId = UniqueIdBuilder.buildComponentCategoryUid(categoryName, VertexTypeEnum.SERVICE_CATEGORY);
cat.setUniqueId(catId);
- metadataProperties.put(GraphPropertyEnum.UNIQUE_ID,catId);
+ metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId);
metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName());
- metadataProperties.put(GraphPropertyEnum.NAME,categoryName);
+ metadataProperties.put(GraphPropertyEnum.NAME, categoryName);
metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
cat.setMetadataProperties(metadataProperties);
cat.updateMetadataJsonWithCurrentMetadataProperties();
-
+
Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat);
-
+
assertTrue(catRes.isLeft());
}
-
- private TopologyTemplate createTopologyTemplate(String name) {
-
+
+ private GraphVertex createTopologyTemplate(String name) {
+
TopologyTemplate service = new TopologyTemplate();
String uniqueId = UniqueIdBuilder.buildResourceUniqueId();
service.setUniqueId(uniqueId);
@@ -337,28 +390,28 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name);
service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId);
service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1");
- service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(),ResourceTypeEnum.VF.name());
- service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(),ComponentTypeEnum.RESOURCE);
+ service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name());
+ service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE);
List<CategoryDefinition> categories = new ArrayList<>();
CategoryDefinition cat = new CategoryDefinition();
categories.add(cat);
cat.setName(categoryName);
service.setCategories(categories);
-
+
service.setComponentType(ComponentTypeEnum.SERVICE);
Either<TopologyTemplate, StorageOperationStatus> createRes = topologyTemplateOperation.createTopologyTemplate(service);
assertTrue(createRes.isLeft());
-
- Either<GraphVertex, TitanOperationStatus> getNodeTyeRes= titanDao.getVertexById(createRes.left().value().getUniqueId());
+
+ Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId());
assertTrue(getNodeTyeRes.isLeft());
-
- serviceVertex = getNodeTyeRes.left().value();
-
- return service;
+
+ // serviceVertex = getNodeTyeRes.left().value();
+
+ return getNodeTyeRes.left().value();
}
-
+
private <T extends ToscaDataDefinition> NodeType createNodeType(String nodeTypeName) {
-
+
NodeType vf = new NodeType();
String uniqueId = UniqueIdBuilder.buildResourceUniqueId();
vf.setUniqueId(uniqueId);
@@ -366,8 +419,8 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), nodeTypeName);
vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId);
vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1");
- vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(),ResourceTypeEnum.VF.name());
- vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(),ComponentTypeEnum.RESOURCE);
+ vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name());
+ vf.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE);
List<CategoryDefinition> categories = new ArrayList<>();
CategoryDefinition cat = new CategoryDefinition();
categories.add(cat);
@@ -378,95 +431,90 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
subCategories.add(subCat);
cat.setSubcategories(subCategories);
vf.setCategories(categories);
-
-
+
List<String> derivedFrom = new ArrayList<>();
derivedFrom.add("root");
vf.setDerivedFrom(derivedFrom);
-
-// Map<String, PropertyDataDefinition> properties = new HashMap<>();
-// PropertyDataDefinition prop1 = new PropertyDataDefinition();
-// prop1.setName("prop1");
-// prop1.setDefaultValue("def1");
-//
-// properties.put("prop1", prop1);
-//
-// PropertyDataDefinition prop2 = new PropertyDataDefinition();
-// prop2.setName("prop2");
-// prop2.setDefaultValue("def2");
-// properties.put("prop2", prop2);
-//
-// PropertyDataDefinition prop3 = new PropertyDataDefinition();
-// prop3.setName("prop3");
-// prop3.setDefaultValue("def3");
-// properties.put("prop3", prop3);
-//
-// vf.setProperties(properties);
- vf.setComponentType(ComponentTypeEnum.RESOURCE);
+
+ // Map<String, PropertyDataDefinition> properties = new HashMap<>();
+ // PropertyDataDefinition prop1 = new PropertyDataDefinition();
+ // prop1.setName("prop1");
+ // prop1.setDefaultValue("def1");
+ //
+ // properties.put("prop1", prop1);
+ //
+ // PropertyDataDefinition prop2 = new PropertyDataDefinition();
+ // prop2.setName("prop2");
+ // prop2.setDefaultValue("def2");
+ // properties.put("prop2", prop2);
+ //
+ // PropertyDataDefinition prop3 = new PropertyDataDefinition();
+ // prop3.setName("prop3");
+ // prop3.setDefaultValue("def3");
+ // properties.put("prop3", prop3);
+ //
+ // vf.setProperties(properties);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf);
assertTrue(createVFRes.isLeft());
-
- Either<GraphVertex, TitanOperationStatus> getNodeTyeRes= titanDao.getVertexById(createVFRes.left().value().getUniqueId());
+
+ Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId());
assertTrue(getNodeTyeRes.isLeft());
-
+
vfVertex = getNodeTyeRes.left().value();
-
-
-
- List<PropertyDataDefinition> addProperties = new ArrayList<>();
- PropertyDataDefinition prop11 = new PropertyDataDefinition();
- prop11.setName("prop11");
- prop11.setDefaultValue("def11");
-
- addProperties.add(prop11);
-
- PropertyDataDefinition prop22 = new PropertyDataDefinition();
- prop22.setName("prop22");
- prop22.setDefaultValue("def22");
- addProperties.add(prop22);
-
- StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME);
- assertTrue(status == StorageOperationStatus.OK);
-
- PropertyDataDefinition prop33 = new PropertyDataDefinition();
- prop33.setName("prop33");
- prop33.setDefaultValue("def33");
-
- status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop33, JsonPresentationFields.NAME);
- assertTrue(status == StorageOperationStatus.OK);
-
- PropertyDataDefinition prop44 = new PropertyDataDefinition();
- prop44.setName("prop44");
- prop44.setDefaultValue("def44");
-
- status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME);
- assertTrue(status == StorageOperationStatus.OK);
-
-
- PropertyDataDefinition capProp = new PropertyDataDefinition();
- capProp.setName( "capProp");
- capProp.setDefaultValue( "capPropDef");
-
- MapDataDefinition dataToCreate = new MapPropertiesDataDefinition();
- dataToCreate.put("capProp", capProp);
-
- Map<String, MapDataDefinition> capProps = new HashMap();
- capProps.put("capName", dataToCreate);
-
- Either<GraphVertex, StorageOperationStatus> res = nodeTypeOperation.assosiateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps);
-
+
+ List<PropertyDataDefinition> addProperties = new ArrayList<>();
+ PropertyDataDefinition prop11 = new PropertyDataDefinition();
+ prop11.setName("prop11");
+ prop11.setDefaultValue("def11");
+
+ addProperties.add(prop11);
+
+ PropertyDataDefinition prop22 = new PropertyDataDefinition();
+ prop22.setName("prop22");
+ prop22.setDefaultValue("def22");
+ addProperties.add(prop22);
+
+ StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME);
+ assertTrue(status == StorageOperationStatus.OK);
+
+ PropertyDataDefinition prop33 = new PropertyDataDefinition();
+ prop33.setName("prop33");
+ prop33.setDefaultValue("def33");
+
+ status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop33, JsonPresentationFields.NAME);
+ assertTrue(status == StorageOperationStatus.OK);
+
+ PropertyDataDefinition prop44 = new PropertyDataDefinition();
+ prop44.setName("prop44");
+ prop44.setDefaultValue("def44");
+
+ status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME);
+ assertTrue(status == StorageOperationStatus.OK);
+
+ PropertyDataDefinition capProp = new PropertyDataDefinition();
+ capProp.setName("capProp");
+ capProp.setDefaultValue("capPropDef");
+
+ MapDataDefinition dataToCreate = new MapPropertiesDataDefinition();
+ dataToCreate.put("capProp", capProp);
+
+ Map<String, MapDataDefinition> capProps = new HashMap();
+ capProps.put("capName", dataToCreate);
+
+ Either<GraphVertex, StorageOperationStatus> res = nodeTypeOperation.assosiateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps);
+
// exportGraphMl(titanDao.getGraph().left().value());
-
- List<String> pathKeys = new ArrayList<>();
- pathKeys.add("capName");
- capProp.setDefaultValue( "BBBB");
- status = nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES,
- capProp, pathKeys, JsonPresentationFields.NAME);
+
+ List<String> pathKeys = new ArrayList<>();
+ pathKeys.add("capName");
+ capProp.setDefaultValue("BBBB");
+ status = nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME);
return vf;
}
-
- private void createRootNodeType() {
-
+
+ private GraphVertex createRootNodeType() {
+
NodeType vf = new NodeType();
String uniqueId = UniqueIdBuilder.buildResourceUniqueId();
vf.setUniqueId(uniqueId);
@@ -475,11 +523,11 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root");
vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId);
vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0");
- vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(),ResourceTypeEnum.VFC.name());
+ vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name());
vf.getMetadata().put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name());
vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root");
vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true);
-
+
List<CategoryDefinition> categories = new ArrayList<>();
CategoryDefinition cat = new CategoryDefinition();
categories.add(cat);
@@ -490,42 +538,42 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
subCategories.add(subCat);
cat.setSubcategories(subCategories);
vf.setCategories(categories);
-
-
+
List<String> derivedFrom = new ArrayList<>();
vf.setDerivedFrom(derivedFrom);
-
- Map<String, PropertyDataDefinition> properties = new HashMap<>();
- PropertyDataDefinition prop1 = new PropertyDataDefinition();
- prop1.setName("derived1");
- prop1.setDefaultValue("deriveddef1");
-
- properties.put("derived1", prop1);
-
- PropertyDataDefinition prop2 = new PropertyDataDefinition();
- prop2.setUniqueId("derived2");
- prop2.setName("deriveddef2");
- properties.put("derived2", prop2);
-
- PropertyDataDefinition prop3 = new PropertyDataDefinition();
- prop3.setName("derived3");
- prop3.setDefaultValue("deriveddef3");
- properties.put("derived3", prop3);
-
- vf.setProperties(properties);
- vf.setComponentType(ComponentTypeEnum.RESOURCE);
+
+ Map<String, PropertyDataDefinition> properties = new HashMap<>();
+ PropertyDataDefinition prop1 = new PropertyDataDefinition();
+ prop1.setName("derived1");
+ prop1.setDefaultValue("deriveddef1");
+
+ properties.put("derived1", prop1);
+
+ PropertyDataDefinition prop2 = new PropertyDataDefinition();
+ prop2.setUniqueId("derived2");
+ prop2.setName("deriveddef2");
+ properties.put("derived2", prop2);
+
+ PropertyDataDefinition prop3 = new PropertyDataDefinition();
+ prop3.setName("derived3");
+ prop3.setDefaultValue("deriveddef3");
+ properties.put("derived3", prop3);
+
+ vf.setProperties(properties);
+ vf.setComponentType(ComponentTypeEnum.RESOURCE);
Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf);
assertTrue(createVFRes.isLeft());
-
- Either<GraphVertex, TitanOperationStatus> getNodeTyeRes= titanDao.getVertexById(createVFRes.left().value().getUniqueId());
+
+ Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId());
assertTrue(getNodeTyeRes.isLeft());
+ return getNodeTyeRes.left().value();
}
private void createUsers() {
-
+
GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER);
ownerV.setUniqueId("user1");
-
+
Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>();
metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId());
metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName());
@@ -535,12 +583,12 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
ownerV.setJson(new HashMap<>());
Either<GraphVertex, TitanOperationStatus> createUserRes = titanDao.createVertex(ownerV);
assertTrue(createUserRes.isLeft());
-
+
ownerVertex = createUserRes.left().value();
-
+
GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER);
modifierV.setUniqueId("user2");
-
+
metadataProperties = new HashMap<>();
metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId());
metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName());
@@ -550,12 +598,24 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
modifierV.setJson(new HashMap<>());
createUserRes = titanDao.createVertex(modifierV);
assertTrue(createUserRes.isLeft());
-
+
modifierVertex = createUserRes.left().value();
-
+
Either<GraphVertex, TitanOperationStatus> getOwnerRes = lifecycleOperation.findUser(ownerVertex.getUniqueId());
assertTrue(getOwnerRes.isLeft());
-
+
+ }
+
+ public void verifyInCatalogData(int expected, List<String> expectedIds) {
+
+ Either<List<CatalogComponent>, StorageOperationStatus> highestResourcesRes = topologyTemplateOperation.getElementCatalogData();
+ assertTrue(highestResourcesRes.isLeft());
+ List<CatalogComponent> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ assertEquals(expected, highestResources.stream().count());
+ if (expectedIds != null) {
+ highestResources.forEach(a -> assertTrue(expectedIds.contains(a.getUniqueId())));
+ }
}
@After
@@ -594,5 +654,5 @@ public class ToscaElementLifecycleOperationTest extends ModelTestBase {
return result;
}
-
+
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java
index d5425504e6..e15d784c7a 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java
@@ -1,19 +1,19 @@
package org.openecomp.sdc.be.model.tosca.converters;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import com.google.gson.JsonObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import javax.json.Json;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-
-import com.google.gson.JsonObject;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
public class DataTypePropertyConverterTest {
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java
index 5367dcb8a3..7e9388ee1b 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/ToscaFloatConverterTest.java
@@ -2,22 +2,73 @@ package org.openecomp.sdc.be.model.tosca.converters;
import org.junit.Test;
+import java.util.Collections;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.Assert.assertNull;
+
public class ToscaFloatConverterTest {
- private ToscaFloatConverter createTestSubject() {
- return ToscaFloatConverter.getInstance();
- }
+ @Test
+ public void convertEmptyString_returnNull() {
+ assertNull(executeFloatConversion(""));
+ }
+
+ @Test
+ public void convertNull_returnNull() {
+ assertNull(executeFloatConversion(null));
+ }
+
+ @Test
+ public void convertWholeNumber() {
+ assertThat(executeFloatConversion("1234"))
+ .isEqualTo("1234");
+ }
+
+ @Test
+ public void convertFloatNumber() {
+ assertThat(executeFloatConversion("3.141"))
+ .isEqualTo("3.141");
+ }
+
+ @Test
+ public void convertNotValidFloat() {
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("123.55.66"));
+ }
+
+ @Test
+ public void convertNumericWithSpecialChars() {
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("123,55"));
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("123&55"));
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("123$$55"));
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("123#55"));
+ }
+
+ @Test
+ public void convertNonNumeric() {
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("1234ABC"));
+ }
-
- @Test
- public void testGetInstance() throws Exception {
- ToscaFloatConverter result;
+ @Test
+ public void convertNumericWithCapitalFloatSign() {
+ assertThat(executeFloatConversion("1234F"))
+ .isEqualTo("1234");
+ }
- // default test
- result = ToscaFloatConverter.getInstance();
- }
+ @Test
+ public void convertNumericWithSmallLetterFloatSign() {
+ assertThat(executeFloatConversion("1234f"))
+ .isEqualTo("1234");
+ }
-
+ @Test
+ public void convertNumericWithFloatSignNotAtTheEnd_ThrowsException() {
+ assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> executeFloatConversion("12f34"));
+ }
+ private String executeFloatConversion(String s) {
+ return ToscaFloatConverter.getInstance().convert(s, null, Collections.emptyMap());
+ }
} \ No newline at end of file
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java
new file mode 100644
index 0000000000..6f33b19de3
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/validators/MapValidatorTest.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.model.tosca.validators;
+
+import org.junit.Test;
+
+import java.util.Collections;
+
+import static org.junit.Assert.*;
+
+public class MapValidatorTest {
+
+ @Test
+ public void isValid_nonMapString() {
+ assertFalse(MapValidator.getInstance().isValid("abc", "string", Collections.emptyMap()));
+ assertFalse(MapValidator.getInstance().isValid("1", "string", Collections.emptyMap()));
+ }
+} \ No newline at end of file
diff --git a/catalog-model/src/test/resources/application-context-test.xml b/catalog-model/src/test/resources/application-context-test.xml
index 58de573b55..ccde197a7f 100644
--- a/catalog-model/src/test/resources/application-context-test.xml
+++ b/catalog-model/src/test/resources/application-context-test.xml
@@ -12,7 +12,8 @@
org.openecomp.sdc.be.dao.jsongraph,
org.openecomp.sdc.be.model.cache,
org.openecomp.sdc.be.dao.titan,
- org.openecomp.sdc.be.dao.cassandra">
+ org.openecomp.sdc.be.dao.cassandra,
+ org.openecomp.sdc.be.model.jsontitan.utils">
</context:component-scan>
diff --git a/catalog-ui/configurations/dev.js b/catalog-ui/configurations/dev.js
index 65d62c83e0..e15dae6b94 100644
--- a/catalog-ui/configurations/dev.js
+++ b/catalog-ui/configurations/dev.js
@@ -47,7 +47,6 @@ const SDC_CONFIG = {
"GET_lifecycle_state_CERTIFICATIONREQUEST":"lifecycleState/CERTIFICATIONREQUEST",
"GET_lifecycle_state_UNDOCHECKOUT":"lifecycleState/UNDOCHECKOUT",
"root": "/sdc1/feProxy/rest",
- "no_proxy_root": "/sdc1/rest",
"PUT_service": "/v1/catalog/services/:id/metadata",
"GET_download_artifact": "/v1/catalog/",
"GET_SDC_Version": "/version",
@@ -59,11 +58,14 @@ const SDC_CONFIG = {
"GET_resource_artifact_types": "/v1/artifactTypes",
"GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
"GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
- "kibana": "/sdc1/kibanaProxy/"
+ "kibana": "/sdc1/kibanaProxy/",
+ "services_api_root": "/v1/catalog/services/",
+ "create_policy_instance":"/v1/catalog/:entityType/:entityId/policies/:policyId",
+ "CRUD_policy":"/v1/catalog/:entityType/policies/:policyId",
},
"resourceTypesFilter":{
- "resource":["CP","VFC","VL"],
- "service":["CP","VF","VL", "PNF","CVFC","SERVICE", "Configuration"]
+ "resource":["CP","VFC","VL","CVFC","GROUP","POLICY"],
+ "service":["CP","VF","VL", "PNF","CR","CVFC","SERVICE","Configuration","GROUP","POLICY"]
},
"logConfig": {
"minLogLevel": "debug",
diff --git a/catalog-ui/configurations/menu.js b/catalog-ui/configurations/menu.js
index 36f9d8076a..9bcf89c0c1 100644
--- a/catalog-ui/configurations/menu.js
+++ b/catalog-ui/configurations/menu.js
@@ -203,8 +203,9 @@ const SDC_MENU_CONFIG = {
"alertMessages": {
"lifecycleState/UNDOCHECKOUT": {"title": "Delete Version Confirmation", "message": "Are you sure you want to delete this version?"},
"exitWithoutSaving": {"title": "Exit Without Saving Confirmation", "message": "All unsaved changes will be lost. Are you sure you want to exit this page?"},
- "deleteInstance": {"title": "Delete Confirmation", "message": "Are you sure you would like to delete %1 ?"},
- "deleteInput": {"title": "Delete Confirmation", "message": "Are you sure you would like to delete %1 ?"}
+ "upgradeInstance": {"title": "Switch Versions", "message": "Switching versions will erase service paths: %1. Are you sure you want to proceed?"},
+ "deleteInstance": {"title": "Delete Confirmation", "message": "Are you sure you would like to delete %1?"},
+ "deleteInput": {"title": "Delete Confirmation", "message": "Are you sure you would like to delete %1?"}
},
"statuses": {
"inDesign": {
@@ -346,6 +347,15 @@ const SDC_MENU_CONFIG = {
{"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
{"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
],
+ "CR":[
+ {"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
+ {"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
+ {"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
+ {"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
+ {"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"},
+ {"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
+ {"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
+ ],
"SERVICE":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
diff --git a/catalog-ui/configurations/prod.js b/catalog-ui/configurations/prod.js
index f08bfa3497..adbd650378 100644
--- a/catalog-ui/configurations/prod.js
+++ b/catalog-ui/configurations/prod.js
@@ -59,11 +59,14 @@ const SDC_CONFIG = {
"GET_resource_artifact_types": "/v1/artifactTypes",
"GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
"GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
- "kibana": "/sdc1/kibanaProxy/"
+ "kibana": "/sdc1/kibanaProxy/",
+ "services_api_root": "/v1/catalog/services/",
+ "create_policy_instance":"/v1/catalog/:entityType/:entityId/policies/:policyId",
+ "CRUD_policy":"/v1/catalog/:entityType/policies/:policyId",
},
"resourceTypesFilter":{
- "resource":["CP","VFC","VL"],
- "service":["CP","VF","VL", "PNF","CVFC","SERVICE","Configuration"]
+ "resource":["CP","VFC","VL","CVFC","GROUP","POLICY"],
+ "service":["CP","VF","VL", "PNF","CR","CVFC","SERVICE","Configuration","GROUP","POLICY"]
},
"logConfig": {
"minLogLevel": "debug",
diff --git a/catalog-ui/package.json b/catalog-ui/package.json
index 3b6223d27d..39049bea38 100644
--- a/catalog-ui/package.json
+++ b/catalog-ui/package.json
@@ -45,7 +45,7 @@
"raw-loader": "^0.5.1",
"sass-loader": "^4.1.1",
"script-loader": "^0.7.0",
- "sdc-ui": "1.6.9",
+ "sdc-ui": "1.6.22",
"source-map-loader": "^0.1.5",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
@@ -87,6 +87,7 @@
"angular-ui-notification": "^0.3.6",
"angular-ui-router": "^0.4.2",
"angular-uuid4": "^0.3.1",
+ "angular2-draggable": "1.1.0",
"angular2-uuid": "^1.1.1",
"animate.css": "^3.5.2",
"awesome-typescript-loader": "^3.0.8",
diff --git a/catalog-ui/pom.xml b/catalog-ui/pom.xml
index 1e14d9f60e..d6268c2631 100644
--- a/catalog-ui/pom.xml
+++ b/catalog-ui/pom.xml
@@ -2,7 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
-
+
<artifactId>catalog-ui</artifactId>
<packaging>pom</packaging>
diff --git a/catalog-ui/src/app/app.ts b/catalog-ui/src/app/app.ts
index e44e4eecb6..24665cccbc 100644
--- a/catalog-ui/src/app/app.ts
+++ b/catalog-ui/src/app/app.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,6 +22,7 @@
//import 'restangular';
//import 'angular-ui-router';
+import * as _ from "lodash";
import "reflect-metadata";
import 'ng-infinite-scroll';
import './modules/filters.ts';
@@ -57,10 +58,8 @@ import {ComponentServiceNg2} from "./ng2/services/component-services/component.s
import {ComponentMetadata} from "./models/component-metadata";
import {Categories} from "./models/categories";
import {IUserProperties} from "./models/user";
-import {SearchWithAutoCompleteComponent} from "./ng2/components/ui/search-with-autocomplete/search-with-autocomplete.component";
import {PluginFrameComponent} from "./ng2/components/ui/plugin/plugin-frame.component";
-
let moduleName:string = 'sdcApp';
let viewModelsModuleName:string = 'Sdc.ViewModels';
let directivesModuleName:string = 'Sdc.Directives';
@@ -146,13 +145,6 @@ _.each(hostedApplications, (hostedApp)=> {
// ===================== Hosted applications section ====================
export const ng1appModule:ng.IModule = angular.module(moduleName, dependentModules);
-angular.module('sdcApp').directive('propertiesAssignment', downgradeComponent({component: PropertiesAssignmentComponent}) as angular.IDirectiveFactory);
-angular.module('sdcApp').directive('ng2SearchWithAutocomplete',
- downgradeComponent({
- component: SearchWithAutoCompleteComponent,
- inputs: ['searchPlaceholder', 'searchBarClass', 'autoCompleteValues'],
- outputs: ['searchChanged', 'searchButtonClicked']
- }) as angular.IDirectiveFactory);
angular.module('sdcApp').directive('pluginFrame', downgradeComponent( {component: PluginFrameComponent, inputs: ['plugin', 'queryParams'], outputs: ['onLoadingDone']} ) as angular.IDirectiveFactory);
ng1appModule.config([
@@ -616,7 +608,6 @@ ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
ng1appModule.value('VendorReleaseValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
ng1appModule.value('VendorNameValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,60}$/);
ng1appModule.value('VendorModelNumberValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,65}$/);
-ng1appModule.value('ServiceTypeAndRoleValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,256}$/);
ng1appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
ng1appModule.value('UserIdValidationPattern', /^[\s\w-]{1,50}$/);
ng1appModule.value('ProjectCodeValidationPattern', /^[\s\w-]{5,50}$/);
@@ -670,7 +661,6 @@ ng1appModule.run([
AngularJSBridge,
$templateCache:ng.ITemplateCacheService):void => {
$templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
- $templateCache.put('notification-custom-template.html', require('./view-models/shared/notification-custom-template.html'));
//handle cache data - version
let initAsdcVersion:Function = ():void => {
diff --git a/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts b/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts
index 14cafa98c4..cda2f9723e 100644
--- a/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts
+++ b/catalog-ui/src/app/directives/capabilities-and-requirements/requirement/requirements-list-directive.ts
@@ -28,6 +28,7 @@
* Created by obarda on 1/8/2017.
*/
'use strict';
+import * as _ from "lodash";
import {RequirementsGroup, Component, Relationship, RelationshipModel} from "app/models";
export interface IRequirementsListScope extends ng.IScope {
diff --git a/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts
index f73c82a190..76bc1692b4 100644
--- a/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts
+++ b/catalog-ui/src/app/directives/ecomp-header/ecomp-header.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {IAppConfigurtaion, User, IUser} from "app/models";
import {IUserProperties} from "../../models/user";
import {UserService} from "../../ng2/services/user.service";
diff --git a/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts b/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts
index c4800fc0b4..25e7143e64 100644
--- a/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts
+++ b/catalog-ui/src/app/directives/export-json-to-excel/export-json-to-excel.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {FileUtils} from "app/utils";
export interface IJsonExportExcelScope extends ng.IScope {
diff --git a/catalog-ui/src/app/directives/file-opener/file-opener.ts b/catalog-ui/src/app/directives/file-opener/file-opener.ts
index 4abd2573bb..8240d07958 100644
--- a/catalog-ui/src/app/directives/file-opener/file-opener.ts
+++ b/catalog-ui/src/app/directives/file-opener/file-opener.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
export interface IFileOpenerScope extends ng.IScope {
importFile:any;
diff --git a/catalog-ui/src/app/directives/file-upload/file-upload.ts b/catalog-ui/src/app/directives/file-upload/file-upload.ts
index 5a8fd87849..4902741927 100644
--- a/catalog-ui/src/app/directives/file-upload/file-upload.ts
+++ b/catalog-ui/src/app/directives/file-upload/file-upload.ts
@@ -22,6 +22,7 @@
* Created by obarda on 1/27/2016.
*/
'use strict';
+import * as _ from "lodash";
import {IAppConfigurtaion} from "app/models";
export class FileUploadModel {
diff --git a/catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts b/catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts
index 2a7fd74e53..81d41509e7 100644
--- a/catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/common/common-graph-utils.ts
@@ -18,8 +18,11 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {CommonNodeBase, CompositionCiLinkBase, RelationshipModel, Relationship, CompositionCiNodeBase, NodesFactory, LinksFactory} from "app/models";
import {GraphUIObjects} from "app/utils";
+import {CompositionCiServicePathLink} from "app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link";
+import {Requirement, Capability} from "app/models";
/**
* Created by obarda on 12/21/2016.
*/
@@ -56,11 +59,11 @@ export class CommonGraphUtils {
classes: compositionGraphNode.classes
});
- if(!node.data().isUcpe) { //ucpe should not have tooltip
- this.initNodeTooltip(node);
- }
- return node;
- };
+ if(!node.data().isUcpe) { //ucpe should not have tooltip
+ this.initNodeTooltip(node);
+ }
+ return node;
+ };
/**
* The function will create a component instance node by the componentInstance position.
@@ -135,33 +138,30 @@ export class CommonGraphUtils {
};
/**
- *
+ * Returns relation source and target nodes.
* @param nodes - all nodes in graph in order to find the edge connecting the two nodes
* @param fromNodeId
* @param toNodeId
- * @returns {boolean} true/false if the edge is certified (from node and to node are certified)
+ * @returns [source, target] array of source node and target node.
*/
- public isRelationCertified(nodes:Cy.CollectionNodes, fromNodeId:string, toNodeId:string):boolean {
- let resourceTemp = _.filter(nodes, function (node:Cy.CollectionFirst) {
- return node.data().id === fromNodeId || node.data().id === toNodeId;
- });
- let certified:boolean = true;
-
- _.forEach(resourceTemp, (item) => {
- certified = certified && item.data().certified;
- });
-
- return certified;
+ public getRelationNodes(nodes:Cy.CollectionNodes, fromNodeId:string, toNodeId:string) {
+ return [
+ _.find(nodes, (node:Cy.CollectionFirst) => node.data().id === fromNodeId),
+ _.find(nodes, (node:Cy.CollectionFirst) => node.data().id === toNodeId)
+ ];
}
/**
* Add link to graph - only draw the link
* @param cy
* @param link
+ * @param getRelationRequirementCapability
*/
- public insertLinkToGraph = (cy:Cy.Instance, link:CompositionCiLinkBase) => {
-
- if (!this.isRelationCertified(cy.nodes(), link.source, link.target)) {
+ public insertLinkToGraph = (cy:Cy.Instance, link:CompositionCiLinkBase, getRelationRequirementCapability:Function) => {
+ const relationNodes = this.getRelationNodes(cy.nodes(), link.source, link.target);
+ const sourceNode:CompositionCiNodeBase = relationNodes[0] && relationNodes[0].data();
+ const targetNode:CompositionCiNodeBase = relationNodes[1] && relationNodes[1].data();
+ if ((sourceNode && !sourceNode.certified) || (targetNode && !targetNode.certified)) {
link.classes = 'not-certified-link';
}
let linkElement = cy.add({
@@ -169,32 +169,85 @@ export class CommonGraphUtils {
data: link,
classes: link.classes
});
- this.initLinkTooltip(linkElement, link);
+ const getLinkRequirementCapability = () =>
+ getRelationRequirementCapability(link.relation.relationships[0], sourceNode.componentInstance, targetNode.componentInstance);
+ this.initLinkTooltip(linkElement, link.relation.relationships[0], getLinkRequirementCapability);
};
/**
+ * Add service path link to graph - only draw the link
+ * @param cy
+ * @param link
+ */
+ public insertServicePathLinkToGraph = (cy:Cy.Instance, link:CompositionCiServicePathLink) => {
+ let linkElement = cy.add({
+ group: 'edges',
+ data: link,
+ classes: link.classes
+ });
+ this.initServicePathTooltip(linkElement, link);
+ };
+
+ /**
+ * Returns function for the link tooltip content
+ * @param {Relationship} linkRelation
+ * @param {Requirement} requirement
+ * @param {Capability} capability
+ * @returns {() => string}
+ * @private
+ */
+ private _getLinkTooltipContent(linkRelation:Relationship, requirement?:Requirement, capability?:Capability):string {
+ return '<div class="line">' +
+ '<span class="req-cap-label">R: </span>' +
+ '<span>' + (requirement ? requirement.getTitle() : linkRelation.relation.requirement) + '</span>' +
+ '</div>' +
+ '<div class="line">' +
+ '<div class="sprite-new link-tooltip-arrow"></div>' +
+ '<span class="req-cap-label">C: </span>' +
+ '<span>' + (capability ? capability.getTitle() : linkRelation.relation.capability) + '</span>' +
+ '</div>';
+ }
+
+ /**
* This function will init qtip tooltip on the link
- * @params linkElement - the link we want the tooltip to apply on,
+ * @param linkElement - the link we want the tooltip to apply on,
+ * @param link
+ * @param getLinkRequirementCapability
* link - the link obj
*/
- public initLinkTooltip(linkElement:Cy.CollectionElements, link:CompositionCiLinkBase) {
+ public initLinkTooltip(linkElement:Cy.CollectionElements, link:Relationship, getLinkRequirementCapability:Function) {
+ const content = () => this._getLinkTooltipContent(link); // base tooltip content without owner names
+ const render = (event, api) => {
+ // on render (called once at first show), get the link requirement and capability and change to full tooltip content (with owner names)
+ getLinkRequirementCapability().then((linkReqCap) => {
+ const fullContent = () => this._getLinkTooltipContent(link, linkReqCap.requirement, linkReqCap.capability);
+ api.set('content.text', fullContent);
+ });
+ };
+ linkElement.qtip(this.prepareInitTooltipData({content, events: {render}}));
+ };
- let opts = {
- content: function () {
- return '<div class="line">' +
- '<span class="req-cap-label">R: </span>' +
- '<span>'+ link.relation.relationships[0].relation.requirement + '</span>' +
- '</div>' +
- '<div class="line">' +
- '<div class="sprite-new link-tooltip-arrow"></div>' +
- '<span class="req-cap-label">C: </span>' +
- '<span>' + link.relation.relationships[0].relation.capability + '</span>' +
- '</div>';
- },
+ /**
+ *
+ * @param linkElement
+ * @param link
+ */
+ public initServicePathTooltip(linkElement:Cy.CollectionElements, link:CompositionCiServicePathLink) {
+ let content = function () {
+ return '<div class="line">' +
+ '<div>'+link.pathName+'</div>' +
+ '</div>';
+ };
+ linkElement.qtip(this.prepareInitTooltipData({content}));
+ };
+
+ private prepareInitTooltipData(options?:Object) {
+ return _.merge({
position: {
my: 'top center',
at: 'bottom center',
- adjust: {x:0, y:0}
+ adjust: {x:0, y:0},
+ effect: false
},
style: {
classes: 'qtip-dark qtip-rounded qtip-custom link-qtip',
@@ -208,24 +261,24 @@ export class CommonGraphUtils {
delay: 1000
},
hide: {event: 'mouseout mousedown'},
- includeLabels: true
- };
-
- linkElement.qtip(opts);
- };
+ includeLabels: true,
+ events: {}
+ }, options);
+ }
/**
* go over the relations and draw links on the graph
* @param cy
* @param instancesRelations
+ * @param getRelationRequirementCapability - function to get requirement and capability of a relation
*/
- public initGraphLinks(cy:Cy.Instance, instancesRelations:Array<RelationshipModel>) {
+ public initGraphLinks(cy:Cy.Instance, instancesRelations:Array<RelationshipModel>, getRelationRequirementCapability:Function) {
if (instancesRelations) {
_.forEach(instancesRelations, (relationshipModel:RelationshipModel) => {
_.forEach(relationshipModel.relationships, (relationship:Relationship) => {
let linkToCreate = this.LinksFactory.createGraphLink(cy, relationshipModel, relationship);
- this.insertLinkToGraph(cy, linkToCreate);
+ this.insertLinkToGraph(cy, linkToCreate, getRelationRequirementCapability);
});
});
}
@@ -297,8 +350,8 @@ export class CommonGraphUtils {
public getCytoscapeNodePosition = (cy:Cy.Instance, event:IDragDropEvent):Cy.Position => {
let targetOffset = $(event.target).offset();
- let x = event.pageX - targetOffset.left;
- let y = event.pageY - targetOffset.top;
+ let x = (event.pageX - targetOffset.left) / cy.zoom();
+ let y = (event.pageY - targetOffset.top) / cy.zoom();
return this.HTMLCoordsToCytoscapeCoords(cy.extent(), {
x: x,
@@ -316,14 +369,14 @@ export class CommonGraphUtils {
return nodePosition;
}
- /**
- * Generic function that can be used for any html elements overlaid on canvas
- * Returns the html position of a node on canvas, including left palette and header offsets. Option to pass in additional offset to add to return position.
- * @param node
- * @param additionalOffset
- * @returns {Cy.Position}
-
- public getNodePositionWithOffset = (node:Cy.CollectionFirstNode, additionalOffset?:Cy.Position): Cy.Position => {
+ /**
+ * Generic function that can be used for any html elements overlaid on canvas
+ * Returns the html position of a node on canvas, including left palette and header offsets. Option to pass in additional offset to add to return position.
+ * @param node
+ * @param additionalOffset
+ * @returns {Cy.Position}
+
+ public getNodePositionWithOffset = (node:Cy.CollectionFirstNode, additionalOffset?:Cy.Position): Cy.Position => {
if(!additionalOffset) additionalOffset = {x: 0, y:0};
let nodePosition = node.renderedPosition();
@@ -334,13 +387,13 @@ export class CommonGraphUtils {
return posWithOffset;
};*/
- /**
- * return true/false if first node contains in second - this used in order to verify is node is entirely inside ucpe
- * @param firstBox
- * @param secondBox
- * @returns {boolean}
- */
- public isFirstBoxContainsInSecondBox(firstBox:Cy.BoundingBox, secondBox:Cy.BoundingBox) {
+ /**
+ * return true/false if first node contains in second - this used in order to verify is node is entirely inside ucpe
+ * @param firstBox
+ * @param secondBox
+ * @returns {boolean}
+ */
+ public isFirstBoxContainsInSecondBox(firstBox:Cy.BoundingBox, secondBox:Cy.BoundingBox) {
return firstBox.x1 > secondBox.x1 && firstBox.x2 < secondBox.x2 && firstBox.y1 > secondBox.y1 && firstBox.y2 < secondBox.y2;
@@ -385,50 +438,50 @@ export class CommonGraphUtils {
*/
public nodeLocationsCompatible(cy:Cy.Instance, node1:Cy.CollectionFirstNode, node2:Cy.CollectionFirstNode) {
- let ucpe = cy.nodes('[?isUcpe]');
- if(!ucpe.length){ return true; }
- if(node1.data().isUcpePart || node2.data().isUcpePart) { return true; }
+ let ucpe = cy.nodes('[?isUcpe]');
+ if(!ucpe.length){ return true; }
+ if(node1.data().isUcpePart || node2.data().isUcpePart) { return true; }
return (this.isFirstBoxContainsInSecondBox(node1.boundingbox(), ucpe.boundingbox()) == this.isFirstBoxContainsInSecondBox(node2.boundingbox(), ucpe.boundingbox()));
}
- /**
- * This function will init qtip tooltip on the node
- * @param node - the node we want the tooltip to apply on
- */
- public initNodeTooltip(node:Cy.CollectionNodes) {
-
- let opts = {
- content: function () {
- return this.data('name');
- },
- position: {
- my: 'top center',
- at: 'bottom center',
- adjust: {x:0, y:-5}
- },
- style: {
- classes: 'qtip-dark qtip-rounded qtip-custom',
- tip: {
- width: 16,
- height: 8
- }
- },
- show: {
- event: 'mouseover',
- delay: 1000
- },
- hide: {event: 'mouseout mousedown'},
- includeLabels: true
- };
-
- if (node.data().isUcpePart){ //fix tooltip positioning for UCPE-cps
- opts.position.adjust = {x:0, y:20};
- }
-
- node.qtip(opts);
+ /**
+ * This function will init qtip tooltip on the node
+ * @param node - the node we want the tooltip to apply on
+ */
+ public initNodeTooltip(node:Cy.CollectionNodes) {
+
+ let opts = {
+ content: function () {
+ return this.data('name');
+ },
+ position: {
+ my: 'top center',
+ at: 'bottom center',
+ adjust: {x:0, y:-5}
+ },
+ style: {
+ classes: 'qtip-dark qtip-rounded qtip-custom',
+ tip: {
+ width: 16,
+ height: 8
+ }
+ },
+ show: {
+ event: 'mouseover',
+ delay: 1000
+ },
+ hide: {event: 'mouseout mousedown'},
+ includeLabels: true
};
+
+ if (node.data().isUcpePart){ //fix tooltip positioning for UCPE-cps
+ opts.position.adjust = {x:0, y:20};
+ }
+
+ node.qtip(opts);
+ };
}
CommonGraphUtils.$inject = ['NodesFactory', 'LinksFactory'];
diff --git a/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts b/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts
index 36c75c55fc..596dcecc13 100644
--- a/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts
@@ -176,6 +176,17 @@ export class ComponentInstanceNodesStyle {
}
},
{
+ selector: '.vl-link-1',
+ css: {
+ 'width': 3,
+ 'line-color': GraphColors.ACTIVE_LINK,
+ 'curve-style': 'unbundled-bezier',
+ 'target-arrow-color': '#3b7b9b',
+ 'target-arrow-shape': 'triangle',
+ 'control-point-step-size': 30
+ }
+ },
+ {
selector: '.ucpe-host-link',
css: {
'width': 0
@@ -196,6 +207,17 @@ export class ComponentInstanceNodesStyle {
},
{
+ selector: '.service-path-link',
+ css: {
+ 'width': 2,
+ 'line-color': GraphColors.SERVICE_PATH_LINK,
+ 'target-arrow-color': GraphColors.SERVICE_PATH_LINK,
+ 'target-arrow-shape': 'triangle',
+ 'curve-style': 'bezier',
+ 'control-point-step-size': 30
+ }
+ },
+ {
selector: '.not-certified',
css: {
'shape': 'rectangle',
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 cdb163bda1..2144ecfbfa 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
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {
Match,
LinkMenu,
@@ -28,13 +29,15 @@ import {
Relationship,
PropertyModel,
Component,
+ Service,
ConnectRelationModel,
CompositionCiNodeBase,
CompositionCiNodeVl,
ModalModel,
ButtonModel,
NodesFactory/*,
- AssetPopoverObj*/
+ AssetPopoverObj*/,
+ Point
} from "app/models";
import {ComponentInstanceFactory, ComponentFactory, GRAPH_EVENTS, GraphColors} from "app/utils";
import {EventListenerService, LoaderService} from "app/services";
@@ -60,13 +63,32 @@ import {ConnectionPropertiesViewComponent} from "../../../ng2/pages/connection-w
import {ComponentInstanceServiceNg2} from "../../../ng2/services/component-instance-services/component-instance.service";
import {EVENTS} from "../../../utils/constants";
import {PropertyBEModel} from "../../../models/properties-inputs/property-be-model";
+import {ComponentType} from "app/utils";
+import {ForwardingPath} from "app/models/forwarding-path";
+import {ServicePathGraphUtils} from "./utils/composition-graph-service-path-utils";
+import {CompositionCiServicePathLink} from "app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link";
+import { ZoneConfig, ZoneInstanceConfig, ZoneInstanceMode } from "app/models/graph/zones/zone-child";
+import { PoliciesService } from "app/ng2/services/policies.service";
+import { PaletteAnimationComponent } from "app/ng2/components/ui/palette-animation/palette-animation.component";
+import { CompositionGraphZoneUtils } from "./utils/composition-graph-zone-utils";
+import {LeftPaletteMetadataTypes} from "../../../models/components/displayComponent";
-interface ICompositionGraphScope extends ng.IScope {
+
+export interface ICompositionGraphScope extends ng.IScope {
component:Component;
isLoading: boolean;
isViewOnly: boolean;
withSidebar: boolean;
+
+ //zones
+ newZoneInstance;
+ zoneTagMode:string;
+ activeZoneInstance:ZoneInstanceConfig;
+ zones:any;
+ zoneInstanceModeChanged(newMode:ZoneInstanceMode, instance:ZoneInstanceConfig, zoneId:string);
+ clickOutsideZoneInstance():void;
+
// Link menu - create link menu
relationMenuDirectiveObj:ConnectRelationModel;
isLinkMenuOpen:boolean;
@@ -76,6 +98,7 @@ interface ICompositionGraphScope extends ng.IScope {
//modify link menu - for now only delete menu
relationMenuTimeout:ng.IPromise<any>;
linkMenuObject:LinkMenu;
+ isOnDrag: boolean;
//left palette functions callbacks
dropCallback(event:JQueryEventObject, ui:any):void;
@@ -95,7 +118,12 @@ interface ICompositionGraphScope extends ng.IScope {
highlightSearchMatches(searchTerm: string): void;
canvasMenuProps:any;
-
+
+ createOrUpdateServicePath(data: any):void;
+ deletePathsOnCy():void;
+ drawPathOnCy(data: ForwardingPath):void;
+ selectedPathId: string;
+
/*//asset popover menu
assetPopoverObj:AssetPopoverObj;
assetPopoverOpen:boolean;
@@ -124,10 +152,13 @@ export class CompositionGraph implements ng.IDirective {
private commonGraphUtils:CommonGraphUtils,
private matchCapabilitiesRequirementsUtils:MatchCapabilitiesRequirementsUtils,
private CompositionGraphPaletteUtils:CompositionGraphPaletteUtils,
+ private compositionGraphZoneUtils:CompositionGraphZoneUtils,
private ComponentServiceNg2: ComponentServiceNg2,
private ModalServiceNg2: ModalService,
private ConnectionWizardServiceNg2: ConnectionWizardService,
- private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2) {
+ private ComponentInstanceServiceNg2: ComponentInstanceServiceNg2,
+ private servicePathGraphUtils: ServicePathGraphUtils,
+ private policiesService:PoliciesService) {
}
@@ -140,7 +171,6 @@ export class CompositionGraph implements ng.IDirective {
};
link = (scope:ICompositionGraphScope, el:JQuery) => {
-
this.loadGraph(scope, el);
if(scope.component.componentInstances && scope.component.componentInstancesRelations) {
@@ -164,15 +194,16 @@ export class CompositionGraph implements ng.IDirective {
private loadGraphData = (scope:ICompositionGraphScope) => {
this.initGraphNodes(scope.component.componentInstances, scope.isViewOnly);
- this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations);
+ this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations, scope.component.getRelationRequirementCapability.bind(scope.component));
this.commonGraphUtils.initUcpeChildren(this._cy);
+ this.compositionGraphZoneUtils.initPolicyInstances(scope.zones.policy, scope.component.policies);
}
private loadGraph = (scope:ICompositionGraphScope, el:JQuery) => {
-
let graphEl = el.find('.sdc-composition-graph-wrapper');
this.initGraph(graphEl, scope.isViewOnly);
this.initDropZone(scope);
+ this.initZones(scope);
this.registerCytoscapeGraphEvents(scope);
this.registerCustomEvents(scope, el);
this.initViewMode(scope.isViewOnly);
@@ -210,6 +241,12 @@ export class CompositionGraph implements ng.IDirective {
private registerCustomEvents(scope:ICompositionGraphScope, el:JQuery) {
this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, (leftPaletteComponent:LeftPaletteComponent) => {
+ if(scope.isOnDrag ||
+ leftPaletteComponent.categoryType === LeftPaletteMetadataTypes.Group ||
+ leftPaletteComponent.categoryType === LeftPaletteMetadataTypes.Policy) {
+ return;
+ }
+
this.$log.info(`composition-graph::registerEventServiceEvents:: palette hover on component: ${leftPaletteComponent.uniqueId}`);
let nodesData = this.NodesGraphUtils.getAllNodesData(this._cy.nodes());
@@ -240,6 +277,33 @@ export class CompositionGraph implements ng.IDirective {
});
});
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_ADD_COMPONENT_INSTANCE_ZONE_START, (component:Component, paletteComponent:LeftPaletteComponent, startPosition:Point) => {
+ this.LoaderService.showLoader('composition-graph');
+
+ let zoneType:string = LeftPaletteMetadataTypes[paletteComponent.categoryType].toLowerCase();
+ scope.zones[zoneType].showZone = true;
+ if(scope.minifyZone) scope.minifyZone = false;
+
+ this.policiesService.createPolicyInstance(component.componentType, component.uniqueId, paletteComponent.type).subscribe((newInstance)=>{
+
+ this.LoaderService.hideLoader('composition-graph');
+ scope.newZoneInstance = newInstance;
+ this.compositionGraphZoneUtils.showAnimationToZone(startPosition, zoneType);
+ }, (error) => {
+ this.LoaderService.hideLoader('composition-graph');
+ });
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_FINISH_ANIMATION_ZONE, () => {
+ if(scope.newZoneInstance){
+ this.compositionGraphZoneUtils.addInstanceToZone(scope.zones['policy'], scope.newZoneInstance);
+ }
+ })
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_ZONE_SIZE_CHANGE, () => {
+ scope.minifyZone = true;
+ })
+
this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT, () => {
this._cy.emit('hidehandles');
this.matchCapabilitiesRequirementsUtils.resetFadedNodes(this._cy);
@@ -362,17 +426,11 @@ export class CompositionGraph implements ng.IDirective {
.updateInstanceCapabilityProperties(
scope.component,
this.ConnectionWizardServiceNg2.selectedMatch.toNode,
- this.ConnectionWizardServiceNg2.selectedMatch.capability.type,
- this.ConnectionWizardServiceNg2.selectedMatch.capability.name,
+ this.ConnectionWizardServiceNg2.selectedMatch.capability,
capabilityPropertiesBE
)
.subscribe((response) => {
console.log("Update resource instance capability properties response: ", response);
- response.forEach((resProperty) => {
- this.ConnectionWizardServiceNg2.selectedMatch.capabilityProperties.find((property) => {
- return property.uniqueId == resProperty.uniqueId;
- }).value = resProperty.value;
- });
this.ConnectionWizardServiceNg2.changedCapabilityProperties = [];
resolve(capabilityPropertiesBE);
});
@@ -400,6 +458,16 @@ export class CompositionGraph implements ng.IDirective {
});
};
+ scope.createOrUpdateServicePath = (data:any) => {
+ this.servicePathGraphUtils.createOrUpdateServicePath(scope, data);
+ };
+ scope.deletePathsOnCy = () => {
+ this.servicePathGraphUtils.deletePathsFromGraph(this._cy, <Service> scope.component);
+ };
+ scope.drawPathOnCy = (data: ForwardingPath) => {
+ this.servicePathGraphUtils.drawPath(this._cy, data, <Service> scope.component);
+ };
+
scope.viewRelation = (link:Cy.CollectionEdges) => {
scope.hideRelationMenu();
@@ -408,41 +476,9 @@ export class CompositionGraph implements ng.IDirective {
const targetNode:CompositionCiNodeBase = link.target().data();
const relationship:Relationship = linkData.relation.relationships[0];
- let capability:Capability;
- _.some(_.values(targetNode.componentInstance.capabilities), (capGroup) => {
- //item.uniqueId + item.ownerId + item.name === (selectedReqOrCapModel.uniqueId + selectedReqOrCapModel.ownerId + selectedReqOrCapModel.name)
- capability = _.find<Capability>(_.values<Capability>(capGroup), (cap:Capability) => (
- cap.uniqueId === relationship.relation.capabilityUid &&
- cap.ownerId === relationship.relation.capabilityOwnerId &&
- cap.name === relationship.relation.capability
- ));
- return capability;
- });
- let requirement:Requirement;
- _.some(_.values(sourceNode.componentInstance.requirements), (reqGroup) => {
- requirement = _.find<Requirement>(_.values<Requirement>(reqGroup), (req:Requirement) => (
- req.uniqueId === relationship.relation.requirementUid &&
- req.ownerId === relationship.relation.requirementOwnerId &&
- req.name === relationship.relation.requirement
- ));
- return requirement;
- });
-
- new Promise<{capability:Capability, requirement:Requirement}>((resolve, reject) => {
- if (capability && requirement) {
- resolve({capability, requirement});
- }
- else {
- scope.component.fetchRelation(relationship.relation.id).then((fetchedRelation) => {
- resolve({
- capability: fetchedRelation.relationships[0].capability,
- requirement: fetchedRelation.relationships[0].requirement
- });
- }, reject);
- }
- }).then((objReqCap) => {
- capability = objReqCap.capability;
- requirement = objReqCap.requirement;
+ scope.component.getRelationRequirementCapability(relationship, sourceNode.componentInstance, targetNode.componentInstance).then((objReqCap) => {
+ const capability = objReqCap.capability;
+ const requirement = objReqCap.requirement;
this.ConnectionWizardServiceNg2.currentComponent = scope.component;
this.ConnectionWizardServiceNg2.connectRelationModel = new ConnectRelationModel(sourceNode, targetNode, []);
@@ -459,11 +495,19 @@ export class CompositionGraph implements ng.IDirective {
this.ModalServiceNg2.addDynamicContentToModal(modalInstance, ConnectionPropertiesViewComponent);
modalInstance.instance.open();
- this.ComponentInstanceServiceNg2.getInstanceCapabilityProperties(scope.component, linkData.target, capability.type, capability.name)
- .subscribe((response: Array<PropertyModel>) => {
- this.ConnectionWizardServiceNg2.selectedMatch.capabilityProperties = response;
- this.ModalServiceNg2.addDynamicContentToModal(modalInstance, ConnectionPropertiesViewComponent);
- }, (error) => {});
+ new Promise((resolve) => {
+ if (!this.ConnectionWizardServiceNg2.selectedMatch.capability.properties) {
+ this.ComponentInstanceServiceNg2.getInstanceCapabilityProperties(scope.component, linkData.target, capability)
+ .subscribe(() => {
+ resolve();
+ }, (error) => {});
+ } else {
+ resolve();
+ }
+ }).then(() => {
+ this.ModalServiceNg2.addDynamicContentToModal(modalInstance, ConnectionPropertiesViewComponent);
+ })
+
}, (error) => {});
};
@@ -504,7 +548,7 @@ export class CompositionGraph implements ng.IDirective {
this.ConnectionWizardServiceNg2.currentComponent = scope.component;
//TODO: init with the selected values
this.ConnectionWizardServiceNg2.selectedMatch = null;
-
+
let steps:Array<StepModel> = [];
let fromNodeName:string = scope.relationMenuDirectiveObj.fromNode.componentInstance.name;
let toNodeName:string = scope.relationMenuDirectiveObj.toNode.componentInstance.name;
@@ -523,6 +567,7 @@ export class CompositionGraph implements ng.IDirective {
}
});
this._cy.on('tapstart', 'node', (event:Cy.EventObject) => {
+ scope.isOnDrag = true;
this._currentlyCLickedNodePosition = angular.copy(event.cyTarget[0].position()); //update node position on drag
if (event.cyTarget.data().isUcpe) {
this._cy.nodes('.ucpe-cp').unlock();
@@ -592,7 +637,7 @@ export class CompositionGraph implements ng.IDirective {
this._cy.on('tapend', (event:Cy.EventObject) => {
-
+ scope.isOnDrag = false;
if (event.cyTarget === this._cy) { //On Background clicked
if (this._cy.$('node:selected').length === 0) { //if the background click but not dragged
this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED);
@@ -603,6 +648,9 @@ export class CompositionGraph implements ng.IDirective {
else if (event.cyTarget.isEdge()) { //On Edge clicked
if (scope.isViewOnly) return;
this.CompositionGraphLinkUtils.handleLinkClick(this._cy, event);
+ if (event.cyTarget.data().type === CompositionCiServicePathLink.LINK_TYPE) {
+ return;
+ }
this.openModifyLinkMenu(scope, this.CompositionGraphLinkUtils.getModifyLinkMenu(event.cyTarget[0], event), 6000);
}
@@ -640,13 +688,6 @@ export class CompositionGraph implements ng.IDirective {
});
}
- /*
- private showNodePopoverMenu = (scope:ICompositionGraphScope, node:Cy.CollectionNodes) => {
-
- scope.assetPopoverObj = this.NodesGraphUtils.createAssetPopover(this._cy, node, scope.isViewOnly);
- scope.assetPopoverOpen = true;
-
- };*/
private openModifyLinkMenu = (scope:ICompositionGraphScope, linkMenuObject:LinkMenu, timeOutInMilliseconds?:number) => {
scope.hideRelationMenu();
this.$timeout(() => {
@@ -732,6 +773,49 @@ export class CompositionGraph implements ng.IDirective {
}
}
+
+ private initZones = (scope:ICompositionGraphScope):void => {
+ scope.zones = this.compositionGraphZoneUtils.createCompositionZones();
+
+ scope.zoneInstanceModeChanged = (newMode:ZoneInstanceMode, instance:ZoneInstanceConfig, zoneId:string):void => {
+ if(scope.zoneTagMode) { //we're in tag mode.
+ if(instance == scope.activeZoneInstance && newMode == ZoneInstanceMode.TAG){ //we want to toggle tag mode off.
+ scope.unsetActiveZoneInstance();
+ }
+ } else {
+ scope.setZoneInstanceMode(newMode, instance, zoneId);
+ }
+ };
+
+ scope.setZoneInstanceMode = (newMode:ZoneInstanceMode, instance:ZoneInstanceConfig, zoneId:string):void => {
+ instance.mode = newMode;
+ switch(newMode){
+ case ZoneInstanceMode.TAG: {
+ scope.zoneTagMode = zoneId + "-tagging";
+ }
+ case ZoneInstanceMode.SELECTED: { //case TAG flows into here as well
+ scope.activeZoneInstance = instance;
+ break;
+ }
+ }
+ };
+
+ scope.unsetActiveZoneInstance = ():void => {
+ scope.activeZoneInstance.mode = ZoneInstanceMode.NONE;
+ scope.activeZoneInstance = null;
+ scope.zoneTagMode = null;
+ };
+
+ scope.clickOutsideZoneInstance = ():void => {
+ if(!scope.zoneTagMode)
+ scope.unsetActiveZoneInstance();
+ };
+
+ };
+
+
+
+
public static factory = ($q,
$log,
$timeout,
@@ -746,10 +830,13 @@ export class CompositionGraph implements ng.IDirective {
CommonGraphUtils,
MatchCapabilitiesRequirementsUtils,
CompositionGraphPaletteUtils,
+ CompositionGraphZoneUtils,
ComponentServiceNg2,
ModalService,
ConnectionWizardService,
- ComponentInstanceServiceNg2) => {
+ ComponentInstanceServiceNg2,
+ ServicePathGraphUtils,
+ PoliciesService) => {
return new CompositionGraph(
$q,
$log,
@@ -765,10 +852,13 @@ export class CompositionGraph implements ng.IDirective {
CommonGraphUtils,
MatchCapabilitiesRequirementsUtils,
CompositionGraphPaletteUtils,
+ CompositionGraphZoneUtils,
ComponentServiceNg2,
ModalService,
ConnectionWizardService,
- ComponentInstanceServiceNg2);
+ ComponentInstanceServiceNg2,
+ ServicePathGraphUtils,
+ PoliciesService);
}
}
@@ -787,8 +877,11 @@ CompositionGraph.factory.$inject = [
'CommonGraphUtils',
'MatchCapabilitiesRequirementsUtils',
'CompositionGraphPaletteUtils',
+ 'CompositionGraphZoneUtils',
'ComponentServiceNg2',
'ModalServiceNg2',
'ConnectionWizardServiceNg2',
- 'ComponentInstanceServiceNg2'
+ 'ComponentInstanceServiceNg2',
+ 'ServicePathGraphUtils',
+ 'PoliciesServiceNg2'
];
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html
index bbf2d6bbb2..487e4cb65a 100644
--- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.html
@@ -1,5 +1,5 @@
<loader display="isLoading" loader-type="composition-graph"></loader>
-<div class="sdc-composition-graph-wrapper" ng-class="{'view-only':isViewOnly}"
+<div class="sdc-composition-graph-wrapper {{zoneTagMode}}" ng-class="{'view-only':isViewOnly}"
data-drop="true"
data-jqyoui-options="{accept: verifyDrop}"
data-jqyoui-droppable="{onDrop:'dropCallback', beforeDrop: 'beforeDropCallback'}">
@@ -11,10 +11,37 @@
<menu-list-ng2 [props]="canvasMenuProps"></menu-list-ng2>
<div class="w-sdc-search-menu" data-ng-class="{'with-sidebar': withSidebar}">
- <ng2-search-with-autocomplete [search-placeholder]="'Type to search'" [auto-complete-values]="componentInstanceNames" (search-changed)="getAutoCompleteValues($event)" (search-button-clicked)="highlightSearchMatches($event)"
- [search-bar-class]="'composition-search'"></ng2-search-with-autocomplete>
+
+ <ng2-service-path-selector
+ ng-if="component.isService()"
+ [service]="component"
+ [draw-path]="drawPathOnCy"
+ [delete-paths]="deletePathsOnCy"
+ [selected-path-id]="selectedPathId">
+ </ng2-service-path-selector>
+ <ng2-service-path
+ ng-if="component.isService()"
+ [service]="component"
+ [on-create]="createOrUpdateServicePath">
+ </ng2-service-path>
+ <ng2-search-with-autocomplete
+ [search-placeholder]="'Type to search'"
+ [auto-complete-values]="componentInstanceNames"
+ (search-changed)="getAutoCompleteValues($event)"
+ (search-button-clicked)="highlightSearchMatches($event)"
+ [search-bar-class]="'composition-search'">
+ </ng2-search-with-autocomplete>
<div class="zoom-icons sprite-new canvas-fit-all" data-ng-click="zoomAll()"></div>
<div class="zoom-icons sprite-new zoom-plus" data-ng-click="zoom(true)"></div>
<div class="zoom-icons sprite-new zoom-minus" data-ng-click="zoom(false)"></div>
</div>
<!--<asset-popover ng-if="assetPopoverOpen" asset-popover-obj="assetPopoverObj" delete-asset="deleteNode(assetPopoverObj.nodeId)"></asset-popover>-->
+<div class="sdc-canvas-zones__wrapper {{zoneTagMode}}" data-ng-class="{'with-sidebar': withSidebar}">
+ <ng2-zone-container data-ng-repeat="zoneConfig in zones" [title]="zoneConfig.title" [class]="zoneConfig.type" [count]="zoneConfig.instances.length" [show-zone] = "zoneConfig.showZone" [minify-zone] = "minifyZone">
+ <ng2-zone-instance
+ data-ng-repeat="instance in zoneConfig.instances" clicked-outside="{onClickedOutside: 'clickOutsideZoneInstance()', clickedOutsideEnable: 'activeZoneInstance == instance'}"
+ [config]="instance" [default-icon-text]="zoneConfig.defaultIconText" [is-active]="activeZoneInstance == instance" [active-instance-mode]="activeZoneInstance && activeZoneInstance.mode"
+ (mode-change)="zoneInstanceModeChanged($event.newMode, $event.instance, zoneConfig.type)">
+ </ng2-zone-instance>
+ </ng2-zone-container>
+</div>
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less
index 56c8b5529d..5a6a104670 100644
--- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/composition-graph.less
@@ -11,4 +11,28 @@ composition-graph {
.view-only{
background-color:rgb(248, 248, 248);
}
+
+ .sdc-canvas-zones__wrapper {
+ position: absolute;
+ bottom: 10px;
+ right: 12px;
+ display:flex;
+ transition: right 0.2s;
+
+ &.with-sidebar {
+ right:310px;
+ }
+
+ ng2-zone-container {
+ display:flex;
+ margin-left: 10px;
+ }
+ }
+
+ .group-tagging {
+ cursor: url("/assets/styles/images/canvas-tagging-icons/adding_group.svg"), pointer;
+ }
+ .policy-tagging {
+ cursor: url("/assets/styles/images/canvas-tagging-icons/adding_policy.svg"), pointer;
+ }
}
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts
index da7d48e6ae..73e03e954d 100644
--- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-general-utils.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {ComponentInstance, Component, Match, CompositionCiLinkBase, CompositionCiNodeUcpeCp} from "app/models";
import {QueueUtils, Dictionary, GraphUIObjects} from "app/utils";
import {LoaderService} from "app/services";
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts
index 89c5e14602..705367c5f7 100644
--- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-links-utils.ts
@@ -21,6 +21,7 @@
/**
* Created by obarda on 6/28/2016.
*/
+import * as _ from "lodash";
import {GraphUIObjects} from "app/utils";
import {LoaderService} from "app/services";
import {
@@ -39,6 +40,7 @@ import {
import {CommonGraphUtils} from "../../common/common-graph-utils";
import {CompositionGraphGeneralUtils} from "./composition-graph-general-utils";
import {MatchCapabilitiesRequirementsUtils} from "./match-capability-requierment-utils";
+import {CompositionCiServicePathLink} from "../../../../models/graph/graph-links/composition-graph-links/composition-ci-service-path-link";
export class CompositionGraphLinkUtils {
@@ -86,7 +88,7 @@ export class CompositionGraphLinkUtils {
let onSuccess:(response:RelationshipModel) => void = (relation:RelationshipModel) => {
link.setRelation(relation);
- this.commonGraphUtils.insertLinkToGraph(cy, link);
+ this.commonGraphUtils.insertLinkToGraph(cy, link, component.getRelationRequirementCapability.bind(component));
};
link.updateLinkDirection();
@@ -212,6 +214,28 @@ export class CompositionGraphLinkUtils {
this.createLink(link, cy, component);
};
+ private handlePathLink(cy:Cy.Instance, event:Cy.EventObject) {
+ let linkData = event.cyTarget.data();
+ let selectedPathId = linkData.pathId;
+ let pathEdges = cy.collection(`[pathId='${selectedPathId}']`);
+ if (pathEdges.length > 1) {
+ setTimeout(() => {
+ pathEdges.select();
+ }, 0);
+ }
+ }
+
+ private handleVLLink(event:Cy.EventObject) {
+ let vl:Cy.CollectionNodes = event.cyTarget[0].target('.vl-node');
+ let connectedEdges:Cy.CollectionEdges = vl.connectedEdges(`[type!="${CompositionCiServicePathLink.LINK_TYPE}"]`);
+ if (vl.length && connectedEdges.length > 1) {
+ setTimeout(() => {
+ vl.select();
+ connectedEdges.select();
+ }, 0);
+ }
+ }
+
/**
* Handles click event on links.
@@ -224,18 +248,13 @@ export class CompositionGraphLinkUtils {
if (cy.$('edge:selected').length > 1 && event.cyTarget[0].selected()) {
cy.$(':selected').unselect();
} else {
-
- let vl:Cy.CollectionNodes = event.cyTarget[0].target('.vl-node');
- let connectedEdges:Cy.CollectionEdges = vl.connectedEdges();
- if (vl.length && connectedEdges.length > 1) {
-
- setTimeout(() => {
- vl.select();
- connectedEdges.select();
- }, 0);
+ if (event.cyTarget[0].data().type === CompositionCiServicePathLink.LINK_TYPE) {
+ this.handlePathLink(cy, event);
+ }
+ else {
+ this.handleVLLink(event);
}
}
-
}
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts
index 449d551cc0..fb1e6650bd 100644
--- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-nodes-utils.ts
@@ -18,11 +18,15 @@
* ============LICENSE_END=========================================================
*/
-import {Component, NodesFactory, ComponentInstance, CompositionCiNodeVl,IAppMenu,AssetPopoverObj} from "app/models";
+import * as _ from "lodash";
+import {Component, NodesFactory, ComponentInstance, CompositionCiNodeVl,IAppMenu,AssetPopoverObj, Service} from "app/models";
import {EventListenerService, LoaderService} from "app/services";
import {GRAPH_EVENTS,ModalsHandler,GraphUIObjects} from "app/utils";
import {CompositionGraphGeneralUtils} from "./composition-graph-general-utils";
import {CommonGraphUtils} from "../../common/common-graph-utils";
+import {CompositionCiServicePathLink} from "app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link";
+import {ServiceGenericResponse} from "app/ng2/services/responses/service-generic-response";
+import {ServiceServiceNg2} from 'app/ng2/services/component-services/service.service';
/**
* Created by obarda on 11/9/2016.
*/
@@ -31,9 +35,10 @@ export class CompositionGraphNodesUtils {
private GeneralGraphUtils:CompositionGraphGeneralUtils,
private commonGraphUtils:CommonGraphUtils,
private eventListenerService:EventListenerService,
- private loaderService:LoaderService /*,
- private sdcMenu: IAppMenu,
- private ModalsHandler: ModalsHandler*/) {
+ private loaderService:LoaderService,
+ private serviceService:ServiceServiceNg2,
+ /*private sdcMenu: IAppMenu,
+ private ModalsHandler: ModalsHandler*/) {
}
@@ -88,9 +93,20 @@ export class CompositionGraphNodesUtils {
this.handleConnectedVlsToDelete(connectedVls);
}
+ // check whether there is a service path going through this node, and if so clean it from the graph.
+ let nodeId = nodeToDelete.data().id;
+ let connectedPathLinks = cy.collection(`[type="${CompositionCiServicePathLink.LINK_TYPE}"][source="${nodeId}"], [type="${CompositionCiServicePathLink.LINK_TYPE}"][target="${nodeId}"]`);
+ _.forEach(connectedPathLinks, (link, key) => {
+ cy.remove(`[pathId="${link.data().pathId}"]`);
+ });
+
+ // update service path list
+ this.serviceService.getComponentCompositionData(component).subscribe((response:ServiceGenericResponse) => {
+ (<Service>component).forwardingPaths = response.forwardingPaths;
+ });
+
//update UI
cy.remove(nodeToDelete);
-
};
let onFailed:(response:any) => void = (response:any) => {
@@ -297,5 +313,5 @@ export class CompositionGraphNodesUtils {
}
- CompositionGraphNodesUtils.$inject = ['NodesFactory', '$log', 'CompositionGraphGeneralUtils', 'CommonGraphUtils', 'EventListenerService', 'LoaderService' /*, 'sdcMenu', 'ModalsHandler'*/]
+ CompositionGraphNodesUtils.$inject = ['NodesFactory', '$log', 'CompositionGraphGeneralUtils', 'CommonGraphUtils', 'EventListenerService', 'LoaderService', 'ServiceServiceNg2' /*, 'sdcMenu', 'ModalsHandler'*/]
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-service-path-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-service-path-utils.ts
new file mode 100644
index 0000000000..ef047d7dd3
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-service-path-utils.ts
@@ -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=========================================================
+ */
+
+import * as _ from "lodash";
+import {LoaderService} from "app/services";
+import {CompositionGraphGeneralUtils} from "./composition-graph-general-utils";
+import {ICompositionGraphScope} from "../composition-graph.directive";
+import {ServiceServiceNg2} from 'app/ng2/services/component-services/service.service';
+import {Service} from "../../../../models/components/service";
+import {ForwardingPath} from "app/models/forwarding-path";
+import {ForwardingPathLink} from "app/models/forwarding-path-link";
+import {CompositionCiServicePathLink} from "../../../../models/graph/graph-links/composition-graph-links/composition-ci-service-path-link";
+import {CommonGraphUtils} from "app/directives/graphs-v2/common/common-graph-utils";
+
+export class ServicePathGraphUtils {
+
+ constructor(
+ private loaderService:LoaderService,
+ private generalGraphUtils:CompositionGraphGeneralUtils,
+ private serviceService:ServiceServiceNg2,
+ private commonGraphUtils:CommonGraphUtils
+ ) {}
+
+ public deletePathsFromGraph(cy: Cy.Instance, service:Service){
+ cy.remove(`[type="${CompositionCiServicePathLink.LINK_TYPE}"]`);
+ }
+
+ public drawPath(cy: Cy.Instance, forwardingPath: ForwardingPath, service:Service) {
+ let pathElements = forwardingPath.pathElements.listToscaDataDefinition;
+
+ _.forEach(pathElements, (link: ForwardingPathLink) => {
+ let data:CompositionCiServicePathLink = new CompositionCiServicePathLink(link);
+ data.source = data.forwardingPathLink.fromNode;
+ data.target = data.forwardingPathLink.toNode;
+ data.pathId = forwardingPath.uniqueId;
+ data.pathName = forwardingPath.name;
+ this.commonGraphUtils.insertServicePathLinkToGraph(cy, data);
+ });
+ }
+
+ public createOrUpdateServicePath = (scope:ICompositionGraphScope, path: any): void => {
+ let service = <Service>scope.component;
+ this.loaderService.showLoader('composition-graph');
+
+ let onSuccess: (response: ForwardingPath) => void = (response: ForwardingPath) => {
+
+ service.forwardingPaths[response.uniqueId] = response;
+ scope.selectedPathId = response.uniqueId;
+ };
+
+ this.generalGraphUtils.getGraphUtilsServerUpdateQueue().addBlockingUIActionWithReleaseCallback(
+ () => this.serviceService.createOrUpdateServicePath(service, path).subscribe(onSuccess),
+ () => this.loaderService.hideLoader('composition-graph')
+ );
+ };
+}
+
+ServicePathGraphUtils.$inject = [
+ 'LoaderService',
+ 'CompositionGraphGeneralUtils',
+ 'ServiceServiceNg2',
+ 'CommonGraphUtils'
+];
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-zone-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-zone-utils.ts
new file mode 100644
index 0000000000..28f2dc85d2
--- /dev/null
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/composition-graph-zone-utils.ts
@@ -0,0 +1,55 @@
+import { PolicyInstance } from "app/models/graph/zones/policy-instance";
+import { ZoneConfig, ZoneInstanceConfig } from "app/models/graph/zones/zone-child";
+import { DynamicComponentService } from "app/ng2/services/dynamic-component.service";
+import { PaletteAnimationComponent } from "app/ng2/components/ui/palette-animation/palette-animation.component";
+import { Point } from "../../../../models";
+
+export class CompositionGraphZoneUtils {
+
+ constructor(private dynamicComponentService: DynamicComponentService) {}
+
+ public createCompositionZones(){
+ let zones = {
+ 'policy': new ZoneConfig('Policies', 'P', 'policy', false),
+ 'group': new ZoneConfig('Groups', 'G', 'group', false)
+ };
+ return zones;
+ }
+
+ public initPolicyInstances(policyZone:ZoneConfig, policies:Array<PolicyInstance>) {
+ if(policies && policies.length){
+ policyZone.showZone = true;
+ }
+ _.forEach(policies, (policy:PolicyInstance) => {
+ policyZone.instances.push(new ZoneInstanceConfig(policy));
+ });
+ }
+
+ public addInstanceToZone(zone:ZoneConfig, instance:PolicyInstance){
+ zone.instances.push(new ZoneInstanceConfig(instance));
+ };
+
+ private findZoneCoordinates(zoneType):Point{
+ let point:Point = new Point(0,0);
+ let zone = angular.element(document.querySelector('.' + zoneType + '-zone'));
+ let wrapperZone = zone.offsetParent();
+ point.x = zone.prop('offsetLeft') + wrapperZone.prop('offsetLeft');
+ point.y = zone.prop('offsetTop') + wrapperZone.prop('offsetTop');
+ return point;
+ }
+
+ public showAnimationToZone = (startPoint:Point, zoneType:string) => {
+
+ let paletteToZoneAnimation = this.dynamicComponentService.createDynamicComponent(PaletteAnimationComponent);
+ paletteToZoneAnimation.instance.from = startPoint;
+ paletteToZoneAnimation.instance.to = this.findZoneCoordinates(zoneType);
+ paletteToZoneAnimation.instance.iconName = zoneType;
+ paletteToZoneAnimation.instance.runAnimation();
+ }
+
+
+}
+
+CompositionGraphZoneUtils.$inject = [
+ 'DynamicComponentService'
+]; \ No newline at end of file
diff --git a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts
index 6a02381902..3a05ce901f 100644
--- a/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {
Requirement, CompositionCiLinkBase, CapabilitiesGroup, RequirementsGroup, Match,
CompositionCiNodeBase, Component, Capability
@@ -142,7 +143,7 @@ export class MatchCapabilitiesRequirementsUtils {
let requirementArray:Array<Requirement> = [];
_.forEach(_.flatten(_.values(requirements)), (requirement:Requirement)=> {
- if (requirement.name !== "dependency" && !MatchCapabilitiesRequirementsUtils.isRequirementFulfilled(fromNodeId, requirement, links)) {
+ if (requirement.name !== 'dependency' && requirement.parentName !== 'dependency' && !MatchCapabilitiesRequirementsUtils.isRequirementFulfilled(fromNodeId, requirement, links)) {
requirementArray.push(requirement);
}
});
diff --git a/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts
index 127f43b734..c542e9fc95 100644
--- a/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-graph.directive.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { Component, Module, NodesFactory, ComponentInstance } from "app/models";
import { ComponentInstanceFactory } from "app/utils";
import { DeploymentGraphGeneralUtils } from "./deployment-utils/deployment-graph-general-utils";
@@ -133,7 +134,7 @@ export class DeploymentGraph implements ng.IDirective {
});
this.initGraphNodes(this._cy, scope.component); //creating instances nodes
- this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations);
+ this.commonGraphUtils.initGraphLinks(this._cy, scope.component.componentInstancesRelations, scope.component.getRelationRequirementCapability.bind(scope.component));
this._cy.collapseAll();
this.registerGraphEvents();
diff --git a/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts
index e481b1d268..3a90115179 100644
--- a/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {Module} from "app/models";
/**
* Created by obarda on 12/21/2016.
diff --git a/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts b/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
index 8abf968c82..9b9235248e 100644
--- a/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-import {Component, IAppMenu, LeftPanelModel, NodesFactory, LeftPaletteComponent, CompositionCiNodeBase, ComponentInstance} from "app/models";
+import * as _ from "lodash";
+import {Component, IAppMenu, LeftPanelModel, NodesFactory, LeftPaletteComponent, CompositionCiNodeBase, ComponentInstance, Point} from "app/models";
import {CompositionGraphGeneralUtils} from "../composition-graph/utils/composition-graph-general-utils";
import {EventListenerService} from "app/services";
import {ResourceType, GRAPH_EVENTS, EVENTS, ComponentInstanceFactory, ModalsHandler} from "app/utils";
@@ -25,6 +26,8 @@ import 'sdc-angular-dragdrop';
import {LeftPaletteLoaderService} from "../../../services/components/utils/composition-left-palette-service";
import {Resource} from "app/models/components/resource";
import {ComponentType} from "app/utils/constants";
+import {LeftPaletteMetadataTypes} from "../../../models/components/displayComponent";
+
interface IPaletteScope {
components:Array<LeftPaletteComponent>;
@@ -39,10 +42,15 @@ interface IPaletteScope {
ui:any
}
+ addInstanceClick: ()=>void; // added code
+ onPopupMouseOver: ()=>void // added code
+ onPopupMouseOut: ()=>void // added code
+
sectionClick:(section:string)=>void;
searchComponents:(searchText:string)=>void;
- onMouseOver:(displayComponent:LeftPaletteComponent)=>void;
+ onMouseOver:(displayComponent:LeftPaletteComponent, elem: HTMLElement)=>void;
onMouseOut:(displayComponent:LeftPaletteComponent)=>void;
+
dragStartCallback:(event:JQueryEventObject, ui, displayComponent:LeftPaletteComponent)=>void;
dragStopCallback:()=>void;
onDragCallback:(event:JQueryEventObject) => void;
@@ -65,8 +73,8 @@ export class Palette implements ng.IDirective {
private CompositionGraphGeneralUtils:CompositionGraphGeneralUtils,
private EventListenerService:EventListenerService,
private sdcMenu:IAppMenu,
- private ModalsHandler:ModalsHandler) {
-
+ private ModalsHandler:ModalsHandler
+ ) {
}
private fetchingComponentFromServer:boolean = false;
@@ -84,7 +92,6 @@ export class Palette implements ng.IDirective {
this.nodeHtmlSubstitute = $('<div class="node-substitute"><span></span><img /></div>');
el.append(this.nodeHtmlSubstitute);
this.registerEventListenerForLeftPalette(scope);
- // this.LeftPaletteLoaderService.loadLeftPanel(scope.currentComponent.componentType);
this.initComponents(scope);
this.initEvents(scope);
@@ -96,31 +103,15 @@ export class Palette implements ng.IDirective {
});
};
- private getUpdateLeftPaletteEventName = (component:Component):string => {
- switch (component.componentType) {
- case ComponentType.SERVICE:
- return EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT;
- case ComponentType.RESOURCE:
- if((<Resource>component).resourceType == ResourceType.PNF){
- return EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT;
- }else{
- return EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT;
- }
- default:
- console.log('ERROR: Component type '+ component.componentType + ' is not exists');
- }
- };
private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
- let updateEventName:string = this.getUpdateLeftPaletteEventName(scope.currentComponent);
- this.EventListenerService.registerObserverCallback(updateEventName, () => {
+ this.EventListenerService.registerObserverCallback(EVENTS.LEFT_PALETTE_UPDATE_EVENT, () => {
this.updateLeftPanelDisplay(scope);
});
};
private unRegisterEventListenerForLeftPalette = (scope:IPaletteScope):void => {
- let updateEventName:string = this.getUpdateLeftPaletteEventName(scope.currentComponent);
- this.EventListenerService.unRegisterObserver(updateEventName);
+ this.EventListenerService.unRegisterObserver(EVENTS.LEFT_PALETTE_UPDATE_EVENT);
};
private leftPanelResourceFilter(resourcesNotAbstract:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):Array<LeftPaletteComponent> {
@@ -132,7 +123,7 @@ export class Palette implements ng.IDirective {
private initLeftPanel(leftPanelComponents:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):LeftPanelModel {
let leftPanelModel = new LeftPanelModel();
-
+
if (resourceFilterTypes && resourceFilterTypes.length) {
leftPanelComponents = this.leftPanelResourceFilter(leftPanelComponents, resourceFilterTypes);
}
@@ -151,10 +142,7 @@ export class Palette implements ng.IDirective {
private initEvents(scope:IPaletteScope) {
- /**
- *
- * @param section
- */
+
scope.sectionClick = (section:string) => {
if (section === scope.expandedSection) {
scope.expandedSection = '';
@@ -163,20 +151,37 @@ export class Palette implements ng.IDirective {
scope.expandedSection = section;
};
- scope.onMouseOver = (displayComponent:LeftPaletteComponent) => {
- if (scope.isOnDrag) {
- return;
+ scope.onMouseOver = (displayComponent:LeftPaletteComponent, sectionElem: HTMLElement) => {
+ if (this.isGroupOrPolicy(displayComponent)) {
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_SHOW_POPUP_PANEL, scope.currentComponent, displayComponent, sectionElem);
+ } else {
+ if (scope.isOnDrag) {
+ return;
+ }
+ scope.isOnDrag = true;
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, displayComponent);
+ this.$log.debug('palette::onMouseOver:: fired');
}
- scope.isOnDrag = true;
- this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_IN, displayComponent);
- this.$log.debug('palette::onMouseOver:: fired');
};
- scope.onMouseOut = () => {
- scope.isOnDrag = false;
- this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT);
+ scope.onMouseOut = (displayComponent:LeftPaletteComponent) => {
+ if(this.isGroupOrPolicy(displayComponent)) {
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HIDE_POPUP_PANEL);
+ } else {
+ scope.isOnDrag = false;
+ this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HOVER_OUT);
+ }
+ };
+ }
+
+ private isGroupOrPolicy(component:LeftPaletteComponent): boolean {
+ if(component &&
+ (component.categoryType === LeftPaletteMetadataTypes.Group ||
+ component.categoryType === LeftPaletteMetadataTypes.Policy)) {
+ return true;
}
+ return false;
}
private initComponents(scope:IPaletteScope) {
@@ -193,10 +198,10 @@ export class Palette implements ng.IDirective {
let entityType:string = scope.currentComponent.componentType.toLowerCase();
let resourceFilterTypes:Array<string> = this.sdcConfig.resourceTypesFilter[entityType];
scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent);
- //remove the container component from the list
+ //remove the container component from the list
let componentTempToDisplay = angular.copy(scope.components);
- componentTempToDisplay = _.remove(componentTempToDisplay, function (component) {
- return component.component.invariantUUID !== scope.currentComponent.invariantUUID;
+ componentTempToDisplay = _.remove(componentTempToDisplay, function (leftPalettecomponent) {
+ return leftPalettecomponent.invariantUUID !== scope.currentComponent.invariantUUID;
});
scope.model = this.initLeftPanel(componentTempToDisplay, resourceFilterTypes);
scope.displaySortedCategories = angular.copy(scope.model.sortedCategories);
@@ -224,7 +229,7 @@ export class Palette implements ng.IDirective {
private initDragEvents(scope:IPaletteScope) {
scope.dragStartCallback = (event:IDragDropEvent, ui, displayComponent:LeftPaletteComponent):void => {
- if (scope.isLoading || !scope.isDragable || scope.isViewOnly) {
+ if (scope.isLoading || !scope.isDragable || scope.isViewOnly || this.isGroupOrPolicy(displayComponent)) {
return;
}
@@ -302,7 +307,8 @@ export class Palette implements ng.IDirective {
CompositionGraphGeneralUtils,
EventListenerService,
sdcMenu,
- ModalsHandler) => {
+ ModalsHandler
+ ) => {
return new Palette($log,
LeftPaletteLoaderService,
sdcConfig,
@@ -312,7 +318,8 @@ export class Palette implements ng.IDirective {
CompositionGraphGeneralUtils,
EventListenerService,
sdcMenu,
- ModalsHandler);
+ ModalsHandler
+ );
};
}
diff --git a/catalog-ui/src/app/directives/graphs-v2/palette/palette.html b/catalog-ui/src/app/directives/graphs-v2/palette/palette.html
index 7f9bfd1e0d..a8139e3140 100644
--- a/catalog-ui/src/app/directives/graphs-v2/palette/palette.html
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/palette.html
@@ -24,9 +24,9 @@
</div>
<div class="i-sdc-designer-leftbar-section-content-item"
data-ng-class="{'default-pointer': isViewOnly}"
- data-ng-mouseover="!isViewOnly && onMouseOver(component)"
- data-ng-mouseleave="!isViewOnly && onMouseOut()"
- data-drag="{{!isViewOnly}}"
+ data-ng-mouseover="!isViewOnly && onMouseOver(component, $event.currentTarget)"
+ data-ng-mouseleave="!isViewOnly && onMouseOut(component)"
+ data-drag="!isViewOnly"
data-jqyoui-options="{revert: 'invalid', helper:setElementTemplate, appendTo:'body', cursorAt: {left:38, top: 38}, cursor:'move'}"
jqyoui-draggable="{index:{{$index}},animate:true,onStart:'dragStartCallback(component)',onStop:'dragStopCallback()', onDrag:'onDragCallback()'}"
data-ng-repeat="component in components | orderBy: 'displayName' track by $index"
@@ -40,14 +40,16 @@
</div>
</div>
<div class="i-sdc-designer-leftbar-section-content-item-info">
- <span class="i-sdc-designer-leftbar-section-content-item-info-title"
- uib-tooltip="{{component.displayName}}" tooltip-class="uib-custom-tooltip"
- tooltip-placement="bottom" tooltip-popup-delay="700">
- {{component.displayName}}</span>
+ <span class="i-sdc-designer-leftbar-section-content-item-info-title"
+ uib-tooltip="{{component.displayName}}" tooltip-class="uib-custom-tooltip"
+ tooltip-placement="bottom" tooltip-popup-delay="700">
+ {{component.displayName}}</span>
<div class="i-sdc-designer-leftbar-section-content-item-info-text">
V.{{component.version}}
</div>
- <div class="i-sdc-designer-leftbar-section-content-item-info-text"> Type:
+ <div class="i-sdc-designer-leftbar-section-content-item-info-text"
+ uib-tooltip="{{component.type}}" tooltip-class="uib-custom-tooltip"
+ tooltip-placement="top" tooltip-popup-delay="700"> Type:
{{component.componentSubType}}
</div>
</div>
diff --git a/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts
index f73e855c0e..78a269ead1 100644
--- a/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/relation-menu/relation-menu.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
'use strict'
+import * as _ from "lodash";
import {Match, ConnectRelationModel} from "app/models";
import {Component} from "../../../models/components/component";
diff --git a/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts
index 476f86d8a6..eed209d438 100644
--- a/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts
+++ b/catalog-ui/src/app/directives/property-types/data-type-fields-structure/data-type-fields-structure.ts
@@ -22,6 +22,7 @@
* Created by obarda on 1/27/2016.
*/
'use strict';
+import * as _ from "lodash";
import {DataTypesService} from "app/services";
import { ValidationUtils } from "app/utils";
import { DataTypePropertyModel } from "app/models/data-type-properties";
diff --git a/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts
index a8bcf3f155..f5e9a36041 100644
--- a/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts
+++ b/catalog-ui/src/app/directives/select-property-types/select-data-type-fields-structure/select-data-type-fields-structure.ts
@@ -22,6 +22,7 @@
* Created by obarda on 1/27/2016.
*/
'use strict';
+import * as _ from "lodash";
import {ValidationUtils} from "app/utils";
import { DataTypesService } from "app/services";
import { DataTypePropertyModel } from "app/models/data-type-properties";
diff --git a/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts
index 4f80ae86c0..59fa700dc9 100644
--- a/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts
+++ b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
'use strict';
+import * as _ from "lodash";
import {RelationshipModel, Component, ComponentInstance} from "app/models";
import {Dictionary} from "app/utils";
diff --git a/catalog-ui/src/app/filters/category-type-filter.ts b/catalog-ui/src/app/filters/category-type-filter.ts
index 5c89277bb8..763b4a94e2 100644
--- a/catalog-ui/src/app/filters/category-type-filter.ts
+++ b/catalog-ui/src/app/filters/category-type-filter.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {ComponentType} from "../utils/constants";
import {CacheService} from "../services/cache-service";
export class CategoryTypeFilter {
diff --git a/catalog-ui/src/app/filters/entity-filter.ts b/catalog-ui/src/app/filters/entity-filter.ts
index 6d04bc3c41..ccac10f802 100644
--- a/catalog-ui/src/app/filters/entity-filter.ts
+++ b/catalog-ui/src/app/filters/entity-filter.ts
@@ -19,6 +19,8 @@
*/
import {Component, Resource} from "../models";
+import {ComponentType} from "../utils/constants";
+
export class EntityFilter {
constructor() {
@@ -56,11 +58,14 @@ export class EntityFilter {
if (filter.selectedCategoriesModel && filter.selectedCategoriesModel.length > 0) {
let filteredCategories = [];
angular.forEach(filteredComponents, (component:Component):void => {
- if (component.categories && filter.selectedCategoriesModel.indexOf(component.categories[0].uniqueId) !== -1) {
- filteredCategories.push(component);
- } else if (component.categories && component.categories[0].subcategories && filter.selectedCategoriesModel.indexOf(component.categories[0].subcategories[0].uniqueId) !== -1) {
- filteredCategories.push(component);
- } else if (component.categories && component.categories[0].subcategories && component.categories[0].subcategories[0].groupings && filter.selectedCategoriesModel.indexOf(component.categories[0].subcategories[0].groupings[0].uniqueId) !== -1) {
+ let componentCategory = component.categoryNormalizedName +
+ ((component.subCategoryNormalizedName) ? '.' + component.subCategoryNormalizedName : '');
+ if (component.componentType === ComponentType.RESOURCE) {
+ componentCategory = 'resourceNewCategory.' + componentCategory;
+ } else if (component.componentType === ComponentType.SERVICE) {
+ componentCategory = 'serviceNewCategory.' + componentCategory;
+ }
+ if (filter.selectedCategoriesModel.indexOf(componentCategory) !== -1) {
filteredCategories.push(component);
}
});
diff --git a/catalog-ui/src/app/filters/resource-name-filter.ts b/catalog-ui/src/app/filters/resource-name-filter.ts
index 97de5a2e76..5aa114d1b4 100644
--- a/catalog-ui/src/app/filters/resource-name-filter.ts
+++ b/catalog-ui/src/app/filters/resource-name-filter.ts
@@ -18,6 +18,8 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
+
export class ResourceNameFilter {
diff --git a/catalog-ui/src/app/models/app-config.ts b/catalog-ui/src/app/models/app-config.ts
index 1f6682f666..54c059afb3 100644
--- a/catalog-ui/src/app/models/app-config.ts
+++ b/catalog-ui/src/app/models/app-config.ts
@@ -84,6 +84,7 @@ export interface IApi {
GET_onboarding:string;
GET_component_from_csar_uuid:string;
kibana:string;
+ services_api_root:string;
}
export interface ILogConfig {
diff --git a/catalog-ui/src/app/models/artifacts.ts b/catalog-ui/src/app/models/artifacts.ts
index 0aa07d11ed..959480b0f0 100644
--- a/catalog-ui/src/app/models/artifacts.ts
+++ b/catalog-ui/src/app/models/artifacts.ts
@@ -20,6 +20,7 @@
'use strict';
+import * as _ from "lodash";
import {ArtifactType} from './../utils';
import {HeatParameterModel} from "./heat-parameters";
diff --git a/catalog-ui/src/app/models/attributes.ts b/catalog-ui/src/app/models/attributes.ts
index 9e2dc98855..9e5828ae69 100644
--- a/catalog-ui/src/app/models/attributes.ts
+++ b/catalog-ui/src/app/models/attributes.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {SchemaAttributeGroupModel, SchemaAttribute} from "./schema-attribute";
import {SchemaPropertyGroupModel, SchemaProperty} from "./aschema-property";
diff --git a/catalog-ui/src/app/models/capability.ts b/catalog-ui/src/app/models/capability.ts
index 2f2e3a8de6..74994b155b 100644
--- a/catalog-ui/src/app/models/capability.ts
+++ b/catalog-ui/src/app/models/capability.ts
@@ -22,6 +22,7 @@
* Created by obarda on 4/20/2016.
*/
'use strict';
+import * as _ from "lodash";
import {PropertyModel} from "./properties";
import {Requirement} from "./requirement";
diff --git a/catalog-ui/src/app/models/components/component.ts b/catalog-ui/src/app/models/components/component.ts
index daa4a19e19..b7f57227ca 100644
--- a/catalog-ui/src/app/models/components/component.ts
+++ b/catalog-ui/src/app/models/components/component.ts
@@ -20,6 +20,7 @@
'use strict';
+import * as _ from "lodash";
import {AsdcComment, ArtifactModel, ArtifactGroupModel, IFileDownload, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
InputModel, DisplayModule, Module, IValidate, RelationshipModel, IMainCategory, RequirementsGroup, CapabilitiesGroup, AdditionalInformationModel,
Resource, IAppMenu, Service} from "../../models";
@@ -31,6 +32,9 @@ import {ArtifactGroupType} from "../../utils/constants";
import {ComponentMetadata} from "../component-metadata";
import {Capability} from "../capability";
import {Requirement} from "../requirement";
+import {Relationship} from "../graph/relationship";
+import { PolicyInstance } from "app/models/graph/zones/policy-instance";
+
// import {}
export interface IComponent {
@@ -57,7 +61,7 @@ export interface IComponent {
//Property API
addOrUpdateProperty(property:PropertyModel):ng.IPromise<PropertyModel>;
deleteProperty(propertyId:string):ng.IPromise<PropertyModel>;
- updateInstanceProperty(property:PropertyModel):ng.IPromise<PropertyModel>;
+ updateInstanceProperties(componentInstanceId:string, properties:PropertyModel[]):ng.IPromise<PropertyModel[]>;
//Attribute API
deleteAttribute(attributeId:string):ng.IPromise<AttributeModel>;
@@ -73,6 +77,7 @@ export interface IComponent {
addOrUpdateInstanceArtifact(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
deleteInstanceArtifact(artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel>;
uploadInstanceEnvFile(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
+ checkComponentInstanceVersionChange(componentUid:string):ng.IPromise<any>;
changeComponentInstanceVersion(componentUid:string):ng.IPromise<Component>;
updateComponentInstance(componentInstance:ComponentInstance):ng.IPromise<ComponentInstance>;
updateMultipleComponentInstances(instances:Array<ComponentInstance>):ng.IPromise<Array<ComponentInstance>>;
@@ -131,6 +136,8 @@ export abstract class Component implements IComponent {
public toscaArtifacts:ArtifactGroupModel;
public distributionStatus:string;
public categories:Array<IMainCategory>;
+ public categoryNormalizedName: string;
+ public subCategoryNormalizedName: string;
public componentInstancesProperties:PropertiesGroup;
public componentInstancesAttributes:AttributesGroup;
public componentInstancesRelations:Array<RelationshipModel>;
@@ -149,6 +156,7 @@ export abstract class Component implements IComponent {
public normalizedName:string;
public systemName:string;
public projectCode:string;
+ public policies:Array<PolicyInstance>;
public groups:Array<Module>;
//custom properties
public componentService:IComponentService;
@@ -172,6 +180,8 @@ export abstract class Component implements IComponent {
this.toscaArtifacts = new ArtifactGroupModel(component.toscaArtifacts);
this.contactId = component.contactId;
this.categories = component.categories;
+ this.categoryNormalizedName = component.categoryNormalizedName;
+ this.subCategoryNormalizedName = component.subCategoryNormalizedName;
this.creatorUserId = component.creatorUserId;
this.creationDate = component.creationDate;
this.creatorFullName = component.creatorFullName;
@@ -423,23 +433,25 @@ export abstract class Component implements IComponent {
return deferred.promise;
};
- public updateInstanceProperty = (property:PropertyModel):ng.IPromise<PropertyModel> => {
- let deferred = this.$q.defer();
- let onSuccess = (newProperty:PropertyModel):void => {
- // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
- let existProperty:PropertyModel = <PropertyModel>_.find(this.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
- uniqueId: newProperty.uniqueId,
- path: newProperty.path
+ public updateInstanceProperties = (componentInstanceId:string, properties:PropertyModel[]):ng.IPromise<PropertyModel[]> => {
+ let deferred = this.$q.defer<PropertyModel[]>();
+ let onSuccess = (newProperties:PropertyModel[]):void => {
+ newProperties.forEach((newProperty) => {
+ // find exist instance property in parent component for update the new value ( find bu uniqueId & path)
+ let existProperty: PropertyModel = <PropertyModel>_.find(this.componentInstancesProperties[newProperty.resourceInstanceUniqueId], {
+ uniqueId: newProperty.uniqueId,
+ path: newProperty.path
+ });
+ let index = this.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
+ this.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
});
- let index = this.componentInstancesProperties[newProperty.resourceInstanceUniqueId].indexOf(existProperty);
- this.componentInstancesProperties[newProperty.resourceInstanceUniqueId][index] = newProperty;
- deferred.resolve(newProperty);
+ deferred.resolve(newProperties);
};
let onFailed = (error:any):void => {
console.log('Failed to update property value');
deferred.reject(error);
};
- this.componentService.updateInstanceProperty(this.uniqueId, property).then(onSuccess, onFailed);
+ this.componentService.updateInstanceProperties(this.uniqueId, componentInstanceId, properties).then(onSuccess, onFailed);
return deferred.promise;
};
@@ -534,6 +546,10 @@ export abstract class Component implements IComponent {
return deferred.promise;
};
+ public checkComponentInstanceVersionChange = (componentUid:string):ng.IPromise<any> => {
+ return this.componentService.checkResourceInstanceVersionChange(this.uniqueId, this.selectedInstance.uniqueId, componentUid);
+ };
+
public createComponentInstance = (componentInstance:ComponentInstance):ng.IPromise<ComponentInstance> => {
let deferred = this.$q.defer();
let onSuccess = (instance:ComponentInstance):void => {
@@ -713,6 +729,33 @@ export abstract class Component implements IComponent {
return deferred.promise;
};
+ public getRelationRequirementCapability(relationship: Relationship, sourceNode:ComponentInstance, targetNode:ComponentInstance): Promise<{requirement:Requirement, capability:Capability}> {
+ // try find the requirement and capability in the source and target component instances:
+ let capability:Capability = targetNode.findCapability(undefined,
+ relationship.relation.capabilityUid,
+ relationship.relation.capabilityOwnerId,
+ relationship.relation.capability);
+ let requirement:Requirement = sourceNode.findRequirement(undefined,
+ relationship.relation.requirementUid,
+ relationship.relation.requirementOwnerId,
+ relationship.relation.requirement);
+
+ return new Promise<{requirement:Requirement, capability:Capability}>((resolve, reject) => {
+ if (capability && requirement) {
+ resolve({capability, requirement});
+ }
+ else {
+ // if requirement and/or capability is missing, then fetch the full relation with its requirement and capability:
+ this.fetchRelation(relationship.relation.id).then((fetchedRelation) => {
+ resolve({
+ capability: capability || fetchedRelation.relationships[0].capability,
+ requirement: requirement || fetchedRelation.relationships[0].requirement
+ });
+ }, reject);
+ }
+ });
+ }
+
public updateRequirementsCapabilities = ():ng.IPromise<any> => {
let deferred = this.$q.defer();
let onSuccess = (response:any):void => {
diff --git a/catalog-ui/src/app/models/components/displayComponent.ts b/catalog-ui/src/app/models/components/displayComponent.ts
index 3a9cbfdaf3..c89490306c 100644
--- a/catalog-ui/src/app/models/components/displayComponent.ts
+++ b/catalog-ui/src/app/models/components/displayComponent.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,14 +22,23 @@
*/
'use strict';
+import * as _ from "lodash";
import {ComponentType} from "../../utils/constants";
import {ComponentMetadata} from "../component-metadata";
+import {PolicyMetadata} from "../policy-metadata";
+import {GroupMetadata} from "../group-metadata";
import {RequirementsGroup} from "../requirement";
import {CapabilitiesGroup} from "../capability";
-export class LeftPaletteComponent {
+export enum LeftPaletteMetadataTypes {
+ Component,
+ Group,
+ Policy
+}
+export class LeftPaletteComponent {
uniqueId:string;
+ type:string;
displayName:string;
version:string;
mainCategory:string;
@@ -48,10 +57,33 @@ export class LeftPaletteComponent {
componentType:string;
systemName:string;
+ invariantUUID:string;
+
capabilities:CapabilitiesGroup;
requirements:RequirementsGroup;
- constructor(public component:ComponentMetadata) {
+ categoryType:LeftPaletteMetadataTypes;
+
+ constructor(metadataType: LeftPaletteMetadataTypes, item: ComponentMetadata | PolicyMetadata) {
+ if (metadataType === LeftPaletteMetadataTypes.Policy) {
+ this.initPolicy(item as PolicyMetadata);
+ return;
+ }
+
+ if (metadataType === LeftPaletteMetadataTypes.Group) {
+ this.initGroup(item as GroupMetadata);
+ return;
+ }
+
+ if (metadataType === LeftPaletteMetadataTypes.Component) {
+ this.initComponent(item as ComponentMetadata);
+ return;
+ }
+ }
+
+ private initComponent(component:ComponentMetadata): void {
+ this.categoryType = LeftPaletteMetadataTypes.Component;
+
this.icon = component.icon;
this.version = component.version;
this.uniqueId = component.uniqueId;
@@ -61,6 +93,7 @@ export class LeftPaletteComponent {
this.allVersions = component.allVersions;
this.componentType = component.componentType;
this.systemName = component.systemName;
+ this.invariantUUID = component.invariantUUID;
if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
this.mainCategory = component.categories[0].name;
@@ -71,6 +104,7 @@ export class LeftPaletteComponent {
}
this.componentSubType = component.resourceType ? component.resourceType: 'SERVICE';
+
this.initDisplayName(component.name);
this.searchFilterTerms = (this.displayName + ' ' + component.description + ' ' + component.tags.join(' ')).toLowerCase() + ' ' + component.version;
this.initIconSprite(component.icon);
@@ -80,6 +114,38 @@ export class LeftPaletteComponent {
}
}
+ private initGroup(group:GroupMetadata): void {
+ this.categoryType = LeftPaletteMetadataTypes.Group;
+
+ this.uniqueId = group.uniqueId;
+ this.displayName = group.type;
+ this.mainCategory = "Groups";
+ this.subCategory = "Groups";
+ this.iconClass = "sprite-group-icons group";
+ this.version = group.version;
+
+ this.type = group.type;
+ this.componentSubType = 'GROUP';
+
+ this.searchFilterTerms = this.displayName + ' ' + group.description + ' ' + group.version;
+ }
+
+ private initPolicy(policy:PolicyMetadata): void {
+ this.categoryType = LeftPaletteMetadataTypes.Policy;
+
+ this.uniqueId = policy.uniqueId;
+ this.displayName = policy.type;
+ this.mainCategory = "Policies";
+ this.subCategory = "Policies";
+ this.iconClass = "sprite-policy-icons policy";
+ this.version = policy.version;
+
+ this.type = policy.type;
+ this.componentSubType = 'POLICY';
+
+ this.searchFilterTerms = this.displayName + ' ' + policy.description + ' ' + policy.version;
+ }
+
public initDisplayName = (name:string):void => {
let newName =
_.last(_.last(_.last(_.last(_.last(_.last(_.last(_.last(name.split('tosca.nodes.'))
diff --git a/catalog-ui/src/app/models/components/resource.ts b/catalog-ui/src/app/models/components/resource.ts
index cd839786c5..5bd80e3b72 100644
--- a/catalog-ui/src/app/models/components/resource.ts
+++ b/catalog-ui/src/app/models/components/resource.ts
@@ -22,6 +22,7 @@
* Created by obarda on 2/3/2016.
*/
'use strict';
+import * as _ from "lodash";
import {InstancesInputsOrPropertiesMapData} from "../instance-inputs-properties-map";
import {PropertyModel} from "../properties";
import {DisplayModule} from "../modules/base-module";
@@ -91,7 +92,7 @@ export class Resource extends Component {
};
public isComplex = ():boolean => {
- return this.resourceType === ResourceType.VF || this.resourceType === ResourceType.PNF || this.resourceType === ResourceType.CVFC;
+ return this.resourceType === ResourceType.VF || this.resourceType === ResourceType.PNF || this.resourceType === ResourceType.CVFC || this.resourceType === ResourceType.CR;
};
public isVl = ():boolean => {
diff --git a/catalog-ui/src/app/models/components/service.ts b/catalog-ui/src/app/models/components/service.ts
index ce6921b1bb..439925f062 100644
--- a/catalog-ui/src/app/models/components/service.ts
+++ b/catalog-ui/src/app/models/components/service.ts
@@ -22,11 +22,13 @@
* Created by obarda on 2/4/2016.
*/
'use strict';
+import * as _ from "lodash";
import {IServiceService} from "../../services/components/service-service";
import {Component, PropertyModel, DisplayModule, InputsAndProperties, InputModel, InstancesInputsOrPropertiesMapData, InstancesInputsPropertiesMap,
Distribution, DistributionComponent, ArtifactGroupModel} from "../../models";
import {ArtifactGroupType} from "../../utils/constants";
import {ComponentMetadata} from "../component-metadata";
+import {ForwardingPath} from "app/models/forwarding-path";
export class Service extends Component {
@@ -37,6 +39,7 @@ export class Service extends Component {
public serviceType:string;
public serviceRole:string;
public environmentContext:string;
+ public forwardingPaths:{ [key:string]:ForwardingPath } = {};
constructor(componentService:IServiceService, $q:ng.IQService, component?:Service) {
super(componentService, $q, component);
diff --git a/catalog-ui/src/app/models/componentsInstances/componentInstance.ts b/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
index 59521ccfc8..e8444b3c54 100644
--- a/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
+++ b/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
@@ -22,6 +22,7 @@
* Created by obarda on 2/4/2016.
*/
'use strict';
+import * as _ from "lodash";
import {ArtifactGroupModel, CapabilitiesGroup,RequirementsGroup, PropertyModel, InputModel, Module} from "../../models";
import {ResourceType,ComponentType} from "../../utils/constants";
import {Capability} from "../capability";
@@ -104,7 +105,7 @@ export class ComponentInstance {
};
public isComplex = () : boolean => {
- return this.originType === ResourceType.VF || this.originType === ResourceType.PNF || this.originType === ResourceType.CVFC ;
+ return this.originType === ResourceType.VF || this.originType === ResourceType.PNF || this.originType === ResourceType.CVFC || this.originType === ResourceType.CR ;
}
public isServiceProxy = () :boolean => {
diff --git a/catalog-ui/src/app/models/forwarding-path-link.ts b/catalog-ui/src/app/models/forwarding-path-link.ts
new file mode 100644
index 0000000000..e09704d34f
--- /dev/null
+++ b/catalog-ui/src/app/models/forwarding-path-link.ts
@@ -0,0 +1,20 @@
+export class ForwardingPathLink {
+ public ownerId: string;
+ public fromNode:string;
+ public fromCP:string;
+ public toNode:string;
+ public toCP:string;
+ public toCPOriginId:string;
+ public fromCPOriginId:string;
+
+
+ constructor(fromNode:string, fromCP:string, toNode:string, toCP:string, fromCPOriginId:string, toCPOriginId:string) {
+ this.fromCP = fromCP;
+ this.fromNode = fromNode;
+ this.toCP = toCP;
+ this.toNode = toNode;
+ this.fromCPOriginId = fromCPOriginId;
+ this.toCPOriginId = toCPOriginId;
+ }
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/forwarding-path.ts b/catalog-ui/src/app/models/forwarding-path.ts
new file mode 100644
index 0000000000..2158dfe479
--- /dev/null
+++ b/catalog-ui/src/app/models/forwarding-path.ts
@@ -0,0 +1,30 @@
+import {PathElements} from './path-elements';
+import {ForwardingPathLink} from "./forwarding-path-link";
+
+export class ForwardingPath {
+ public name:string;
+ public destinationPortNumber:string;
+ public protocol:string;
+ public uniqueId:string;
+ public ownerId: string;
+ public pathElements: PathElements;
+
+ addPathLink(fromNode:string, fromCP:string, toNode:string, toCP:string, fromCPOriginId: string, toCPOriginId: string) {
+ if (!this.pathElements) {
+ this.pathElements = new PathElements();
+ }
+ this.pathElements.listToscaDataDefinition[this.pathElements.listToscaDataDefinition.length] = new ForwardingPathLink(fromNode, fromCP, toNode, toCP, fromCPOriginId, toCPOriginId);
+ }
+
+ deserialize(response:any) {
+ this.name = response.name;
+ this.destinationPortNumber = response.destinationPortNumber;
+ this.protocol = response.protocol;
+ if (response.pathElements && response.pathElements.listToscaDataDefinition) {
+ let list = response.pathElements.listToscaDataDefinition;
+ for (let i = 0; i < list.length; i++) {
+ this.addPathLink(list[i].fromNode, list[i].fromCP, list[i].toNode, list[i].toCP, list[i].fromCPOriginId, list[i].toCPOriginId);
+ }
+ }
+ }
+};
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link.ts
index 6271e1f59d..7aa4650e4e 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java
+++ b/catalog-ui/src/app/models/graph/graph-links/composition-graph-links/composition-ci-service-path-link.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,36 +18,23 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+import {CommonLinkBase} from "../common-base-link";
+import {ForwardingPathLink} from "app/models/forwarding-path-link";
-public class PropertyHeatMetaDefinition {
+export class CompositionCiServicePathLink extends CommonLinkBase {
+ static LINK_TYPE = 'service-path-link';
+ forwardingPathLink:ForwardingPathLink;
+ pathId:string;
+ pathName:string;
- String name;
- boolean value;
+ constructor(forwardingPathLink:ForwardingPathLink) {
+ super();
+ this.type = CompositionCiServicePathLink.LINK_TYPE;
+ this.classes = 'service-path-link';
+ this.pathId = '';
+ this.pathName = '';
+ this.forwardingPathLink = forwardingPathLink;
+ }
- public PropertyHeatMetaDefinition() {
- super();
- }
-
- public String getName() {
- return name;
- }
-
- public boolean isValue() {
- return value;
- }
-
- public void setValue(boolean value) {
- this.value = value;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "PropertyHeatMetaDefinition [name=" + name + ", value=" + value + "]";
- }
}
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 88c5323330..cc037a7e22 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
@@ -21,6 +21,7 @@
* Created by obarda on 5/1/2016.
*/
'use strict';
+import * as _ from "lodash";
import {RelationshipModel, Relationship, CompositionCiLinkBase, CompositionCiNodeBase, LinkUcpeHost, CompositionCiUcpeLink,
CompositionCiVlUcpeLink, CompositionCiSimpleLink, ModuleCiLinkBase, ModuleCiVlLink, CompositionCiVLink} from "../../../models";
diff --git a/catalog-ui/src/app/models/graph/match-relation.ts b/catalog-ui/src/app/models/graph/match-relation.ts
index 8d139d6405..2a1b2146b9 100644
--- a/catalog-ui/src/app/models/graph/match-relation.ts
+++ b/catalog-ui/src/app/models/graph/match-relation.ts
@@ -29,7 +29,6 @@ export class Match {
isFromTo:boolean;
fromNode:string;
toNode:string;
- capabilityProperties:Array<PropertyModel>; // use this to store the capability properties, since there are times the capability itself is not available (when fulfilled).
private _relationship:Relationship;
constructor(requirement:Requirement, capability:Capability, isFromTo:boolean, fromNode:string, toNode:string) {
diff --git a/catalog-ui/src/app/models/graph/nodes-and-links-map.ts b/catalog-ui/src/app/models/graph/nodes-and-links-map.ts
new file mode 100644
index 0000000000..8c8d6cc944
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/nodes-and-links-map.ts
@@ -0,0 +1,7 @@
+export class ServicePathMapItem {
+ constructor(public data: MapItemData, public id: string) {}
+}
+
+export class MapItemData {
+ constructor(public name:string, public id: string, public ownerId?: string, public options?: Array<ServicePathMapItem>) {}
+}
diff --git a/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts
index 29cd9256d9..eded75d5da 100644
--- a/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts
+++ b/catalog-ui/src/app/models/graph/nodes/composition-graph-nodes/composition-ci-node-vl.ts
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {ComponentInstance} from "../../../componentsInstances/componentInstance";
import {ImageCreatorService} from "../../../../directives/graphs-v2/image-creator/image-creator.service";
import {CompositionCiNodeBase} from "./composition-ci-node-base";
diff --git a/catalog-ui/src/app/models/graph/relationship.ts b/catalog-ui/src/app/models/graph/relationship.ts
index 57ff45ef00..8d56272fa0 100644
--- a/catalog-ui/src/app/models/graph/relationship.ts
+++ b/catalog-ui/src/app/models/graph/relationship.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
'use strict';
+import * as _ from "lodash";
import {Capability} from "../capability";
import {Requirement} from "../requirement";
diff --git a/catalog-ui/src/app/models/graph/zones/policy-instance.ts b/catalog-ui/src/app/models/graph/zones/policy-instance.ts
new file mode 100644
index 0000000000..63136e6e21
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/zones/policy-instance.ts
@@ -0,0 +1,43 @@
+import { PropertyModel } from "app/models";
+import { CommonUtils } from "app/utils";
+
+
+export class PolicyInstance {
+ componentName:string;
+ description:string;
+ empty:boolean;
+ invariantName:string;
+ invariantUUID:string;
+ isFromCsar:boolean;
+
+ name:string;
+ normalizedName:string;
+ policyTypeName:string;
+ policyTypeUid:string;
+ policyUUID:string;
+ properties:Array<PropertyModel>;
+ targets:Array<string>;
+ uniqueId:string;
+ version:string;
+
+ constructor(policy?:PolicyInstance) {
+ this.componentName = policy.componentName;
+ this.description = policy.description;
+ this.empty = policy.empty;
+ this.invariantName = policy.invariantName;
+ this.invariantUUID = policy.invariantUUID;
+ this.isFromCsar = policy.isFromCsar;
+
+ this.name = policy.name;
+ this.normalizedName =policy.normalizedName;
+ this.policyTypeName = policy.policyTypeName;
+ this.policyTypeUid = policy.policyTypeUid;
+ this.policyUUID = policy.policyUUID;
+ this.properties = CommonUtils.initProperties(policy.properties);
+ this.targets = policy.targets;
+ this.uniqueId = policy.uniqueId;
+ this.version = policy.version;
+
+ }
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/graph/zones/zone-child.ts b/catalog-ui/src/app/models/graph/zones/zone-child.ts
new file mode 100644
index 0000000000..d6d7198222
--- /dev/null
+++ b/catalog-ui/src/app/models/graph/zones/zone-child.ts
@@ -0,0 +1,48 @@
+import { Type, Component } from "@angular/core";
+import { PolicyInstance } from "app/models/graph/zones/policy-instance";
+
+export class ZoneConfig {
+ title:string;
+ defaultIconText:string;
+ type:string; 'policy|group';
+ tagModeId:string;
+ instances:Array<ZoneInstanceConfig>;
+ showZone:boolean;
+
+
+ constructor (title:string, defaultText:string, type:string, showZone:boolean) {
+ this.title = title;
+ this.defaultIconText = defaultText;
+ this.type = type;
+ this.tagModeId = this.type + "-tagging";
+ this.instances = [];
+ this.showZone = showZone;
+ }
+}
+
+export class ZoneInstanceConfig {
+
+ name:string;
+ assignments:Array<string>; //targets or members
+ instanceData:PolicyInstance; // | GroupInstance;
+ mode:ZoneInstanceMode;
+
+ constructor(instance:PolicyInstance) { /* | GroupInstance */
+
+ this.name = instance.name;
+ this.instanceData = instance;
+ this.mode = ZoneInstanceMode.NONE;
+
+ if(instance instanceof PolicyInstance) {
+ this.assignments = instance.targets;
+ }
+ }
+
+}
+
+export enum ZoneInstanceMode {
+ NONE,
+ HOVER,
+ SELECTED,
+ TAG
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/group-metadata.ts b/catalog-ui/src/app/models/group-metadata.ts
new file mode 100644
index 0000000000..ecd6e3e91c
--- /dev/null
+++ b/catalog-ui/src/app/models/group-metadata.ts
@@ -0,0 +1,33 @@
+export class GroupMetadata {
+ public uniqueId: string;
+ public type: string;
+ public version: string;
+ public description: string;
+ public creationTime: number;
+ public modificationTime: number;
+ public highestVersion: boolean;
+ public empty: boolean;
+
+ deserialize (response): GroupMetadata {
+ this.uniqueId = response.uniqueId;
+ this.type = response.type;
+ this.version = response.version;
+ this.description = response.description;
+ this.creationTime = response.creationTime;
+ this.modificationTime = response.modificationTime;
+ this.highestVersion = response.highestVersion;
+ this.empty = response.empty;
+
+ return this;
+ }
+}
+
+export interface GroupTpes {
+ groupTypes: Array<GroupMetadata>;
+ excludeMapping: ExcludedGroupTypes;
+}
+
+export interface ExcludedGroupTypes {
+ componentType: string;
+ excludedGroupTypes: Array<string>;
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/instance-inputs-properties-map.ts b/catalog-ui/src/app/models/instance-inputs-properties-map.ts
index 650a6d7b51..fdc6f926e3 100644
--- a/catalog-ui/src/app/models/instance-inputs-properties-map.ts
+++ b/catalog-ui/src/app/models/instance-inputs-properties-map.ts
@@ -22,6 +22,7 @@
* Created by obarda on 9/12/2016.
*/
'use strict';
+import * as _ from "lodash";
import {InputPropertyBase} from "./input-property-base";
import {PropertyModel} from "./properties";
import {InputModel} from "./inputs";
diff --git a/catalog-ui/src/app/models/member.ts b/catalog-ui/src/app/models/member.ts
index fff523ea5e..eeb292eeaa 100644
--- a/catalog-ui/src/app/models/member.ts
+++ b/catalog-ui/src/app/models/member.ts
@@ -22,6 +22,7 @@
* Created by obarda on 8/2/2016.
*/
'use strict';
+import * as _ from "lodash";
export class Members {
diff --git a/catalog-ui/src/app/models/modal.ts b/catalog-ui/src/app/models/modal.ts
index b7bdf251fe..f0a632727a 100644
--- a/catalog-ui/src/app/models/modal.ts
+++ b/catalog-ui/src/app/models/modal.ts
@@ -6,13 +6,15 @@ export class ModalModel {
content: any;
buttons: Array<ButtonModel>;
type: string; 'standard|error|alert'
+ isMovable: boolean;
- constructor(size?: string, title?: string, content?: any, buttons?: Array<ButtonModel>, type?:string) {
+ constructor(size?: string, title?: string, content?: any, buttons?: Array<ButtonModel>, type?: string, isMovable?: boolean) {
this.size = size;
this.title = title;
this.content = content;
this.buttons = buttons;
this.type = type || 'standard';
+ this.isMovable = !!isMovable;
}
}
diff --git a/catalog-ui/src/app/models/modules/base-module.ts b/catalog-ui/src/app/models/modules/base-module.ts
index 53a28f076e..63f4cc7103 100644
--- a/catalog-ui/src/app/models/modules/base-module.ts
+++ b/catalog-ui/src/app/models/modules/base-module.ts
@@ -25,9 +25,11 @@
* Created by obarda on 2/4/2016.
*/
'use strict';
+import * as _ from "lodash";
import {PropertyModel} from "../properties";
import {ArtifactModel} from "../artifacts";
import {CommonUtils} from "../../utils/common-utils";
+
export class Module {
public name:string;
diff --git a/catalog-ui/src/app/models/path-elements.ts b/catalog-ui/src/app/models/path-elements.ts
new file mode 100644
index 0000000000..b4dbec4383
--- /dev/null
+++ b/catalog-ui/src/app/models/path-elements.ts
@@ -0,0 +1,5 @@
+import {ForwardingPathLink} from './forwarding-path-link';
+export class PathElements {
+ public listToscaDataDefinition:Array<ForwardingPathLink> = [];
+ public ownerId: string;
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/policy-metadata.ts b/catalog-ui/src/app/models/policy-metadata.ts
new file mode 100644
index 0000000000..33e0185e33
--- /dev/null
+++ b/catalog-ui/src/app/models/policy-metadata.ts
@@ -0,0 +1,33 @@
+export class PolicyMetadata {
+ public uniqueId: string;
+ public type: string;
+ public version: string;
+ public description: string;
+ public creationTime: number;
+ public modificationTime: number;
+ public highestVersion: boolean;
+ public empty: boolean;
+
+ deserialize (response): PolicyMetadata {
+ this.uniqueId = response.uniqueId;
+ this.type = response.type;
+ this.version = response.version;
+ this.description = response.description;
+ this.creationTime = response.creationTime;
+ this.modificationTime = response.modificationTime;
+ this.highestVersion = response.highestVersion;
+ this.empty = response.empty;
+
+ return this;
+ }
+}
+
+export interface PolicyTpes {
+ policyTypes: Array<PolicyMetadata>;
+ excludeMapping: ExcludedPolicyTypes;
+}
+
+export interface ExcludedPolicyTypes {
+ componentType: string;
+ excludedPolicyTypes: Array<string>;
+} \ No newline at end of file
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 8ed5c734c0..33e83ce00a 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
@@ -18,14 +18,18 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { SchemaPropertyGroupModel, SchemaProperty } from '../aschema-property';
-import { DerivedPropertyType, PropertyBEModel } from '../../models';
+import { DerivedPropertyType, PropertyBEModel, PropertyFEModel } from '../../models';
import { PROPERTY_TYPES } from 'app/utils';
import { UUID } from "angular2-uuid";
export class DerivedFEProperty extends PropertyBEModel {
- valueObj: any;
+ valueObj: any;
+ valueObjIsValid: boolean;
+ valueObjOrig: any;
+ valueObjIsChanged: boolean;
parentName: string;
propertiesName: string; //"network_assignments#ipv4_subnet#use_ipv4 = parentPath + name
derivedDataType: DerivedPropertyType;
@@ -36,6 +40,7 @@ export class DerivedFEProperty extends PropertyBEModel {
isChildOfListOrMap: boolean;
canBeDeclared: boolean;
mapKey: string;
+ mapKeyError: string;
constructor(property: PropertyBEModel, parentName?: string, createChildOfListOrMap?: boolean, key?:string, value?:any) {
if (!createChildOfListOrMap) { //creating a standard derived prop
@@ -54,17 +59,44 @@ export class DerivedFEProperty extends PropertyBEModel {
if (property.type == PROPERTY_TYPES.LIST) {
this.mapKey = property.schema.property.type.split('.').pop();
+ this.mapKeyError = null;
this.type = property.schema.property.type;
} else { //map
- this.mapKey = key || "";
+ if (key) {
+ this.mapKey = key;
+ this.mapKeyError = null;
+ } else {
+ this.mapKey = '';
+ this.mapKeyError = 'Key cannot be empty.';
+ }
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.updateValueObjOrig();
}
+ this.valueObjIsValid = true;
this.derivedDataType = this.getDerivedPropertyType();
}
-
+
+ public getActualMapKey() {
+ return (this.mapKeyError) ? this.name : this.mapKey;
+ }
+
+ public updateValueObj(valueObj:any, isValid:boolean) {
+ this.valueObj = PropertyFEModel.cleanValueObj(valueObj);
+ this.valueObjIsValid = isValid;
+ this.valueObjIsChanged = this.hasValueObjChanged();
+ }
+
+ public updateValueObjOrig() {
+ this.valueObjOrig = _.cloneDeep(this.valueObj);
+ this.valueObjIsChanged = false;
+ }
+
+ public hasValueObjChanged() {
+ return !_.isEqual(this.valueObj, this.valueObjOrig);
+ }
}
export class DerivedFEPropertyMap {
[parentPath: string]: Array<DerivedFEProperty>;
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
index f6548a352c..942d775c6e 100644
--- a/catalog-ui/src/app/models/properties-inputs/input-be-model.ts
+++ b/catalog-ui/src/app/models/properties-inputs/input-be-model.ts
@@ -41,9 +41,6 @@ export class InputBEModel extends PropertyBEModel {
this.inputPath = input.inputPath;
}
- public toJSON = (): any => {
- };
-
}
export interface ComponentInstanceModel extends InputBEModel {
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 630374aac3..c349f41ea2 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
@@ -18,15 +18,22 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { SchemaPropertyGroupModel, SchemaProperty } from "../aschema-property";
-import { PropertyBEModel } from "../../models";
+import {PropertyFEModel} from "../../models";
import {PROPERTY_DATA} from "../../utils/constants";
import {InputBEModel} from "./input-be-model";
+import {DerivedPropertyType} from "./property-be-model";
export class InputFEModel extends InputBEModel {
isSimpleType: boolean;
relatedPropertyValue: any;
relatedPropertyName: string;
+ defaultValueObj:any;
+ defaultValueObjIsValid:boolean;
+ defaultValueObjOrig:any;
+ defaultValueObjIsChanged:boolean;
+ derivedDataType: DerivedPropertyType;
constructor(input?: InputBEModel) {
super(input);
@@ -37,7 +44,37 @@ export class InputFEModel extends InputBEModel {
this.relatedPropertyValue = relatedProperty.value;
this.relatedPropertyName = relatedProperty.name;
}
+ this.derivedDataType = this.getDerivedPropertyType();
+ this.resetDefaultValueObjValidation();
+ this.updateDefaultValueObjOrig();
}
}
+ public updateDefaultValueObj(defaultValueObj:any, isValid:boolean) {
+ this.defaultValueObj = PropertyFEModel.cleanValueObj(defaultValueObj);
+ this.defaultValueObjIsValid = isValid;
+ this.defaultValueObjIsChanged = this.hasDefaultValueChanged();
+ }
+
+ public updateDefaultValueObjOrig() {
+ this.defaultValueObjOrig = _.cloneDeep(this.defaultValueObj);
+ this.defaultValueObjIsChanged = false;
+ }
+
+ public getJSONDefaultValue(): string {
+ return PropertyFEModel.stringifyValueObj(this.defaultValueObj, this.schema.property.type, this.derivedDataType);
+ }
+
+ public getDefaultValueObj(): any {
+ return PropertyFEModel.parseValueObj(this.defaultValue, this.type, this.derivedDataType);
+ }
+
+ public resetDefaultValueObjValidation() {
+ this.defaultValueObjIsValid = true;
+ }
+
+ hasDefaultValueChanged(): boolean {
+ return !_.isEqual(this.defaultValueObj, this.defaultValueObjOrig);
+ }
+
} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts b/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts
index 6faa6ada84..a0c087bdc2 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
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {SchemaPropertyGroupModel, SchemaProperty} from '../aschema-property';
import { PROPERTY_DATA, PROPERTY_TYPES } from 'app/utils';
import { FilterPropertiesAssignmentData, PropertyBEModel, DerivedPropertyType, DerivedFEPropertyMap, DerivedFEProperty } from 'app/models';
@@ -34,6 +35,10 @@ export class PropertyFEModel extends PropertyBEModel {
propertiesName: string;
uniqueId: string;
valueObj: any; //this is the only value we relate to in the html templates
+ valueObjValidation: any;
+ valueObjIsValid: boolean;
+ valueObjOrig: any; //this is valueObj representation as saved in server
+ valueObjIsChanged: boolean;
derivedDataType: DerivedPropertyType;
constructor(property: PropertyBEModel){
@@ -44,19 +49,50 @@ export class PropertyFEModel extends PropertyBEModel {
this.derivedDataType = this.getDerivedPropertyType();
this.flattenedChildren = [];
this.propertiesName = this.name;
+ this.valueObj = null;
+ this.updateValueObjOrig();
+ this.resetValueObjValidation();
}
- 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 => (typeof item == 'string')? JSON.parse(item) : item));
- } catch (e){}
+ public updateValueObj(valueObj:any, isValid:boolean) {
+ this.valueObj = PropertyFEModel.cleanValueObj(valueObj);
+ this.valueObjValidation = this.valueObjIsValid = isValid;
+ this.valueObjIsChanged = this.hasValueObjChanged();
+ }
+
+ public updateValueObjOrig() {
+ this.valueObjOrig = _.cloneDeep(this.valueObj);
+ this.valueObjIsChanged = false;
+ }
+
+ public calculateValueObjIsValid(valueObjValidation?: any) {
+ valueObjValidation = (valueObjValidation !== undefined) ? valueObjValidation : this.valueObjValidation;
+ if (valueObjValidation instanceof Array) {
+ return valueObjValidation.every((v) => this.calculateValueObjIsValid(v));
+ } else if (valueObjValidation instanceof Object) {
+ return Object.keys(valueObjValidation).every((k) => this.calculateValueObjIsValid(valueObjValidation[k]));
}
+ return Boolean(valueObjValidation);
+ }
- return (this.derivedDataType == DerivedPropertyType.SIMPLE) ? this.valueObj : JSON.stringify(this.valueObj);
+ public resetValueObjValidation() {
+ if (this.derivedDataType === DerivedPropertyType.SIMPLE) {
+ this.valueObjValidation = null;
+ } else if (this.derivedDataType === DerivedPropertyType.LIST) {
+ this.valueObjValidation = [];
+ } else {
+ this.valueObjValidation = {};
+ }
+ this.valueObjIsValid = true;
+ }
+
+ public getJSONValue = (): string => {
+ return PropertyFEModel.stringifyValueObj(this.valueObj, this.schema.property.type, this.derivedDataType);
+ }
+
+ public getValueObj = (): any => {
+ return PropertyFEModel.parseValueObj(this.value, this.type, this.derivedDataType, this.defaultValue);
}
public setNonDeclared = (childPath?: string): void => {
@@ -106,12 +142,94 @@ export class PropertyFEModel extends PropertyBEModel {
public childPropUpdated = (childProp: DerivedFEProperty): void => {
let parentNames = this.getParentNamesArray(childProp.propertiesName, []);
if (parentNames.length) {
- _.set(this.valueObj, parentNames.join('.'), childProp.valueObj);
+ const childPropName = parentNames.join('.');
+ // unset value only if is null and valid, and not in a list
+ if (childProp.valueObj === null && childProp.valueObjIsValid) {
+ const parentChildProp = this.flattenedChildren.find((ch) => ch.propertiesName === childProp.parentName) || this;
+ if (parentChildProp.derivedDataType !== DerivedPropertyType.LIST) {
+ _.unset(this.valueObj, childPropName);
+ this.valueObj = PropertyFEModel.cleanValueObj(this.valueObj);
+ } else {
+ _.set(this.valueObj, childPropName, null);
+ }
+ } else {
+ _.set(this.valueObj, childPropName, childProp.valueObj);
+ }
+ if (childProp.valueObjIsChanged) {
+ _.set(this.valueObjValidation, childPropName, childProp.valueObjIsValid);
+ this.valueObjIsValid = childProp.valueObjIsValid && this.calculateValueObjIsValid();
+ this.valueObjIsChanged = true;
+ } else {
+ _.unset(this.valueObjValidation, childPropName);
+ this.valueObjIsValid = this.calculateValueObjIsValid();
+ this.valueObjIsChanged = this.hasValueObjChanged();
+ }
+ }
+ };
+
+ childPropMapKeyUpdated = (childProp: DerivedFEProperty, newMapKey: string, forceValidate: boolean = false) => {
+ if (!childProp.isChildOfListOrMap || childProp.derivedDataType !== DerivedPropertyType.MAP) {
+ return;
+ }
+
+ const childParentNames = this.getParentNamesArray(childProp.parentName);
+ const oldActualMapKey = childProp.getActualMapKey();
+
+ childProp.mapKey = newMapKey;
+ if (childProp.mapKey === null) { // null -> remove map key
+ childProp.mapKeyError = null;
+ } else if (!childProp.mapKey) {
+ childProp.mapKeyError = 'Key cannot be empty.';
+ } else if (this.flattenedChildren
+ .filter((fch) => fch !== childProp && fch.parentName === childProp.parentName) // filter sibling child props
+ .map((fch) => fch.mapKey)
+ .indexOf(childProp.mapKey) !== -1) {
+ childProp.mapKeyError = 'This key already exists.';
+ } else {
+ childProp.mapKeyError = null;
+ }
+ const newActualMapKey = childProp.getActualMapKey();
+ const newMapKeyIsValid = !childProp.mapKeyError;
+
+ // if mapKey was changed, then replace the old key with the new one
+ if (newActualMapKey !== oldActualMapKey) {
+ const oldChildPropNames = childParentNames.concat([oldActualMapKey]);
+ const newChildPropNames = (newActualMapKey) ? childParentNames.concat([newActualMapKey]) : null;
+
+ // add map key to valueObj and valueObjValidation
+ if (newChildPropNames) {
+ const newChildVal = _.get(this.valueObj, oldChildPropNames);
+ if (newChildVal !== undefined) {
+ _.set(this.valueObj, newChildPropNames, newChildVal);
+ _.set(this.valueObjValidation, newChildPropNames, _.get(this.valueObjValidation, oldChildPropNames, childProp.valueObjIsValid));
+ }
+ }
+
+ // remove map key from valueObj and valueObjValidation
+ _.unset(this.valueObj, oldChildPropNames);
+ _.unset(this.valueObjValidation, oldChildPropNames);
+
+ // force validate after map key change
+ forceValidate = true;
+ }
+
+ if (forceValidate) {
+ // add custom entry for map key validation:
+ const childMapKeyNames = childParentNames.concat(`%%KEY:${childProp.name}%%`);
+ if (newActualMapKey) {
+ _.set(this.valueObjValidation, childMapKeyNames, newMapKeyIsValid);
+ } else {
+ _.unset(this.valueObjValidation, childMapKeyNames);
+ }
+
+ this.valueObjIsValid = newMapKeyIsValid && this.calculateValueObjIsValid();
+ this.valueObjIsChanged = this.hasValueObjChanged();
}
};
/* Returns array of individual parents for given prop path, with list/map UUIDs replaced with index/mapkey */
public getParentNamesArray = (parentPropName: string, parentNames?: Array<string>): Array<string> => {
+ parentNames = parentNames || [];
if (parentPropName.indexOf("#") == -1) { return parentNames; } //finished recursing parents. return
let parentProp: DerivedFEProperty = this.flattenedChildren.find(prop => prop.propertiesName === parentPropName);
@@ -119,7 +237,7 @@ export class PropertyFEModel extends PropertyBEModel {
if (parentProp.isChildOfListOrMap) {
if (parentProp.derivedDataType == DerivedPropertyType.MAP) {
- nameToInsert = parentProp.mapKey;
+ nameToInsert = parentProp.getActualMapKey();
} else { //LIST
let siblingProps = this.flattenedChildren.filter(prop => prop.parentName == parentProp.parentName).map(prop => prop.propertiesName);
nameToInsert = siblingProps.indexOf(parentProp.propertiesName).toString();
@@ -130,5 +248,72 @@ export class PropertyFEModel extends PropertyBEModel {
return this.getParentNamesArray(parentProp.parentName, parentNames); //continue recursing
}
+ public hasValueObjChanged() {
+ return !_.isEqual(this.valueObj, this.valueObjOrig);
+ }
+ static stringifyValueObj(valueObj: any, propertyType: PROPERTY_TYPES, propertyDerivedType: DerivedPropertyType): string {
+ // if valueObj is null, return null
+ if (valueObj === null || valueObj === undefined) {
+ return null;
+ }
+
+ //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 (propertyDerivedType == DerivedPropertyType.LIST && propertyType == PROPERTY_TYPES.JSON) {
+ try {
+ return JSON.stringify(valueObj.map(item => (typeof item == 'string') ? JSON.parse(item) : item));
+ } catch (e){}
+ }
+
+ // if type is anything but string, then stringify valueObj
+ if ((typeof valueObj) !== 'string') {
+ return JSON.stringify(valueObj);
+ }
+
+ // return string value as is
+ return valueObj;
+ }
+
+ static parseValueObj(value: string, propertyType: PROPERTY_TYPES, propertyDerivedType: DerivedPropertyType, defaultValue?: string): any {
+ let valueObj;
+ if (propertyDerivedType === DerivedPropertyType.SIMPLE) {
+ valueObj = value || defaultValue || null; // use null for empty value object
+ if (valueObj &&
+ propertyType !== PROPERTY_TYPES.STRING &&
+ propertyType !== PROPERTY_TYPES.JSON &&
+ PROPERTY_DATA.SCALAR_TYPES.indexOf(<string>propertyType) == -1) {
+ valueObj = JSON.parse(value); // the value object contains the real value ans not the value as string
+ }
+ } else if (propertyDerivedType == DerivedPropertyType.LIST) {
+ valueObj = _.merge([], JSON.parse(defaultValue || '[]'), JSON.parse(value || '[]')); // value object should be merged value and default value. Value takes higher precedence. Set value object to empty obj if undefined.
+ } else {
+ valueObj = _.merge({}, JSON.parse(defaultValue || '{}'), JSON.parse(value || '{}')); // value object should be merged value and default value. Value takes higher precedence. Set value object to empty obj if undefined.
+ }
+ return valueObj;
+ };
+
+ static cleanValueObj(valueObj: any, unsetEmpty?: boolean): any {
+ // By default - unsetEmpty undefined - will make valueObj cleaned (no null or empty objects, but array will keep null or empty objects).
+ if (valueObj === undefined || valueObj === null || valueObj === '') {
+ return null;
+ }
+ if (valueObj instanceof Array) {
+ const cleanArr = valueObj.map((v) => PropertyFEModel.cleanValueObj(v)).filter((v) => v !== null);
+ valueObj.splice(0, valueObj.length, ...cleanArr)
+ } else if (valueObj instanceof Object) {
+ Object.keys(valueObj).forEach((k) => {
+ // clean each item in the valueObj (by default, unset empty objects)
+ valueObj[k] = PropertyFEModel.cleanValueObj(valueObj[k], unsetEmpty !== undefined ? unsetEmpty : true);
+ if (valueObj[k] === null) {
+ delete valueObj[k];
+ }
+ });
+ // if unsetEmpty flag is true and valueObj is empty
+ if (unsetEmpty && !Object.keys(valueObj).length) {
+ return null;
+ }
+ }
+ return valueObj;
+ }
}
diff --git a/catalog-ui/src/app/models/properties.ts b/catalog-ui/src/app/models/properties.ts
index 7a1f1a39ef..7ff27706b0 100644
--- a/catalog-ui/src/app/models/properties.ts
+++ b/catalog-ui/src/app/models/properties.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {SchemaPropertyGroupModel, SchemaProperty} from "./aschema-property";
import {InputPropertyBase} from "./input-property-base";
import {PropertyBEModel} from "./properties-inputs/property-be-model";
diff --git a/catalog-ui/src/app/models/requirement.ts b/catalog-ui/src/app/models/requirement.ts
index d880456b06..65428b398e 100644
--- a/catalog-ui/src/app/models/requirement.ts
+++ b/catalog-ui/src/app/models/requirement.ts
@@ -22,7 +22,9 @@
* Created by obarda on 4/20/2016.
*/
'use strict';
+import * as _ from "lodash";
import {RequirementCapabilityModel} from "./capability";
+
//this is an object contains keys, when each key has matching array.
// for example: key = tosca.capabilities.network. and the match array is array of requirements objects
export class RequirementsGroup {
@@ -44,6 +46,7 @@ export class Requirement implements RequirementCapabilityModel{
name:string;
ownerId:string;
ownerName:string;
+ parentName: string;
node:string;
uniqueId:string;
relationship:string;
@@ -60,6 +63,7 @@ export class Requirement implements RequirementCapabilityModel{
this.name = requirement.name;
this.ownerId = requirement.ownerId;
this.ownerName = requirement.ownerName;
+ this.parentName = requirement.parentName;
this.node = requirement.node;
this.uniqueId = requirement.uniqueId;
this.relationship = requirement.relationship;
diff --git a/catalog-ui/src/app/modules/directive-module.ts b/catalog-ui/src/app/modules/directive-module.ts
index 4039a7683a..1babeefbdb 100644
--- a/catalog-ui/src/app/modules/directive-module.ts
+++ b/catalog-ui/src/app/modules/directive-module.ts
@@ -72,11 +72,12 @@ import {CompositionGraphGeneralUtils} from "../directives/graphs-v2/composition-
import {CompositionGraphLinkUtils} from "../directives/graphs-v2/composition-graph/utils/composition-graph-links-utils";
import {DeploymentGraphGeneralUtils} from "../directives/graphs-v2/deployment-graph/deployment-utils/deployment-graph-general-utils";
import {CompositionGraphPaletteUtils} from "../directives/graphs-v2/composition-graph/utils/composition-graph-palette-utils";
+import {CompositionGraphZoneUtils} from "../directives/graphs-v2/composition-graph/utils/composition-graph-zone-utils";
import {MatchCapabilitiesRequirementsUtils} from "../directives/graphs-v2/composition-graph/utils/match-capability-requierment-utils";
-import {AssetPopoverDirective} from "../directives/graphs-v2/asset-popover/asset-popover";
-import {downgradeComponent} from "@angular/upgrade/static";
import {CapabilitiesListDirective} from "../directives/capabilities-and-requirements/capability/capabilities-list-directive";
import {RequirementsListDirective} from "../directives/capabilities-and-requirements/requirement/requirements-list-directive";
+import {ServicePathGraphUtils} from "../directives/graphs-v2/composition-graph/utils/composition-graph-service-path-utils";
+import {PaletteAnimationComponent} from './../ng2/components/ui/palette-animation/palette-animation.component';
let moduleName:string = 'Sdc.Directives';
let directiveModule:ng.IModule = angular.module(moduleName, []);
@@ -157,7 +158,10 @@ directiveModule.service('CompositionGraphNodesUtils', CompositionGraphNodesUtils
directiveModule.service('CompositionGraphGeneralUtils', CompositionGraphGeneralUtils);
directiveModule.service('CompositionGraphLinkUtils', CompositionGraphLinkUtils);
directiveModule.service('CompositionGraphPaletteUtils', CompositionGraphPaletteUtils);
+directiveModule.service('CompositionGraphZoneUtils', CompositionGraphZoneUtils);
directiveModule.service('MatchCapabilitiesRequirementsUtils', MatchCapabilitiesRequirementsUtils);
+directiveModule.service('ServicePathGraphUtils', ServicePathGraphUtils);
+
//
// //Deployment Graph Utils
directiveModule.service('DeploymentGraphGeneralUtils', DeploymentGraphGeneralUtils);
@@ -169,15 +173,70 @@ directiveModule.directive('requirementsList', RequirementsListDirective.factory)
// *** NG2 Components (downgraded) *** //
-import {MenuListNg2Component} from "../ng2/components/downgrade-wrappers/menu-list-ng2/menu-list-ng2.component";
-import {TopNavComponent} from "../ng2/components/layout/top-nav/top-nav.component";
+import { downgradeComponent } from "@angular/upgrade/static";
+import { MenuListNg2Component } from "../ng2/components/downgrade-wrappers/menu-list-ng2/menu-list-ng2.component";
+import { TopNavComponent } from "../ng2/components/layout/top-nav/top-nav.component";
+import { ZoneContainerComponent } from "../ng2/components/ui/canvas-zone/zone-container.component";
+import { ZoneInstanceComponent } from "../ng2/components/ui/canvas-zone/zone-instance/zone-instance.component";
+import { PropertiesAssignmentComponent } from "../ng2/pages/properties-assignment/properties-assignment.page.component";
+import { SearchWithAutoCompleteComponent } from "../ng2/components/ui/search-with-autocomplete/search-with-autocomplete.component";
+import { PalettePopupPanelComponent } from "../ng2/components/ui/palette-popup-panel/palette-popup-panel.component";
+import { ServicePathComponent } from '../ng2/components/logic/service-path/service-path.component';
+import { ServicePathSelectorComponent } from '../ng2/components/logic/service-path-selector/service-path-selector.component';
directiveModule.directive('menuListNg2', downgradeComponent({
component: MenuListNg2Component,
inputs: ['props']
}) as angular.IDirectiveFactory);
+
directiveModule.directive('topNav', downgradeComponent({
component: TopNavComponent,
inputs: ['version', 'menuModel', 'topLvlSelectedIndex', 'hideSearch', 'searchTerm', 'notificationIconCallback'],
outputs: ['searchTermChange']
}) as ng.IDirectiveFactory);
+
+directiveModule.directive('ng2ZoneContainer', downgradeComponent({
+ component: ZoneContainerComponent,
+ inputs: ['title', 'count', 'class', 'showZone', 'minifyZone'],
+ outputs: []
+}) as angular.IDirectiveFactory);
+
+directiveModule.directive('ng2ZoneInstance', downgradeComponent({
+ component: ZoneInstanceComponent,
+ inputs: ['config', 'isActive', 'activeInstanceMode', 'defaultIconText'],
+ outputs: ['modeChange']
+}) as angular.IDirectiveFactory);
+
+directiveModule.directive('propertiesAssignment', downgradeComponent({
+ component: PropertiesAssignmentComponent
+}) as angular.IDirectiveFactory);
+
+directiveModule.directive('ng2SearchWithAutocomplete', downgradeComponent({
+ component: SearchWithAutoCompleteComponent,
+ inputs: ['searchPlaceholder', 'searchBarClass', 'autoCompleteValues'],
+ outputs: ['searchChanged', 'searchButtonClicked']
+}) as angular.IDirectiveFactory);
+
+directiveModule.directive('ng2PaletteAnimation', downgradeComponent({
+ component: PaletteAnimationComponent,
+ inputs: ['from', 'to', 'icon' ],
+ outputs: []
+ }) as angular.IDirectiveFactory);
+
+directiveModule.directive('ng2PalettePopupPanel', downgradeComponent({
+ component: PalettePopupPanelComponent,
+ inputs: [],
+ outputs: []
+}) as angular.IDirectiveFactory);
+
+directiveModule.directive('ng2ServicePath', downgradeComponent({
+ component: ServicePathComponent,
+ inputs: ['onCreate', 'service'],
+ outputs: []
+}) as angular.IDirectiveFactory);
+
+directiveModule.directive('ng2ServicePathSelector', downgradeComponent({
+ component: ServicePathSelectorComponent,
+ inputs: ['drawPath', 'deletePaths', 'service', 'selectedPathId'],
+ outputs: []
+}) as angular.IDirectiveFactory);
diff --git a/catalog-ui/src/app/modules/service-module.ts b/catalog-ui/src/app/modules/service-module.ts
index 387332cae5..c934b630c8 100644
--- a/catalog-ui/src/app/modules/service-module.ts
+++ b/catalog-ui/src/app/modules/service-module.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -48,11 +48,14 @@ import {downgradeInjectable} from "@angular/upgrade/static";
import {ModalService} from "../ng2/services/modal.service";
import {ComponentServiceNg2} from "../ng2/services/component-services/component.service";
import {ServiceServiceNg2} from "../ng2/services/component-services/service.service";
+import {ComponentServiceFactoryNg2} from "../ng2/services/component-services/component.service.factory";
import {ConnectionWizardService} from "../ng2/pages/connection-wizard/connection-wizard.service";
import {ComponentInstanceServiceNg2} from "../ng2/services/component-instance-services/component-instance.service";
import {UserService as UserServiceNg2} from "../ng2/services/user.service";
import {PluginsService} from "../ng2/services/plugins.service";
import {EventBusService} from "../ng2/services/event-bus.service";
+import {PoliciesService as PoliciesServiceNg2} from "../ng2/services/policies.service";
+import {DynamicComponentService} from "app/ng2/services/dynamic-component.service";
let moduleName:string = 'Sdc.Services';
let serviceModule:ng.IModule = angular.module(moduleName, []);
@@ -92,6 +95,7 @@ serviceModule.factory('Sdc.Services.CategoryResourceService', CategoryResourceSe
// Angular2 upgraded services - This is in order to use the service in angular1 till we finish remove all angular1 code
serviceModule.factory('ComponentServiceNg2', downgradeInjectable(ComponentServiceNg2));
+serviceModule.factory('ComponentServiceFactoryNg2', downgradeInjectable(ComponentServiceFactoryNg2));
serviceModule.factory('ServiceServiceNg2', downgradeInjectable(ServiceServiceNg2));
serviceModule.factory('ModalServiceNg2', downgradeInjectable(ModalService));
serviceModule.factory('ConnectionWizardServiceNg2', downgradeInjectable(ConnectionWizardService));
@@ -99,3 +103,5 @@ serviceModule.factory('ComponentInstanceServiceNg2', downgradeInjectable(Compone
serviceModule.factory('UserServiceNg2', downgradeInjectable(UserServiceNg2));
serviceModule.factory('PluginsService', downgradeInjectable(PluginsService));
serviceModule.factory('EventBusService', downgradeInjectable(EventBusService));
+serviceModule.factory('PoliciesServiceNg2', downgradeInjectable(PoliciesServiceNg2));
+serviceModule.factory('DynamicComponentService', downgradeInjectable(DynamicComponentService));
diff --git a/catalog-ui/src/app/ng2/app.module.ts b/catalog-ui/src/app/ng2/app.module.ts
index ffeb1fd89f..727f0fe8f5 100644
--- a/catalog-ui/src/app/ng2/app.module.ts
+++ b/catalog-ui/src/app/ng2/app.module.ts
@@ -28,7 +28,8 @@ import {UpgradeModule} from '@angular/upgrade/static';
import {PropertiesAssignmentModule} from './pages/properties-assignment/properties-assignment.module';
import {
DataTypesServiceProvider, SharingServiceProvider, CookieServiceProvider, StateServiceFactory,
- StateParamsServiceFactory, CacheServiceProvider, EventListenerServiceProvider, ScopeServiceFactory
+ StateParamsServiceFactory, CacheServiceProvider, EventListenerServiceProvider, ScopeServiceFactory,
+ NotificationServiceProvider
} from "./utils/ng1-upgraded-provider";
import {ConfigService} from "./services/config.service";
import {HttpModule} from '@angular/http';
@@ -36,6 +37,7 @@ import {HttpService} from './services/http.service';
import {AuthenticationService} from './services/authentication.service';
import {Cookie2Service} from "./services/cookie.service";
import {ComponentServiceNg2} from "./services/component-services/component.service";
+import {ComponentServiceFactoryNg2} from "./services/component-services/component.service.factory";
import {ServiceServiceNg2} from "./services/component-services/service.service";
import {ComponentInstanceServiceNg2} from "./services/component-instance-services/component-instance.service";
import {ModalService} from "./services/modal.service";
@@ -43,12 +45,18 @@ import {UiElementsModule} from "./components/ui/ui-elements.module";
import {ConnectionWizardModule} from "./pages/connection-wizard/connection-wizard.module";
import {LayoutModule} from "./components/layout/layout.module";
import {UserService} from "./services/user.service";
+import {PoliciesService} from "./services/policies.service";
+import {DynamicComponentService} from "./services/dynamic-component.service";
import {SdcConfig} from "./config/sdc-config.config";
import { TranslateModule } from "./shared/translator/translate.module";
import { TranslationServiceConfig } from "./config/translation.service.config";
+import {ServicePathCreatorModule} from './pages/service-path-creator/service-path-creator.module';
+import {ServicePathsListModule} from './pages/service-paths-list/service-paths-list.module';
import {PluginFrameModule} from "./components/ui/plugin/plugin-frame.module";
import {PluginsService} from "./services/plugins.service";
import {EventBusService} from "./services/event-bus.service";
+import {ServicePathModule} from 'app/ng2/components/logic/service-path/service-path.module';
+import {ServicePathSelectorModule} from 'app/ng2/components/logic/service-path-selector/service-path-selector.module';
export const upgradeAdapter = new UpgradeAdapter(forwardRef(() => AppModule));
@@ -76,7 +84,11 @@ export function configServiceFactory(config:ConfigService) {
//We need to import them here since we use them in angular1
ConnectionWizardModule,
PropertiesAssignmentModule,
- PluginFrameModule
+ PluginFrameModule,
+ ServicePathCreatorModule,
+ ServicePathsListModule,
+ ServicePathModule,
+ ServicePathSelectorModule
],
exports: [],
entryComponents: [],
@@ -85,18 +97,22 @@ export function configServiceFactory(config:ConfigService) {
SharingServiceProvider,
CookieServiceProvider,
StateServiceFactory,
- ScopeServiceFactory,
StateParamsServiceFactory,
+ ScopeServiceFactory,
CacheServiceProvider,
EventListenerServiceProvider,
+ NotificationServiceProvider,
AuthenticationService,
Cookie2Service,
ConfigService,
ComponentServiceNg2,
+ ComponentServiceFactoryNg2,
ModalService,
ServiceServiceNg2,
HttpService,
UserService,
+ PoliciesService,
+ DynamicComponentService,
SdcConfig,
ComponentInstanceServiceNg2,
TranslationServiceConfig,
diff --git a/catalog-ui/src/app/ng2/components/layout/top-nav/top-nav.component.ts b/catalog-ui/src/app/ng2/components/layout/top-nav/top-nav.component.ts
index b8b0e80861..12f8df8296 100644
--- a/catalog-ui/src/app/ng2/components/layout/top-nav/top-nav.component.ts
+++ b/catalog-ui/src/app/ng2/components/layout/top-nav/top-nav.component.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {Component, Inject, Input, Output, EventEmitter} from "@angular/core";
import {IHostedApplication, IUserProperties} from "app/models";
import {MenuItemGroup, MenuItem} from "app/utils";
@@ -142,9 +143,9 @@ export class TopNavComponent {
}
}
- goToState(state:string, params:any):Promise<boolean> {
+ goToState(state:string, params:Array<any>):Promise<boolean> {
return new Promise((resolve, reject) => {
- this.$state.go(state, params || undefined);
+ this.$state.go(state, params && params.length > 0 ? [0] : undefined);
resolve(true);
});
}
diff --git a/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.html b/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.html
index ddda82ab58..cc8aed70d4 100644
--- a/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.html
+++ b/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.html
@@ -7,7 +7,7 @@
<checkbox [label]="'All'" [(checked)]="allSelected" (checkedChange)="selectAll()" data-tests-id="filter-checkbox-all"></checkbox>
</div>
<div *ngFor="let type of typesOptions">
- <checkbox [label]="type" [(checked)]="selectedTypes[type]" (checkedChange)="onTypeSelected(type)"></checkbox>
+ <checkbox [label]="type" [(checked)]="selectedTypes[type]" (checkedChange)="onTypeSelected(type)" [attr.data-tests-id]="'filter-checkbox-' + type.toLowerCase()"></checkbox>
</div>
</div>
<div class="field">
diff --git a/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.ts b/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.ts
index 5a9bfbcecb..fe2c7bb09a 100644
--- a/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.ts
+++ b/catalog-ui/src/app/ng2/components/logic/filter-properties-assignment/filter-properties-assignment.component.ts
@@ -21,6 +21,7 @@
/**
* Created by rc2122 on 5/16/2017.
*/
+import * as _ from "lodash";
import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
import {ButtonModel, ButtonsModelMap, FilterPropertiesAssignmentData} from "app/models";
import * as sdcConfig from "../../../../../../configurations/dev"
diff --git a/catalog-ui/src/app/ng2/components/logic/hierarchy-navigtion/hierarchy-navigation.component.ts b/catalog-ui/src/app/ng2/components/logic/hierarchy-navigtion/hierarchy-navigation.component.ts
index dc0a02c277..1698157e90 100644
--- a/catalog-ui/src/app/ng2/components/logic/hierarchy-navigtion/hierarchy-navigation.component.ts
+++ b/catalog-ui/src/app/ng2/components/logic/hierarchy-navigtion/hierarchy-navigation.component.ts
@@ -37,12 +37,10 @@ export class HierarchyNavigationComponent {
onClick = ($event, item) => {
$event.stopPropagation();
- this.selectedItem = item;
this.updateSelected.emit(item);
};
onSelectedUpdate = ($event) => {
- this.selectedItem = $event;
this.updateSelected.emit($event);
}
}
diff --git a/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.html b/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.html
index 57e0474c66..b7cde7eb23 100644
--- a/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.html
+++ b/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.html
@@ -30,11 +30,11 @@
<dynamic-element class="value-input"
*ngIf="input.isSimpleType"
pattern="validationUtils.getValidationPattern(input.type)"
- [(value)]="input.defaultValue"
+ [value]="input.defaultValueObj"
[type]="input.type"
[name]="input.name"
- (change)="onInputValueChanged(input);"
- [readonly]="readonly">
+ (elementChanged)="onInputChanged(input, $event)"
+ [readonly]="readonly">
</dynamic-element>
<div class="delete-button-container">
<span *ngIf="input.instanceUniqueId && !readonly" class="sprite-new delete-btn" (click)="openDeleteModal(input)" data-tests-id="delete-input-button"></span>
diff --git a/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.less b/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.less
index 0545874f53..d709f3f0c5 100644
--- a/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.less
+++ b/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.less
@@ -11,7 +11,7 @@
text-align:left;
.inner-cell-div{
- width: 100%;
+ max-width: 100%;
text-overflow: ellipsis;
overflow: hidden;
height: 20px;
@@ -85,8 +85,8 @@
border-right:#d2d2d2 solid 1px;
}
&.col1 {
- flex: 1 0 200px;
- max-width:300px;
+ flex: 1 0 210px;
+ max-width:210px;
display: flex;
justify-content: space-between;
@@ -121,7 +121,6 @@
.value-input {
flex: 1;
- max-height: 24px;
border: none;
background-color: inherit;
diff --git a/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.ts b/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.ts
index 0add1cd707..ebecbc9390 100644
--- a/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.ts
+++ b/catalog-ui/src/app/ng2/components/logic/inputs-table/inputs-table.component.ts
@@ -36,7 +36,7 @@ export class InputsTableComponent {
@Input() instanceNamesMap: Map<string, string>;
@Input() readonly:boolean;
@Input() isLoading:boolean;
- @Output() inputValueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output() inputChanged: EventEmitter<any> = new EventEmitter<any>();
@Output() deleteInput: EventEmitter<any> = new EventEmitter<any>();
selectedInputToDelete:InputFEModel;
@@ -44,8 +44,9 @@ export class InputsTableComponent {
constructor(private modalService: ModalService){
}
- onInputValueChanged = (input) => {
- this.inputValueChanged.emit(input);
+ onInputChanged = (input, event) => {
+ input.updateDefaultValueObj(event.value, event.isValid);
+ this.inputChanged.emit(input);
};
onDeleteInput = () => {
diff --git a/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.html b/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.html
index 14b6c7d4c0..4805875d83 100644
--- a/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.html
+++ b/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.html
@@ -10,7 +10,16 @@
</div>
<div class="table-cell" *ngIf="!canBeDeclared && !property.isChildOfListOrMap">{{property.name}}</div> <!-- simple children of complex type within map or list -->
<div class="table-cell map-entry" *ngIf="property.isChildOfListOrMap && propType == derivedPropertyTypes.MAP"><!-- map left cell -->
- <input [value]="property.mapKey" #mapKey (change)="mapKeyChanged.emit(mapKey)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly, 'error':!mapKey.validity.valid}" required/>
+ <!--<input [value]="property.mapKey" [placeholder]="property.name" (input)="mapKeyChanged.emit($event.target.value)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly, 'error':property.mapKeyError}" required/>-->
+ <dynamic-element #mapKeyInput
+ class="value-input"
+ pattern="validationUtils.getValidationPattern(string)"
+ [value]="property.mapKey"
+ type="string"
+ [name]="property.name"
+ (elementChanged)="mapKeyChanged.emit($event.value)"
+ [readonly]="readonly"
+ ></dynamic-element>
</div>
</ng-container>
<!-- RIGHT CELL OR FULL WIDTH CELL-->
@@ -18,11 +27,11 @@
<div class="table-cell">
<dynamic-element class="value-input"
pattern="validationUtils.getValidationPattern(property.type)"
- [(value)]="property.valueObj"
+ [value]="property.valueObj"
[type]="property.isDeclared ? 'string' : property.type"
[name]="property.name"
[path]="property.propertiesName"
- (valueChange)="valueChanged.emit();"
+ (elementChanged)="onElementChanged($event)"
[readonly]="readonly || property.isDeclared || property.isDisabled"
></dynamic-element>
</div>
@@ -54,8 +63,8 @@
[propertyNameSearchText]="propertyNameSearchText"
[readonly]="readonly"
[hasChildren]="getHasChildren(prop)"
- (valueChanged)="childValueChanged(prop)"
- (mapKeyChanged)="removeValueFromParent(prop, $event)"
+ (propertyChanged)="childValueChanged(prop)"
+ (mapKeyChanged)="updateChildKeyInParent(prop, $event)"
(expandChild)="expandChildById($event)"
(deleteItem)="deleteListOrMapItem($event)"
(clickOnPropertyRow)="onClickPropertyRow($event)"
diff --git a/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.ts b/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.ts
index 04cb26d030..6f7e57b643 100644
--- a/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.ts
+++ b/catalog-ui/src/app/ng2/components/logic/properties-table/dynamic-property/dynamic-property.component.ts
@@ -18,13 +18,15 @@
* ============LICENSE_END=========================================================
*/
-import {Component, Input, Output, EventEmitter} from "@angular/core";
+import * as _ from "lodash";
+import {Component, Input, Output, EventEmitter, ViewChild, ComponentRef} from "@angular/core";
import { PropertyFEModel, DerivedFEProperty, DerivedPropertyType } from "app/models";
import { PROPERTY_TYPES } from 'app/utils';
import { DataTypeService } from "../../../../services/data-type.service";
import { trigger, state, style, transition, animate } from '@angular/core';
import {PropertiesUtils} from "../../../../pages/properties-assignment/services/properties.utils";
-
+import {IUiElementChangeEvent} from "../../../ui/form-components/ui-element-base.component";
+import {DynamicElementComponent} from "../../../ui/dynamic-element/dynamic-element.component";
@Component({
selector: 'dynamic-property',
@@ -49,7 +51,7 @@ export class DynamicPropertyComponent {
@Input() hasChildren: boolean;
@Input() hasDeclareOption:boolean;
- @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output('propertyChanged') emitter: EventEmitter<void> = new EventEmitter<void>();
@Output() expandChild: EventEmitter<string> = new EventEmitter<string>();
@Output() checkProperty: EventEmitter<string> = new EventEmitter<string>();
@Output() deleteItem: EventEmitter<string> = new EventEmitter<string>();
@@ -57,6 +59,7 @@ export class DynamicPropertyComponent {
@Output() mapKeyChanged: EventEmitter<string> = new EventEmitter<string>();
@Output() addChildPropsToParent: EventEmitter<Array<DerivedFEProperty>> = new EventEmitter<Array<DerivedFEProperty>>();
+ @ViewChild('mapKeyInput') public mapKeyInput: DynamicElementComponent;
constructor(private propertiesUtils: PropertiesUtils, private dataTypeService: DataTypeService) {
}
@@ -68,6 +71,17 @@ export class DynamicPropertyComponent {
this.nestedLevel = (this.property.propertiesName.match(/#/g) || []).length;
}
+ ngDoCheck() {
+ // set custom error for mapKeyInput
+ if (this.mapKeyInput) {
+ const mapKeyInputControl = this.mapKeyInput.cmpRef.instance.control;
+ const mapKeyError = (<DerivedFEProperty>this.property).mapKeyError;
+ if (mapKeyInputControl.getError('mapKeyError') !== mapKeyError) {
+ mapKeyInputControl.setErrors({mapKeyError});
+ }
+ }
+ }
+
onClickPropertyRow = (property, event) => {
// Because DynamicPropertyComponent is recrusive second time the event is fire event.stopPropagation = undefined
@@ -91,9 +105,15 @@ export class DynamicPropertyComponent {
}).length > 1;
}
+ onElementChanged = (event: IUiElementChangeEvent) => {
+ this.property.updateValueObj(event.value, event.isValid);
+ this.emitter.emit();
+ };
+
createNewChildProperty = (): void => {
- let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, "", undefined);
+ let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, "", null);
+ this.propertiesUtils.assignFlattenedChildrenValues(this.property.valueObj, [newProps[0]], this.property.propertiesName);
if (this.property instanceof PropertyFEModel) {
this.addChildProps(newProps, this.property.name);
} else {
@@ -108,28 +128,25 @@ export class DynamicPropertyComponent {
this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
this.expandChildById(newProps[0].propertiesName);
-
- if(!newProps[0].schema.property.isSimpleType){
- if ( newProps[0].mapKey ) {//prevent update the new item value on parent property valueObj and saving on BE if it is map item, it will be updated and saved only after user enter key (when it is list item- the map key is the es type)
- this.updateMapKeyValueOnMainParent(newProps);
- if (this.property.getParentNamesArray(newProps[0].propertiesName, []).indexOf('') === -1) {
- this.valueChanged.emit(this.property.name);
- }
- }
- }
+ this.updateMapKeyValueOnMainParent(newProps);
+ this.emitter.emit();
}
}
updateMapKeyValueOnMainParent(childrenProps: Array<DerivedFEProperty>){
if (this.property instanceof PropertyFEModel) {
+ const property: PropertyFEModel = <PropertyFEModel>this.property;
//Update only if all this property parents has key name
- if (this.property.getParentNamesArray(childrenProps[0].propertiesName, []).indexOf('') === -1){
+ if (property.getParentNamesArray(childrenProps[0].propertiesName, []).indexOf('') === -1){
angular.forEach(childrenProps, (prop:DerivedFEProperty):void => { //Update parent PropertyFEModel with value for each child, including nested props
- (<PropertyFEModel>this.property).childPropUpdated(prop);
+ property.childPropUpdated(prop);
+ if (prop.isChildOfListOrMap && prop.mapKey !== undefined) {
+ property.childPropMapKeyUpdated(prop, prop.mapKey, true);
+ }
},this);
//grab the cumulative value for the new item from parent PropertyFEModel and assign that value to DerivedFEProp[0] (which is the list or map parent with UUID of the set we just added)
- let parentNames = (<PropertyFEModel>this.property).getParentNamesArray(childrenProps[0].propertiesName, []);
- childrenProps[0].valueObj = _.get(this.property.valueObj, parentNames.join('.'));
+ let parentNames = (<PropertyFEModel>property).getParentNamesArray(childrenProps[0].propertiesName, []);
+ childrenProps[0].valueObj = _.get(property.valueObj, parentNames.join('.'), null);
}
}
}
@@ -140,7 +157,7 @@ export class DynamicPropertyComponent {
if (this.property.getParentNamesArray(property.propertiesName, []).indexOf('') === -1) {//If one of the parents is empty key -don't save
this.property.childPropUpdated(property);
this.dataTypeService.checkForCustomBehavior(this.property);
- this.valueChanged.emit(this.property.name);
+ this.emitter.emit();
}
}
}
@@ -153,46 +170,42 @@ export class DynamicPropertyComponent {
}
}
- removeValueFromParent = (item: DerivedFEProperty, target?: any) => {
+ removeValueFromParent = (item: DerivedFEProperty) => {
if (this.property instanceof PropertyFEModel) {
- let itemParent = (item.parentName == this.property.name) ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
+ let itemParent = (item.parentName == this.property.name)
+ ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
+ if (!itemParent) {
+ return;
+ }
if (item.derivedDataType == DerivedPropertyType.MAP) {
- let oldKey = item.mapKey;
- if (target && typeof target.value == 'string') { //allow saving empty string
- let replaceKey:string = target.value;
- if (!replaceKey) {//prevent delete map key
- return;
- }
- if(Object.keys(itemParent.valueObj).indexOf(replaceKey) > -1){//the key is exists
- target.setCustomValidity('This key is already exists.');
- return;
- }else {
- target.setCustomValidity('');
- _.set(itemParent.valueObj, replaceKey, itemParent.valueObj[oldKey]);
- item.mapKey = replaceKey;
- //If the map key was empty its valueObj was not updated on its prent property valueObj, and now we should update it.
- if(!oldKey && !item.schema.property.isSimpleType){
- //Search this map item children and update these value on parent property valueOBj
- let mapKeyFlattenChildren:Array<DerivedFEProperty> = _.filter(this.property.flattenedChildren, (prop:DerivedFEProperty) => {
- return _.startsWith(prop.propertiesName, item.propertiesName);
- });
- this.updateMapKeyValueOnMainParent(mapKeyFlattenChildren);
- }
- }
- }
+ const oldKey = item.getActualMapKey();
delete itemParent.valueObj[oldKey];
+ if (itemParent instanceof PropertyFEModel) {
+ delete itemParent.valueObjValidation[oldKey];
+ itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
+ }
+ this.property.childPropMapKeyUpdated(item, null); // remove map key
} else {
- let itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName);
+ const itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName);
itemParent.valueObj.splice(itemIndex, 1);
- }
- if (item.mapKey) {//prevent going to BE if user tries to delete map item without key (it was not saved in BE)
- if (itemParent instanceof PropertyFEModel) { //direct child
- this.valueChanged.emit(this.property.name);
- } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
- this.childValueChanged(itemParent);
+ if (itemParent instanceof PropertyFEModel) {
+ itemParent.valueObjValidation.splice(itemIndex, 1);
+ itemParent.valueObjIsValid = itemParent.calculateValueObjIsValid();
}
}
+ if (itemParent instanceof PropertyFEModel) { //direct child
+ this.emitter.emit();
+ } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
+ this.childValueChanged(itemParent);
+ }
+ }
+ }
+
+ updateChildKeyInParent(childProp: DerivedFEProperty, newMapKey: string) {
+ if (this.property instanceof PropertyFEModel) {
+ this.property.childPropMapKeyUpdated(childProp, newMapKey);
+ this.emitter.emit();
}
}
diff --git a/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.html b/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.html
index 933b80f577..ecfa7e7c5e 100644
--- a/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.html
+++ b/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.html
@@ -48,7 +48,7 @@
[expandedChildId]="property.expandedChildPropertyId"
[propertyNameSearchText]="propertyNameSearchText"
[readonly]="readonly"
- (valueChanged)="propValueChanged(property);"
+ (propertyChanged)="onPropertyChanged(property)"
(expandChild)="property.updateExpandedChildPropertyId($event)"
(clickOnPropertyRow)="onClickPropertyInnerRow($event, instanceId)"
(checkProperty)="propertyChecked(property, $event)"
diff --git a/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.ts b/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.ts
index 32bbb1b3a0..093fae1684 100644
--- a/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.ts
+++ b/catalog-ui/src/app/ng2/components/logic/properties-table/properties-table.component.ts
@@ -39,7 +39,7 @@ export class PropertiesTableComponent {
@Input() hasDeclareOption:boolean;
@Input() hidePropertyType:boolean;
- @Output() valueChanged: EventEmitter<any> = new EventEmitter<any>();
+ @Output('propertyChanged') emitter: EventEmitter<PropertyFEModel> = new EventEmitter<PropertyFEModel>();
@Output() selectPropertyRow: EventEmitter<PropertyRowSelectedEvent> = new EventEmitter<PropertyRowSelectedEvent>();
@Output() updateCheckedPropertyCount: EventEmitter<boolean> = new EventEmitter<boolean>();//only for hasDeclareOption
@@ -49,8 +49,8 @@ export class PropertiesTableComponent {
ngOnInit() {
}
- propValueChanged = (property) => {
- this.valueChanged.emit(property);
+ onPropertyChanged = (property) => {
+ this.emitter.emit(property);
};
// Click on main row (row of propertyFEModel)
diff --git a/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.html b/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.html
index bcd33efc30..6e0f93f750 100644
--- a/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.html
+++ b/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.html
@@ -22,7 +22,8 @@
</div>
</div>
<div class="inner-container properties-table-container" *ngIf="selectedReqOrCapOption == 'Capability'" [ngClass]="{'cap-selected':selectedReqOrCapModel}">
- <properties-table *ngIf="selectedReqOrCapModel"
+ <loader [display]="loadingCapabilityProperties" size="medium" [relative]="true"></loader>
+ <properties-table *ngIf="selectedReqOrCapModel && !loadingCapabilityProperties"
class="properties-table"
[readonly]="true"
[fePropertiesMap]="capabilityProperties"
diff --git a/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.ts b/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.ts
index ab67dc1850..2e3c21c210 100644
--- a/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.ts
+++ b/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.component.ts
@@ -1,10 +1,10 @@
/**
* Created by rc2122 on 9/4/2017.
*/
+import * as _ from "lodash";
import {Component, EventEmitter, Input, OnInit, Output, SimpleChanges} from '@angular/core';
-import {RadioButtonModel, Match, PropertyModel, InstanceFePropertiesMap, Component as ComponentModel} from "app/models";
+import {RadioButtonModel, PropertyModel, InstanceFePropertiesMap, Component as ComponentModel} from "app/models";
import {Dictionary} from "lodash";
-import {DropdownValue} from "../../ui/form-components/dropdown/ui-element-dropdown.component";
import {ComponentInstanceServiceNg2} from "../../../services/component-instance-services/component-instance.service";
import {PropertiesUtils} from "app/ng2/pages/properties-assignment/services/properties.utils";
import {Requirement} from "../../../../models/requirement";
@@ -33,7 +33,6 @@ export class SelectRequirementOrCapabilityComponent implements OnInit {
@Input() selectedReqOrCapModel:RequirementCapabilityModel;
@Output() updateSelectedReqOrCap:EventEmitter<RequirementCapabilityModel> = new EventEmitter<RequirementCapabilityModel>();
- @Output() updateCapabilityProperties:EventEmitter<Array<PropertyModel>> = new EventEmitter<Array<PropertyModel>>();
types:Array<string> = [];
selectedType:string;
@@ -47,10 +46,14 @@ export class SelectRequirementOrCapabilityComponent implements OnInit {
displayCapReqListFilterByType:RequirementCapabilityModel[];
capabilityProperties:InstanceFePropertiesMap;
+ loadingCapabilityProperties:boolean;
+
+ private _loadingCapabilityProperties: Array<Capability>;
constructor(private componentInstanceServiceNg2:ComponentInstanceServiceNg2,
private propertiesUtils:PropertiesUtils) {
this.selectOptions = [new RadioButtonModel(REQUIREMENT, REQUIREMENT), new RadioButtonModel(CAPABILITY, CAPABILITY)];
+ this._loadingCapabilityProperties = [];
}
private initDefaultReqOrCapSelection = (): void => {
@@ -87,14 +90,17 @@ export class SelectRequirementOrCapabilityComponent implements OnInit {
initCapabilityPropertiesTable = ():void => {
if(this.selectedReqOrCapModel instanceof Capability ) {
let selectedCapability = <Capability>this.selectedReqOrCapModel;
- if(selectedCapability.properties){
+ if (selectedCapability.properties && selectedCapability.properties.length) {
this.capabilityProperties = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren({ CAPABILITY : selectedCapability.properties}, false);
+ } else {
+ this.capabilityProperties = null;
}
}
}
ngOnChanges(changes:SimpleChanges) {
if (changes.selectedReqOrCapModel) {
+ this.capabilityProperties = null;
if (this.selectedReqOrCapModel && this.selectedReqOrCapOption === CAPABILITY) {
this.setCapabilityProperties();
}
@@ -168,15 +174,27 @@ export class SelectRequirementOrCapabilityComponent implements OnInit {
private setCapabilityProperties = ():void => {
let selectedCapability = <Capability>this.selectedReqOrCapModel;
- if (selectedCapability.properties === undefined) {
- this.componentInstanceServiceNg2.getInstanceCapabilityProperties(this.currentComponent, this.componentInstanceId, selectedCapability.type, selectedCapability.name)
- .subscribe((response:Array<PropertyModel>) => {
- this.capabilityProperties = (response && response.length) ? this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren({CAPABILITY : response}, false) : null;
- this.updateCapabilityProperties.emit(response);
- }, error => {});
- }else{
- this.capabilityProperties = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren({CAPABILITY : selectedCapability.properties}, false);
- this.updateCapabilityProperties.emit(selectedCapability.properties);
+ if (!selectedCapability.properties) {
+ this.loadingCapabilityProperties = true;
+ if (this._loadingCapabilityProperties.indexOf(selectedCapability) == -1) {
+ this._loadingCapabilityProperties.push(selectedCapability);
+ this.componentInstanceServiceNg2.getInstanceCapabilityProperties(this.currentComponent, this.componentInstanceId, selectedCapability)
+ .subscribe((response: Array<PropertyModel>) => {
+ if (this.selectedReqOrCapModel === selectedCapability) {
+ delete this.loadingCapabilityProperties;
+ }
+ this.initCapabilityPropertiesTable();
+ }, (error) => {
+ if (this.selectedReqOrCapModel === selectedCapability) {
+ delete this.loadingCapabilityProperties;
+ }
+ }, () => {
+ this._loadingCapabilityProperties.splice(this._loadingCapabilityProperties.indexOf(selectedCapability), 1);
+ });
+ }
+ } else {
+ delete this.loadingCapabilityProperties;
+ this.initCapabilityPropertiesTable();
}
}
}
diff --git a/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.module.ts b/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.module.ts
index cb12dea02a..259ae12380 100644
--- a/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.module.ts
+++ b/catalog-ui/src/app/ng2/components/logic/select-requirement-or-capability/select-requirement-or-capability.module.ts
@@ -5,6 +5,7 @@ import {FormElementsModule} from "../../ui/form-components/form-elements.module"
import {CommonModule} from "@angular/common";
import {GlobalPipesModule} from "app/ng2/pipes/global-pipes.module";
import {PropertyTableModule} from "../properties-table/property-table.module";
+import {UiElementsModule} from "../../ui/ui-elements.module";
@NgModule({
declarations: [
@@ -15,7 +16,9 @@ import {PropertyTableModule} from "../properties-table/property-table.module";
FormsModule,
FormElementsModule,
GlobalPipesModule,
- PropertyTableModule],
+ UiElementsModule,
+ PropertyTableModule
+ ],
exports: [SelectRequirementOrCapabilityComponent],
providers: []
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.html b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.html
new file mode 100644
index 0000000000..72e083534c
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.html
@@ -0,0 +1,11 @@
+<div class="service-path-selector">
+ <label>Service Paths:</label>
+ <ui-element-dropdown
+ class="path-dropdown"
+ data-tests-id="service-path-selector"
+ [readonly]="dropdownOptions.length < 3"
+ [(value)]="selectedPathId"
+ [values]="dropdownOptions"
+ (valueChange)="onSelectPath()">
+ </ui-element-dropdown>
+</div>
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.less b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.less
new file mode 100644
index 0000000000..f3cb4a3c34
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.less
@@ -0,0 +1,24 @@
+@import './../../../../../assets/styles/variables.less';
+.service-path-selector {
+ margin: 10px 35px 10px 0;
+ display: flex;
+ font-size: 12px;
+
+ /deep/ .path-dropdown {
+ width: 150px;
+ select {
+ font-size: 14px;
+ font-family: @font-opensans-regular;
+ padding: 4px 10px;
+ }
+ }
+
+ label {
+ margin-right: 10px;
+ align-self: center;
+ font-size: 14px;
+ font-family: @font-opensans-regular;
+ font-weight: normal;
+ margin-bottom: initial;
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.ts b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.ts
new file mode 100644
index 0000000000..be9966acef
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.component.ts
@@ -0,0 +1,134 @@
+import * as _ from "lodash";
+import {Component, Input, KeyValueDiffer, IterableDiffers, KeyValueDiffers, DoCheck} from '@angular/core';
+import {Service} from "app/models/components/service";
+import {TranslateService} from "app/ng2/shared/translator/translate.service";
+import {ForwardingPath} from "app/models/forwarding-path";
+import {DropdownValue} from "app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component";
+
+@Component({
+ selector: 'service-path-selector',
+ templateUrl: './service-path-selector.component.html',
+ styleUrls:['service-path-selector.component.less'],
+ providers: [TranslateService]
+})
+
+export class ServicePathSelectorComponent implements DoCheck {
+
+ defaultSelectedId: string;
+ hideAllValue: string;
+ hideAllId: string = '0';
+ showAllValue: string;
+ showAllId: string = '1';
+
+ paths: Array<ForwardingPath> = [];
+ dropdownOptions: Array<DropdownValue>;
+ differ: KeyValueDiffer;
+
+ @Input() service: Service;
+ @Input() drawPath: Function;
+ @Input() deletePaths: Function;
+ @Input() selectedPathId: string;
+
+ constructor(private differs: KeyValueDiffers, private translateService: TranslateService) {
+
+ this.defaultSelectedId = this.hideAllId;
+ this.convertPathsToDropdownOptions();
+
+ this.translateService.languageChangedObservable.subscribe(lang => {
+ this.hideAllValue = this.translateService.translate("SERVICE_PATH_SELECTOR_HIDE_ALL_VALUE");
+ this.showAllValue = this.translateService.translate("SERVICE_PATH_SELECTOR_SHOW_ALL_VALUE");
+ this.convertPathsToDropdownOptions();
+ });
+
+ }
+
+ ngOnInit(): void {
+
+ this.selectedPathId = this.defaultSelectedId;
+ this.differ = this.differs.find(this.service.forwardingPaths).create(null);
+
+ }
+
+ ngDoCheck(): void {
+
+ const pathsChanged = this.differ.diff(this.service.forwardingPaths);
+
+ if (pathsChanged) {
+ let oldPaths = _.cloneDeep(this.paths);
+ this.populatePathsFromService();
+
+ if (!(_.isEqual(oldPaths, this.paths))) {
+ this.convertPathsToDropdownOptions();
+
+ let temp = this.selectedPathId;
+ this.selectedPathId = '-1';
+
+ setTimeout(() => {
+ this.selectedPathId = temp;
+ this.onSelectPath();
+ }, 0);
+ }
+ }
+
+ }
+
+ populatePathsFromService(): void {
+
+ this.paths = [];
+ let {forwardingPaths} = this.service;
+
+ _.forEach(forwardingPaths, path => {
+ this.paths.push(path);
+ });
+ this.paths.sort((a:ForwardingPath, b:ForwardingPath)=> {
+ return a.name.localeCompare(b.name);
+ });
+
+ }
+
+ convertPathsToDropdownOptions(): void {
+
+ let result = [
+ new DropdownValue(this.hideAllId, this.hideAllValue),
+ new DropdownValue(this.showAllId, this.showAllValue)
+ ];
+
+ _.forEach(this.paths, (value: ForwardingPath) => {
+ result[result.length] = new DropdownValue(value.uniqueId, value.name);
+ });
+
+ this.dropdownOptions = result;
+
+ }
+
+ onSelectPath = (): void => {
+
+ if (this.selectedPathId !== '-1') {
+ this.deletePaths();
+
+ switch (this.selectedPathId) {
+ case this.hideAllId:
+ break;
+
+ case this.showAllId:
+ _.forEach(this.paths, path =>
+ this.drawPath(path)
+ );
+ break;
+
+ default:
+ let path = this.paths.find(path =>
+ path.uniqueId === this.selectedPathId
+ );
+ if (!path) {
+ this.selectedPathId = this.defaultSelectedId;
+ this.onSelectPath(); // currently does nothing in default case, but if one day it does, we want the selection to behave accordingly.
+ break;
+ }
+ this.drawPath(path);
+ break;
+ }
+ }
+
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.module.ts b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.module.ts
new file mode 100644
index 0000000000..c07061ce9a
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path-selector/service-path-selector.module.ts
@@ -0,0 +1,21 @@
+import { NgModule } from "@angular/core";
+import {CommonModule} from "@angular/common";
+import {ServicePathSelectorComponent} from "./service-path-selector.component";
+import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module";
+
+@NgModule({
+ declarations: [
+ ServicePathSelectorComponent
+ ],
+ imports: [
+ CommonModule,
+ UiElementsModule
+ ],
+ exports: [],
+ entryComponents: [
+ ServicePathSelectorComponent
+ ],
+ providers: []
+})
+export class ServicePathSelectorModule {
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.html b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.html
new file mode 100644
index 0000000000..ff7902e2b9
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.html
@@ -0,0 +1,22 @@
+<div class='service-path'>
+ <button class='zoom-icons create-path-button' data-tests-id="pathsMenuBtn" (click)="showServicePathMenu = !showServicePathMenu">...</button>
+ <div class="service-path-menu"
+ *ngIf="showServicePathMenu" >
+ <div >
+ <ul>
+ <li><div class="hand" (click)="onCreateServicePath()" data-tests-id="createPathMenuItem">
+ Create Service Path
+ </div></li>
+ <li><div class="hand" (click)="onListServicePath()" data-tests-id="pathsListMenuItem">
+ Service Paths List
+ </div></li>
+ </ul>
+ </div>
+ </div>
+ <!-- TODO - ask Orit about positioning issues and styling issues -->
+ <!--
+ <menu-list [open]="showServicePathMenu" [position]="menuPos" >
+ <menu-item [action]="onCreateServicePath">Create Path</menu-item>
+ <menu-item [action]="onListServicePath">Paths' List</menu-item>
+ </menu-list> -->
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.less b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.less
new file mode 100644
index 0000000000..777b206714
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.less
@@ -0,0 +1,51 @@
+//@import 'src/assets/styles/variables.less';
+@import './../../../../../assets/styles/variables.less';
+.service-path {
+ position: relative;
+ .create-path-button{
+ &:extend(.search-bar-button);
+ width: 30px;
+ height: 30px;
+ &:hover {
+ color: @main_color_a;
+ }
+ &:active {
+ background: @main_color_a;
+ color: @main_color_p;
+ }
+ &:focus {
+ outline: none;
+ }
+ }
+ .service-path-menu {
+ border: 1px solid @main_color_o;
+ border-radius: 0 0 2px 2px;
+ border-top-color: @main_color_a;
+ border-top-width: 3px;
+
+ box-sizing: border-box;
+ box-shadow: 0 2px 4px 0 rgba(0,0,0,0.30);
+
+ background-color: @main_color_p;
+
+ padding: 5px 0;
+ right: 34px;
+ position: absolute;
+ top: 10px;
+ width: 150px;
+ font-size: 13px;
+ font-family: @font-opensans-regular;
+
+ li {
+ color: @main_color_m;
+ padding: 0 10px;
+ line-height: 20px;
+ &:hover {
+ cursor: pointer;
+ color: @main_color_a;
+ background-color: fade(@main_color_a, 5%);
+ }
+ }
+
+ }
+}
diff --git a/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.ts b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.ts
new file mode 100644
index 0000000000..4a6209fb6f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.component.ts
@@ -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=========================================================
+ */
+
+import {Component, Input, ComponentRef} from '@angular/core';
+import {ModalService} from 'app/ng2/services/modal.service';
+import {ModalModel, ButtonModel} from 'app/models';
+import {ServicePathCreatorComponent} from 'app/ng2/pages/service-path-creator/service-path-creator.component';
+import {ModalComponent} from 'app/ng2/components/ui/modal/modal.component';
+import ServicePathsListComponent from "app/ng2/pages/service-paths-list/service-paths-list.component";
+import {Service} from "app/models/components/service";
+
+@Component({
+ selector: 'service-path',
+ templateUrl: './service-path.component.html',
+ styleUrls: ['service-path.component.less'],
+ providers: [ModalService]
+})
+
+export class ServicePathComponent {
+ showServicePathMenu: boolean = false;
+ modalInstance: ComponentRef<ModalComponent>;
+ @Input() service: Service;
+ @Input() onCreate: Function;
+ @Input() onSave: Function;
+
+ constructor(private ModalServiceNg2: ModalService) {}
+
+ onCreateServicePath = ():void => {
+ this.showServicePathMenu = false;
+ let cancelButton: ButtonModel = new ButtonModel('Cancel', 'outline white', this.ModalServiceNg2.closeCurrentModal);
+ let saveButton: ButtonModel = new ButtonModel('Create', 'blue', this.createPath, this.getDisabled );
+ let modalModel: ModalModel = new ModalModel('l', 'Create Service Path', '', [saveButton, cancelButton], 'standard', true);
+ this.modalInstance = this.ModalServiceNg2.createCustomModal(modalModel);
+ this.ModalServiceNg2.addDynamicContentToModal(this.modalInstance, ServicePathCreatorComponent, {service: this.service});
+ this.modalInstance.instance.open();
+ };
+
+ onListServicePath = ():void => {
+ this.showServicePathMenu = false;
+ let cancelButton: ButtonModel = new ButtonModel('Close', 'outline white', this.ModalServiceNg2.closeCurrentModal);
+ let modalModel: ModalModel = new ModalModel('md', 'Service Paths List','', [cancelButton], 'standard', true);
+ this.modalInstance = this.ModalServiceNg2.createCustomModal(modalModel);
+ this.ModalServiceNg2.addDynamicContentToModal(this.modalInstance, ServicePathsListComponent, {service: this.service,
+ onCreateServicePath: this.onCreateServicePath, onEditServicePath: this.onEditServicePath});
+ this.modalInstance.instance.open();
+ };
+
+ createPath = ():void => {
+ this.onCreate(this.modalInstance.instance.dynamicContent.instance.createServicePathData());
+ this.ModalServiceNg2.closeCurrentModal();
+ };
+
+ onEditServicePath = (id:string):void => {
+ let cancelButton: ButtonModel = new ButtonModel('Cancel', 'outline white', this.ModalServiceNg2.closeCurrentModal);
+ let saveButton: ButtonModel = new ButtonModel('Save', 'blue', this.createPath, this.getDisabled );
+ let modalModel: ModalModel = new ModalModel('l', 'Edit Path', '', [saveButton, cancelButton]);
+ this.modalInstance = this.ModalServiceNg2.createCustomModal(modalModel);
+ this.ModalServiceNg2.addDynamicContentToModal(this.modalInstance, ServicePathCreatorComponent, {service: this.service, pathId: id});
+ this.modalInstance.instance.open();
+ };
+
+ getDisabled = ():boolean => {
+ return !this.modalInstance.instance.dynamicContent.instance.checkFormValidForSubmit();
+ };
+}
+
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.module.ts
index 82e9a36780..96af247086 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java
+++ b/catalog-ui/src/app/ng2/components/logic/service-path/service-path.module.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,22 +18,22 @@
* ============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;
- }
-
-}
+import { NgModule } from "@angular/core";
+import {CommonModule} from "@angular/common";
+import {ServicePathComponent} from "./service-path.component";
+import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module";
+
+@NgModule({
+ declarations: [
+ ServicePathComponent
+ ],
+ imports: [CommonModule,
+ UiElementsModule],
+ exports: [],
+ entryComponents: [
+ ServicePathComponent
+ ],
+ providers: []
+})
+export class ServicePathModule {
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.html b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.html
new file mode 100644
index 0000000000..e279e3f704
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.html
@@ -0,0 +1,11 @@
+<div class="sdc-canvas-zone {{class}}-zone" [class.minimized]="minifyZone" [class.hidden]="!showZone">
+ <div class="sdc-canvas-zone__header" (click)="unminifyZone()" >
+ <div class="sdc-canvas-zone__title">{{title}}
+ <span class="sdc-canvas-zone__counter">{{count}}</span>
+ </div>
+ <span class="sdc-canvas-zone__state-button">&ndash;</span>
+ </div>
+ <div class="sdc-canvas-zone__container">
+ <ng-content></ng-content>
+ </div>
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.less b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.less
new file mode 100644
index 0000000000..3e77c5ca3b
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.less
@@ -0,0 +1,62 @@
+.sdc-canvas-zone {
+ width: 280px;
+ max-height:186px;
+ display:flex;
+ flex-direction:column;
+ align-self: flex-end;
+ color:white;
+ font-family:OpenSans-Regular, sans-serif;
+ transition: width .2s ease-in-out, max-height .2s ease-in-out .1s;
+ position:relative;
+ bottom:0px;
+
+ .sdc-canvas-zone__header {
+ background: #5A5A5A;
+ border-radius: 2px 2px 0 0;
+ padding: 5px 10px;
+ display:flex;
+ justify-content: space-between;
+ font-size: 14px;
+ text-transform:uppercase;
+ .sdc-canvas-zone__state-button {
+ font-weight:bold;
+ cursor:pointer;
+ }
+ }
+
+ .sdc-canvas-zone__container {
+ padding:5px;
+ background-color: #5A5A5A;
+ opacity:0.9;
+ flex: 1;
+ display:flex;
+ flex-direction: row;
+ align-items: flex-start;
+ flex-wrap:wrap;
+ overflow-y:auto;
+ min-height: 80px;
+ max-height: 170px;
+ }
+
+
+ &.minimized {
+ max-height:30px;
+ width:120px;
+ cursor:pointer;
+
+ .sdc-canvas-zone__state-button {
+ display:none;
+ }
+ .sdc-canvas-zone__container {
+ flex: 0 0 0;
+ min-height: 0;
+ padding: 0;
+ overflow-y:hidden;
+ transition: min-height .2s ease-in-out .2s;
+ transition: padding .1s ease-in-out 0s;
+ }
+ }
+ &.hidden {
+ display:none;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.ts b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.ts
new file mode 100644
index 0000000000..7e60cb37a6
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-container.component.ts
@@ -0,0 +1,25 @@
+import { Component, Input, Output, ViewEncapsulation, EventEmitter } from '@angular/core';
+import { EventListenerService } from 'app/services';
+import { GRAPH_EVENTS } from 'app/utils';
+
+@Component({
+ selector: 'zone-container',
+ templateUrl: './zone-container.component.html',
+ styleUrls: ['./zone-container.component.less'],
+ encapsulation: ViewEncapsulation.None
+})
+
+export class ZoneContainerComponent {
+ @Input() title:string;
+ @Input() class:string;
+ @Input() count:number;
+ @Input() showZone:boolean;
+ @Input() minifyZone:boolean;
+ constructor(private eventListenerService:EventListenerService) {}
+
+ private unminifyZone = () => {
+ this.minifyZone = !this.minifyZone;
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_ZONE_SIZE_CHANGE);
+ }
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.html b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.html
new file mode 100644
index 0000000000..d36b7aec6f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.html
@@ -0,0 +1,8 @@
+<div class="zone-child mode-{{config.mode}}" [class.locked]="activeInstanceMode > MODE.HOVER"
+ (mouseenter)="setMode(MODE.HOVER)" (mouseleave)="setMode(MODE.NONE)" (click)="setMode(MODE.SELECTED)">
+ <div class="zone-child__handle" (click)="setMode(MODE.TAG, $event)">+</div>
+ <div class="zone-child__body">
+ <div class="zone-child__body-content">{{config.count || defaultIconText}}</div>
+ </div>
+ <div class="zone-child__name">{{config.name}}</div>
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.less b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.less
new file mode 100644
index 0000000000..a1d56df96e
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.less
@@ -0,0 +1,110 @@
+.zone-child {
+ position:relative;
+ width:76px;
+ margin:5px;
+
+ .zone-child__handle {
+ display:none;
+ position:absolute;
+ right:4px;
+ top:10px;
+ width:22px;
+ height:22px;
+ cursor:pointer;
+ border: solid white 1px;
+ border-radius: 2px;
+ text-align: center;
+ font-weight:bold;
+ }
+
+ .zone-child__body {
+ margin:0 auto;
+ width:43px;
+ height:43px;
+ display:flex;
+ padding:3px;
+
+ }
+
+ .zone-child__body-content {
+ border-radius: 2px;
+ flex:1;
+ color:white;
+ font-size:18px;
+ text-align:center;
+ display:flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ .zone-child__name {
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+ text-align:center;
+ }
+ /* Dynamic classes below */
+
+ &.mode-1, &.mode-2, &.mode-3 { //hover, selected, tag
+ .zone-child__body {
+ border:solid 2px;
+ border-radius: 2px;
+ padding:2px;
+ cursor:pointer;
+ }
+ .zone-child__handle{
+ display:block;
+ cursor:pointer;
+ }
+ }
+
+ &.locked {
+ cursor: default;
+ }
+
+ // &:not(.locked):hover .zone-child__handle{
+ // display:block;
+ // }
+ .zone-child__body {
+ cursor: default;
+ }
+ &.mode-3 .zone-child__handle {
+ width:24px;
+ height:24px;
+ right:3px;
+ top:9px;
+ display:block;
+ background-image: linear-gradient(-140deg, #009E98 0%, #97D648 100%);
+ border: 2px solid #FFFFFF;
+ border-radius: 2px;
+ box-shadow: inset 2px -2px 3px 0 #007A3E;
+ cursor: pointer;
+ }
+
+}
+.sdc-canvas-zone.group-zone {
+ .zone-child__handle {
+ background-color:#009FDB;
+ }
+ .zone-child__body {
+ border-color:#009FDB;
+ }
+ .zone-child__body-content {
+ background: #009FDB;
+ }
+}
+
+.sdc-canvas-zone.policy-zone {
+ .zone-child__handle {
+ background-color:#0568AE;
+ }
+ .zone-child__body {
+ border-color:#1287D9;
+ .zone-child__body-content {
+ background: #1287D9;
+ }
+ }
+ .zone-child__body-content {
+ background: #0568AE;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.ts b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.ts
new file mode 100644
index 0000000000..8057ae908a
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/canvas-zone/zone-instance/zone-instance.component.ts
@@ -0,0 +1,28 @@
+import { Component, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core';
+import { ZoneInstanceConfig, ZoneInstanceMode } from 'app/models/graph/zones/zone-child';
+
+@Component({
+ selector: 'zone-instance',
+ templateUrl: './zone-instance.component.html',
+ styleUrls: ['./zone-instance.component.less'],
+ encapsulation: ViewEncapsulation.None
+})
+export class ZoneInstanceComponent {
+
+ @Input() config:ZoneInstanceConfig;
+ @Input() defaultIconText:string;
+ @Input() isActive:boolean;
+ @Input() activeInstanceMode: ZoneInstanceMode;
+ @Output() modeChange: EventEmitter<any> = new EventEmitter<any>();
+ private MODE = ZoneInstanceMode;
+
+ private setMode = (mode:ZoneInstanceMode, event?:any):void => {
+ if(!this.isActive || this.isActive && mode == ZoneInstanceMode.TAG){ //when active, do not allow hover/select mode toggling
+ this.modeChange.emit({newMode: mode, instance: this.config});
+ }
+ if(event){
+ event.stopPropagation();
+ }
+ }
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/dynamic-element/dynamic-element.component.ts b/catalog-ui/src/app/ng2/components/ui/dynamic-element/dynamic-element.component.ts
index 53d1590b1c..d1e68f3088 100644
--- a/catalog-ui/src/app/ng2/components/ui/dynamic-element/dynamic-element.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/dynamic-element/dynamic-element.component.ts
@@ -18,14 +18,25 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { Component, Compiler, EventEmitter, ViewContainerRef, ViewChild, Input, Output, ElementRef, ComponentRef, ComponentFactoryResolver } from '@angular/core'
import {ValidationConfiguration} from "app/models";
+import {IUiElementChangeEvent} from "../form-components/ui-element-base.component";
import {UiElementInputComponent} from "../form-components/input/ui-element-input.component";
import {UiElementPopoverInputComponent} from "../form-components/popover-input/ui-element-popover-input.component";
import {UiElementIntegerInputComponent} from "../form-components/integer-input/ui-element-integer-input.component";
import {UiElementDropDownComponent, DropdownValue} from "../form-components/dropdown/ui-element-dropdown.component";
import {PROPERTY_DATA} from "../../../../utils/constants";
+enum DynamicElementComponentCreatorIdentifier {
+ STRING,
+ INTEGER,
+ FLOAT,
+ BOOLEAN,
+ SUBNETPOOLID,
+ DEFAULT
+}
+
@Component({
selector: 'dynamic-element',
template: `<div #target></div>`,
@@ -44,16 +55,14 @@ export class DynamicElementComponent {
@Input() name: string;
@Input() readonly:boolean;
@Input() path:string;//optional param. used only for for subnetpoolid type
- value:any;
- // Two way binding for value (need to write the "Change" word like this)
- @Output('valueChange') emitter: EventEmitter<string> = new EventEmitter<any>();
- @Input('value') set setValueValue(value) {
- this.value = value;
- }
+ @Input() value: any;
+ @Output() valueChange: EventEmitter<any> = new EventEmitter<any>();
+ @Output('elementChanged') emitter: EventEmitter<IUiElementChangeEvent> = new EventEmitter<IUiElementChangeEvent>();
cmpRef: ComponentRef<any>;
private isViewInitialized: boolean = false;
+ private elementCreatorIdentifier: DynamicElementComponentCreatorIdentifier;
validation = ValidationConfiguration.validation;
constructor(
@@ -66,29 +75,72 @@ export class DynamicElementComponent {
if (!this.isViewInitialized) {
return;
}
- if (this.cmpRef) {
- this.cmpRef.destroy();
- }
- // Factory to create component based on type or peroperty name.
+ // Factory to create component based on type or other property attributes.
+ const prevElementCreatorIdentifier: DynamicElementComponentCreatorIdentifier = this.elementCreatorIdentifier;
switch(true) {
case this.path && this.path.toUpperCase().indexOf("SUBNETPOOLID") !== -1:
+ this.elementCreatorIdentifier = DynamicElementComponentCreatorIdentifier.SUBNETPOOLID;
+ break;
+ case this.type === 'integer':
+ this.elementCreatorIdentifier = DynamicElementComponentCreatorIdentifier.INTEGER;
+ break;
+ case this.type === 'float':
+ this.elementCreatorIdentifier = DynamicElementComponentCreatorIdentifier.FLOAT;
+ break;
+ case PROPERTY_DATA.SCALAR_TYPES.indexOf(this.type) > -1:
+ case this.type === 'string':
+ this.elementCreatorIdentifier = DynamicElementComponentCreatorIdentifier.STRING;
+ break;
+ case this.type === 'boolean':
+ this.elementCreatorIdentifier = DynamicElementComponentCreatorIdentifier.BOOLEAN;
+ break;
+ default:
+ this.elementCreatorIdentifier = DynamicElementComponentCreatorIdentifier.DEFAULT;
+ }
+
+ // In case the dynamic element creator is changed, then destroy old and build new.
+ if (this.elementCreatorIdentifier !== prevElementCreatorIdentifier) {
+ if (this.cmpRef) {
+ this.cmpRef.destroy();
+ }
+ this.createComponentByIdentifier();
+ }
+
+ // Update attributes in base element class
+ if (this.cmpRef) {
+ this.cmpRef.instance.name = this.name;
+ this.cmpRef.instance.type = this.type;
+ this.cmpRef.instance.value = this.value;
+ this.cmpRef.instance.readonly = this.readonly;
+ }
+ }
+
+ createComponentByIdentifier() {
+ switch(this.elementCreatorIdentifier) {
+ case DynamicElementComponentCreatorIdentifier.SUBNETPOOLID:
if(this.name.toUpperCase().indexOf("SUBNETPOOLID") == -1){//if it's an item of subnetpoolid list get the parent name
let pathArray = this.path.split("#");
this.name = pathArray[pathArray.length - 2];
}
this.createComponent(UiElementPopoverInputComponent);
break;
- case this.type == 'integer':
+
+ case DynamicElementComponentCreatorIdentifier.INTEGER:
this.createComponent(UiElementIntegerInputComponent);
this.cmpRef.instance.pattern = this.validation.validationPatterns.integer;
break;
- case PROPERTY_DATA.SCALAR_TYPES.indexOf(this.type) > -1:
- case this.type == 'string':
+
+ case DynamicElementComponentCreatorIdentifier.FLOAT:
+ this.createComponent(UiElementIntegerInputComponent);
+ this.cmpRef.instance.pattern = /^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;
+ break;
+
+ case DynamicElementComponentCreatorIdentifier.STRING:
this.createComponent(UiElementInputComponent);
break;
- case this.type == 'boolean':
+ case DynamicElementComponentCreatorIdentifier.BOOLEAN:
this.createComponent(UiElementDropDownComponent);
// Build drop down values
@@ -96,25 +148,20 @@ export class DynamicElementComponent {
tmp.push(new DropdownValue(true,'TRUE'));
tmp.push(new DropdownValue(false,'FALSE'));
this.cmpRef.instance.values = tmp;
+ if(!_.isUndefined(this.value)){//contains the real value (and not a string)
+ this.value = JSON.parse(this.value);
+ }
break;
+
+ case DynamicElementComponentCreatorIdentifier.DEFAULT:
default:
this.createComponent(UiElementInputComponent);
console.log("ERROR: No ui component to handle type: " + this.type);
}
- // Additional attributes in base element class
- if (this.cmpRef) {
- 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
- this.cmpRef.instance.baseEmitter.subscribe((value):void => {
- this.emitter.emit(value)
- });
-
+ this.cmpRef.instance.baseEmitter.subscribe((event) => { this.emitter.emit(event); });
+ this.cmpRef.instance.valueChange.subscribe((event) => { this.valueChange.emit(event); });
}
createComponent(ComponentToCreate:any):void {
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.html b/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.html
index c6b8384183..805e5ac295 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.html
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.html
@@ -1,3 +1,3 @@
-<select name='{{name}}' [(ngModel)]="value" (change)="onSave()" [ngClass]="{'disabled':readonly}" data-tests-id="SelectType">
+<select name='{{name}}' [(ngModel)]="value" (change)="onChange()" [ngClass]="{'disabled':readonly}" data-tests-id="SelectType">
<option *ngFor="let ddvalue of values" [ngValue]="ddvalue.label != undefined ? ddvalue.value : ddvalue">{{ddvalue.label||ddvalue}}</option>
</select>
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.ts b/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.ts
index 5abf32c61b..03a1fc6040 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component.ts
@@ -43,9 +43,4 @@ export class UiElementDropDownComponent extends UiElementBase implements UiEleme
constructor() {
super();
}
-
- onSave() {
- this.baseEmitter.emit(this.value);
- }
-
}
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.html b/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.html
index b7d7c859c7..057e731ada 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.html
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.html
@@ -4,7 +4,7 @@
type="text"
[name]="name"
[(ngModel)]="value"
- (change)="onSave()"
+ (input)="onChange()"
[attr.maxlength]="validation.propertyValue.max"
[attr.minlength]="validation.propertyValue.min"
[pattern]="pattern"
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.ts b/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.ts
index fb3b3db859..ce231e76e8 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/input/ui-element-input.component.ts
@@ -32,10 +32,4 @@ export class UiElementInputComponent extends UiElementBase implements UiElementB
super();
this.pattern = this.validation.validationPatterns.comment;
}
-
- onSave() {
- if (!this.control.invalid){
- this.baseEmitter.emit(this.value);
- }
- }
}
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.html b/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.html
index 9fbc9e1094..e1555e87fd 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.html
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.html
@@ -4,7 +4,7 @@
type="text"
[name]="name"
[(ngModel)]="value"
- (change)="onSave()"
+ (input)="onChange()"
[attr.maxlength]="validation.propertyValue.max"
[attr.minlength]="validation.propertyValue.min"
[pattern]="pattern"
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.ts b/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.ts
index 1667f4393d..9aa4b5872c 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/integer-input/ui-element-integer-input.component.ts
@@ -33,9 +33,8 @@ export class UiElementIntegerInputComponent extends UiElementBase implements UiE
//this.pattern = this.validation.validationPatterns.comment;
}
- onSave() {
- if (!this.control.invalid){
- this.baseEmitter.emit(this.value ? JSON.parse(this.value) : this.value);
- }
+ onChange() {
+ this.value = this.control.valid && this.value ? JSON.parse(this.value) : this.value;
+ super.onChange();
}
}
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/popover-input/ui-element-popover-input.component.ts b/catalog-ui/src/app/ng2/components/ui/form-components/popover-input/ui-element-popover-input.component.ts
index 61688df3f0..525cd1742c 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/popover-input/ui-element-popover-input.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/popover-input/ui-element-popover-input.component.ts
@@ -35,17 +35,10 @@ export class UiElementPopoverInputComponent extends UiElementBase implements UiE
saveButton: ButtonModel;
buttonsArray: ButtonsModelMap;
- onSave = ():void => {
- if (!this.control.invalid){
- this.baseEmitter.emit(this.value);
- this.popoverContentComponent.hide();
- }
- }
-
constructor() {
super();
// Create Save button and insert to buttons map
- this.saveButton = new ButtonModel('save', 'blue', this.onSave);
+ this.saveButton = new ButtonModel('save', 'blue', this.onChange);
this.buttonsArray = { 'test': this.saveButton };
// Define the regex pattern for this controller
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/radio-buttons/radio-buttons.component.ts b/catalog-ui/src/app/ng2/components/ui/form-components/radio-buttons/radio-buttons.component.ts
index 0f80e2ad44..3e8c3b5813 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/radio-buttons/radio-buttons.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/radio-buttons/radio-buttons.component.ts
@@ -12,10 +12,6 @@ import {UiElementBaseInterface, UiElementBase} from "../ui-element-base.componen
})
export class RadioButtonComponent extends UiElementBase implements UiElementBaseInterface {
- onSave() {
- this.baseEmitter.emit(this.value);
- }
-
@Input() options:Array<RadioButtonModel>;
@Input() readonly:boolean;
@Input() direction:string = 'vertical'; //get 'horizontal' | 'vertical'
@@ -23,7 +19,7 @@ export class RadioButtonComponent extends UiElementBase implements UiElementBas
select(value:any) {
this.value = value;
- this.baseEmitter.emit(this.value);
+ this.onChange();
}
}
diff --git a/catalog-ui/src/app/ng2/components/ui/form-components/ui-element-base.component.ts b/catalog-ui/src/app/ng2/components/ui/form-components/ui-element-base.component.ts
index ae2013ff70..b4e9e7d36a 100644
--- a/catalog-ui/src/app/ng2/components/ui/form-components/ui-element-base.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/form-components/ui-element-base.component.ts
@@ -23,7 +23,12 @@ import { ValidationConfiguration } from "app/models";
import { FormControl, Validators } from '@angular/forms';
export interface UiElementBaseInterface {
- onSave();
+ onChange();
+}
+
+export interface IUiElementChangeEvent {
+ value: any;
+ isValid: boolean;
}
@Component({
@@ -35,21 +40,29 @@ export class UiElementBase {
protected validation = ValidationConfiguration.validation;
protected control: FormControl;
- // Two way binding for value (need to write the "Change" word like this)
- @Output('valueChange') baseEmitter: EventEmitter<string> = new EventEmitter<any>();
- @Input('value') set setValueValue(value) {
- this.value = value;
- }
+ @Input() value: any;
+ @Output() valueChange: EventEmitter<any> = new EventEmitter<any>();
+ @Output('elementChanged') baseEmitter: EventEmitter<IUiElementChangeEvent> = new EventEmitter<IUiElementChangeEvent>();
@Input() name: string;
@Input() type: string;
- @Input() value: any;
@Input() pattern: any;
@Input() readonly:boolean;
constructor() {
//this.control = new FormControl('', [Validators.required]);
this.control = new FormControl('', []);
+
+ this.baseEmitter.subscribe((changeEvent: IUiElementChangeEvent) => {
+ this.valueChange.emit(changeEvent.value);
+ })
+ }
+
+ onChange() {
+ this.baseEmitter.emit({
+ value: this.value,
+ isValid: this.control.valid
+ });
}
}
diff --git a/catalog-ui/src/app/ng2/components/ui/loader/loader.component.ts b/catalog-ui/src/app/ng2/components/ui/loader/loader.component.ts
index f66aa551e2..585c36660e 100644
--- a/catalog-ui/src/app/ng2/components/ui/loader/loader.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/loader/loader.component.ts
@@ -74,10 +74,10 @@ export class LoaderComponent {
if (this.relative === true) {
let parentElement = this.viewContainerRef.element.nativeElement.parentElement;
this.offset = {
- left: (parentElement.offsetLeft) ? parentElement.offsetLeft + "px" : undefined,
- top: (parentElement.offsetTop) ? parentElement.offsetTop + "px" : undefined,
- width: (parentElement.offsetWidth) ? parentElement.offsetWidth + "px" : undefined,
- height: (parentElement.offsetHeight) ? parentElement.offsetHeight + "px" : undefined
+ left: (parentElement.offsetLeft !== undefined) ? parentElement.offsetLeft + "px" : undefined,
+ top: (parentElement.offsetTop !== undefined) ? parentElement.offsetTop + "px" : undefined,
+ width: (parentElement.offsetWidth !== undefined) ? parentElement.offsetWidth + "px" : undefined,
+ height: (parentElement.offsetHeight !== undefined) ? parentElement.offsetHeight + "px" : undefined
};
}
this.isVisible = true;
diff --git a/catalog-ui/src/app/ng2/components/ui/modal/modal.component.html b/catalog-ui/src/app/ng2/components/ui/modal/modal.component.html
index 9a0fdf6bf4..6fc55d19e7 100644
--- a/catalog-ui/src/app/ng2/components/ui/modal/modal.component.html
+++ b/catalog-ui/src/app/ng2/components/ui/modal/modal.component.html
@@ -1,6 +1,14 @@
<div class="custom-modal {{input.size}}">
- <div class="ng2-modal-content">
- <div class="ng2-modal-header modal-type-{{input.type}}">
+ <div class="ng2-modal-content"
+ ngDraggable
+ [ngDraggable]="input.isMovable"
+ [handle]="ModalHandle"
+ [bounds]="ModalBounds"
+ [inBounds]="true"
+ [preventDefaultEvent]="false">
+ <div #ModalHandle
+ class="ng2-modal-header modal-type-{{input.type}}"
+ [ngClass]="{'movable': input.isMovable}">
<span class="title">{{ input.title }}</span>
<span class="close-button" (click)="close()"></span>
</div>
@@ -18,4 +26,4 @@
</div>
</div>
</div>
-<div class="modal-background"></div>
+<div #ModalBounds class="modal-background" [ngClass]="{'transparent': input.isMovable}"></div>
diff --git a/catalog-ui/src/app/ng2/components/ui/modal/modal.component.less b/catalog-ui/src/app/ng2/components/ui/modal/modal.component.less
index fac1ae74a8..03b2a70667 100644
--- a/catalog-ui/src/app/ng2/components/ui/modal/modal.component.less
+++ b/catalog-ui/src/app/ng2/components/ui/modal/modal.component.less
@@ -12,7 +12,7 @@
bottom: 0;
left: 0;
z-index: 15007;
- overflow: auto;
+ overflow: visible;
margin: auto;
display: flex;
align-items: center;
@@ -22,6 +22,8 @@
width: 100%;
box-shadow: 0 5px 15px rgba(0,0,0,.5);
border-radius: 4px;
+
+
.ng2-modal-body{
padding: 20px;
}
@@ -29,19 +31,28 @@
.ng2-modal-header{
.m_18_r;
font-weight: bold;
+
-webkit-box-flex: 1;
-ms-flex-positive: 1;
flex-grow: 1;
+
height: 50px;
line-height: 50px;
+ margin: 0px 20px;
+
display: -webkit-box;
display: -ms-flexbox;
display: flex;
+
text-align: left;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
- margin: 0px 20px;
+
+ &.ng-draggable {
+ cursor: move;
+ user-select: none;
+ }
&.modal-type-standard {
border-bottom: solid 3px @main_color_a;
@@ -101,9 +112,14 @@
background-color: #000;
opacity: 0.5;
z-index: 900;
+
+ &.transparent {
+ background-color: transparent;
+ }
}
+
.xl {
width: 1200px;
}
diff --git a/catalog-ui/src/app/ng2/components/ui/modal/modal.component.ts b/catalog-ui/src/app/ng2/components/ui/modal/modal.component.ts
index 89db8d1140..777e9bdc06 100644
--- a/catalog-ui/src/app/ng2/components/ui/modal/modal.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/modal/modal.component.ts
@@ -33,6 +33,7 @@ import { ButtonsModelMap, ModalModel } from 'app/models';
})
export class ModalComponent implements OnInit, OnDestroy {
+ @Input() isMovable: boolean;
@Input() input: ModalModel;
@Input() dynamicContent: any;
@ViewChild('dynamicContentContainer', { read: ViewContainerRef }) dynamicContentContainer: ViewContainerRef; //Allows for custom component as body instead of simple message. See ModalService.createActionModal for implementation details, and HttpService's catchError() for example.
diff --git a/catalog-ui/src/app/ng2/components/ui/modal/modal.module.ts b/catalog-ui/src/app/ng2/components/ui/modal/modal.module.ts
index c38e60194b..2999528d13 100644
--- a/catalog-ui/src/app/ng2/components/ui/modal/modal.module.ts
+++ b/catalog-ui/src/app/ng2/components/ui/modal/modal.module.ts
@@ -1,5 +1,6 @@
import { NgModule } from "@angular/core";
import { CommonModule } from '@angular/common';
+import { AngularDraggableModule } from 'angular2-draggable';
import { ModalService } from 'app/ng2/services/modal.service';
import { ErrorMessageComponent } from "./error-message/error-message.component";
import {ModalComponent} from "./modal.component";
@@ -9,7 +10,7 @@ import {ModalComponent} from "./modal.component";
ModalComponent,
ErrorMessageComponent
],
- imports: [CommonModule],
+ imports: [CommonModule, AngularDraggableModule],
exports: [ModalComponent, ErrorMessageComponent],
entryComponents: [ //need to add anything that will be dynamically created
ModalComponent,
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.html b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.html
new file mode 100644
index 0000000000..2a776d444f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.html
@@ -0,0 +1,4 @@
+<div class="palette-animation-wrapper" [style.top]="from.y + 50 + 'px'" [style.left]="from.x + 'px'" [style.transform]="transformStyle" [class.hidden]="!visible"
+ (transitionend)="animationComplete()">
+<div class="medium small sprite-resource-icons sprite-{{iconName}}-icons {{iconName}}" ></div>
+</div>
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.less b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.less
new file mode 100644
index 0000000000..54f04189c0
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.less
@@ -0,0 +1,5 @@
+.palette-animation-wrapper{
+ position: absolute;
+ z-index: 100;
+ transition: all 2s ease-in-out;
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.ts b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.ts
new file mode 100644
index 0000000000..609a1fc5e1
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.component.ts
@@ -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=========================================================
+ */
+
+import {Component, Input } from '@angular/core';
+import {BrowserModule} from '@angular/platform-browser';
+import { setTimeout } from 'core-js/library/web/timers';
+import { EventListenerService } from 'app/services';
+import { GRAPH_EVENTS } from 'app/utils';
+import { Point } from 'app/models';
+
+
+
+@Component({
+ selector: 'palette-animation',
+ templateUrl: './palette-animation.component.html',
+ styleUrls:['./palette-animation.component.less'],
+})
+
+export class PaletteAnimationComponent {
+
+ @Input() from : Point;
+ @Input() to : Point;
+ @Input() iconName : string;
+ @Input() data : any;
+
+ public animation;
+ private visible:boolean = false;
+ private transformStyle:string = "";
+
+
+ constructor(private eventListenerService:EventListenerService) {}
+
+ public runAnimation() {
+ this.visible = true;
+ let positionDiff:Point = new Point(this.to.x - this.from.x, this.to.y - this.from.y);
+ setTimeout(()=>{
+ this.transformStyle = 'translate('+ positionDiff.x + 'px,' + positionDiff.y +'px)';
+ }, 0);
+ };
+
+ public animationComplete = (e) => {
+ this.visible = false;
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_FINISH_ANIMATION_ZONE);
+ };
+
+
+}
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.module.ts b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.module.ts
new file mode 100644
index 0000000000..8674571138
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-animation/palette-animation.module.ts
@@ -0,0 +1,16 @@
+import { NgModule } from "@angular/core";
+import { CommonModule } from "@angular/common";
+import { PaletteAnimationComponent } from "./palette-animation.component";
+
+
+@NgModule({
+ declarations: [
+ PaletteAnimationComponent
+ ],
+ imports: [ CommonModule ],
+ exports: [ PaletteAnimationComponent ]
+})
+
+export class PaletteAnimationModule {
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.html b/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.html
new file mode 100644
index 0000000000..ed172bf2b0
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.html
@@ -0,0 +1,9 @@
+<div class="popup-panel" [ngClass]="{'hide':!isShowPanel}" [style.left]="popupPanelPosition.x + 'px'" [style.top]="popupPanelPosition.y + 'px'"
+ (mousedown)="addZoneInstance()"
+ (mouseenter)="onMouseEnter()"
+ (mouseleave)="onMouseLeave()">
+ <div class="popup-panel-group">
+ <div class="popup-panel-plus">+</div>
+ <div class="popup-panel-title">{{panelTitle}}</div>
+ </div>
+</div>
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.less b/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.less
new file mode 100644
index 0000000000..24f0485e76
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.less
@@ -0,0 +1,37 @@
+.popup-panel {
+ position: absolute;
+ display: inline-block;
+ background-color: white;
+ border: solid 1px #d2d2d2;
+ border-top: solid 3px #13a7df;
+ left: 208px; top: 0px;
+ width: 140px;
+ height: 40px;
+ z-index: 10000;
+
+ &:hover {
+ background-color: whitesmoke;
+ }
+
+ .popup-panel-group {
+ padding-left: 8px;
+ padding-top: 8px;
+ cursor: pointer;
+
+ .popup-panel-plus {
+ border-radius: 50%;
+ color: white;
+ background-color: #13a7df;
+ width: 20px;
+ text-align: center;
+ display: inline-block;
+ }
+
+ .popup-panel-title {
+ padding-left: 10px;
+ display: inline-block;
+ }
+
+ }
+
+}
diff --git a/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.ts b/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.ts
new file mode 100644
index 0000000000..d30d5f6178
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/ui/palette-popup-panel/palette-popup-panel.component.ts
@@ -0,0 +1,87 @@
+import {Component, OnInit} from '@angular/core';
+import {GRAPH_EVENTS} from "app/utils";
+import {LeftPaletteComponent, Point} from "app/models";
+import {EventListenerService} from "app/services";
+import {LeftPaletteMetadataTypes} from "../../../../models/components/displayComponent";
+
+@Component({
+ selector: 'app-palette-popup-panel',
+ templateUrl: './palette-popup-panel.component.html',
+ styleUrls: [ './palette-popup-panel.component.less' ],
+})
+export class PalettePopupPanelComponent implements OnInit {
+
+ public panelTitle: string;
+ public isShowPanel: boolean;
+ private component: Component;
+ private displayComponent: LeftPaletteComponent;
+ private popupPanelPosition:Point = new Point(0,0);
+
+ constructor(private eventListenerService: EventListenerService) {
+ this.isShowPanel = false;
+ }
+
+ ngOnInit() {
+ this.registerObserverCallbacks();
+ }
+
+ public onMouseEnter() {
+ this.isShowPanel = true;
+ }
+
+ public onMouseLeave() {
+ this.isShowPanel = false;
+ }
+
+ public addZoneInstance(): void {
+ if(this.displayComponent) {
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_ADD_COMPONENT_INSTANCE_ZONE_START, this.component, this.displayComponent, this.popupPanelPosition);
+ }
+ }
+
+ private registerObserverCallbacks() {
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_SHOW_POPUP_PANEL,
+ (component: Component, displayComponent: LeftPaletteComponent, sectionElem: HTMLElement) => {
+
+ this.component = component;
+ this.showPopupPanel(displayComponent, sectionElem);
+ });
+
+ this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_PALETTE_COMPONENT_HIDE_POPUP_PANEL, () => this.hidePopupPanel());
+ }
+
+ private getPopupPanelPosition (sectionElem: HTMLElement):Point {
+ let pos: ClientRect = sectionElem.getBoundingClientRect();
+ let offsetX: number = -30;
+ const offsetY: number = pos.height / 2;
+ return new Point((pos.right + offsetX), (pos.top - offsetY + window.pageYOffset));
+ };
+
+ private setPopupPanelTitle(component: LeftPaletteComponent): void {
+ if (component.categoryType === LeftPaletteMetadataTypes.Group) {
+ this.panelTitle = "Add Group";
+ return;
+ }
+
+ if (component.categoryType === LeftPaletteMetadataTypes.Policy) {
+ this.panelTitle = "Add Policy";
+ return;
+ }
+ }
+
+ private showPopupPanel(displayComponent:LeftPaletteComponent, sectionElem: HTMLElement) {
+ if(!this.isShowPanel){
+ this.displayComponent = displayComponent;
+ this.setPopupPanelTitle(displayComponent);
+ this.popupPanelPosition = this.getPopupPanelPosition(sectionElem);
+ this.isShowPanel = true;
+ }
+ };
+
+ private hidePopupPanel() {
+ if(this.isShowPanel){
+ this.isShowPanel = false;
+ }
+ };
+}
diff --git a/catalog-ui/src/app/ng2/components/ui/popover/popover-content.component.html b/catalog-ui/src/app/ng2/components/ui/popover/popover-content.component.html
index 6d76f0ad06..fc6e821f34 100644
--- a/catalog-ui/src/app/ng2/components/ui/popover/popover-content.component.html
+++ b/catalog-ui/src/app/ng2/components/ui/popover/popover-content.component.html
@@ -15,7 +15,8 @@
<ng-content></ng-content>
<div class="popover-footer">
<button *ngFor="let buttonName of buttonsNames"
- class="tlv-btn {{buttons[buttonName].cssClass}}"
+ class="tlv-btn {{buttons[buttonName].cssClass}}"
+ [attr.data-tests-id]="'filter-' + buttons[buttonName].text.toLowerCase() + '-button'"
[disabled] = "buttons[buttonName].getDisabled && buttons[buttonName].getDisabled()"
(click) = "buttons[buttonName].callback()">{{buttons[buttonName].text}}</button>
</div>
diff --git a/catalog-ui/src/app/ng2/components/ui/tabs/tabs.component.ts b/catalog-ui/src/app/ng2/components/ui/tabs/tabs.component.ts
index 21d2bbad43..f4b410347b 100644
--- a/catalog-ui/src/app/ng2/components/ui/tabs/tabs.component.ts
+++ b/catalog-ui/src/app/ng2/components/ui/tabs/tabs.component.ts
@@ -23,6 +23,8 @@ import { Tab } from './tab/tab.component';
import { ViewEncapsulation } from '@angular/core';
import { trigger, state, style, transition, animate, keyframes } from '@angular/core';
+export {Tab};
+
@Component({
selector: 'tabs',
templateUrl: './tabs.component.html',
diff --git a/catalog-ui/src/app/ng2/components/ui/ui-elements.module.ts b/catalog-ui/src/app/ng2/components/ui/ui-elements.module.ts
index 526096524c..44314734c3 100644
--- a/catalog-ui/src/app/ng2/components/ui/ui-elements.module.ts
+++ b/catalog-ui/src/app/ng2/components/ui/ui-elements.module.ts
@@ -27,6 +27,10 @@ import {ModalModule} from "./modal/modal.module";
import {PopoverModule} from "./popover/popover.module";
import {SearchBarComponent} from "./search-bar/search-bar.component";
import {SearchWithAutoCompleteComponent} from "./search-with-autocomplete/search-with-autocomplete.component";
+import {PalettePopupPanelComponent} from "./palette-popup-panel/palette-popup-panel.component";
+import {ZoneContainerComponent} from "./canvas-zone/zone-container.component";
+import {ZoneInstanceComponent } from "./canvas-zone/zone-instance/zone-instance.component";
+import {PaletteAnimationComponent} from "./palette-animation/palette-animation.component"
import {TabModule} from "./tabs/tabs.module";
import {TooltipModule} from "./tooltip/tooltip.module";
import {CommonModule} from "@angular/common";
@@ -35,15 +39,21 @@ import {BrowserModule} from "@angular/platform-browser";
import {MultiStepsWizardModule} from "./multi-steps-wizard/multi-steps-wizard.module";
import {MenuListModule} from "./menu/menu-list.module";
import {MenuListNg2Module} from "../downgrade-wrappers/menu-list-ng2/menu-list-ng2.module";
+//import {SdcUiComponentsModule} from "sdc-ui/lib/angular";
@NgModule({
declarations: [
LoaderComponent,
SearchBarComponent,
- SearchWithAutoCompleteComponent
- ],
+ SearchWithAutoCompleteComponent,
+ PalettePopupPanelComponent,
+ ZoneContainerComponent,
+ ZoneInstanceComponent,
+ PaletteAnimationComponent
+],
imports: [
+ //SdcUiComponentsModule,
BrowserModule,
FormsModule,
CommonModule,
@@ -63,6 +73,9 @@ import {MenuListNg2Module} from "../downgrade-wrappers/menu-list-ng2/menu-list-n
MultiStepsWizardModule,
SearchBarComponent,
SearchWithAutoCompleteComponent,
+ PalettePopupPanelComponent,
+ ZoneContainerComponent,
+ ZoneInstanceComponent,
DynamicElementModule,
NavbarModule,
FormElementsModule,
@@ -71,10 +84,10 @@ import {MenuListNg2Module} from "../downgrade-wrappers/menu-list-ng2/menu-list-n
TabModule,
TooltipModule,
MenuListModule,
- MenuListNg2Module
+ MenuListNg2Module,
+ PaletteAnimationComponent
],
-
- entryComponents: [SearchWithAutoCompleteComponent]
+ entryComponents: [SearchWithAutoCompleteComponent, PalettePopupPanelComponent, ZoneContainerComponent, ZoneInstanceComponent, PaletteAnimationComponent]
})
export class UiElementsModule {}
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/connection-wizard.service.ts b/catalog-ui/src/app/ng2/pages/connection-wizard/connection-wizard.service.ts
index a097fb04ea..bf5ec4c4f6 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/connection-wizard.service.ts
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/connection-wizard.service.ts
@@ -1,3 +1,4 @@
+import * as _ from "lodash";
import {ConnectRelationModel} from "../../../models/graph/connectRelationModel";
import {Injectable} from "@angular/core";
import { Requirement, Capability} from "app/models";
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.html b/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.html
index 0c9d9e6e26..a45f07b3e2 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.html
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.html
@@ -3,6 +3,5 @@
[selectedReqOrCapModel]="connectWizardService.selectedMatch && (connectWizardService.selectedMatch.isFromTo ? connectWizardService.selectedMatch.requirement : connectWizardService.selectedMatch.capability)"
[currentComponent]="connectWizardService.currentComponent"
[componentInstanceId]="connectWizardService.connectRelationModel.fromNode.componentInstance.uniqueId"
- (updateSelectedReqOrCap)="updateSelectedReqOrCap($event)"
- (updateCapabilityProperties)="onCapabilityPropertiesUpdate($event)">
+ (updateSelectedReqOrCap)="updateSelectedReqOrCap($event)">
</select-requirement-or-capability> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.ts b/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.ts
index edbbf8a0a3..054d38b063 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.ts
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/from-node-step/from-node-step.component.ts
@@ -32,10 +32,6 @@ export class FromNodeStepComponent implements IStepComponent, OnInit{
return true;
}
- onCapabilityPropertiesUpdate(capabilityProperties:Array<PropertyModel>) {
- this.connectWizardService.selectedMatch.capabilityProperties = capabilityProperties;
- }
-
private updateSelectedReqOrCap = (selected:Requirement|Capability):void => {
if(!selected){
this.connectWizardService.selectedMatch = null;
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.html b/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.html
index 9e34893272..9b1df69d77 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.html
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.html
@@ -5,7 +5,7 @@
</div>
<div class="properties-table-container">
<properties-table class="properties-table"
- (valueChanged)="propertyValueChanged($event)"
+ (propertyChanged)="propertyValueChanged($event)"
[fePropertiesMap]="capabilityPropertiesMap"
[selectedPropertyId]="''"
[hidePropertyType]="true">
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.ts b/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.ts
index 3e48785a3c..946d1858dc 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.ts
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/properties-step/properties-step.component.ts
@@ -25,7 +25,7 @@ export class PropertiesStepComponent implements IStepComponent{
constructor(@Inject(forwardRef(() => ConnectionWizardService)) public connectWizardService: ConnectionWizardService, private componentInstanceServiceNg2:ComponentInstanceServiceNg2, private propertiesUtils:PropertiesUtils) {
- this.capabilityPropertiesMap = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren({'capability' : connectWizardService.selectedMatch.capabilityProperties}, false);
+ this.capabilityPropertiesMap = this.propertiesUtils.convertPropertiesMapToFEAndCreateChildren({'capability' : connectWizardService.selectedMatch.capability.properties}, false);
}
ngOnInit() {
@@ -42,7 +42,8 @@ export class PropertiesStepComponent implements IStepComponent{
propertyValueChanged = (property: PropertyFEModel) => {
if (!property.isDeclared) {
const propChangedIdx = this.connectWizardService.changedCapabilityProperties.indexOf(property);
- if (this.componentInstanceServiceNg2.hasPropertyChanged(property)) {
+ if (property.hasValueObjChanged()) {
+ // if (this.componentInstanceServiceNg2.hasPropertyChanged(property)) {
console.log("==>" + this.constructor.name + ": propertyValueChanged " + property);
if (propChangedIdx === -1) {
this.connectWizardService.changedCapabilityProperties.push(property);
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.html b/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.html
index 67bb12e6fc..a8343ce7e2 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.html
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.html
@@ -4,6 +4,5 @@
[selectedReqOrCapOption]="displayRequirementsOrCapabilities"
[currentComponent]="connectWizardService.currentComponent"
[componentInstanceId]="connectWizardService.connectRelationModel.toNode.componentInstance.uniqueId"
- (updateSelectedReqOrCap)="updateSelectedReqOrCap($event)"
- (updateCapabilityProperties)="onCapabilityPropertiesUpdate($event)">
+ (updateSelectedReqOrCap)="updateSelectedReqOrCap($event)">
</select-requirement-or-capability> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.ts b/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.ts
index 9c7bf4dfe6..ea3b129c7b 100644
--- a/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.ts
+++ b/catalog-ui/src/app/ng2/pages/connection-wizard/to-node-step/to-node-step.component.ts
@@ -43,10 +43,6 @@ export class ToNodeStepComponent implements IStepComponent{
return false;
}
- onCapabilityPropertiesUpdate(capabilityProperties:Array<PropertyModel>) {
- this.connectWizardService.selectedMatch.capabilityProperties = capabilityProperties;
- }
-
private updateSelectedReqOrCap = (selected:Requirement|Capability):void => {
if (!selected) {
if (this.connectWizardService.selectedMatch.isFromTo) {
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 203c75dd11..907f7638bb 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
@@ -32,6 +32,7 @@ import {DataTypeService} from "../../services/data-type.service";
import {PropertiesAssignmentComponent} from "./properties-assignment.page.component";
import {HierarchyNavService} from "./services/hierarchy-nav.service";
import {PropertiesUtils} from "./services/properties.utils";
+import {InputsUtils} from "./services/inputs.utils";
import {ComponentModeService} from "../../services/component-services/component-mode.service";
@NgModule({
@@ -53,7 +54,7 @@ import {ComponentModeService} from "../../services/component-services/component-
exports: [
PropertiesAssignmentComponent
],
- providers: [PropertiesService, HierarchyNavService, PropertiesUtils, DataTypeService, ComponentModeService]
+ providers: [PropertiesService, HierarchyNavService, PropertiesUtils, InputsUtils, DataTypeService, 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 beea3fe73f..03e9f1fa7e 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
@@ -1,43 +1,50 @@
<div class="properties-assignment-page">
<div class="main-content">
<div class="left-column">
- <tabs #propertyInputTabs tabStyle="round-tabs" (tabChanged)="tabChanged($event)" [hideIndicationOnTabChange]="true">
- <tab tabTitle="Properties">
- <properties-table class="properties-table"
- [fePropertiesMap]="instanceFePropertiesMap"
- [feInstanceNamesMap]="componentInstanceNamesMap"
- [searchTerm]="searchQuery"
- [selectedPropertyId]="selectedFlatProperty.path"
- [propertyNameSearchText]="searchPropertyName"
- [readonly]="isReadonly"
- [isLoading]="loadingProperties"
- [hasDeclareOption]="true"
- (valueChanged)="propertyValueChanged($event)"
- (propertySelected)="propertySelected($event)"
- (selectPropertyRow)="selectPropertyRow($event)"
- (selectChildProperty)="selectChildProperty($event)"
- (updateCheckedPropertyCount)="updateCheckedPropertyCount($event)"
- (selectInstanceRow)="selectInstanceRow($event)">
+ <div class="main-tabs-section">
+ <tabs #propertyInputTabs tabStyle="round-tabs" (tabChanged)="tabChanged($event)" [hideIndicationOnTabChange]="true">
+ <tab tabTitle="Properties">
+ <properties-table class="properties-table"
+ [fePropertiesMap]="instanceFePropertiesMap"
+ [feInstanceNamesMap]="componentInstanceNamesMap"
+ [searchTerm]="searchQuery"
+ [selectedPropertyId]="selectedFlatProperty.path"
+ [propertyNameSearchText]="searchPropertyName"
+ [readonly]="isReadonly"
+ [isLoading]="loadingProperties || savingChangedData"
+ [hasDeclareOption]="true"
+ (propertyChanged)="dataChanged($event)"
+ (propertySelected)="propertySelected($event)"
+ (selectPropertyRow)="selectPropertyRow($event)"
+ (selectChildProperty)="selectChildProperty($event)"
+ (updateCheckedPropertyCount)="updateCheckedPropertyCount($event)"
+ (selectInstanceRow)="selectInstanceRow($event)">
</properties-table>
- </tab>
- <tab tabTitle="Inputs">
- <inputs-table class="properties-table"
- [readonly]="isReadonly"
- [inputs]="inputs | searchFilter:'name':searchQuery"
- [instanceNamesMap]="componentInstanceNamesMap"
- [isLoading]="loadingInputs"
- (deleteInput)="deleteInput($event)"
- (inputValueChanged)="inputValueChanged($event)"></inputs-table>
- </tab>
- </tabs>
+ </tab>
+ <tab tabTitle="Inputs">
+ <inputs-table class="properties-table"
+ [readonly]="isReadonly"
+ [inputs]="inputs | searchFilter:'name':searchQuery"
+ [instanceNamesMap]="componentInstanceNamesMap"
+ [isLoading]="loadingInputs"
+ (deleteInput)="deleteInput($event)"
+ (inputChanged)="dataChanged($event)">
+ </inputs-table>
+ </tab>
+ </tabs>
+ <div class="main-tabs-section-buttons">
+ <button class="tlv-btn outline blue" [disabled]="!hasChangedData || savingChangedData" (click)="reverseChangedData()" data-tests-id="properties-reverse-button">Discard</button>
+ <button class="tlv-btn blue" [disabled]="!hasChangedData || !isValidChangedData || savingChangedData" (click)="doSaveChangedData()" data-tests-id="properties-save-button">{{savingChangedData ? 'Saving' : 'Save'}}</button>
+ </div>
+ </div>
<div class="header">
- <div class="search-filter-container" [class.without-filter]="isInpusTabSelected">
- <span *ngIf="displayClearSearch && !isInpusTabSelected" (click)="clickOnClearSearch()" class="clear-filter" data-tests-id="clear-filter-button">Clear All</span>
+ <div class="search-filter-container" [class.without-filter]="isInputsTabSelected">
+ <span *ngIf="displayClearSearch && isPropertiesTabSelected" (click)="clickOnClearSearch()" class="clear-filter" data-tests-id="clear-filter-button">Clear All</span>
<input type="text" class="search-box" placeholder="Search" [(ngModel)]="searchQuery" data-tests-id="search-box"/>
<span class="sprite search-icon" data-tests-id="search-button"></span>
- <filter-properties-assignment *ngIf="!isInpusTabSelected" #advanceSearch class="advance-search" [componentType]="component.componentType" (searchProperties)="searchPropertiesInstances($event)"></filter-properties-assignment>
+ <filter-properties-assignment *ngIf="isPropertiesTabSelected" #advanceSearch class="advance-search" [componentType]="component.componentType" (searchProperties)="searchPropertiesInstances($event)"></filter-properties-assignment>
</div>
- <button class="tlv-btn blue declare-button" [disabled]="!checkedPropertiesCount || isReadonly" (click)="declareProperties()" data-tests-id="declare-button">Declare</button>
+ <button class="tlv-btn blue declare-button" [disabled]="!checkedPropertiesCount || isReadonly || hasChangedData" (click)="declareProperties()" data-tests-id="declare-button">Declare</button>
</div>
</div>
<div class="right-column gray-border">
@@ -48,10 +55,10 @@
<div class="hierarchy-header white-sub-header">
<span tooltip="{{component.name}}">{{component.name}}</span>
</div>
- <div *ngIf="!instancesNavigationData || instancesNavigationData.length === 0 || isInpusTabSelected">No data to display</div>
+ <div *ngIf="!instancesNavigationData || instancesNavigationData.length === 0 || isInputsTabSelected">No data to display</div>
<hierarchy-navigation class="hierarchy-nav"
(updateSelected)="onInstanceSelectedUpdate($event)"
- [displayData]="isInpusTabSelected ? []: instancesNavigationData"
+ [displayData]="isInputsTabSelected ? []: instancesNavigationData"
[selectedItem]="selectedInstanceData.uniqueId"
[displayOptions]="hierarchyInstancesDisplayOptions"></hierarchy-navigation>
</div>
@@ -59,12 +66,12 @@
<tab tabTitle="Property Structure">
<div class="hierarchy-nav-container">
<div class="hierarchy-header white-sub-header" [class.selected]="selectedFlatProperty.path == propertyStructureHeader">
- <span tooltip="{{!isInpusTabSelected ? propertyStructureHeader : ''}}">{{!isInpusTabSelected ? (propertyStructureHeader || "No Property Selected") : "No Property Selected"}}</span>
+ <span tooltip="{{isPropertiesTabSelected ? propertyStructureHeader : ''}}">{{isPropertiesTabSelected ? (propertyStructureHeader || "No Property Selected") : "No Property Selected"}}</span>
</div>
- <div *ngIf="!propertiesNavigationData || propertiesNavigationData.length === 0 || isInpusTabSelected">No data to display</div>
+ <div *ngIf="!propertiesNavigationData || propertiesNavigationData.length === 0 || isInputsTabSelected">No data to display</div>
<hierarchy-navigation class="hierarchy-nav"
(updateSelected)="onPropertySelectedUpdate($event)"
- [displayData]="isInpusTabSelected ? [] : propertiesNavigationData"
+ [displayData]="isInputsTabSelected ? [] : propertiesNavigationData"
[selectedItem]="selectedFlatProperty.path"
[displayOptions]="hierarchyPropertiesDisplayOptions"></hierarchy-navigation>
</div>
@@ -72,4 +79,9 @@
</tabs>
</div>
</div>
+ <template #saveChangedDataModalContentTemplate>
+ <loader [display]="savingChangedData" [size]="'medium'" [relative]="true"></loader>
+ Your changes{{isValidChangedData ? '' : ' (invalid)'}} have not been saved.<br>
+ Do you want to {{isValidChangedData ? 'save' : 'discard'}} them?
+ </template>
</div>
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less
index 03974bf723..6de6dda7bb 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
@@ -76,6 +76,7 @@
outline: none;
font-style: italic;
color:@ng2-med-dark-gray;
+ width: auto;
&::-moz-placeholder { color:@ng2-med-dark-gray;}
&::-webkit-input-placeholder{ color:@ng2-med-dark-gray;}
@@ -113,6 +114,17 @@
top: 0;
right: 0;
}
+
+ .main-tabs-section {
+ position: relative;
+
+ .main-tabs-section-buttons {
+ position: absolute;
+ top: 45px;
+ right: 0;
+ padding: 4px;
+ }
+ }
}
.right-column {
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 9603648bd8..40818bce78 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
@@ -18,11 +18,11 @@
* ============LICENSE_END=========================================================
*/
-import {Component, ViewChild, ElementRef, Renderer, Inject} from "@angular/core";
+import * as _ from "lodash";
+import {Component, ViewChild, Inject, TemplateRef} from "@angular/core";
import { PropertiesService } from "../../services/properties.service";
-import { PropertyFEModel, InstanceFePropertiesMap, InstanceBePropertiesMap, InstancePropertiesAPIMap, Component as ComponentData, FilterPropertiesAssignmentData } from "app/models";
+import { PropertyFEModel, InstanceFePropertiesMap, InstanceBePropertiesMap, InstancePropertiesAPIMap, Component as ComponentData, FilterPropertiesAssignmentData, ModalModel, ButtonModel } from "app/models";
import { 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 { InputBEModel, InputFEModel, ComponentInstance, PropertyBEModel, DerivedFEProperty, ResourceInstance, SimpleFlatProperty } from "app/models";
@@ -35,6 +35,9 @@ import {PropertyRowSelectedEvent} from "../../components/logic/properties-table/
import {HierarchyNavService} from "./services/hierarchy-nav.service";
import {PropertiesUtils} from "./services/properties.utils";
import {ComponentModeService} from "../../services/component-services/component-mode.service";
+import {ModalService} from "../../services/modal.service";
+import {Tabs, Tab} from "../../components/ui/tabs/tabs.component";
+import {InputsUtils} from "./services/inputs.utils";
@Component({
templateUrl: './properties-assignment.page.component.html',
@@ -64,24 +67,36 @@ export class PropertiesAssignmentComponent {
hierarchyInstancesDisplayOptions:HierarchyDisplayOptions = new HierarchyDisplayOptions('uniqueId', 'name');
displayClearSearch = false;
searchPropertyName:string;
- isInpusTabSelected:boolean;
+ currentMainTab:Tab;
+ isInputsTabSelected:boolean;
+ isPropertiesTabSelected:boolean;
isReadonly:boolean;
loadingInstances:boolean = false;
loadingInputs:boolean = false;
loadingProperties:boolean = false;
-
- @ViewChild('hierarchyNavTabs') hierarchyNavTabs: ElementRef;
- @ViewChild('propertyInputTabs') propertyInputTabs: ElementRef;
+ changedData:Array<PropertyFEModel|InputFEModel>;
+ hasChangedData:boolean;
+ isValidChangedData:boolean;
+ savingChangedData:boolean;
+ stateChangeStartUnregister:Function;
+
+ @ViewChild('hierarchyNavTabs') hierarchyNavTabs: Tabs;
+ @ViewChild('propertyInputTabs') propertyInputTabs: Tabs;
@ViewChild('advanceSearch') advanceSearch: FilterPropertiesAssignmentComponent;
+ @ViewChild('saveChangedDataModalContentTemplate') saveChangedDataModalContentTemplateRef: TemplateRef<void>;
constructor(private propertiesService: PropertiesService,
private hierarchyNavService: HierarchyNavService,
private propertiesUtils:PropertiesUtils,
+ private inputsUtils:InputsUtils,
private componentServiceNg2:ComponentServiceNg2,
private componentInstanceServiceNg2:ComponentInstanceServiceNg2,
@Inject("$stateParams") _stateParams,
- private renderer: Renderer,
+ @Inject("$scope") private $scope:ng.IScope,
+ @Inject("$state") private $state:ng.ui.IStateService,
+ @Inject("Notification") private Notification:any,
private componentModeService:ComponentModeService,
+ private ModalService:ModalService,
private EventListenerService:EventListenerService) {
this.instanceFePropertiesMap = new InstanceFePropertiesMap();
@@ -91,6 +106,10 @@ export class PropertiesAssignmentComponent {
this.component = _stateParams.component;
this.EventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.onCheckout);
this.updateViewMode();
+
+ this.changedData = [];
+ this.updateHasChangedData();
+ this.isValidChangedData = true;
}
ngOnInit() {
@@ -102,7 +121,9 @@ export class PropertiesAssignmentComponent {
.getComponentInputs(this.component)
.subscribe(response => {
_.forEach(response.inputs, (input: InputBEModel) => {
- this.inputs.push(new InputFEModel(input)); //only push items that were declared via SDC
+ const newInput: InputFEModel = new InputFEModel(input);
+ this.inputsUtils.resetInputDefaultValue(newInput, input.defaultValue);
+ this.inputs.push(newInput); //only push items that were declared via SDC
});
this.loadingInputs = false;
@@ -123,10 +144,22 @@ export class PropertiesAssignmentComponent {
this.selectFirstInstanceByDefault();
}, error => {}); //ignore error
+ this.stateChangeStartUnregister = this.$scope.$on('$stateChangeStart', (event, toState, toParams) => {
+ // stop if has changed properties
+ if (this.hasChangedData) {
+ event.preventDefault();
+ this.openChangedDataModal().then((proceed) => {
+ if (proceed) {
+ this.$state.go(toState, toParams);
+ }
+ });
+ }
+ });
};
ngOnDestroy() {
this.EventListenerService.unRegisterObserver(EVENTS.ON_CHECKOUT);
+ this.stateChangeStartUnregister();
}
selectFirstInstanceByDefault = () => {
@@ -147,12 +180,23 @@ export class PropertiesAssignmentComponent {
onInstanceSelectedUpdate = (resourceInstance: ResourceInstance) => {
console.log("==>" + this.constructor.name + ": onInstanceSelectedUpdate");
+
+ // stop if has changed properties
+ if (this.hasChangedData) {
+ this.openChangedDataModal().then((proceed) => {
+ if (proceed) {
+ this.onInstanceSelectedUpdate(resourceInstance);
+ }
+ });
+ return;
+ }
+
let instanceBePropertiesMap: InstanceBePropertiesMap = new InstanceBePropertiesMap();
this.selectedInstanceData = resourceInstance;
this.selectedInstanceType = resourceInstance.originType;
this.loadingProperties = true;
- if(this.isInput(resourceInstance.originType)) {
+ if (this.isInput(resourceInstance.originType)) {
this.componentInstanceServiceNg2
.getComponentInstanceInputs(this.component, resourceInstance)
.subscribe(response => {
@@ -160,7 +204,8 @@ export class PropertiesAssignmentComponent {
this.processInstancePropertiesResponse(instanceBePropertiesMap, true);
this.loadingProperties = false;
- }, error => {}); //ignore error
+ }, error => {
+ }); //ignore error
} else {
this.componentInstanceServiceNg2
.getComponentInstanceProperties(this.component, resourceInstance.uniqueId)
@@ -168,14 +213,15 @@ export class PropertiesAssignmentComponent {
instanceBePropertiesMap[resourceInstance.uniqueId] = response;
this.processInstancePropertiesResponse(instanceBePropertiesMap, false);
this.loadingProperties = false;
- }, error => {}); //ignore error
+ }, error => {
+ }); //ignore error
}
- if(resourceInstance.componentName === "vnfConfiguration") {
+ if (resourceInstance.componentName === "vnfConfiguration") {
this.isReadonly = true;
}
- if( this.searchPropertyName ){
+ if (this.searchPropertyName) {
this.clearSearch();
}
//clear selected property from the navigation
@@ -193,41 +239,31 @@ export class PropertiesAssignmentComponent {
/*** 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.isInput(this.selectedInstanceData.originType)) {
- 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 response: ", response);
- }, error => {}); //ignore error
- }
- else {
- let propertyBe = new PropertyBEModel(event);
- this.componentInstanceServiceNg2
- .updateInstanceProperty(this.component, this.selectedInstanceData.uniqueId, propertyBe)
- .subscribe(response => {
- console.log("Update resource instance property response: ", response);
- }, error => {}); //ignore error
- console.log(event);
+ dataChanged = (item:PropertyFEModel|InputFEModel) => {
+ let itemHasChanged;
+ if (this.isPropertiesTabSelected && item instanceof PropertyFEModel) {
+ itemHasChanged = item.hasValueObjChanged();
+ } else if (this.isInputsTabSelected && item instanceof InputFEModel) {
+ itemHasChanged = item.hasDefaultValueChanged();
}
- };
-
- inputValueChanged = (event) => {
- console.log("==>" + this.constructor.name + ": inputValueChanged");
- let inputToUpdate = new PropertyBEModel(event);
+ const dataChangedIdx = this.changedData.findIndex((changedItem) => changedItem === item);
+ if (itemHasChanged) {
+ if (dataChangedIdx === -1) {
+ this.changedData.push(item);
+ }
+ } else {
+ if (dataChangedIdx !== -1) {
+ this.changedData.splice(dataChangedIdx, 1);
+ }
+ }
- this.componentServiceNg2
- .updateComponentInput(this.component, inputToUpdate)
- .subscribe(response => {
- console.log("updated the component input and got this response: ", response);
- }, error => {}); //ignore error
+ if (this.isPropertiesTabSelected) {
+ this.isValidChangedData = this.changedData.every((changedItem) => (<PropertyFEModel>changedItem).valueObjIsValid);
+ } else if (this.isInputsTabSelected) {
+ this.isValidChangedData = this.changedData.every((changedItem) => (<InputFEModel>changedItem).defaultValueObjIsValid);
+ }
+ this.updateHasChangedData();
};
@@ -272,7 +308,7 @@ export class PropertiesAssignmentComponent {
// Set selected property in table
this.selectedFlatProperty = this.hierarchyNavService.createSimpleFlatProperty(property, instanceName);
- this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Property Structure']);
+ this.hierarchyNavTabs.triggerTabChange('Property Structure');
};
@@ -280,13 +316,27 @@ export class PropertiesAssignmentComponent {
this.selectedInstanceData = _.find(this.instancesNavigationData, (instance:ComponentInstance) => {
return instance.name == $event;
});
- this.renderer.invokeElementMethod(
- this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
+ this.hierarchyNavTabs.triggerTabChange('Composition');
};
tabChanged = (event) => {
+ // stop if has changed properties
+ if (this.hasChangedData) {
+ this.openChangedDataModal().then((proceed) => {
+ if (proceed) {
+ this.propertyInputTabs.selectTab(this.propertyInputTabs.tabs.find((tab) => tab.title === event.title));
+ }
+ });
+
+ // return to show the current tab
+ this.propertyInputTabs.triggerTabChange(this.currentMainTab.title);
+ return;
+ }
+
console.log("==>" + this.constructor.name + ": tabChanged " + event);
- this.isInpusTabSelected = event.title === "Inputs";
+ this.currentMainTab = this.propertyInputTabs.tabs.find((tab) => tab.title === event.title);
+ this.isPropertiesTabSelected = this.currentMainTab.title === "Properties";
+ this.isInputsTabSelected = this.currentMainTab.title === "Inputs";
this.propertyStructureHeader = null;
this.searchQuery = '';
};
@@ -320,12 +370,180 @@ export class PropertiesAssignmentComponent {
this.checkedPropertiesCount = 0;
_.forEach(response, (input: InputBEModel) => {
let newInput: InputFEModel = new InputFEModel(input);
+ this.inputsUtils.resetInputDefaultValue(newInput, input.defaultValue);
this.inputs.push(newInput);
this.updatePropertyValueAfterDeclare(newInput);
});
}, error => {}); //ignore error
};
+ saveChangedData = ():Promise<(PropertyBEModel|InputBEModel)[]> => {
+ return new Promise((resolve, reject) => {
+ if (!this.isValidChangedData) {
+ reject('Changed data is invalid - cannot save!');
+ return;
+ }
+ if (!this.changedData.length) {
+ resolve([]);
+ return;
+ }
+
+ // make request and its handlers
+ let request;
+ let handleSuccess, handleError;
+ if (this.isPropertiesTabSelected) {
+ const changedProperties: PropertyBEModel[] = this.changedData.map((changedProp) => {
+ changedProp = <PropertyFEModel>changedProp;
+ const propBE = new PropertyBEModel(changedProp);
+ propBE.value = changedProp.getJSONValue();
+ return propBE;
+ });
+
+ if (this.isInput(this.selectedInstanceData.originType)) {
+ request = this.componentInstanceServiceNg2
+ .updateInstanceInputs(this.component, this.selectedInstanceData.uniqueId, changedProperties);
+ handleSuccess = (response) => {
+ // reset each changed property with new value and remove it from changed properties list
+ response.forEach((resInput) => {
+ const changedProp = <PropertyFEModel>this.changedData.shift();
+ this.propertiesUtils.resetPropertyValue(changedProp, resInput.value);
+ });
+ console.log('updated instance inputs:', response);
+ };
+ } else {
+ request = this.componentInstanceServiceNg2
+ .updateInstanceProperties(this.component, this.selectedInstanceData.uniqueId, changedProperties)
+ handleSuccess = (response) => {
+ // reset each changed property with new value and remove it from changed properties list
+ response.forEach((resProp) => {
+ const changedProp = <PropertyFEModel>this.changedData.shift();
+ this.propertiesUtils.resetPropertyValue(changedProp, resProp.value);
+ });
+ resolve(response);
+ console.log("updated instance properties: ", response);
+ };
+ }
+ } else if (this.isInputsTabSelected) {
+ const changedInputs: InputBEModel[] = this.changedData.map((changedInput) => {
+ changedInput = <InputFEModel>changedInput;
+ const inputBE = new InputBEModel(changedInput);
+ inputBE.defaultValue = changedInput.getJSONDefaultValue();
+ return inputBE;
+ });
+ request = this.componentServiceNg2
+ .updateComponentInputs(this.component, changedInputs);
+ handleSuccess = (response) => {
+ // reset each changed property with new value and remove it from changed properties list
+ response.forEach((resInput) => {
+ const changedInput = <InputFEModel>this.changedData.shift();
+ this.inputsUtils.resetInputDefaultValue(changedInput, resInput.defaultValue);
+ });
+ console.log("updated the component inputs and got this response: ", response);
+ }
+ }
+
+ this.savingChangedData = true;
+ request.subscribe(
+ (response) => {
+ this.savingChangedData = false;
+ handleSuccess && handleSuccess(response);
+ this.updateHasChangedData();
+ resolve(response);
+ },
+ (error) => {
+ this.savingChangedData = false;
+ handleError && handleError(error);
+ this.updateHasChangedData();
+ reject(error);
+ }
+ );
+ });
+ };
+
+ reverseChangedData = ():void => {
+ // make reverse item handler
+ let handleReverseItem;
+ if (this.isPropertiesTabSelected) {
+ handleReverseItem = (changedItem) => {
+ changedItem = <PropertyFEModel>changedItem;
+ this.propertiesUtils.resetPropertyValue(changedItem, changedItem.value);
+ };
+ } else if (this.isInputsTabSelected) {
+ handleReverseItem = (changedItem) => {
+ changedItem = <InputFEModel>changedItem;
+ this.inputsUtils.resetInputDefaultValue(changedItem, changedItem.defaultValue);
+ };
+ }
+
+ this.changedData.forEach(handleReverseItem);
+ this.changedData = [];
+ this.updateHasChangedData();
+ };
+
+ updateHasChangedData = ():boolean => {
+ const curHasChangedData:boolean = (this.changedData.length > 0);
+ if (curHasChangedData !== this.hasChangedData) {
+ this.hasChangedData = curHasChangedData;
+ this.$scope.$emit('setWorkspaceTopBarActive', !this.hasChangedData);
+ }
+ return this.hasChangedData;
+ };
+
+ doSaveChangedData = ():void => {
+ this.saveChangedData().then(
+ () => {
+ this.Notification.success({
+ message: 'Successfully saved changes',
+ title: 'Saved'
+ });
+ },
+ () => {
+ this.Notification.error({
+ message: 'Failed to save changes!',
+ title: 'Failure'
+ });
+ }
+ );
+ };
+
+ openChangedDataModal = ():Promise<boolean> => {
+ let modalTitle;
+ if (this.isPropertiesTabSelected) {
+ modalTitle = `Unsaved properties for ${this.selectedInstanceData.name}`;
+ } else if (this.isInputsTabSelected) {
+ modalTitle = `Unsaved inputs for ${this.component.name}`;
+ }
+
+ return new Promise<boolean>((resolve) => {
+ const modal = this.ModalService.createCustomModal(new ModalModel(
+ 'sm',
+ modalTitle,
+ null,
+ [
+ new ButtonModel('Cancel', 'outline grey', () => {
+ modal.instance.close();
+ resolve(false);
+ }),
+ new ButtonModel('Discard', 'outline blue', () => {
+ this.reverseChangedData();
+ modal.instance.close();
+ resolve(true);
+ }),
+ new ButtonModel('Save', 'blue', () => {
+ this.saveChangedData().then(() => {
+ modal.instance.close();
+ resolve(true);
+ }, () => {
+ modal.instance.close();
+ resolve(false);
+ });
+ }, () => !this.isValidChangedData)
+ ]
+ ));
+ this.ModalService.addDynamicTemplateToModal(modal, this.saveChangedDataModalContentTemplateRef);
+ modal.instance.open();
+ });
+ };
updatePropertyValueAfterDeclare = (input: InputFEModel) => {
if (this.instanceFePropertiesMap[input.instanceUniqueId]) {
@@ -346,12 +564,12 @@ export class PropertiesAssignmentComponent {
};
setInputTabIndication = (numInputs: number): void => {
- this.renderer.invokeElementMethod(this.propertyInputTabs, 'setTabIndication', ['Inputs', numInputs]);
+ this.propertyInputTabs.setTabIndication('Inputs', numInputs);
};
deleteInput = (input: InputFEModel) => {
console.log("==>" + this.constructor.name + ": deleteInput");
- let inputToDelete = new PropertyBEModel(input);
+ let inputToDelete = new InputBEModel(input);
this.componentServiceNg2
.deleteInput(this.component, inputToDelete)
@@ -389,7 +607,7 @@ export class PropertiesAssignmentComponent {
this.processInstancePropertiesResponse(response, false);
this.hierarchyPropertiesDisplayOptions.searchText = filterData.propertyName;//mark results in tree
this.searchPropertyName = filterData.propertyName;//mark in table
- this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
+ this.hierarchyNavTabs.triggerTabChange('Composition');
this.propertiesNavigationData = [];
this.displayClearSearch = true;
}, error => {}); //ignore error
@@ -408,12 +626,11 @@ export class PropertiesAssignmentComponent {
clickOnClearSearch = () => {
this.clearSearch();
this.selectFirstInstanceByDefault();
- this.renderer.invokeElementMethod(
- this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
+ this.hierarchyNavTabs.triggerTabChange('Composition');
};
private isInput = (instanceType:string):boolean =>{
- return instanceType === ResourceType.VF || instanceType === ResourceType.PNF || instanceType === ResourceType.CVFC;
+ return instanceType === ResourceType.VF || instanceType === ResourceType.PNF || instanceType === ResourceType.CVFC || instanceType === ResourceType.CR;
}
}
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/services/hierarchy-nav.service.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/services/hierarchy-nav.service.ts
index 016b04788e..1a800baac7 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/services/hierarchy-nav.service.ts
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/services/hierarchy-nav.service.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { Injectable } from '@angular/core';
import { SimpleFlatProperty, PropertyFEModel, DerivedFEProperty } from 'app/models';
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java b/catalog-ui/src/app/ng2/pages/properties-assignment/services/inputs.utils.ts
index a713d5089f..408a00e7b4 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/services/inputs.utils.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,22 +18,23 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes.enums;
+import { Injectable } from '@angular/core';
+import { InputFEModel} from "app/models";
-public enum AuditEnum {
+@Injectable()
+export class InputsUtils {
- 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");
+ constructor() {}
- String value;
+ public initDefaultValueObject = (input: InputFEModel): void => {
+ input.resetDefaultValueObjValidation();
+ input.defaultValueObj = input.getDefaultValueObj();
+ input.updateDefaultValueObjOrig();
+ };
- private AuditEnum(String value) {
- this.value = value;
- }
-
- public String getValue() {
-
- return value.toLowerCase();
- }
+ public resetInputDefaultValue = (input: InputFEModel, newDefaultValue: string): void => {
+ input.defaultValue = newDefaultValue;
+ this.initDefaultValueObject(input);
+ }
}
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts
index 8f46c6f603..e7b59b96ba 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/services/properties.utils.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { Injectable } from '@angular/core';
import { DataTypeModel, PropertyFEModel, PropertyBEModel, InstanceBePropertiesMap, InstanceFePropertiesMap, DerivedFEProperty, DerivedPropertyType, InputFEModel} from "app/models";
import { DataTypeService } from "app/ng2/services/data-type.service";
@@ -47,10 +48,13 @@ export class PropertiesUtils {
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 (newFEProp.getInputValues && newFEProp.getInputValues.length) { //if this prop (or any children) are declared, set isDeclared and disable checkbox on parents/children
+ this.initValueObjectRef(newFEProp); //initialize valueObj.
+ propertyFeArray.push(newFEProp);
+ newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children
+ this.dataTypeService.checkForCustomBehavior(newFEProp);
+
+ //if this prop (or any children) are declared, set isDeclared and disable checkbox on parents/children
+ if (newFEProp.getInputValues && newFEProp.getInputValues.length) {
newFEProp.getInputValues.forEach(propInputDetail => {
let inputPath = propInputDetail.inputPath;
if (!inputPath) { //TODO: this is a workaround until Marina adds inputPath
@@ -63,10 +67,6 @@ export class PropertiesUtils {
this.propertiesService.disableRelatedProperties(newFEProp, inputPath);
});
}
- this.initValueObjectRef(newFEProp); //initialize valueObj.
- propertyFeArray.push(newFEProp);
- newFEProp.updateExpandedChildPropertyId(newFEProp.name); //display only the first level of children
- this.dataTypeService.checkForCustomBehavior(newFEProp);
}
});
instanceFePropertiesMap[instanceId] = propertyFeArray;
@@ -103,33 +103,29 @@ export class PropertiesUtils {
* 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 => {
- 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) {
- if(typeof property.valueObj == 'object'){
- property.valueObj = JSON.stringify(property.valueObj);
- }
- }else if(property.valueObj &&
- property.type !== PROPERTY_TYPES.STRING &&
- property.type !== PROPERTY_TYPES.JSON &&
- PROPERTY_DATA.SCALAR_TYPES.indexOf(property.type) == -1){
- property.valueObj = JSON.parse(property.valueObj);//The valueObj contains the real value ans not the value as string
+ property.resetValueObjValidation();
+ if (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 || null; // use null for empty value object
+ if (property.valueObj && 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.LIST || property.derivedDataType == DerivedPropertyType.MAP) && Object.keys(property.valueObj).length) {
+ property.valueObj = property.getValueObj();
+ if (property.derivedDataType == DerivedPropertyType.LIST || property.derivedDataType == DerivedPropertyType.MAP) {
+ property.flattenedChildren = [];
Object.keys(property.valueObj).forEach((key) => {
property.flattenedChildren.push(...this.createListOrMapChildren(property, key, property.valueObj[key]))
});
- } else {
+ } else if (property.derivedDataType === DerivedPropertyType.COMPLEX) {
+ property.flattenedChildren = this.createFlattenedChildren(property.type, property.name);
this.assignFlattenedChildrenValues(property.valueObj, property.flattenedChildren, property.name);
+ property.flattenedChildren.forEach((childProp) => {
+ property.childPropUpdated(childProp);
+ });
}
}
- }
+ property.updateValueObjOrig();
+ };
/*
* Loops through flattened properties array and to assign values
@@ -142,22 +138,24 @@ export class PropertiesUtils {
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
+ prop.valueObj = _.get(parentValueJSON, propNameInObj, prop.value || prop.defaultValue || null); //assign value -first value of parent if exists. If not, prop.value if not, prop.defaultvalue
+ prop.value = (prop.valueObj !== null && (typeof prop.valueObj) != 'string') ? JSON.stringify(prop.valueObj) : prop.valueObj;
- if ( prop.isDeclared && typeof prop.valueObj == 'object') { //Stringify objects of items that are declared
- prop.valueObj = JSON.stringify(prop.valueObj);
- } else if(typeof prop.valueObj == PROPERTY_TYPES.STRING
- && (prop.type == PROPERTY_TYPES.INTEGER || prop.type == PROPERTY_TYPES.FLOAT || prop.type == PROPERTY_TYPES.BOOLEAN)){ //parse ints and non-string simple types
- prop.valueObj = JSON.parse(prop.valueObj);
+ if ((prop.isDeclared || prop.type == PROPERTY_TYPES.STRING || prop.type == PROPERTY_TYPES.JSON)) { //Stringify objects of items that are declared or from type string/json
+ prop.valueObj = (prop.valueObj !== null && typeof prop.valueObj == 'object') ? JSON.stringify(prop.valueObj) : prop.valueObj;
+ } else if(prop.type == PROPERTY_TYPES.INTEGER || prop.type == PROPERTY_TYPES.FLOAT || prop.type == PROPERTY_TYPES.BOOLEAN){ //parse ints and non-string simple types
+ prop.valueObj = (prop.valueObj !== null && typeof prop.valueObj == PROPERTY_TYPES.STRING) ? JSON.parse(prop.valueObj) : prop.valueObj;
} else { //parse strings that should be objects
- if (prop.derivedDataType == DerivedPropertyType.COMPLEX && 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 || '[]');
- } else if (prop.derivedDataType == DerivedPropertyType.MAP && typeof prop.valueObj != 'object' && (!prop.isChildOfListOrMap || !prop.schema.property.isSimpleType)) { //dont parse values for children of map of simple
- prop.valueObj = JSON.parse(prop.valueObj || '{}');
+ if (prop.derivedDataType == DerivedPropertyType.COMPLEX) {
+ prop.valueObj = (prop.valueObj === null || typeof prop.valueObj != 'object') ? JSON.parse(prop.valueObj || '{}') : prop.valueObj;
+ } else if (prop.derivedDataType == DerivedPropertyType.LIST) {
+ prop.valueObj = (prop.valueObj === null || typeof prop.valueObj != 'object') ? JSON.parse(prop.valueObj || '[]') : prop.valueObj;
+ } else if (prop.derivedDataType == DerivedPropertyType.MAP) {
+ if (!prop.isChildOfListOrMap || !prop.schema.property.isSimpleType) {
+ prop.valueObj = (prop.valueObj === null || typeof prop.valueObj != 'object') ? JSON.parse(prop.valueObj || '{}') : prop.valueObj;
+ }
}
- if ((prop.derivedDataType == DerivedPropertyType.LIST || prop.derivedDataType == DerivedPropertyType.MAP) && typeof prop.valueObj == 'object' && Object.keys(prop.valueObj).length) {
+ if ((prop.derivedDataType == DerivedPropertyType.LIST || prop.derivedDataType == DerivedPropertyType.MAP) && typeof prop.valueObj == 'object' && prop.valueObj !== null && Object.keys(prop.valueObj).length) {
let newProps: Array<DerivedFEProperty> = [];
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
@@ -165,6 +163,8 @@ export class PropertiesUtils {
propsToPushMap[index + 1] = newProps;
}
}
+
+ prop.valueObj = PropertyFEModel.cleanValueObj(prop.valueObj);
});
//add props after we're done looping (otherwise our loop gets messed up). Push in reverse order, so we dont mess up indexes.
@@ -178,11 +178,10 @@ export class PropertiesUtils {
if (nestedPath) {
let newProp = property.flattenedChildren.find(prop => prop.propertiesName == nestedPath);
newProp && this.assignFlattenedChildrenValues(JSON.parse(newValue), [newProp], property.name);
+ property.updateValueObjOrig();
} else {
this.initValueObjectRef(property);
}
}
-
-
}
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.html b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.html
new file mode 100644
index 0000000000..bbbf6ae694
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.html
@@ -0,0 +1,5 @@
+<ui-element-dropdown data-tests-id="linkSrc" [readonly]="!link.isFirst || (link.isFirst && !link.canEdit)" class="cell link-selector" [values]="source" [(value)]="link.fromNode" (valueChange)="onSourceSelected($event)"></ui-element-dropdown>
+<ui-element-dropdown data-tests-id="linkSrcCP" [readonly]="!link.isFirst || (link.isFirst && !link.canEdit)" class="cell link-selector" [values]="srcCP" [(value)]="link.fromCP" (valueChange)="onSrcCPSelected($event)"></ui-element-dropdown>
+<ui-element-dropdown data-tests-id="linkTarget" [readonly]="!link.canEdit" class="cell link-selector" [values]="target" [(value)]="link.toNode" (valueChange)="onTargetSelected($event)"></ui-element-dropdown>
+<ui-element-dropdown data-tests-id="linkTargetCP" [readonly]="!link.canEdit" class="cell link-selector" [values]="targetCP" [(value)]="link.toCP" (valueChange)="onTargetCPSelected($event)"></ui-element-dropdown>
+<div class="cell remove" data-tests-id="removeLnk"><span *ngIf="link.canRemove" class="sprite-new delete-item-icon" (click)="removeRow()"></span></div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less
new file mode 100644
index 0000000000..beec9bd567
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.less
@@ -0,0 +1,21 @@
+@import './../../../../../assets/styles/variables.less';
+.remove {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.cell {
+ padding: 0;
+}
+
+/deep/ .link-selector {
+ select {
+ height: 30px;
+ border: none;
+ stroke: none;
+ }
+
+}
+
+
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts
new file mode 100644
index 0000000000..16433242d6
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link-row.component.ts
@@ -0,0 +1,110 @@
+import {Component, Input} from '@angular/core';
+import {DropdownValue} from "app/ng2/components/ui/form-components/dropdown/ui-element-dropdown.component";
+import {Link} from './link.model';
+import {ServicePathMapItem} from "app/models/graph/nodes-and-links-map";
+
+@Component({
+ selector: 'link-row',
+ templateUrl: './link-row.component.html',
+ styleUrls: ['./link-row.component.less']
+})
+
+
+export class LinkRowComponent {
+ @Input() data:Array<ServicePathMapItem>;
+ @Input() link:Link;
+ @Input() removeRow:Function;
+ source:Array<DropdownValue> = [];
+ target: Array<DropdownValue> = [];
+ srcCP: Array<DropdownValue> = [];
+ targetCP: Array<DropdownValue> = [];
+
+ ngOnChanges() {
+ if (this.data) {
+ this.parseInitialData(this.data);
+ }
+ }
+
+ parseInitialData(data: Array<ServicePathMapItem>) {
+ this.source = this.convertValuesToDropDownOptions(data);
+ if (this.link.fromNode) {
+ let srcCPOptions = this.findOptions(data, this.link.fromNode);
+ if (!srcCPOptions) { return; }
+ this.srcCP = this.convertValuesToDropDownOptions(srcCPOptions);
+ if (this.link.fromCP) {
+ let targetOptions = this.findOptions(srcCPOptions, this.link.fromCP);
+ if (!targetOptions) { return; }
+ this.target = this.convertValuesToDropDownOptions(targetOptions);
+ if (this.link.toNode) {
+ let targetCPOptions = this.findOptions(targetOptions, this.link.toNode);
+ if (!targetCPOptions) { return; }
+ this.targetCP = this.convertValuesToDropDownOptions(targetCPOptions);
+ }
+ }
+ }
+ }
+
+ private findOptions(items: Array<ServicePathMapItem>, nodeOrCPId: string) {
+ let item = items.find((dataItem)=> nodeOrCPId === dataItem.id);
+ if (item && item.data && item.data.options) {
+ return item.data.options;
+ }
+ console.warn('no option was found to match selection of Node/CP with id:' + nodeOrCPId);
+ return null;
+ }
+
+ private convertValuesToDropDownOptions(values: Array<ServicePathMapItem>) : Array<DropdownValue> {
+ let result = [];
+ for (let i = 0; i < values.length ; i++) {
+ result[result.length] = new DropdownValue(values[i].id, values[i].data.name);
+ }
+ return result;
+ }
+
+ onSourceSelected(id) {
+ if (id) {
+ let srcCPOptions = this.findOptions(this.data, id);
+ this.srcCP = this.convertValuesToDropDownOptions(srcCPOptions);
+ this.link.fromCP = '';
+ this.link.toNode = '';
+ this.link.toCP = '';
+ this.target = [];
+ this.targetCP = [];
+ }
+ }
+
+ onSrcCPSelected (id) {
+ if (id) {
+ let srcCPData = this.data.find((dataItem)=> this.link.fromNode === dataItem.id).data;
+ let srcCPOptions = srcCPData.options;
+ let targetOptions = this.findOptions(srcCPOptions, id);
+ this.target = this.convertValuesToDropDownOptions(targetOptions);
+ this.link.fromCPOriginId = srcCPData.ownerId;
+ this.link.toNode = '';
+ this.link.toCP = '';
+ this.targetCP = [];
+ }
+
+ }
+
+ onTargetSelected(id) {
+ if (id) {
+ let srcCPOptions = this.findOptions(this.data, this.link.fromNode);
+ let targetOptions = this.findOptions(srcCPOptions, this.link.fromCP);
+ let targetCPOptions = this.findOptions(targetOptions, id);
+ this.targetCP = this.convertValuesToDropDownOptions(targetCPOptions);
+ this.link.toCP = '';
+ }
+
+ }
+
+ onTargetCPSelected(id) {
+ if (id) {
+ let srcCPOptions = this.findOptions(this.data, this.link.fromNode);
+ let targetOptions = this.findOptions(srcCPOptions, this.link.fromCP);
+ let targetCPOptions = this.findOptions(targetOptions, this.link.toNode);
+ let targetCPDataObj = targetCPOptions.find((dataItem)=> id === dataItem.id).data;
+ this.link.toCPOriginId = targetCPDataObj.ownerId;
+ }
+ }
+} \ No newline at end of file
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link.model.ts
index 809a51c2ff..80128eb42e 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/migration/v1707/CommonMigrationUtils.java
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/link-row/link.model.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,23 +17,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
-package org.openecomp.sdc.ci.tests.migration.v1707;
-
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertNull;
-
-import com.thinkaurelius.titan.core.TitanGraph;
-
-public class CommonMigrationUtils {
-
- public static void assertKeyNotExist(TitanGraph graph, String key) {
- assertNull(graph.getPropertyKey(key));
- }
-
- public static void assertKeyExists(TitanGraph graph, String key) {
- assertNotNull(graph.getPropertyKey(key));
+'use strict';
+import {ForwardingPathLink} from "app/models/forwarding-path-link";
+
+export class Link extends ForwardingPathLink {
+ public canEdit:boolean = false;
+ public canRemove:boolean = false;
+ public isFirst:boolean = false;
+
+ constructor(link: ForwardingPathLink, canEdit: boolean, canRemove: boolean, isFirst: boolean) {
+ super(link.fromNode,link.fromCP, link.toNode, link.toCP, link.fromCPOriginId, link.toCPOriginId);
+ this.canEdit = canEdit;
+ this.canRemove = canRemove;
+ this.isFirst = isFirst;
}
+}
-}
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html
new file mode 100644
index 0000000000..96cd83eef6
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.html
@@ -0,0 +1,43 @@
+<div class="service-path-creator">
+ <form class="w-sdc-form">
+ <div class="i-sdc-form-item" >
+ <label class="i-sdc-form-label required">Path Name</label>
+ <!-- <ui-element-input type="text" name="pathName" [value]="pathName" ></ui-element-input> -->
+ <input type="text" data-tests-id="pathName" name="pathName" [(ngModel)]="forwardingPath.name" [attr.maxLength]="100" /> <!-- TODO - make unique -->
+ </div>
+
+ <div class="side-by-side">
+ <div class="i-sdc-form-item" >
+ <label class="i-sdc-form-label">Protocol</label>
+ <!-- <ui-element-input type="text" name="protocol" [value]="protocol" ></ui-element-input> -->
+ <input type="text" data-tests-id="pathProtocol" name="protocol" [(ngModel)]="forwardingPath.protocol" [attr.maxLength]="100" />
+ </div>
+ <div class="i-sdc-form-item" >
+ <label class="i-sdc-form-label">Destination Port Numbers</label>
+ <!-- <ui-element-input type="text" name="portNumbers" [value]="portNumbers" ></ui-element-input> -->
+ <input type="text" data-tests-id="pathPortNumbers" name="portNumbers" [(ngModel)]="forwardingPath.destinationPortNumber" pattern="[0-9,]*" /> <!-- TODO - validate delimiter -->
+ </div>
+ </div>
+
+ <div class="separator-buttons">
+ <span class="based-on-title">Based On</span>
+ <a (click)="addRow()" [ngClass]="{'disabled':!isExtendAllowed()}" data-tests-id="extendPathlnk">Extend Path</a>
+ </div>
+
+ <div class="generic-table">
+ <div class="header-row">
+ <div class="cell header-cell" *ngFor="let header of headers">
+ {{header}}
+ </div>
+ </div>
+ <div *ngIf="links && links.length === 0" class="no-row-text" >
+ There is no data to display
+ </div>
+ <div>
+ <link-row *ngFor="let link of links" [data]="linksMap" [link]="link" [removeRow]="removeRow" class="data-row" ></link-row>
+ </div>
+ </div>
+
+
+ </form>
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less
new file mode 100644
index 0000000000..5c9e53e229
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.less
@@ -0,0 +1,45 @@
+@import './../../../../assets/styles/variables.less';
+.service-path-creator {
+ font-family: @font-opensans-regular;
+ .separator-buttons {
+ margin: 10px 0;
+ display: flex;
+ justify-content: space-between;
+ }
+ .i-sdc-form-label {
+ font-size: 12px;
+ }
+ .w-sdc-form .i-sdc-form-item {
+ margin-bottom: 15px;
+ }
+
+ .side-by-side {
+ display: flex;
+ .i-sdc-form-item {
+ flex-basis: 100%;
+ &:first-child {
+ margin-right: 10px;
+ }
+ }
+ }
+
+ .generic-table {
+ max-height: 233px;
+ .header-row .header-cell {
+ &:last-child {
+ padding: 0;
+ }
+ }
+ /deep/ .cell {
+ &:last-child {
+ min-width: 30px;
+ }
+ }
+ }
+
+ .based-on-title {
+ text-transform: uppercase;
+ font-size: 18px;
+ font-family: @font-opensans-regular;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts
new file mode 100644
index 0000000000..dac41a37bc
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.component.ts
@@ -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=========================================================
+ */
+
+import * as _ from "lodash";
+import { Component, ElementRef, forwardRef, Inject } from '@angular/core';
+import {Link} from './link-row/link.model';
+import {ForwardingPath} from 'app/models/forwarding-path';
+import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service";
+import {ForwardingPathLink} from "app/models/forwarding-path-link";
+import {ServicePathMapItem} from "app/models/graph/nodes-and-links-map";
+
+@Component({
+ selector: 'service-path-creator',
+ templateUrl: './service-path-creator.component.html',
+ styleUrls:['./service-path-creator.component.less'],
+ providers: [ServiceServiceNg2]
+})
+
+export class ServicePathCreatorComponent {
+
+ linksMap:Array<ServicePathMapItem>;
+ links:Array<Link> = [];
+ input:any;
+ headers: Array<string> = [];
+ removeRow: Function;
+ forwardingPath:ForwardingPath;
+ //isExtendAllowed:boolean = false;
+
+ constructor(private serviceService: ServiceServiceNg2) {
+ this.forwardingPath = new ForwardingPath();
+ this.links = [new Link(new ForwardingPathLink('', '', '', '', '', ''), true, false, true)];
+ this.headers = ['Source', 'Source Connection Point', 'Target', 'Target Connection Point', ' '];
+ this.removeRow = () => {
+ if (this.links.length === 1) {
+ return;
+ }
+ this.links.splice(this.links.length-1, 1);
+ this.enableCurrentRow();
+ };
+ }
+
+ ngOnInit() {
+ this.serviceService.getNodesAndLinksMap(this.input.service).subscribe((res:any) => {
+ this.linksMap = res;
+ });
+ this.processExistingPath();
+
+ }
+
+ private processExistingPath() {
+ if (this.input.pathId) {
+ let forwardingPath = <ForwardingPath>{...this.input.service.forwardingPaths[this.input.pathId]};
+ this.forwardingPath.name = forwardingPath.name;
+ this.forwardingPath.destinationPortNumber = forwardingPath.destinationPortNumber;
+ this.forwardingPath.protocol = forwardingPath.protocol;
+ this.forwardingPath.uniqueId = forwardingPath.uniqueId;
+ this.links = [];
+ _.forEach(forwardingPath.pathElements.listToscaDataDefinition, (link:ForwardingPathLink) => {
+ this.links[this.links.length] = new Link( link, false, false, false);
+ });
+ this.links[this.links.length -1].canEdit = true;
+ this.links[this.links.length -1].canRemove = true;
+ this.links[0].isFirst = true;
+
+ }
+ }
+
+ isExtendAllowed():boolean {
+ if (this.links[this.links.length-1].toCP) {
+ return true;
+ }
+ return false;
+ }
+
+ enableCurrentRow() {
+ this.links[this.links.length-1].canEdit = true;
+ if (this.links.length !== 1) {
+ this.links[this.links.length-1].canRemove = true;
+ }
+ }
+
+ addRow() {
+ this.disableRows();
+ this.links[this.links.length] = new Link( new ForwardingPathLink(this.links[this.links.length-1].toNode,this.links[this.links.length-1].toCP,'','',this.links[this.links.length-1].toCPOriginId,''),true, true, false);
+ }
+
+ disableRows() {
+ for (let i = 0 ; i < this.links.length ; i++) {
+ this.links[i].canEdit = false;
+ this.links[i].canRemove = false;
+ }
+ }
+
+ createPathLinksObject() {
+ for (let i = 0 ; i < this.links.length ; i++) {
+ let link = this.links[i];
+ this.forwardingPath.addPathLink(link.fromNode, link.fromCP, link.toNode, link.toCP, link.fromCPOriginId, link.toCPOriginId);
+ }
+ }
+
+ createServicePathData() {
+ this.createPathLinksObject();
+ return this.forwardingPath;
+ }
+
+ checkFormValidForSubmit():boolean {
+ if (this.forwardingPath.name && this.isPathValid() ) {
+ return true;
+ }
+ return false;
+ }
+
+ isPathValid():boolean {
+ let lastLink = this.links[this.links.length -1] ;
+ if (lastLink.toNode && lastLink.toCP && lastLink.fromNode && lastLink.fromCP) {
+ return true;
+ }
+ return false;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.module.ts b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.module.ts
new file mode 100644
index 0000000000..78005317a2
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-path-creator/service-path-creator.module.ts
@@ -0,0 +1,25 @@
+import { NgModule } from "@angular/core";
+import {CommonModule} from "@angular/common";
+import {ServicePathCreatorComponent} from "./service-path-creator.component";
+import {FormsModule} from "@angular/forms";
+import {FormElementsModule} from "app/ng2/components/ui/form-components/form-elements.module";
+import {UiElementsModule} from "app/ng2/components/ui/ui-elements.module";
+import {LinkRowComponent} from './link-row/link-row.component'
+@NgModule({
+ declarations: [
+ ServicePathCreatorComponent,
+ LinkRowComponent
+ ],
+ imports: [CommonModule,
+ FormsModule,
+ FormElementsModule,
+ UiElementsModule
+ ],
+ exports: [],
+ entryComponents: [
+ ServicePathCreatorComponent
+ ],
+ providers: []
+})
+export class ServicePathCreatorModule {
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html
new file mode 100644
index 0000000000..8a31c76998
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.html
@@ -0,0 +1,21 @@
+<div class="service-path-list">
+ <div class="add-path-link"><a (click)="onAddServicePath()" data-tests-id="add-service-path-lnk" >+ Add Path</a></div>
+ <div class="generic-table table-container" >
+ <div class="header-row">
+ <div class="cell header-cell" *ngFor="let header of headers">
+ {{header}}
+ </div>
+ </div>
+ <div *ngFor="let path of paths" class="data-row" >
+ <div class="cell" data-tests-id="path-name" >{{path.name}}</div>
+ <div class="cell path-action-buttons">
+ <span class="sprite-new update-component-icon" (click)="onEditServicePath(path.uniqueId)" data-tests-id="update-service-path-btn" ></span>
+ <span class="sprite-new delete-item-icon" (click)="deletePath(path.uniqueId)" data-tests-id="delete-service-path-btn"></span>
+ </div>
+ </div>
+ <div *ngIf="paths && paths.length === 0" class="no-row-text" >
+ No paths have been added yet.
+ </div>
+ </div>
+
+</div> \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less
new file mode 100644
index 0000000000..aff597fd85
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.less
@@ -0,0 +1,21 @@
+@import './../../../../assets/styles/variables.less';
+
+.add-path-link {
+ display: flex;
+ align-items: flex-end;
+ flex-direction: column;
+ padding-bottom: 10px;
+}
+
+.generic-table {
+ max-height: 233px;
+}
+
+.path-action-buttons {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ .sprite-new {
+ cursor: pointer;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts
new file mode 100644
index 0000000000..04083e8685
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.component.ts
@@ -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=========================================================
+ */
+
+import * as _ from "lodash";
+import {Component, ComponentRef} from '@angular/core';
+import {ForwardingPath} from "app/models/forwarding-path";
+import {ServiceServiceNg2} from "app/ng2/services/component-services/service.service";
+import {ModalService} from "app/ng2/services/modal.service";
+import {ModalComponent} from "app/ng2/components/ui/modal/modal.component";
+
+@Component({
+ selector: 'service-paths-list',
+ templateUrl: './service-paths-list.component.html',
+ styleUrls:['service-paths-list.component.less'],
+ providers: [ServiceServiceNg2, ModalService]
+})
+export default class ServicePathsListComponent {
+ modalInstance: ComponentRef<ModalComponent>;
+ headers: Array<string> = [];
+ paths: Array<ForwardingPath> = [];
+ input:any;
+ onAddServicePath: Function;
+ onEditServicePath: Function;
+
+ constructor(private serviceService:ServiceServiceNg2) {
+ this.headers = ['Path Name','Actions'];
+ }
+
+ ngOnInit() {
+ _.forEach(this.input.service.forwardingPaths, (path: ForwardingPath)=> {
+ this.paths[this.paths.length] = path;
+ });
+ this.paths.sort((a:ForwardingPath, b:ForwardingPath)=> {
+ return a.name.localeCompare(b.name);
+ });
+ this.onAddServicePath = this.input.onCreateServicePath;
+ this.onEditServicePath = this.input.onEditServicePath;
+ }
+
+ deletePath = (id:string):void => {
+ this.serviceService.deleteServicePath(this.input.service, id).subscribe((res:any) => {
+ delete this.input.service.forwardingPaths[id];
+ this.paths = this.paths.filter(function(path){
+ return path.uniqueId !== id;
+ });
+ });
+ };
+
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts
new file mode 100644
index 0000000000..c236934002
--- /dev/null
+++ b/catalog-ui/src/app/ng2/pages/service-paths-list/service-paths-list.module.ts
@@ -0,0 +1,17 @@
+import { NgModule } from "@angular/core";
+import {CommonModule} from "@angular/common";
+import ServicePathsListComponent from "./service-paths-list.component";
+
+@NgModule({
+ declarations: [
+ ServicePathsListComponent
+ ],
+ imports: [CommonModule],
+ exports: [],
+ entryComponents: [
+ ServicePathsListComponent
+ ],
+ providers: []
+})
+export class ServicePathsListModule {
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts b/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts
index e89a816e95..3761aa808f 100644
--- a/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts
+++ b/catalog-ui/src/app/ng2/pipes/global-pipes.module.ts
@@ -13,7 +13,6 @@ import {SafeUrlSanitizerPipe} from "./safeUrlSanitizer.pipe";
SearchFilterPipe,
SafeUrlSanitizerPipe
],
-
exports: [
ContentAfterLastDotPipe,
GroupByPipe,
diff --git a/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
index b852539edd..0947b2aa7f 100644
--- a/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
+++ b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
@@ -23,10 +23,9 @@ import {Response, RequestOptions, Headers} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {PropertyFEModel, PropertyBEModel} from "app/models";
import {CommonUtils} from "app/utils";
-import {Component, ComponentInstance, InputModel} from "app/models";
+import {Component, ComponentInstance, Capability, PropertyModel} from "app/models";
import { HttpService } from '../http.service';
import {SdcConfigToken, ISdcConfig} from "../../config/sdc-config.config";
-import {isEqual} from "lodash";
@Injectable()
export class ComponentInstanceServiceNg2 {
@@ -52,43 +51,45 @@ export class ComponentInstanceServiceNg2 {
})
}
- updateInstanceProperty(component: Component, componentInstanceId: string, property: PropertyBEModel): Observable<PropertyBEModel> {
+ updateInstanceProperties(component: Component, componentInstanceId: string, properties: PropertyBEModel[]) {
- return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/property', property)
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/properties', properties)
.map((res: Response) => {
- return new PropertyBEModel(res.json());
- })
+ return res.json().map((resProperty) => new PropertyBEModel(resProperty));
+ });
}
- getInstanceCapabilityProperties(component: Component, componentInstanceId: string, capabilityType: string, capabilityName: string): Observable<Array<PropertyBEModel>> {
+ getInstanceCapabilityProperties(component: Component, componentInstanceId: string, capability: Capability): Observable<Array<PropertyModel>> {
- return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capabilityType +
- '/capabilityName/' + capabilityName + '/properties')
+ return this.http.get(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capability.type +
+ '/capabilityName/' + capability.name + '/ownerId/' + capability.ownerId + '/properties')
.map((res: Response) => {
- return CommonUtils.initBeProperties(res.json());
+ capability.properties = res.json().map((capProp) => new PropertyModel(capProp)); // update capability properties
+ return capability.properties;
})
}
- updateInstanceCapabilityProperties(component: Component, componentInstanceId: string, capabilityType: string, capabilityName: string, properties: PropertyBEModel[]): Observable<PropertyBEModel[]> {
+ updateInstanceCapabilityProperties(component: Component, componentInstanceId: string, capability: Capability, properties: PropertyBEModel[]): Observable<Array<PropertyModel>> {
- return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capabilityType +
- '/capabilityName/' + capabilityName +'/properties', properties)
+ return this.http.put(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/componentInstances/' + componentInstanceId + '/capability/' + capability.type +
+ '/capabilityName/' + capability.name + '/ownerId/' + capability.ownerId + '/properties', properties)
.map((res: Response) => {
- return res.json().map((resProperty) => new PropertyBEModel(resProperty));
+ const savedProperties: PropertyModel[] = res.json().map((resProperty) => new PropertyModel(resProperty));
+ savedProperties.forEach((savedProperty) => {
+ const propIdx = capability.properties.findIndex((p) => p.uniqueId === savedProperty.uniqueId);
+ if (propIdx !== -1) {
+ capability.properties.splice(propIdx, 1, savedProperty);
+ }
+ });
+ return savedProperties;
})
}
- updateInstanceInput(component: Component, componentInstanceId: string, input: PropertyBEModel): Observable<PropertyBEModel> {
+ updateInstanceInputs(component: Component, componentInstanceId: string, inputs: PropertyBEModel[]): Observable<PropertyBEModel[]> {
- return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/input', input)
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/resourceInstance/' + componentInstanceId + '/inputs', inputs)
.map((res: Response) => {
- return new PropertyBEModel(res.json());
- })
- }
-
- hasPropertyChanged(property: PropertyFEModel) {
- let oldValue: any = property.value;
- const newValue = property.getJSONValue();
- return ((oldValue || newValue) && !isEqual(oldValue, newValue));
+ return res.json().map((resInput) => new PropertyBEModel(resInput));
+ });
}
}
diff --git a/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts b/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts
new file mode 100644
index 0000000000..6e9d0e8031
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/component-services/component.service.factory.ts
@@ -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=========================================================
+ */
+
+
+import {Injectable} from "@angular/core";
+import {Component} from "../../../models/components/component";
+import {ComponentServiceNg2} from "./component.service";
+import {ServiceServiceNg2} from "./service.service";
+
+@Injectable()
+export class ComponentServiceFactoryNg2 {
+ componentService: ComponentServiceNg2;
+ serviceService: ServiceServiceNg2;
+ constructor(componentService: ComponentServiceNg2, serviceService: ServiceServiceNg2) {
+ this.serviceService = serviceService;
+ this.componentService = componentService;
+ }
+ getComponentService(component: Component):ComponentServiceNg2 {
+ if (component.isService()) {
+ return this.serviceService;
+ }
+ return this.componentService;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/services/component-services/component.service.ts b/catalog-ui/src/app/ng2/services/component-services/component.service.ts
index ba1cb15561..9c3f78a444 100644
--- a/catalog-ui/src/app/ng2/services/component-services/component.service.ts
+++ b/catalog-ui/src/app/ng2/services/component-services/component.service.ts
@@ -18,13 +18,13 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {Injectable, Inject} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Response, URLSearchParams} from '@angular/http';
-import { Component, PropertyBEModel, InstancePropertiesAPIMap, FilterPropertiesAssignmentData} from "app/models";
-import {downgradeInjectable} from '@angular/upgrade/static';
+import { Component, InputBEModel, InstancePropertiesAPIMap, FilterPropertiesAssignmentData} from "app/models";
import {COMPONENT_FIELDS} from "app/utils";
import {ComponentGenericResponse} from "../responses/component-generic-response";
import {InstanceBePropertiesMap} from "../../../models/properties-inputs/property-fe-map";
@@ -40,11 +40,11 @@ export class ComponentServiceNg2 {
protected baseUrl;
- constructor(private http:HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) {
+ constructor(protected http:HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) {
this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root;
}
- private getComponentDataByFieldsName(componentType:string, componentId: string, fields:Array<string>):Observable<ComponentGenericResponse> {
+ protected getComponentDataByFieldsName(componentType:string, componentId: string, fields:Array<string>):Observable<ComponentGenericResponse> {
let params:URLSearchParams = new URLSearchParams();
_.forEach(fields, (field:string):void => {
@@ -53,10 +53,14 @@ export class ComponentServiceNg2 {
return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/filteredDataByParams', {search: params})
.map((res:Response) => {
- return new ComponentGenericResponse().deserialize(res.json());
+ return this.analyzeComponentDataResponse(res);
});
}
+ protected analyzeComponentDataResponse(res: Response):ComponentGenericResponse {
+ return new ComponentGenericResponse().deserialize(res.json());
+ }
+
private getServerTypeUrl = (componentType:string):string => {
switch (componentType) {
case ComponentType.SERVICE:
@@ -78,8 +82,8 @@ export class ComponentServiceNg2 {
return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_ATTRIBUTES]);
}
- getComponentInstancesAndRelation(component:Component):Observable<ComponentGenericResponse> {
- return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES]);
+ getComponentCompositionData(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, COMPONENT_FIELDS.COMPONENT_POLICIES, COMPONENT_FIELDS.COMPONENT_GROUPS]);
}
getComponentResourceInstances(component:Component):Observable<ComponentGenericResponse> {
@@ -125,19 +129,19 @@ export class ComponentServiceNg2 {
})
}
- deleteInput(component:Component, input:PropertyBEModel):Observable<PropertyBEModel> {
+ deleteInput(component:Component, input:InputBEModel):Observable<InputBEModel> {
return this.http.delete(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/delete/' + input.uniqueId + '/input')
.map((res:Response) => {
- return new PropertyBEModel(res.json());
+ return new InputBEModel(res.json());
})
}
- updateComponentInput(component:Component, input:PropertyBEModel):Observable<PropertyBEModel> {
+ updateComponentInputs(component:Component, inputs:InputBEModel[]):Observable<InputBEModel[]> {
- return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/update/inputs', input)
+ return this.http.post(this.baseUrl + component.getTypeUrl() + component.uniqueId + '/update/inputs', inputs)
.map((res:Response) => {
- return new PropertyBEModel(res.json())
+ return res.json().map((input) => new InputBEModel(input));
})
}
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 f38dbef595..0439f2047e 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
@@ -22,19 +22,30 @@ import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
-import { Response } from '@angular/http';
+import { Response, URLSearchParams } from '@angular/http';
import {Service} from "app/models";
import { downgradeInjectable } from '@angular/upgrade/static';
import { HttpService } from '../http.service';
+
import {SdcConfigToken, ISdcConfig} from "../../config/sdc-config.config";
+import {ForwardingPath} from "app/models/forwarding-path";
+import {ComponentMetadata} from "app/models/component-metadata";
+import {ComponentType} from "app/utils";
+import {Component} from "app/models/components/component";
+import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
+import {COMPONENT_FIELDS, SERVICE_FIELDS} from "app/utils/constants";
+import {ComponentServiceNg2} from "./component.service";
+import {ServiceGenericResponse} from "app/ng2/services/responses/service-generic-response";
+import {ServicePathMapItem} from "app/models/graph/nodes-and-links-map";
@Injectable()
-export class ServiceServiceNg2 {
+export class ServiceServiceNg2 extends ComponentServiceNg2 {
protected baseUrl = "";
- constructor(private http: HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) {
+ constructor(protected http: HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) {
+ super(http, sdcConfig);
this.baseUrl = sdcConfig.api.root + sdcConfig.api.component_api_root;
}
@@ -46,4 +57,106 @@ export class ServiceServiceNg2 {
});
}
+ getNodesAndLinksMap(service: Service):Observable<Array<ServicePathMapItem>> {
+ return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/linksMap').map(res => {
+ return <Array<ServicePathMapItem>>res.json();
+ });
+ }
+
+ getServicePath(service: Service, id: string):Observable<any> {
+ return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths/' + id)
+ .map(res => {
+ return res.json();
+ })
+ }
+
+ getServicePaths(service: Service):Observable<any> {
+ return this.http.get(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths')
+ .map(res => {
+ return res.json();
+ })
+ }
+
+ createOrUpdateServicePath(service: Service, inputsToCreate: ForwardingPath):Observable<ForwardingPath> {
+ if (inputsToCreate.uniqueId) {
+ return this.updateServicePath(service, inputsToCreate);
+ } else {
+ return this.createServicePath(service, inputsToCreate);
+ }
+ }
+
+ createServicePath(service: Service, inputsToCreate: ForwardingPath):Observable<ForwardingPath> {
+ let input = new ServicePathRequestData(inputsToCreate);
+
+ return this.http.post(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths', input)
+ .map(res => {
+ return this.parseServicePathResponse(res);
+ });
+ }
+
+ deleteServicePath(service: Service, id: string):Observable<any> {
+ return this.http.delete(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths/' + id )
+ .map((res) => {
+ return res.json();
+ });
+ }
+
+ updateServicePath(service: Service, inputsToUpdate:ForwardingPath):Observable<ForwardingPath> {
+ let input = new ServicePathRequestData(inputsToUpdate);
+
+ return this.http.put(this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths', input)
+ .map((res) => {
+ return this.parseServicePathResponse(res);
+ });
+ }
+
+ checkComponentInstanceVersionChange(service: Service, newVersionId: string):Observable<Array<string>> {
+ let instanceId = service.selectedInstance.uniqueId;
+ let queries = {componentInstanceId: instanceId, newComponentInstanceId: newVersionId};
+
+ let params:URLSearchParams = new URLSearchParams();
+ _.map(_.keys(queries), (key:string):void => {
+ params.append(key, queries[key]);
+ });
+
+ let url = this.baseUrl + service.getTypeUrl() + service.uniqueId + '/paths-to-delete';
+ return this.http.get(url, {search: params}).map((res: Response) => {
+ return res.json().forwardingPathToDelete;
+ });
+ }
+
+ getComponentCompositionData(component:Component):Observable<ComponentGenericResponse> {
+ return this.getComponentDataByFieldsName(component.componentType, component.uniqueId, [COMPONENT_FIELDS.COMPONENT_INSTANCES_RELATION, COMPONENT_FIELDS.COMPONENT_INSTANCES, SERVICE_FIELDS.FORWARDING_PATHS]);
+ }
+
+ protected analyzeComponentDataResponse(res: Response):ComponentGenericResponse {
+ return new ServiceGenericResponse().deserialize(res.json());
+ }
+
+ private parseServicePathResponse(res: Response):ForwardingPath {
+ let resJSON = res.json();
+ let pathId = Object.keys(resJSON.forwardingPaths)[0];
+ let forwardingPath = resJSON.forwardingPaths[pathId];
+ let path:ForwardingPath = new ForwardingPath();
+ path.deserialize(forwardingPath);
+ path.uniqueId = pathId;
+ return path;
+ }
}
+
+class ServicePathRequestData {
+ forwardingPaths: { [key:string]:ForwardingPath } = {};
+ componentMetadataDefinition: ComponentMetadata;
+ toscaType: string = "topology_template";
+
+ constructor(fp? : ForwardingPath) {
+ this.componentMetadataDefinition = new ComponentMetadata();
+ this.componentMetadataDefinition.ecompGeneratedNaming = true;
+ this.componentMetadataDefinition.componentType = ComponentType.SERVICE;
+ if (fp) {
+ let id = fp.uniqueId ? fp.uniqueId : "NEW";
+ this.forwardingPaths[fp.uniqueId] = fp;
+ }
+ }
+}
+
diff --git a/catalog-ui/src/app/ng2/services/config.service.ts b/catalog-ui/src/app/ng2/services/config.service.ts
index 053f2c7659..3e6e667285 100644
--- a/catalog-ui/src/app/ng2/services/config.service.ts
+++ b/catalog-ui/src/app/ng2/services/config.service.ts
@@ -37,8 +37,8 @@ export class ConfigService {
public api:IApi;
constructor(private http: Http, @Inject(SdcConfigToken) private sdcConfig:ISdcConfig) {
- this.api = this.sdcConfig.api;
- this.baseUrl = this.api.root + this.api.component_api_root;
+ this.api = this.sdcConfig.api;
+ this.baseUrl = this.sdcConfig.api.root + this.sdcConfig.api.component_api_root;
}
loadValidationConfiguration(): Promise<ValidationConfiguration> {
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 30c02a4141..6b5908903e 100644
--- a/catalog-ui/src/app/ng2/services/data-type.service.ts
+++ b/catalog-ui/src/app/ng2/services/data-type.service.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { Injectable } from '@angular/core';
import { DataTypeModel, DataTypesMap, PropertyBEModel, PropertyFEModel, DerivedFEProperty, DerivedFEPropertyMap } from "app/models";
import { DataTypesService } from "app/services/data-types-service";
diff --git a/catalog-ui/src/app/ng2/services/dynamic-component.service.ts b/catalog-ui/src/app/ng2/services/dynamic-component.service.ts
new file mode 100644
index 0000000000..29dd1e9e09
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/dynamic-component.service.ts
@@ -0,0 +1,28 @@
+import {
+ Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef
+} from '@angular/core';
+
+
+
+@Injectable()
+export class DynamicComponentService {
+
+ constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
+
+ //Creates a component dynamically (aka during runtime). If a view container is not specified, it will append the new component to the app root.
+ //To subscribe to an event from invoking component: componentRef.instance.clicked.subscribe((m) => console.log(m.name));
+ public createDynamicComponent<T>(componentType: Type<T>, viewContainerRef?:ViewContainerRef): ComponentRef<T> {
+
+ viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
+ viewContainerRef.clear();
+
+ let factory: ComponentFactory<T> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
+ let componentRef: ComponentRef<T> = viewContainerRef.createComponent(factory);
+ return componentRef;
+ }
+
+
+ private getRootViewContainerRef(): ViewContainerRef {
+ return this.applicationRef.components[0].instance.viewContainerRef;
+ }
+}; \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/services/modal.service.ts b/catalog-ui/src/app/ng2/services/modal.service.ts
index 22b56c7004..4e86d6accf 100644
--- a/catalog-ui/src/app/ng2/services/modal.service.ts
+++ b/catalog-ui/src/app/ng2/services/modal.service.ts
@@ -1,11 +1,12 @@
import {
Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef,
-
+ TemplateRef
} from '@angular/core';
import { ModalModel, ButtonModel, StepModel } from 'app/models';
import {MultiStepsWizardComponent} from "../components/ui/multi-steps-wizard/multi-steps-wizard.component";
import {ModalComponent} from "../components/ui/modal/modal.component";
import {WizardHeaderBaseComponent} from "app/ng2/components/ui/multi-steps-wizard/multi-steps-wizard-header-base.component";
+import { DynamicComponentService } from 'app/ng2/services/dynamic-component.service';
@Injectable()
@@ -13,7 +14,7 @@ export class ModalService {
currentModal: ComponentRef<any>;
- constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
+ constructor(private dynamicComponentService: DynamicComponentService) { }
/* Shortcut method to open an alert modal with title, message, and close button that simply closes the modal. */
@@ -52,7 +53,7 @@ export class ModalService {
/* Use this method to create a modal with title, message, and completely custom buttons. Use response.instance.open() to open */
public createCustomModal = (customModalData: ModalModel): ComponentRef<ModalComponent> => {
- let customModal: ComponentRef<ModalComponent> = this.createDynamicComponent(ModalComponent);
+ let customModal: ComponentRef<ModalComponent> = this.dynamicComponentService.createDynamicComponent(ModalComponent);
customModal.instance.input = customModalData;
this.currentModal = customModal;
@@ -62,12 +63,12 @@ export class ModalService {
public createMultiStepsWizard = (title: string, steps:Array<StepModel>, callback: Function, dynamicHeaderType?: Type<WizardHeaderBaseComponent>): ComponentRef<MultiStepsWizardComponent> => {
let cancelButton: ButtonModel = new ButtonModel('Cancel', 'outline blue', this.closeCurrentModal);
let modalModel: ModalModel = new ModalModel('xl', title, '', [cancelButton]);
- let wizardInstance: ComponentRef<MultiStepsWizardComponent> = this.createDynamicComponent(MultiStepsWizardComponent);
+ let wizardInstance: ComponentRef<MultiStepsWizardComponent> = this.dynamicComponentService.createDynamicComponent(MultiStepsWizardComponent);
wizardInstance.instance.input = modalModel;
wizardInstance.instance.steps = steps;
wizardInstance.instance.callback = callback;
if(dynamicHeaderType){
- let dynamicHeader = this.createDynamicComponent(dynamicHeaderType, wizardInstance.instance.dynamicHeaderContainer);
+ let dynamicHeader = this.dynamicComponentService.createDynamicComponent(dynamicHeaderType, wizardInstance.instance.dynamicHeaderContainer);
wizardInstance.instance.dynamicHeader = dynamicHeader;
wizardInstance.instance.dynamicHeader.instance.currentStepIndex = 0;
}
@@ -76,38 +77,28 @@ export class ModalService {
return wizardInstance;
}
-
+
public closeCurrentModal = () => {
if (!this.currentModal) return;
this.currentModal.instance.close();
this.currentModal.destroy();
+ delete this.currentModal;
}
public addDynamicContentToModal = (modalInstance: ComponentRef<ModalComponent>, dynamicComponentType: Type<any>, dynamicComponentInput?: any) => {
- let dynamicContent = this.createDynamicComponent(dynamicComponentType, modalInstance.instance.dynamicContentContainer);
+ let dynamicContent = this.dynamicComponentService.createDynamicComponent(dynamicComponentType, modalInstance.instance.dynamicContentContainer);
dynamicContent.instance.input = dynamicComponentInput;
modalInstance.instance.dynamicContent = dynamicContent;
return modalInstance;
}
- //Creates a component dynamically (aka during runtime). If a view container is not specified, it will append the new component to the app root.
- //To subscribe to an event from invoking component: componentRef.instance.clicked.subscribe((m) => console.log(m.name));
- private createDynamicComponent<T>(componentType: Type<T>, viewContainerRef?:ViewContainerRef): ComponentRef<T> {
-
- viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
- viewContainerRef.clear();
+ public addDynamicTemplateToModal = (modalInstance: ComponentRef<ModalComponent>, templateRef: TemplateRef<void>) => {
+ modalInstance.instance.dynamicContentContainer.clear();
+ modalInstance.instance.dynamicContentContainer.createEmbeddedView(templateRef);
+ return modalInstance;
+ };
- let factory: ComponentFactory<T> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
- let componentRef: ComponentRef<T> = viewContainerRef.createComponent(factory);
- return componentRef;
- }
-
- private getRootViewContainerRef(): ViewContainerRef {
- return this.applicationRef.components[0].instance.viewContainerRef;
- }
}
-
-
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java b/catalog-ui/src/app/ng2/services/policies.service.ts
index 015d228acf..2b564b8915 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java
+++ b/catalog-ui/src/app/ng2/services/policies.service.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,32 +18,32 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.ci.tests.datatypes;
+import { Injectable, Inject } from "@angular/core";
+import { Headers } from "@angular/http";
+import { Observable } from "rxjs/Observable";
+import { HttpService } from "./http.service";
+import { Cookie2Service } from "./cookie.service";
+import {SdcConfigToken, ISdcConfig} from "../config/sdc-config.config";
-public class ServiceAssetStructure extends AssetStructure {
- private String distributionStatus;
+@Injectable()
+export class PoliciesService {
+ protected baseUrl;
- public ServiceAssetStructure() {
- super();
- }
+ private mapApiDirections = {
+ 'RESOURCE':'resources',
+ 'SERVICE':'services'
+ }
- 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);
- }
+ constructor(private http: HttpService, @Inject(SdcConfigToken) sdcConfig:ISdcConfig) {
+ this.baseUrl = sdcConfig.api.root ;
+ }
- @Override
- public String toString() {
- return "ServiceAssetStructure [distributionStatus=" + distributionStatus + "]";
- }
-
- public String getDistributionStatus() {
- return distributionStatus;
- }
-
- public void setDistributionStatus(String distributionStatus) {
- this.distributionStatus = distributionStatus;
- }
+ public createPolicyInstance(entityType:string, id:string, policyType:string) {
+ return this.http.post(this.baseUrl + '/v1/catalog/' + this.mapApiDirections[entityType] + '/' + id +'/policies/' + policyType, {}).map(resp => {
+ return resp.json();
+ });
+ }
}
+
diff --git a/catalog-ui/src/app/ng2/services/properties.service.ts b/catalog-ui/src/app/ng2/services/properties.service.ts
index 86cd2f5c72..c86d207915 100644
--- a/catalog-ui/src/app/ng2/services/properties.service.ts
+++ b/catalog-ui/src/app/ng2/services/properties.service.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import { Injectable } from '@angular/core';
import { PropertyFEModel, PropertyBEModel, PropertyDeclareAPIModel, DerivedFEProperty} from "app/models";
diff --git a/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts b/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts
index 9450e4bc04..e7c88a0ab8 100644
--- a/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts
+++ b/catalog-ui/src/app/ng2/services/responses/component-generic-response.ts
@@ -27,6 +27,7 @@ import { ArtifactGroupModel, PropertyModel, PropertiesGroup, AttributeModel, Att
import {CommonUtils} from "app/utils";
import {Serializable} from "../utils/serializable";
import {PropertyBEModel} from "../../../models/properties-inputs/property-be-model";
+import { PolicyInstance } from "app/models/graph/zones/policy-instance";
export class ComponentGenericResponse implements Serializable<ComponentGenericResponse> {
@@ -43,6 +44,7 @@ export class ComponentGenericResponse implements Serializable<ComponentGenericR
public requirements:RequirementsGroup;
public properties:Array<PropertyModel>;
public attributes:Array<AttributeModel>;
+ public policies:Array<PolicyInstance>;
public groups:Array<Module>;
public interfaces:any;
public additionalInformation:any;
@@ -92,6 +94,9 @@ export class ComponentGenericResponse implements Serializable<ComponentGenericR
if(response.groups) {
this.groups = CommonUtils.initModules(response.groups);
}
+ if(response.policies) {
+ this.policies = CommonUtils.initPolicies(response.policies);
+ }
return this;
}
}
diff --git a/catalog-ui/src/app/ng2/services/responses/service-generic-response.ts b/catalog-ui/src/app/ng2/services/responses/service-generic-response.ts
new file mode 100644
index 0000000000..d32ed26bb2
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/responses/service-generic-response.ts
@@ -0,0 +1,22 @@
+import * as _ from "lodash";
+import {Serializable} from "../utils/serializable";
+import {ComponentGenericResponse} from "./component-generic-response";
+import {ForwardingPath} from "../../../models/forwarding-path";
+
+export class ServiceGenericResponse extends ComponentGenericResponse implements Serializable<ServiceGenericResponse> {
+ public forwardingPaths: { [key:string]:ForwardingPath } = {};
+
+ deserialize (response): ServiceGenericResponse {
+ super.deserialize(response);
+ if(response.forwardingPaths) {
+ _.forEach(response.forwardingPaths, (pathResponse, id) => {
+ let pathId = id;
+ let path:ForwardingPath = new ForwardingPath();
+ path.deserialize(pathResponse);
+ path.uniqueId = pathId;
+ this.forwardingPaths[pathId] = path;
+ });
+ }
+ return this;
+ }
+} \ No newline at end of file
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 51314c04bd..c005efcbe8 100644
--- a/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts
+++ b/catalog-ui/src/app/ng2/utils/ng1-upgraded-provider.ts
@@ -27,6 +27,7 @@ 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";
+import IScope = angular.IScope;
/** Services we need to upgrade from angular1 to angular2 - in the future we need to rewrite them all to angular2 **/
@@ -62,6 +63,10 @@ export function eventListenerServiceServiceFactory(cacheObj: ICacheObject) {
return cacheObj.get('EventListenerService');
}
+export function notificationServiceFactory(cacheObj: ICacheObject) {
+ return cacheObj.get('Notification');
+}
+
export const DataTypesServiceProvider = {
provide: DataTypesService,
useFactory: dataTypesServiceFactory,
@@ -111,3 +116,9 @@ export const EventListenerServiceProvider = {
useFactory: eventListenerServiceServiceFactory,
deps: ['$injector']
};
+
+export const NotificationServiceProvider = {
+ provide: 'Notification',
+ useFactory: notificationServiceFactory,
+ 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 1b2b9f2fa1..74166a0c9f 100644
--- a/catalog-ui/src/app/services/components/component-service.ts
+++ b/catalog-ui/src/app/services/components/component-service.ts
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
'use strict';
+import * as _ from "lodash";
import {ArtifactModel, IFileDownload, InstancesInputsPropertiesMap, InputModel, IValidate, RelationshipModel, PropertyModel, Component, ComponentInstance,
AttributeModel, IAppConfigurtaion, Resource, Module, DisplayModule, ArtifactGroupModel, InputsAndProperties} from "app/models";
import {ComponentInstanceFactory, CommonUtils} from "app/utils";
@@ -40,6 +41,7 @@ export interface IComponentService {
updateAttribute(componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel>;
deleteProperty(componentId:string, propertyId:string):ng.IPromise<PropertyModel>;
deleteAttribute(componentId:string, attributeId:string):ng.IPromise<AttributeModel>;
+ checkResourceInstanceVersionChange(componentId:string, componentInstanceId:string, componentUid:string):ng.IPromise<any>;
changeResourceInstanceVersion(componentId:string, componentInstanceId:string, componentUid:string):ng.IPromise<ComponentInstance>;
updateInstanceArtifact(componentId:string, instanceId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
addInstanceArtifact(componentId:string, instanceId:string, artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
@@ -55,7 +57,7 @@ export interface IComponentService {
deleteRelation(componentId:string, link:RelationshipModel):ng.IPromise<RelationshipModel>;
fetchRelation(componentId:string, linkId:string):ng.IPromise<RelationshipModel>;
getRequirementsCapabilities(componentId:string):ng.IPromise<any>;
- updateInstanceProperty(componentId:string, property:PropertyModel):ng.IPromise<PropertyModel>;
+ updateInstanceProperties(componentId:string, componentInstanceId:string, properties:PropertyModel[]):ng.IPromise<PropertyModel[]>;
updateInstanceAttribute(componentId:string, attribute:AttributeModel):ng.IPromise<AttributeModel>;
getComponentInstancesFilteredByInputsAndProperties(componentId:string, searchText:string):ng.IPromise<Array<ComponentInstance>>
getComponentInstanceInputs(componentId:string, instanceId:string, originComponentUid):ng.IPromise<Array<InputModel>>;
@@ -422,6 +424,16 @@ export class ComponentService implements IComponentService {
return deferred.promise;
};
+ public checkResourceInstanceVersionChange = (componentId:string, componentInstanceId:string, componentUid:string):ng.IPromise<ComponentInstance> => {
+ let deferred = this.$q.defer();
+ this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).one(componentUid).one("checkForwardingPathOnVersionChange").get().then((response:any) => {
+ deferred.resolve(response);
+ }, err => {
+ deferred.reject(err);
+ });
+ return deferred.promise;
+ };
+
public changeResourceInstanceVersion = (componentId:string, componentInstanceId:string, componentUid:string):ng.IPromise<ComponentInstance> => {
let deferred = this.$q.defer();
this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).one("changeVersion").customPOST({'componentUid': componentUid}).then((response:any) => {
@@ -498,14 +510,16 @@ export class ComponentService implements IComponentService {
return deferred.promise;
};
- public updateInstanceProperty = (componentId:string, property:PropertyModel):ng.IPromise<PropertyModel> => {
- let deferred = this.$q.defer();
- let instanceId = property.resourceInstanceUniqueId;
- this.restangular.one(componentId).one("resourceInstance").one(instanceId).one("property").customPOST(JSON.stringify(property)).then((response:any) => {
- let newProperty = new PropertyModel(response);
- newProperty.readonly = true;
- newProperty.resourceInstanceUniqueId = instanceId;
- deferred.resolve(newProperty);
+ public updateInstanceProperties = (componentId:string, componentInstanceId:string, properties:PropertyModel[]):ng.IPromise<PropertyModel[]> => {
+ let deferred = this.$q.defer<PropertyModel[]>();
+ this.restangular.one(componentId).one("resourceInstance").one(componentInstanceId).one("properties").customPOST(JSON.stringify(properties)).then((response:any) => {
+ const newProperties = response.map((res) => {
+ const newProperty = new PropertyModel(res);
+ newProperty.readonly = true;
+ newProperty.resourceInstanceUniqueId = componentInstanceId;
+ return newProperty;
+ });
+ deferred.resolve(newProperties);
}, (err)=> {
deferred.reject(err);
});
diff --git a/catalog-ui/src/app/services/components/resource-service.ts b/catalog-ui/src/app/services/components/resource-service.ts
index 641d7cba48..aabc14f8bd 100644
--- a/catalog-ui/src/app/services/components/resource-service.ts
+++ b/catalog-ui/src/app/services/components/resource-service.ts
@@ -22,6 +22,7 @@
* Created by obarda on 2/4/2016.
*/
'use strict';
+import * as _ from "lodash";
import {IComponentService, ComponentService} from "./component-service";
import {PropertyModel, IAppConfigurtaion, Resource, Component} from "../../models";
import {SharingService} from "../sharing-service";
diff --git a/catalog-ui/src/app/services/components/service-service.ts b/catalog-ui/src/app/services/components/service-service.ts
index 4229c4aa2a..d55cae75ce 100644
--- a/catalog-ui/src/app/services/components/service-service.ts
+++ b/catalog-ui/src/app/services/components/service-service.ts
@@ -22,6 +22,7 @@
* Created by obarda on 2/4/2016.
*/
'use strict';
+import * as _ from "lodash";
import {IComponentService, ComponentService} from "./component-service";
import {Distribution, DistributionComponent, Service, PropertyModel, Component, IAppConfigurtaion} from "app/models";
import {SharingService} from "../sharing-service";
diff --git a/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
index a1fa65159f..2ed995c78c 100644
--- a/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
+++ b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
@@ -21,25 +21,28 @@
* Created by obarda on 3/13/2016.
*/
'use strict';
-import {LeftPaletteComponent} from "../../../models/components/displayComponent";
-import {Component} from "../../../models/components/component";
+import * as _ from "lodash";
+import {LeftPaletteComponent, LeftPaletteMetadataTypes} from "app/models/components/displayComponent";
+import {Component} from "app/models/components/component";
import {EventListenerService} from "../../event-listener-service";
import {ComponentFactory} from "../../../utils/component-factory";
-import {IAppConfigurtaion} from "../../../models/app-config";
+import {IAppConfigurtaion} from "app/models/app-config";
import {ResourceType, ComponentType, EVENTS} from "../../../utils/constants";
-import {ComponentMetadata} from "../../../models/component-metadata";
+import {ComponentMetadata} from "app/models/component-metadata";
+import {GroupMetadata, GroupTpes} from "app/models/group-metadata";
+import {PolicyMetadata, PolicyTpes} from "app/models/policy-metadata";
import {Resource} from "app/models/components/resource";
-export class LeftPaletteDataObject {
- displayLeftPanelComponents:Array<LeftPaletteComponent>;
- onFinishLoadingEvent:string;
+// export class LeftPaletteDataObject {
+// displayLeftPanelComponents:Array<LeftPaletteComponent>;
+// onFinishLoadingEvent:string;
- constructor(onFinishEventListener:string) {
+// constructor(onFinishEventListener:string) {
- this.displayLeftPanelComponents = new Array<LeftPaletteComponent>();
- this.onFinishLoadingEvent = onFinishEventListener;
- }
-}
+// this.displayLeftPanelComponents = new Array<LeftPaletteComponent>();
+// this.onFinishLoadingEvent = onFinishEventListener;
+// }
+// }
export class LeftPaletteLoaderService {
@@ -62,55 +65,72 @@ export class LeftPaletteLoaderService {
}
- private serviceLeftPaletteData:LeftPaletteDataObject;
- private resourceLeftPaletteData:LeftPaletteDataObject;
- private resourcePNFLeftPaletteData:LeftPaletteDataObject;
- private vlData:LeftPaletteDataObject;
+ // private serviceLeftPaletteData:LeftPaletteDataObject;
+ // private resourceLeftPaletteData:LeftPaletteDataObject;
+ // private resourcePNFLeftPaletteData:LeftPaletteDataObject;
+ // private vlData:LeftPaletteDataObject;
+ leftPanelComponents:Array<LeftPaletteComponent>;
public loadLeftPanel = (component:Component):void => {
- this.serviceLeftPaletteData = new LeftPaletteDataObject(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
- this.resourceLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
- this.resourcePNFLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT);
- this.updateComponentLeftPalette(component);
+ // this.serviceLeftPaletteData = new LeftPaletteDataObject(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
+ // this.resourceLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
+ // this.resourcePNFLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT);
+ this.leftPanelComponents = [];
+ this.updateLeftPaletteForTopologyTemplate(component);
}
- private getResourceLeftPaletteDataByResourceType = (resourceType:string):LeftPaletteDataObject => {
- if(resourceType == ResourceType.PNF) {
- return this.resourcePNFLeftPaletteData;
- }
- return this.resourceLeftPaletteData;
- }
+ // private getResourceLeftPaletteDataByResourceType = (resourceType:string):LeftPaletteDataObject => {
+ // if(resourceType == ResourceType.PNF) {
+ // return this.resourcePNFLeftPaletteData;
+ // }
+ // return this.resourceLeftPaletteData;
+ // }
- private onFinishLoading = (componentType:string, leftPaletteData:LeftPaletteDataObject):void => {
- this.EventListenerService.notifyObservers(leftPaletteData.onFinishLoadingEvent);
- };
-
- private updateLeftPalette = (componentType, componentInternalType:string, leftPaletteData:LeftPaletteDataObject):void => {
+ private updateLeftPalette = (componentInternalType:string):void => {
+ /* add components */
this.restangular.one("resources").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
_.forEach(leftPaletteComponentMetadata, (componentMetadata:ComponentMetadata) => {
- leftPaletteData.displayLeftPanelComponents.push(new LeftPaletteComponent(componentMetadata));
+ this.leftPanelComponents.push(new LeftPaletteComponent(LeftPaletteMetadataTypes.Component, componentMetadata));
});
- this.onFinishLoading(componentType, leftPaletteData);
+ this.EventListenerService.notifyObservers(EVENTS.LEFT_PALETTE_UPDATE_EVENT);
});
- };
+
+ /* add groups */
+ //TODO: In backend implement like this:
+ //this.restangular.one("groups").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
+ this.restangular.one('/groupTypes').get().then((leftPaletteGroupTypes:GroupTpes) => {
+ _.forEach(leftPaletteGroupTypes.groupTypes, (groupMetadata: GroupMetadata) => {
+ this.leftPanelComponents.push(new LeftPaletteComponent(LeftPaletteMetadataTypes.Group, groupMetadata));
+ });
+ this.EventListenerService.notifyObservers(EVENTS.LEFT_PALETTE_UPDATE_EVENT);
+ });
+
+ /* add policies */
+ //TODO: In backend implement like this:
+ //this.restangular.one("policies").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
+ this.restangular.one('/policyTypes').get().then((leftPalettePolicyTypes:PolicyTpes) => {
+ _.forEach(leftPalettePolicyTypes.policyTypes, (policyMetadata: PolicyMetadata) => {
+ this.leftPanelComponents.push(new LeftPaletteComponent(LeftPaletteMetadataTypes.Policy, policyMetadata));
+ });
+ this.EventListenerService.notifyObservers(EVENTS.LEFT_PALETTE_UPDATE_EVENT);
+ });
+ }
public getLeftPanelComponentsForDisplay = (component:Component):Array<LeftPaletteComponent> => {
- switch (component.componentType) {
- case ComponentType.SERVICE:
- return this.serviceLeftPaletteData.displayLeftPanelComponents;
- default://resource
- return this.getResourceLeftPaletteDataByResourceType((<Resource>component).resourceType).displayLeftPanelComponents;
- }
+ return this.leftPanelComponents;
};
- public updateComponentLeftPalette = (component:Component):void => {
+ /**
+ * Update left palete items according to current topology templates we are in.
+ */
+ public updateLeftPaletteForTopologyTemplate = (component:Component):void => {
switch (component.componentType) {
case ComponentType.SERVICE:
- this.updateLeftPalette(ComponentType.SERVICE, ComponentType.SERVICE, this.serviceLeftPaletteData);
+ this.updateLeftPalette(ComponentType.SERVICE);
break;
case ComponentType.RESOURCE:
- this.updateLeftPalette(ComponentType.RESOURCE, (<Resource>component).resourceType, this.getResourceLeftPaletteDataByResourceType((<Resource>component).resourceType));
+ this.updateLeftPalette((<Resource>component).resourceType);
break;
default:
console.log('ERROR: Component type '+ component.componentType + ' is not exists');
diff --git a/catalog-ui/src/app/services/entity-service.ts b/catalog-ui/src/app/services/entity-service.ts
index 27b0513b39..b7ac8805ce 100644
--- a/catalog-ui/src/app/services/entity-service.ts
+++ b/catalog-ui/src/app/services/entity-service.ts
@@ -54,13 +54,13 @@ export class EntityService implements IEntityService {
let followedResponse: IComponentsArray = response.data;
let componentsList:Array<Component> = new Array();
- followedResponse.services.forEach((serviceResponse:Service) => {
+ followedResponse.services && followedResponse.services.forEach((serviceResponse:Service) => {
let component:Service = this.ComponentFactory.createService(serviceResponse); // new Service(serviceResponse);
componentsList.push(component);
this.sharingService.addUuidValue(component.uniqueId, component.uuid);
});
- followedResponse.resources.forEach((resourceResponse:Resource) => {
+ followedResponse.resources && followedResponse.resources.forEach((resourceResponse:Resource) => {
let component:Resource = this.ComponentFactory.createResource(resourceResponse);
componentsList.push(component);
this.sharingService.addUuidValue(component.uniqueId, component.uuid);
diff --git a/catalog-ui/src/app/services/event-listener-service.ts b/catalog-ui/src/app/services/event-listener-service.ts
index 96f9e17641..360edad700 100644
--- a/catalog-ui/src/app/services/event-listener-service.ts
+++ b/catalog-ui/src/app/services/event-listener-service.ts
@@ -21,6 +21,7 @@
* Created by obarda on 7/4/2016.
*/
'use strict';
+import * as _ from "lodash";
import {Dictionary} from "../utils/dictionary/dictionary";
interface IEventListenerService {
diff --git a/catalog-ui/src/app/services/onboarding-service.ts b/catalog-ui/src/app/services/onboarding-service.ts
index 3dd7269326..3a6e940c6e 100644
--- a/catalog-ui/src/app/services/onboarding-service.ts
+++ b/catalog-ui/src/app/services/onboarding-service.ts
@@ -75,7 +75,7 @@ export class OnboardingService implements IOnboardingService {
};
downloadOnboardingCsar = (packageId:string):ng.IPromise<IFileDownload> => {
- let defer = this.$q.defer();
+ let defer = this.$q.defer<IFileDownload>();
this.$http({
url: this.api.GET_onboarding + "/" + packageId,
method: "get",
diff --git a/catalog-ui/src/app/utils/artifacts-utils.ts b/catalog-ui/src/app/utils/artifacts-utils.ts
index d6ea616c1e..e99b6411c4 100644
--- a/catalog-ui/src/app/utils/artifacts-utils.ts
+++ b/catalog-ui/src/app/utils/artifacts-utils.ts
@@ -18,10 +18,12 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {ArtifactModel} from "../models/artifacts";
import {IArtifactResourceFormViewModelScope} from "../view-models/forms/artifact-form/artifact-form-view-model";
import {Component} from "../models/components/component";
import {ArtifactGroupType, ArtifactType} from "./constants";
+
export class ArtifactsUtils {
static '$inject' = [
diff --git a/catalog-ui/src/app/utils/common-utils.ts b/catalog-ui/src/app/utils/common-utils.ts
index 1719034354..97177949ee 100644
--- a/catalog-ui/src/app/utils/common-utils.ts
+++ b/catalog-ui/src/app/utils/common-utils.ts
@@ -18,9 +18,11 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
import {Module, AttributeModel, ResourceInstance, PropertyModel, InputFEModel} from "../models";
import {ComponentInstanceFactory} from "./component-instance-factory";
import {InputBEModel, PropertyBEModel, RelationshipModel} from "app/models";
+import { PolicyInstance } from "app/models/graph/zones/policy-instance";
export class CommonUtils {
@@ -112,5 +114,17 @@ export class CommonUtils {
return componentInstancesRelations;
}
};
+
+ static initPolicies = (policiesObj: Array<PolicyInstance>):Array<PolicyInstance> => {
+ let policies = new Array<PolicyInstance>();
+
+ if (policiesObj) {
+ _.forEach(policiesObj, (policy: PolicyInstance): void => {
+ policies.push(new PolicyInstance(policy));
+ })
+ }
+
+ return policies;
+ }
}
diff --git a/catalog-ui/src/app/utils/component-factory.ts b/catalog-ui/src/app/utils/component-factory.ts
index f869ef68d3..bf4f23b6eb 100644
--- a/catalog-ui/src/app/utils/component-factory.ts
+++ b/catalog-ui/src/app/utils/component-factory.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {DEFAULT_ICON, ResourceType, ComponentType} from "./constants";
import {ServiceService, CacheService, ResourceService} from "app/services";
import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service} from "app/models";
@@ -150,6 +151,7 @@ export class ComponentFactory {
case ResourceType.VL:
case ResourceType.VFC:
case ResourceType.CP:
+ case ResourceType.CR:
case ResourceType.PNF:
case ResourceType.CVFC:
case ResourceType.CONFIGURATION:
diff --git a/catalog-ui/src/app/utils/constants.ts b/catalog-ui/src/app/utils/constants.ts
index ea0848eee6..c8603424bb 100644
--- a/catalog-ui/src/app/utils/constants.ts
+++ b/catalog-ui/src/app/utils/constants.ts
@@ -46,6 +46,7 @@ export class ResourceType {
static PNF = 'PNF';
static CVFC = 'CVFC';
static CONFIGURATION = 'Configuration';
+ static CR = 'CR';
}
export class ComponentState {
@@ -189,6 +190,7 @@ export class GraphColors {
public static NODE_UCPE_CP = '#9063cd';
public static NODE_UCPE = '#fbfbfb';
public static NODE_SELECTED_BORDER_COLOR = '#30bdf2';
+ public static SERVICE_PATH_LINK = '#70208a';
}
export class GraphTransactionLogText {
public static REMOVE_TEMP_LINK = "remove tempLink";
@@ -244,10 +246,11 @@ export class States {
}
export class EVENTS {
- static RESOURCE_LEFT_PALETTE_UPDATE_EVENT = "resourceLeftPanelUpdateEvent";
- static RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT = "resourcePNFLeftPanelUpdateEvent";
- static SERVICE_LEFT_PALETTE_UPDATE_EVENT = "serviceLeftPanelUpdateEvent";
- static VL_LEFT_PALETTE_UPDATE_EVENT = "vlLeftPanelUdateEvent";
+ // static RESOURCE_LEFT_PALETTE_UPDATE_EVENT = "resourceLeftPanelUpdateEvent";
+ // static RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT = "resourcePNFLeftPanelUpdateEvent";
+ // static SERVICE_LEFT_PALETTE_UPDATE_EVENT = "serviceLeftPanelUpdateEvent";
+ //static VL_LEFT_PALETTE_UPDATE_EVENT = "vlLeftPanelUdateEvent";
+ static LEFT_PALETTE_UPDATE_EVENT = "leftPanelUpdateEvent";
static ON_CSAR_LOADING = "onCsarLoading";
static DOWNLOAD_ARTIFACT_FINISH_EVENT = "downloadArtifactFinishEvent";
static ON_WORKSPACE_SAVE_BUTTON_CLICK = "onWorkspaceSaveButtonClick";
@@ -283,6 +286,8 @@ export class GRAPH_EVENTS {
static ON_PALETTE_COMPONENT_HOVER_OUT = 'onPaletteComponentHoverOut';
static ON_PALETTE_COMPONENT_DRAG_START = 'onPaletteComponentDragStart';
static ON_PALETTE_COMPONENT_DRAG_ACTION = 'onPaletteComponentDragAction';
+ static ON_PALETTE_COMPONENT_SHOW_POPUP_PANEL = 'onPaletteComponentShowPopupPanel';
+ static ON_PALETTE_COMPONENT_HIDE_POPUP_PANEL = 'onPaletteComponentHidePopupPanel';
static ON_COMPONENT_INSTANCE_NAME_CHANGED = 'onComponentInstanceNameChanged';
static ON_DELETE_COMPONENT_INSTANCE = 'onDeleteComponentInstance';
static ON_DELETE_MULTIPLE_COMPONENTS = 'onDeleteMultipleComponents';
@@ -291,6 +296,9 @@ export class GRAPH_EVENTS {
static ON_REMOVE_NODE_FROM_UCPE = 'onRemoveNodeFromUCPE';
static ON_VERSION_CHANGED = 'onVersionChanged';
static ON_CREATE_COMPONENT_INSTANCE = 'onCreateComponentInstance';
+ static ON_ADD_COMPONENT_INSTANCE_ZONE_START = 'onCreateComponentInstanceZone';
+ static ON_FINISH_ANIMATION_ZONE = 'onFinishAnimationZone';
+ static ON_ZONE_SIZE_CHANGE = 'onZoneSizeChange';
}
@@ -308,9 +316,15 @@ export class COMPONENT_FIELDS {
static COMPONENT_CAPABILITIES = "capabilities";
static COMPONENT_REQUIREMENTS = "requirements";
static COMPONENT_TOSCA_ARTIFACTS = "toscaArtifacts";
+ static COMPONENT_POLICIES = "policies";
static COMPONENT_GROUPS = "groups";
}
+
+export class SERVICE_FIELDS {
+ static FORWARDING_PATHS = "forwardingPaths";
+}
+
export class API_QUERY_PARAMS {
static INCLUDE = "include";
}
diff --git a/catalog-ui/src/app/utils/menu-handler.ts b/catalog-ui/src/app/utils/menu-handler.ts
index d48412a6ed..fc6eb2081a 100644
--- a/catalog-ui/src/app/utils/menu-handler.ts
+++ b/catalog-ui/src/app/utils/menu-handler.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {WorkspaceMode, ComponentState} from "./constants";
import {IAppConfigurtaion, IAppMenu, Component} from "../models";
import {ComponentFactory} from "./component-factory";
@@ -92,36 +93,36 @@ export class MenuHandler {
}
- generateBreadcrumbsModelFromComponents = (components:Array<Component>, selected:Component):MenuItemGroup => {
- let result = new MenuItemGroup(0, [], false);
- if (components) {
+ findBreadcrumbComponentIndex = (components:Array<Component>, selected:Component):number => {
+ let selectedItemIdx;
+
+ // Search the component in all components by uuid (and not uniqueid, gives access to an assets's minor versions).
+ selectedItemIdx = _.findIndex(components, (item:Component) => {
+ return item.uuid === selected.uuid;
+ });
- // Search the component in all components by uuid (and not uniqueid, gives access to an assets's minor versions).
- let selectedItem = _.find(components, (item:Component) => {
- return item.uuid === selected.uuid;
+ // If not found search by invariantUUID
+ if (selectedItemIdx === -1) {
+ selectedItemIdx = _.findIndex(components, (item:Component) => {
+ //invariantUUID && Certified State matches between major versions
+ return item.invariantUUID === selected.invariantUUID && item.lifecycleState === ComponentState.CERTIFIED;
});
+ }
- // If not found search by invariantUUID
- if (undefined == selectedItem) {
- selectedItem = _.find(components, (item:Component) => {
- //invariantUUID && Certified State matches between major versions
- return item.invariantUUID === selected.invariantUUID && item.lifecycleState === ComponentState.CERTIFIED;
- });
- }
+ // If not found search by name (name is unique).
+ if (selectedItemIdx === -1) {
+ selectedItemIdx = _.findIndex(components, (item:Component) => {
+ return item.name === selected.name;
+ });
+ }
- // If not found search by name (name is unique).
- if (undefined == selectedItem) {
- selectedItem = _.find(components, (item:Component) => {
- return item.name === selected.name;
- });
- }
-
- if(!selectedItem){
- result.selectedIndex = components.length;
- }else{
- result.selectedIndex = components.indexOf(selectedItem);
- }
- components[result.selectedIndex] = selected;
+ return selectedItemIdx;
+ };
+
+ generateBreadcrumbsModelFromComponents = (components:Array<Component>, selected:Component):MenuItemGroup => {
+ let result = new MenuItemGroup(0, [], false);
+ if (components) {
+ result.selectedIndex = this.findBreadcrumbComponentIndex(components, selected);
let clickItemCallback = (component:Component):ng.IPromise<boolean> => {
this.$state.go('workspace.general', {
id: component.uniqueId,
diff --git a/catalog-ui/src/app/utils/modals-handler.ts b/catalog-ui/src/app/utils/modals-handler.ts
index 0d17683116..48ce487f9d 100644
--- a/catalog-ui/src/app/utils/modals-handler.ts
+++ b/catalog-ui/src/app/utils/modals-handler.ts
@@ -310,7 +310,7 @@ export class ModalsHandler implements IModalsHandler {
};
- openEditModulePropertyModal = (property:PropertyModel, component:Component, selectedModule:DisplayModule):ng.IPromise<any> => {
+ openEditModulePropertyModal = (property:PropertyModel, component:Component, selectedModule:DisplayModule, filteredProperties:Array<PropertyModel>):ng.IPromise<any> => {
let deferred = this.$q.defer();
let modalOptions:ng.ui.bootstrap.IModalSettings = {
@@ -328,6 +328,9 @@ export class ModalsHandler implements IModalsHandler {
},
selectedModule: ():DisplayModule => {
return selectedModule;
+ },
+ filteredProperties: ():Array<PropertyModel> => {
+ return filteredProperties;
}
}
};
diff --git a/catalog-ui/src/app/utils/validation-utils.ts b/catalog-ui/src/app/utils/validation-utils.ts
index 6b45149b1e..cd90ba7752 100644
--- a/catalog-ui/src/app/utils/validation-utils.ts
+++ b/catalog-ui/src/app/utils/validation-utils.ts
@@ -18,6 +18,8 @@
* ============LICENSE_END=========================================================
*/
+import * as _ from "lodash";
+
class basePattern {
pattern:RegExp;
base:number;
diff --git a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts
index db94a475d1..45232b7a61 100644
--- a/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts
+++ b/catalog-ui/src/app/view-models/admin-dashboard/user-management/user-management-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {ModalsHandler} from "app/utils";
import {User, IUserProperties, IUser, IAppConfigurtaion} from "app/models";
import {UserService} from "../../../ng2/services/user.service";
diff --git a/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts b/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
index 10aa47e0ed..2296aa7cdf 100644
--- a/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
+++ b/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {Component, IMainCategory, IGroup, IConfigStatuses, IAppMenu, IAppConfigurtaion, IUserProperties, ISubCategory} from "app/models";
import {EntityService, CacheService} from "app/services";
import {ComponentFactory, ResourceType, MenuHandler, ChangeLifecycleStateHandler} from "app/utils";
@@ -149,7 +150,7 @@ export class CatalogViewModel {
// Checklist init
this.$scope.checkboxes = <Checkboxes>{};
this.$scope.checkboxes.componentTypes = ['Resource', 'Service'];
- this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'PNF', 'CP', 'VL'];
+ this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CR', 'PNF', 'CP', 'VL'];
// Checkboxes filter init
this.$scope.checkboxesFilter = <CheckboxesFilter>{};
diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts b/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
index 80a9bcac3e..42628607c9 100644
--- a/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
@@ -318,6 +318,13 @@ export class DashboardViewModel {
});
};
+ this.$scope.createCR = ():void => {
+ this.$state.go('workspace.general', {
+ type: ComponentType.RESOURCE.toLowerCase(),
+ resourceType: ResourceType.CR
+ });
+ };
+
this.$scope.entitiesCount = (folderItem:FoldersItemsMenu):any => {
let self = this;
let total:number = 0;
diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
index 0ef5f4a1f9..bddcbcd46c 100644
--- a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
@@ -21,6 +21,7 @@
<div class="w-sdc-dashboard-card-new-content-plus" data-ng-show="!displayActions"></div>
<div class="sdc-dashboard-create-element-container" data-ng-show="displayActions">
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createResourceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('RESOURCE')">Add VF</button>
+ <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createCRButton" class="tlv-btn outline blue" data-ng-click="createCR()">Add CR</button>
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createPNFButton" class="tlv-btn outline blue" data-ng-click="createPNF()">Add PNF</button>
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createServiceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('SERVICE')">Add Service</button>
</div>
diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts
index d21011d4b3..19bc548e74 100644
--- a/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts
+++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {MenuItemGroup, MenuItem} from "app/utils";
import {BreadcrumbsPath, BreadcrumbsMenu} from "../onboard-vendor/onboard-vendor-view-model";
import {CacheService} from "app/services";
diff --git a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts
index 1306565016..a09e30c330 100644
--- a/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts
+++ b/catalog-ui/src/app/view-models/forms/artifact-form/artifact-form-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {ArtifactModel, Resource, Component} from "app/models";
import {ArtifactsUtils, FormState, ValidationUtils, ArtifactType} from "app/utils";
import {CacheService} from "app/services";
diff --git a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts
index 4c114b16e6..0e4a851aa6 100644
--- a/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts
+++ b/catalog-ui/src/app/view-models/forms/attribute-form/attribute-from-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {AttributeModel, Component} from "app/models";
import {IMapRegex, ValidationUtils, FormState, PROPERTY_TYPES} from "app/utils";
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts
index 726b61eda2..1f922cdaf9 100644
--- a/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts
+++ b/catalog-ui/src/app/view-models/forms/property-forms/base-property-form/property-form-base-model.ts
@@ -22,6 +22,7 @@
* Created by obarda on 1/19/2017.
*/
'use strict';
+import * as _ from "lodash";
import {DataTypesService} from "app/services/data-types-service";
import {PropertyModel, DataTypesMap, Component} from "app/models";
import {ValidationUtils, PROPERTY_DATA} from "app/utils";
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
index 0ad55715db..8ea2e8cf76 100644
--- a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
+++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {
PROPERTY_TYPES, ModalsHandler, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA} from "app/utils";
import {DataTypesService} from "app/services";
@@ -257,7 +258,7 @@ export class PropertyFormViewModel {
let myValueString:string = JSON.stringify(this.$scope.myValue);
property.value = myValueString;
}
- this.component.updateInstanceProperty(property).then(onPropertySuccess, onPropertyFaild);
+ this.component.updateInstanceProperties(property.resourceInstanceUniqueId, [property]).then((propertiesFromBE) => onPropertySuccess(propertiesFromBE[0]), onPropertyFaild);
} else {
if (!this.$scope.editPropertyModel.property.simpleType && !this.$scope.isSimpleType(property.type)) {
let myValueString:string = JSON.stringify(this.$scope.myValue);
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts b/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts
index 3a61371e85..510814b333 100644
--- a/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts
+++ b/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-model.ts
@@ -22,6 +22,7 @@
* Created by obarda on 1/18/2017.
*/
'use strict';
+import * as _ from "lodash";
import {PropertyModel, DisplayModule, Component, Resource, Service, ComponentInstance} from "app/models";
import {UNIQUE_GROUP_PROPERTIES_NAME} from "app/utils";
import {IPropertyFormBaseViewScope, PropertyFormBaseView} from "../base-property-form/property-form-base-model";
@@ -102,7 +103,9 @@ export class ModulePropertyView extends PropertyFormBaseView {
}
} else {
deferred.resolve(true);
- this.$uibModalInstance.close();
+ if (isNeedToCloseModal === true) {
+ this.$uibModalInstance.close();
+ }
}
return deferred.promise;
@@ -147,6 +150,13 @@ export class ModulePropertyView extends PropertyFormBaseView {
this.initValidation();
+ this.$scope.clearValidationError = ():void => {
+ this.$scope.forms.editForm.$valid = true;
+ this.$scope.forms.editForm.$invalid = false;
+ this.$scope.forms.editForm['value'].$error = {};
+ this.$scope.forms.editForm.$error = {};
+ }
+
// put default value when instance value is empty
this.$scope.onValueChange = ():void => {
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html b/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html
index 175f4c199b..ff48cc2357 100644
--- a/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html
+++ b/catalog-ui/src/app/view-models/forms/property-forms/module-property-modal/module-property-view.html
@@ -12,7 +12,8 @@
name="value"
data-ng-pattern="getValidationPattern(property.type)"
data-ng-model-options="{ debounce: 200 }"
- data-ng-change="onValueChange()"
+ data-ng-blur="onValueChange()"
+ data-ng-focus="clearValidationError()"
/>
<select class="i-sdc-form-select"
data-tests-id="booleantype"
diff --git a/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
index fa027296d6..67d135c575 100644
--- a/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
+++ b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {ComponentInstanceFactory} from "app/utils";
import {ComponentInstance} from "app/models";
import {Requirement, Component, Capability} from "app/models";
diff --git a/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts
index eeadcd4e83..155216557f 100644
--- a/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts
+++ b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts
@@ -22,6 +22,7 @@
* Created by rc2122 on 7/4/2017.
*/
'use strict';
+import * as _ from "lodash";
import {ComponentFactory} from "app/utils";
import {AvailableIconsService} from "app/services";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
index f77a29b003..10f41f6b61 100644
--- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "underscore";
import {IUserProperties} from "app/models";
import {MenuItemGroup, MenuItem} from "app/utils";
import {CacheService} from "app/services";
diff --git a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts
index 961d5b3677..c438c7ace6 100644
--- a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts
+++ b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view-model.ts
@@ -37,7 +37,7 @@ export interface IHierarchyScope extends ng.IScope {
onModuleNameChanged(module:DisplayModule):void;
updateHeatName():void;
loadInstanceModules(instance:ComponentInstance):ng.IPromise<boolean>;
- openEditPropertyModal(property:PropertyModel):void;
+ openEditPropertyModal(property:PropertyModel, filteredProperties:Array<PropertyModel>):void;
}
export class HierarchyViewModel {
@@ -110,8 +110,8 @@ export class HierarchyViewModel {
this.$scope.component.updateGroupMetadata(new DisplayModule(this.$scope.selectedModule)).then(onSuccess, onFailed);
};
- this.$scope.openEditPropertyModal = (property:PropertyModel):void => {
- this.ModalsHandler.openEditModulePropertyModal(property, this.$scope.component, this.$scope.selectedModule).then(() => {
+ this.$scope.openEditPropertyModal = (property:PropertyModel, filteredProperties:Array<PropertyModel>):void => {
+ this.ModalsHandler.openEditModulePropertyModal(property, this.$scope.component, this.$scope.selectedModule, filteredProperties).then(() => {
});
}
}
diff --git a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html
index 9eaa3a0f76..3b7b5fc36a 100644
--- a/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html
+++ b/catalog-ui/src/app/view-models/tabs/hierarchy/hierarchy-view.html
@@ -82,12 +82,12 @@
</div>
<expand-collapse-list-header title="Properties" expand-collapse-list-data="expandCollapsePropertiesList"></expand-collapse-list-header>
- <div ng-repeat="property in selectedModule.properties | filter: expandCollapsePropertiesList.filter | orderBy:expandCollapsePropertiesList.orderByField track by $index" data-ng-if="expandCollapsePropertiesList.expandCollapse">
+ <div ng-repeat="property in filteredProperties=(selectedModule.properties | filter: expandCollapsePropertiesList.filter | orderBy:expandCollapsePropertiesList.orderByField) track by $index" data-ng-if="expandCollapsePropertiesList.expandCollapse">
<div class="list-item property-data" data-ng-class="{'last':$last}">
<div class="property-name module-text-overflow" data-tests-id="selected-module-property-name">
<span tooltips tooltip-content="{{property.name}}"
data-ng-class="{'hand': !isViewOnly}"
- data-ng-click="!isViewOnly && openEditPropertyModal(property)">{{property.name}}</span>
+ data-ng-click="!isViewOnly && openEditPropertyModal(property, filteredProperties)">{{property.name}}</span>
</div>
<div class="module-text-overflow property-info" data-tests-id="selected-module-property-type"> Type: {{property.type}}</div>
<div class="module-text-overflow property-info" data-tests-id="selected-module-property-schema-type">Value: {{property.value}}</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
index 5d22d65f52..452224a829 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {Activity} from "app/models";
import {ActivityLogService} from "app/services";
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 5236259f30..46c2d2edf9 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts
@@ -18,14 +18,18 @@
* ============LICENSE_END=========================================================
*/
'use strict';
+import * as _ from "lodash";
import {Component, ComponentInstance, IAppMenu} from "app/models";
import {SharingService, CacheService, EventListenerService, LeftPaletteLoaderService} from "app/services";
import {ModalsHandler, GRAPH_EVENTS, ComponentFactory, ChangeLifecycleStateHandler, MenuHandler, EVENTS} from "app/utils";
import {IWorkspaceViewModelScope} from "../../workspace-view-model";
-import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
import {Resource} from "app/models/components/resource";
-import {ResourceType,ComponentType} from "../../../../utils/constants";
+import {ResourceType,ComponentType} from "app/utils/constants";
+import {ComponentServiceFactoryNg2} from "app/ng2/services/component-services/component.service.factory";
+import {ServiceGenericResponse} from "app/ng2/services/responses/service-generic-response";
+import {Service} from "app/models/components/service";
+
export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
@@ -39,6 +43,8 @@ export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
version:string;
isViewOnly:boolean;
isLoadingRightPanel:boolean;
+ disabledTabs:boolean;
+ openVersionChangeModal(pathsToDelete:string[]):ng.IPromise<any>;
onComponentInstanceVersionChange(component:Component);
isComponentInstanceSelected():boolean;
updateSelectedComponent():void
@@ -49,6 +55,7 @@ export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
printScreen():void;
isPNF():boolean;
isConfiguration():boolean;
+ preventMoveTab(state: boolean):void;
cacheComponentsInstancesFullData:Component;
}
@@ -70,7 +77,7 @@ export class CompositionViewModel {
'LeftPaletteLoaderService',
'ModalsHandler',
'EventListenerService',
- 'ComponentServiceNg2'
+ 'ComponentServiceFactoryNg2'
];
constructor(private $scope:ICompositionViewModelScope,
@@ -87,7 +94,7 @@ export class CompositionViewModel {
private LeftPaletteLoaderService:LeftPaletteLoaderService,
private ModalsHandler:ModalsHandler,
private eventListenerService:EventListenerService,
- private ComponentServiceNg2: ComponentServiceNg2) {
+ private ComponentServiceFactoryNg2: ComponentServiceFactoryNg2) {
this.$scope.setValidState(true);
this.initScope();
@@ -99,9 +106,14 @@ export class CompositionViewModel {
private initGraphData = ():void => {
if(!this.$scope.component.componentInstances || !this.$scope.component.componentInstancesRelations ) {
this.$scope.isLoading = true;
- this.ComponentServiceNg2.getComponentInstancesAndRelation(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ let service = this.ComponentServiceFactoryNg2.getComponentService(this.$scope.component);
+ service.getComponentCompositionData(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ if (this.$scope.component.isService()) {
+ (<Service> this.$scope.component).forwardingPaths = (<ServiceGenericResponse>response).forwardingPaths;
+ }
this.$scope.component.componentInstances = response.componentInstances;
this.$scope.component.componentInstancesRelations = response.componentInstancesRelations;
+ this.$scope.component.policies = response.policies;
this.$scope.isLoading = false;
this.initComponent();
this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_COMPOSITION_GRAPH_DATA_LOADED);
@@ -116,17 +128,15 @@ export class CompositionViewModel {
private cacheComponentsInstancesFullData:Array<Component>;
private initComponent = ():void => {
-
this.$scope.currentComponent = this.$scope.component;
this.$scope.selectedComponent = this.$scope.currentComponent;
this.updateUuidMap();
this.$scope.isViewOnly = this.$scope.isViewMode();
};
- private registerGraphEvents = (scope:ICompositionViewModelScope):void => {
+ private registerGraphEvents = (scope:ICompositionViewModelScope):void => {
this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_NODE_SELECTED, scope.setSelectedInstance);
this.eventListenerService.registerObserverCallback(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, scope.onBackgroundClick);
-
};
private openUpdateComponentInstanceNameModal = ():void => {
@@ -136,7 +146,7 @@ export class CompositionViewModel {
};
private removeSelectedComponentInstance = ():void => {
- this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DELETE_MULTIPLE_COMPONENTS);
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_DELETE_COMPONENT_INSTANCE, this.$scope.currentComponent.selectedInstance)
this.$scope.currentComponent.selectedInstance = null;
this.$scope.selectedComponent = this.$scope.currentComponent;
};
@@ -151,7 +161,6 @@ export class CompositionViewModel {
};
private initScope = ():void => {
-
this.$scope.sharingService = this.sharingService;
this.$scope.sdcMenu = this.sdcMenu;
this.$scope.isLoading = false;
@@ -231,20 +240,60 @@ export class CompositionViewModel {
};
this.$scope.deleteSelectedComponentInstance = ():void => {
- let state = "deleteInstance";
- let onOk = ():void => {
- this.removeSelectedComponentInstance();
- //this.$scope.graphApi.deleteSelectedNodes();
- };
- let title:string = this.$scope.sdcMenu.alertMessages[state].title;
- let message:string = this.$scope.sdcMenu.alertMessages[state].message.format([this.$scope.currentComponent.selectedInstance.name]);
- this.ModalsHandler.openAlertModal(title, message).then(onOk);
+ const {currentComponent} = this.$scope;
+ const {title, message} = this.$scope.sdcMenu.alertMessages['deleteInstance'];
+ let modalText = message.format([currentComponent.selectedInstance.name]);
+
+ if (currentComponent.isService()) {
+ const {forwardingPaths} = (<Service>currentComponent);
+ const instanceId = currentComponent.selectedInstance.uniqueId;
+
+ const relatedPaths = _.filter(forwardingPaths, forwardingPath => {
+ const pathElements = forwardingPath.pathElements.listToscaDataDefinition;
+ return pathElements.find(path => path.fromNode === instanceId || path.toNode === instanceId);
+ });
+
+ if (relatedPaths.length) {
+ const pathNames = _.map(relatedPaths, path => path.name).join(', ');
+ modalText += `<p>The following service paths will be erased: ${pathNames}</p>`;
+ }
+ }
+
+ this.ModalsHandler.openAlertModal(title, modalText).then(this.removeSelectedComponentInstance);
+ };
+
+ this.$scope.openVersionChangeModal = (pathsToDelete:string[]):ng.IPromise<any> => {
+ const {currentComponent} = this.$scope;
+ const {forwardingPaths} = <Service>currentComponent;
+
+ const relatedPaths = _.filter(forwardingPaths, path =>
+ _.find(pathsToDelete, id =>
+ path.uniqueId === id
+ )
+ ).map(path => path.name);
+ const pathNames = _.join(relatedPaths, ', ') || 'none';
+
+ const {title, message} = this.$scope.sdcMenu.alertMessages['upgradeInstance'];
+ return this.ModalsHandler.openConfirmationModal(title, message.format([pathNames]), false);
};
this.$scope.onComponentInstanceVersionChange = (component:Component):void => {
- this.$scope.currentComponent = component;
- this.$scope.setComponent(this.$scope.currentComponent);
- this.$scope.updateSelectedComponent();
+ let onChange = () => {
+ this.$scope.currentComponent = component;
+ this.$scope.setComponent(this.$scope.currentComponent);
+ this.$scope.updateSelectedComponent();
+ this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_VERSION_CHANGED, this.$scope.currentComponent);
+ };
+
+ if (component.isService()) {
+ const service = this.ComponentServiceFactoryNg2.getComponentService(component);
+ service.getComponentCompositionData(component).subscribe((response:ServiceGenericResponse) => {
+ (<Service>component).forwardingPaths = response.forwardingPaths;
+ onChange();
+ });
+ } else {
+ onChange();
+ }
};
this.$scope.isPNF = (): boolean => {
@@ -255,6 +304,10 @@ export class CompositionViewModel {
return this.$scope.selectedComponent.isResource() && (<Resource>this.$scope.selectedComponent).resourceType === ResourceType.CONFIGURATION;
};
+ this.$scope.preventMoveTab = (state: boolean): void => {
+ this.$scope.disabledTabs = state;
+ };
+
this.eventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.$scope.reload);
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
index bfb2865348..fceb73b882 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
@@ -5,6 +5,8 @@
is-view-only="isViewOnly"
is-loading="isLoading"></palette>
+ <ng2-palette-popup-panel></ng2-palette-popup-panel>
+
<composition-graph component="currentComponent" data-tests-id="canvas"
is-view-only="isViewOnly" with-sidebar="displayDesignerRightSidebar"></composition-graph>
</div>
@@ -46,7 +48,8 @@
<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"
data-ui-sref="workspace.composition.details"
tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Information"
- data-tests-id="information-tab">
+ data-tests-id="information-tab"
+ data-ng-class="{'disabled': disabledTabs}">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new info"></div>
</button>
<!--<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"-->
@@ -58,32 +61,38 @@
data-ui-sref="workspace.composition.deployment"
tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Deployment Artifacts"
data-tests-id="deployment-artifact-tab"
- data-ng-if="!isPNF() && !isConfiguration() && !(isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy())">
+ data-ng-if="!isPNF() && !isConfiguration() && !(isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy())"
+ data-ng-class="{'disabled': disabledTabs}">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new deployment-artifacts"></div>
</button>
<button tooltips tooltip-class="tooltip-custom tab-tooltip"
tooltip-content="{{selectedComponent.isResource() || (isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy()) ? 'Properties and Attributes': 'Inputs'}}"
class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"
data-ui-sref="workspace.composition.properties"
- data-tests-id="properties-and-attributes-tab">
+ data-tests-id="properties-and-attributes-tab"
+ data-ng-class="{'disabled': disabledTabs}">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new"
ng-class="selectedComponent.isResource() || (isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy()) ? 'properties': 'inputs'"></div>
</button>
<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"
data-ui-sref="workspace.composition.artifacts"
data-ng-if="!isConfiguration() && !(isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy())"
- tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Information Artifacts">
+ tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Information Artifacts"
+ data-ng-class="{'disabled': disabledTabs}">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new information-artifacts"></div>
</button>
<button data-ng-if="!selectedComponent.isService() || (isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy())" class="i-sdc-designer-sidebar-tab"
data-ui-sref-active="active" ui-sref="workspace.composition.relations"
tooltips tooltip-class="tooltip-custom tab-tooltip tooltip-rightside"
- tooltip-content="Requirements and Capabilities">
+ data-tests-id="requirements-and-capabilities"
+ tooltip-content="Requirements and Capabilities"
+ data-ng-class="{'disabled': disabledTabs}">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new relations"></div>
</button>
<button data-ng-if="selectedComponent.isService() && !(isComponentInstanceSelected() && currentComponent.selectedInstance.isServiceProxy())" class="i-sdc-designer-sidebar-tab"
data-ui-sref-active="active" ui-sref="workspace.composition.api" data-tests-id="tab-api"
- tooltips tooltip-class="tooltip-custom tab-tooltip tooltip-rightside" tooltip-content="API">
+ tooltips tooltip-class="tooltip-custom tab-tooltip tooltip-rightside" tooltip-content="API"
+ data-ng-class="{'disabled': disabledTabs}">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new api"></div>
</button>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less
index 624ed03431..f351450e6d 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition.less
@@ -1,3 +1,33 @@
+ .i-sdc-designer-leftbar-section-popup-panel {
+ position: absolute;
+ display: inline-block;
+ background-color: white;
+ border: solid 1px #d2d2d2;
+ border-top: solid 3px #13a7df;
+ width: 140px;
+ height: 40px;
+ z-index: 10000;
+ }
+
+ .i-sdc-designer-leftbar-section-popup-panel-group {
+ padding-left: 8px;
+ padding-top: 8px;
+ }
+
+ .i-sdc-designer-leftbar-section-popup-panel-plus {
+ border-radius: 50%;
+ color: white;
+ background-color: #13a7df;
+ width: 20px;
+ text-align: center;
+ display: inline-block;
+ cursor: pointer;
+ }
+
+ .i-sdc-designer-leftbar-section-popup-panel-title {
+ padding-left: 10px;
+ display: inline-block;
+ }
.composition{
.sdc-workspace-container{
@@ -791,7 +821,16 @@
.g_1;
line-height: 18px;
}
-
+
+ .service-path-buttons {
+ margin-top: 12px;
+ position: absolute;
+ right: 70px;
+ top: 53px;
+ &.with-sidebar {
+ right: 380px;
+ }
+ }
//Canvas search menu
.w-sdc-search-menu {
position:absolute;
@@ -815,8 +854,8 @@
padding:2px 50px 2px 10px;
transition:all 0.4s;
}
- .clear-search-x {
- top: 17px
+ .search-bar-container {
+ position:relative;
}
&:not(:hover):not(.autocomplete-visible):not(.active){
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 b80b63cac9..627d20528e 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
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {
ArtifactModel,
Service,
@@ -131,6 +132,7 @@ export class ResourceArtifactsViewModel {
this.$scope.allowDeleteAndUpdateArtifactMap[artifact.artifactLabel] = this.allowDeleteAndUpdateArtifact(artifact);
});
this.$scope.isLoading = false;
+ this.$scope.preventMoveTab(false);
};
@@ -213,6 +215,7 @@ export class ResourceArtifactsViewModel {
};
this.$scope.isLoading = true;
+ this.$scope.preventMoveTab(true);
if (this.$scope.isComponentInstanceSelected()) {
this.$scope.component.getComponentInstanceArtifactsByGroupType(this.$scope.component.selectedInstance.uniqueId, this.convertToArtifactUrl(this.$scope.artifactType)).then(onGetInstanceArtifactsSuccess, onError);
} else {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
index 0d8d17ec73..6e3258f69b 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
@@ -19,11 +19,15 @@
*/
'use strict';
+import * as _ from "lodash";
import {Component} from "app/models";
import {GRAPH_EVENTS} from "app/utils";
import {LeftPaletteLoaderService, EventListenerService} from "app/services";
import {ICompositionViewModelScope} from "../../composition-view-model";
import {LeftPaletteComponent} from "../../../../../../models/components/displayComponent";
+import {ComponentServiceFactoryNg2} from "app/ng2/services/component-services/component.service.factory";
+import {ServiceServiceNg2} from 'app/ng2/services/component-services/service.service';
+import {Service} from "app/models/components/service";
export interface IEditResourceVersion {
allVersions:any;
@@ -45,13 +49,16 @@ export class DetailsViewModel {
static '$inject' = [
'$scope',
'LeftPaletteLoaderService',
- 'EventListenerService'
-
+ 'EventListenerService',
+ 'ComponentServiceFactoryNg2',
+ 'ServiceServiceNg2'
];
constructor(private $scope:IDetailsViewModelScope,
private LeftPaletteLoaderService:LeftPaletteLoaderService,
- private eventListenerService:EventListenerService) {
+ private eventListenerService:EventListenerService,
+ private ComponentServiceFactoryNg2: ComponentServiceFactoryNg2,
+ private serviceService: ServiceServiceNg2) {
this.initScope();
}
@@ -112,22 +119,43 @@ export class DetailsViewModel {
this.$scope.isLoading = true;
this.$scope.$parent.isLoading = true;
- let onSuccess = (component:Component)=> {
+ let service = <Service>this.$scope.currentComponent;
+ let {changeVersion} = this.$scope.editResourceVersion;
+ let componentUid:string = this.$scope.editResourceVersion.allVersions[changeVersion];
+
+ let onCancel = (error:any) => {
this.$scope.isLoading = false;
this.$scope.$parent.isLoading = false;
- this.$scope.onComponentInstanceVersionChange(component);
+ this.$scope.editResourceVersion.changeVersion = this.$scope.currentComponent.selectedInstance.componentVersion;
- this.eventListenerService.notifyObservers(GRAPH_EVENTS.ON_VERSION_CHANGED, this.$scope.currentComponent);
+ if (error) {
+ console.log(error);
+ }
};
- let onFailed = (error:any)=> {
- this.$scope.isLoading = false;
- this.$scope.$parent.isLoading = false;
- console.log(error);
+ let onUpdate = () => {
+ let onSuccess = (component:Component) => {
+ this.$scope.isLoading = false;
+ this.$scope.$parent.isLoading = false;
+ this.$scope.onComponentInstanceVersionChange(component);
+ };
+
+ this.$scope.currentComponent.changeComponentInstanceVersion(componentUid).then(onSuccess, onCancel);
};
- let componentUid:string = this.$scope.editResourceVersion.allVersions[this.$scope.editResourceVersion.changeVersion];
- this.$scope.currentComponent.changeComponentInstanceVersion(componentUid).then(onSuccess, onFailed);
+ this.serviceService.checkComponentInstanceVersionChange(service, componentUid).subscribe((pathsToDelete:string[]) => {
+ if (pathsToDelete && pathsToDelete.length) {
+ this.$scope.isLoading = false;
+ this.$scope.$parent.isLoading = false;
+ this.$scope.$parent.openVersionChangeModal(pathsToDelete).then(() => {
+ this.$scope.isLoading = true;
+ this.$scope.$parent.isLoading = true;
+ onUpdate();
+ }, onCancel);
+ } else {
+ onUpdate();
+ }
+ }, onCancel);
};
}
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html
index 5020c73df4..033c4668f3 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html
@@ -26,7 +26,7 @@
data-ng-if="!isComponentInstanceSelected()" data-tests-id="rightTab_version" data-ng-bind="selectedComponent.version"></span>
<ng-form name="editForm" data-ng-if="isComponentInstanceSelected()">
- <select data-ng-model="editResourceVersion.changeVersion" name="changeVersion" data-tests-id="changeVersion" data-ng-disabled="$parent.isViewOnly"
+ <select data-ng-model="editResourceVersion.changeVersion" name="changeVersion" data-tests-id="changeVersion" data-ng-disabled="$parent.isViewOnly || selectedComponent.uniqueId != editResourceVersion.allVersions[editResourceVersion.changeVersion]"
class="i-sdc-designer-sidebar-section-content-item-value i-sdc-form-select"
data-ng-class="{'minor': (editResourceVersion.changeVersion)%1}"
data-ng-change="changeResourceVersion()">
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 99bbd8d7ac..efd5cfd84d 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
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {
AttributeModel,
AttributesGroup,
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts
index 4c53edf6bd..ce44aaff50 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/relations/relations-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {ICompositionViewModelScope} from "../../composition-view-model";
import {CapabilitiesGroup, Requirement, RequirementsGroup} from "app/models";
import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
index 86bc478048..c652da4eab 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
@@ -20,6 +20,7 @@
//@require "./*.html"
'use strict';
+import * as _ from "lodash";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {ArtifactModel, ArtifactGroupModel, Resource} from "app/models";
import {ArtifactsUtils, ModalsHandler, ValidationUtils} from "app/utils";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts
index 5ffae64689..eab06f28e8 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {Distribution, DistributionComponent, ExportExcel} from "app/models";
interface IDistributionStatusModalViewModelScope {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
index 663361cd85..47ec1fd9e3 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {Distribution, DistributionComponent, Service} from "app/models";
import {ModalsHandler, Dictionary} from "app/utils";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html
index 710336af15..f32e7c7fdf 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view.html
@@ -5,6 +5,7 @@
<div class="header-spacer"></div>
<div class="top-search">
<input type="text"
+ style="width: auto;"
class="search-text"
data-tests-id="searchTextbox"
placeholder="Search"
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
index 6060130191..b03d7c4d7c 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
ResourceType, ComponentState} from "app/utils";
import {CacheService, EventListenerService, ProgressService, OnboardingService} from "app/services";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
index e3eb903a36..36976c610e 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
@@ -28,7 +28,6 @@
name="componentName"
data-ng-init="isCreateMode() && validateName(true)"
data-ng-maxlength="50"
- maxlength="50"
data-ng-model="component.name"
type="text"
data-required
@@ -117,7 +116,6 @@
data-ng-model="component.description"
data-ng-model-options="{ debounce: 500 }"
data-ng-pattern="validation.commentValidationPattern"
- maxlength="1024"
data-tests-id="description"></textarea>
<!-- placeholder="Description here..." -->
@@ -178,10 +176,11 @@
data-ng-pattern="validation.contactIdValidationPattern"
data-ng-model-options="{ debounce: 500 }"
data-tests-id="contactId"
- maxlength="50"
+ data-ng-maxlength="50"
/>
<div class="input-error" data-ng-show="validateField(editForm.contactId)">
+ <span ng-show="editForm.contactId.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
<span ng-show="editForm.contactId.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED"></span>
<span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
</div>
@@ -196,7 +195,7 @@
data-ng-model="component.projectCode"
data-ng-class="{'view-mode': isViewMode()}"
data-ng-model-options="{ debounce: 500 }"
- maxlength="50"
+ data-ng-maxlength="50"
data-required
name="projectCode"
data-ng-pattern="validation.projectCodeValidationPattern"
@@ -204,6 +203,7 @@
/>
<div class="input-error" data-ng-show="validateField(editForm.projectCode)">
+ <span ng-show="editForm.contactId.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
<span ng-show="editForm.projectCode.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED"></span>
<span ng-show="editForm.projectCode.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID"></span>
</div>
@@ -222,7 +222,6 @@
name="vendorName"
data-ng-change="onVendorNameChange(oldValue)"
data-ng-pattern="validation.VendorNameValidationPattern"
- maxlength="60"
data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.vendorName && component.vendorName!=='')"
data-tests-id="vendorName"
/>
@@ -250,7 +249,6 @@
data-required
name="vendorRelease"
data-ng-pattern="validation.VendorReleaseValidationPattern"
- maxlength="25"
data-ng-disabled="component.isCsarComponent() && component.vendorRelease && component.vendorRelease!==''"
data-tests-id="vendorRelease"
/>
@@ -275,7 +273,6 @@
data-ng-maxlength="65"
name="resourceVendorModelNumber"
data-ng-pattern="validation.VendorModelNumberValidationPattern"
- maxlength="65"
data-tests-id="resourceVendorModelNumber"
/>
@@ -312,10 +309,9 @@
<div ng-if="component.isService()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.namingPolicy)}">
<label class="i-sdc-form-label">Naming policy</label>
<input class="i-sdc-form-input"
- name="fullName"
+ name="namingPolicy"
data-ng-class="{'view-mode': isViewMode() || !component.ecompGeneratedNaming}"
data-ng-maxlength="100"
- maxlength="100"
data-ng-model="component.namingPolicy"
type="text"
data-ng-model-options="{ debounce: 500 }"
@@ -345,10 +341,9 @@
data-tests-id="serviceType"
data-ng-maxlength="256"
data-ng-pattern="validation.ServiceTypeAndRoleValidationPattern"
- maxlength="256"
/>
<div class="input-error" data-ng-show="validateField(editForm.serviceType)">
- <span ng-show="editForm.serviceType.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.serviceType.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
<span ng-show="editForm.serviceType.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
</div>
@@ -367,10 +362,9 @@
data-tests-id="serviceRole"
data-ng-maxlength="256"
data-ng-pattern="validation.ServiceTypeAndRoleValidationPattern"
- maxlength="256"
/>
<div class="input-error" data-ng-show="validateField(editForm.serviceRole)">
- <span ng-show="editForm.serviceRole.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.serviceRole.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '256' }"></span>
<span ng-show="editForm.serviceRole.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
index b2fd4d68c0..47a96fb385 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {ModalsHandler} from "app/utils";
import {SharingService} from "app/services";
import {IAppConfigurtaion, ArtifactModel, IFileDownload} from "app/models";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
index 2e871a5f8d..2a7cd3dd65 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {ComponentInstance, InstancesInputsOrPropertiesMapData, Resource, PropertyModel, InputModel} from "app/models";
import {ModalsHandler} from "app/utils";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
index 00f3347b74..bdbc0a4334 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {ComponentInstance, InstancesInputsOrPropertiesMapData, Service, IAppMenu, InputModel, PropertyModel, InputPropertyBase} from "app/models";
import {DataTypesService} from "app/services";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
index 488e4c774d..af11e1cf9a 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
@@ -19,6 +19,7 @@
*/
'use strict';
+import * as _ from "lodash";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {VendorModel} from "app/view-models/workspace/tabs/management-workflow/management-workflow-view-model";
import {ResourceType, ArtifactType} from "app/utils";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
index b6cbf65cf0..f63ab1ccbc 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
@@ -22,6 +22,7 @@
* Created by rcohen on 9/22/2016.
*/
'use strict';
+import * as _ from "lodash";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {ModalsHandler} from "app/utils";
import {Capability, PropertyModel, Requirement} from "app/models";
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
index 77b5ab74eb..a1f8152cea 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
@@ -19,10 +19,12 @@
*/
'use strict';
+import * as _ from "lodash";
import {ArtifactModel, IFileDownload} from "app/models";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+
export interface IToscaArtifactsScope extends IWorkspaceViewModelScope {
artifacts:Array<ArtifactModel>;
tableHeadersList:Array<any>;
diff --git a/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
index ca34d6fdc4..01b3aa3b22 100644
--- a/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,6 +22,7 @@
* Created by obarda on 3/30/2016.
*/
'use strict';
+import * as _ from "lodash";
import {IUserProperties, IAppMenu, Resource, Component, Plugin, PluginsConfiguration, PluginDisplayOptions} from "app/models";
import {
WorkspaceMode, ComponentFactory, ChangeLifecycleStateHandler, Role, ComponentState, MenuItemGroup, MenuHandler,
@@ -50,6 +51,7 @@ export interface IWorkspaceViewModelScope extends ng.IScope {
isNew:boolean;
isFromImport:boolean;
isValidForm:boolean;
+ isActiveTopBar:boolean;
mode:WorkspaceMode;
breadcrumbsModel:Array<MenuItemGroup>;
sdcMenu:IAppMenu;
@@ -197,6 +199,7 @@ export class WorkspaceViewModel {
this.$scope.isComposition = (this.$state.current.name.indexOf(States.WORKSPACE_COMPOSITION) > -1);
this.$scope.isDeployment = this.$state.current.name == States.WORKSPACE_DEPLOYMENT;
this.$scope.progressService = this.progressService;
+ this.$scope.isActiveTopBar = true;
this.$scope.getComponent = ():Component => {
return this.$scope.component;
@@ -267,7 +270,7 @@ export class WorkspaceViewModel {
this.$scope.onVersionChanged = (selectedId:string):void => {
if (this.$state.current.data && this.$state.current.data.unsavedChanges) {
this.$scope.changeVersion.selectedVersion = _.find(this.$scope.versionsList, (versionObj)=> {
- return versionObj.versionId === this.$scope.component.uniqueId;
+ return versionObj.versionId === this.$scope.component.uniqueId;
});
}
this.$scope.isLoading = true;
@@ -323,13 +326,15 @@ export class WorkspaceViewModel {
this.showSuccessNotificationMessage();
this.progressService.deleteProgressValue(this.$scope.component.uniqueId);
- //update components for breadcrumbs
+
+ // Update the components list for breadcrumbs
this.components.unshift(component);
+
this.$state.go(States.WORKSPACE_GENERAL, {
id: component.uniqueId,
type: component.componentType.toLowerCase(),
components: this.components
- });
+ }, { inherit: false });
deferred.resolve(true);
};
@@ -347,17 +352,20 @@ export class WorkspaceViewModel {
return item === component.name
});
- // Update the components
+ // Update the components list for breadcrumbs
+ const bcIdx = this.MenuHandler.findBreadcrumbComponentIndex(this.components, component);
+ if (bcIdx !== -1) {
+ this.components[bcIdx] = component;
+ this.initBreadcrumbs(); // re-calculate breadcrumbs
+ }
+
+ // Update the component
this.$scope.component = component;
this.$scope.originComponent = this.ComponentFactory.createComponent(this.$scope.component);
- //update components for breadcrumbs
- this.components.unshift(component);
-
// Enable left tags
this.$scope.enabledTabs();
-
if (this.$state.current.data) {
this.$state.current.data.unsavedChanges = false;
}
@@ -469,11 +477,11 @@ export class WorkspaceViewModel {
}
//when checking out a minor version uuid remains
- let bcComponent:Component = _.find(this.components, (item) => {
+ const bcIdx = _.findIndex(this.components, (item) => {
return item.uuid === component.uuid;
});
- if (bcComponent) {
- this.components[this.components.indexOf(bcComponent)] = component;
+ if (bcIdx !== -1) {
+ this.components[bcIdx] = component;
} else {
//when checking out a major(certified) version
this.components.unshift(component);
@@ -681,7 +689,7 @@ export class WorkspaceViewModel {
});
this.$scope.getTabTitle = ():string => {
- return this.$scope.leftBarTabs.menuItems.find((menuItem:MenuItem)=>{
+ return this.$scope.leftBarTabs.menuItems.find((menuItem:MenuItem) => {
return menuItem.state == this.$scope.$state.current.name;
}).text;
};
@@ -690,6 +698,10 @@ export class WorkspaceViewModel {
this.$state.go(this.$state.current.name,{id:component.uniqueId},{reload:true});
};
+ this.$scope.$on('setWorkspaceTopBarActive', (event:ng.IAngularEvent, isActive:boolean) => {
+ this.$scope.isActiveTopBar = isActive;
+ });
+
};
private initAfterScope = ():void => {
@@ -718,9 +730,9 @@ export class WorkspaceViewModel {
return new MenuItem(text, null, States.WORKSPACE_GENERAL, 'goToState', [this.$state.params]);
};
- private updateMenuItemByRole = (menuItems:Array<any>, role:string) : Array<any> => {
- let tempMenuItems:Array<any> = new Array<any>();
- menuItems.forEach((item:any) => {
+ private updateMenuItemByRole = (menuItems:Array<MenuItem>, role:string) => {
+ let tempMenuItems:Array<MenuItem> = new Array<MenuItem>();
+ menuItems.forEach((item:MenuItem) => {
//remove item if role is disabled
if (!(item.disabledRoles && item.disabledRoles.indexOf(role) > -1)) {
tempMenuItems.push(item);
@@ -810,6 +822,4 @@ export class WorkspaceViewModel {
});
};
-}
-
-
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/view-models/workspace/workspace-view.html b/catalog-ui/src/app/view-models/workspace/workspace-view.html
index d724b8d058..0f686b1d64 100644
--- a/catalog-ui/src/app/view-models/workspace/workspace-view.html
+++ b/catalog-ui/src/app/view-models/workspace/workspace-view.html
@@ -1,13 +1,12 @@
<div class="sdc-workspace-container">
<loader data-display="isLoading"></loader>
<div class="w-sdc-main-container">
-
<div class="w-sdc-left-sidebar" data-ng-if="!isComposition">
<div class="menu-header" tooltips tooltip-content="{{menuComponentTitle}}">
{{menuComponentTitle}}
</div>
- <div class="i-sdc-designer-sidebar-section-content-item" ng-class="{'selected': isSelected(menuItem)}" ng-repeat="menuItem in leftBarTabs.menuItems track by $index">
- <div class="expand-collapse-menu-box-item-text" ng-click="menuItem.callback()" ng-class="{'disabled': menuItem.isDisabled }" data-tests-id="{{menuItem.text}}LeftSideMenu">{{menuItem.text}}</div>
+ <div class="i-sdc-designer-sidebar-section-content-item" ng-class="{'selected': menuItem.state == $state.current.name}" ng-repeat="menuItem in leftBarTabs.menuItems track by $index">
+ <div class="expand-collapse-menu-box-item-text" ng-click="onMenuItemPressed(menuItem.state)" ng-class="{'disabled': menuItem.isDisabled }" data-tests-id="{{menuItem.text}}LeftSideMenu">{{menuItem.text}}</div>
</div>
</div>
@@ -18,7 +17,7 @@
<div class="version-container">
<span data-ng-if="!isCreateMode() && !component.isLatestVersion()" class="not-latest"></span>
- <select class="version-selector" data-ng-if="!isCreateMode()" data-tests-id="versionHeader" data-ng-model="changeVersion.selectedVersion"
+ <select class="version-selector" data-ng-if="!isCreateMode()" data-tests-id="versionHeader" data-ng-model="changeVersion.selectedVersion" data-ng-class="{'disabled': !isActiveTopBar}"
ng-options="'V'+version.versionNumber for version in versionsList" data-ng-change="onVersionChanged(changeVersion.selectedVersion.versionId)">
</select>
</div>
@@ -35,10 +34,10 @@
<div class="sdc-workspace-top-bar-buttons">
- <span ng-if="!isCreateMode() && !component.isLatestVersion() && !showChangeStateButton()">Switch to the&nbsp;<a ng-click="getLatestVersion()">latest version</a></span>
+ <span ng-if="!isCreateMode() && !component.isLatestVersion() && !showChangeStateButton()" [disabled]="!isActiveTopBar">Switch to the&nbsp;<a ng-click="getLatestVersion()">latest version</a></span>
<button ng-if="isDesigner() && !isCreateMode()"
- data-ng-class="{'disabled' :!isValidForm || isDisableMode() || isViewMode()}"
+ data-ng-class="{'disabled' :!isValidForm || isDisableMode() || isViewMode() || !isActiveTopBar}"
ng-click="save()"
class="tlv-btn blue"
data-tests-id="create/save"
@@ -48,22 +47,22 @@
<button ng-repeat="(key,button) in changeLifecycleStateButtons"
ng-click="changeLifecycleState(key)"
ng-if="showChangeStateButton() && key != 'deleteVersion'"
- data-ng-disabled="isCreateMode() || button.disabled || disabledButtons || !isValidForm"
+ data-ng-disabled="isCreateMode() || button.disabled || disabledButtons || !isValidForm || !isActiveTopBar"
class="change-lifecycle-state-btn tlv-btn"
ng-class="$first ? 'outline green' : 'grey'"
data-tests-id="{{button.text | testsId}}">
{{button.text}}
</button>
- <button ng-if="!isViewMode() && isCreateMode()" data-ng-disabled="!isValidForm || isDisableMode() || isLoading" ng-click="save()" class="tlv-btn outline green" data-tests-id="create/save">Create</button>
+ <button ng-if="!isViewMode() && isCreateMode()" data-ng-disabled="!isValidForm || isDisableMode() || isLoading || !isActiveTopBar" ng-click="save()" class="tlv-btn outline green" data-tests-id="create/save">Create</button>
<span data-ng-if="isDesigner() && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
- data-ng-class="{'disabled' : !isValidForm || isDisableMode() || isViewMode()}" ng-click="changeLifecycleState('deleteVersion')"
+ data-ng-class="{'disabled' : !isValidForm || isDisableMode() || isViewMode() || !isActiveTopBar}" ng-click="changeLifecycleState('deleteVersion')"
class="sprite-new delete-btn" data-tests-id="delete_version" sdc-smart-tooltip="">Delete</span>
- <span data-ng-if="isDesigner()" data-ng-class="{'disabled' :isDisableMode() || isViewMode()}" ng-click="revert()" class="sprite-new revert-btn" data-tests-id="revert"
+ <span data-ng-if="isDesigner()" data-ng-class="{'disabled' :isDisableMode() || isViewMode() || !isActiveTopBar}" ng-click="revert()" class="sprite-new revert-btn" data-tests-id="revert"
data-ng-show="showFullIcons()" sdc-smart-tooltip="">Revert</span>
-
+
<span class="delimiter"></span>
<span class="sprite-new x-btn" data-ng-click="goToBreadcrumbHome()" sdc-smart-tooltip="">Close</span>
diff --git a/catalog-ui/src/assets/languages/en_US.json b/catalog-ui/src/assets/languages/en_US.json
index f824f90a41..70018afab6 100644
--- a/catalog-ui/src/assets/languages/en_US.json
+++ b/catalog-ui/src/assets/languages/en_US.json
@@ -441,6 +441,10 @@
"MAX_VALIDATION_ERROR": "Value cannot be higher than the 'max_vf_module_instances' and 'initial_count'",
"MIN_MAX_VALIDATION": "Value must be between 'min_vf_module_instances' and 'max vf module instances'",
"MIN_VALIDATION_VF_LEVE_ERROR": " Value of 'min_vf_module_instances' must not be lower than defined in VF level",
- "MAX_VALIDATION_VF_LEVE_ERROR": " Value of 'max_vf_module_instances' must not be higher than defined in VF level"
+ "MAX_VALIDATION_VF_LEVE_ERROR": " Value of 'max_vf_module_instances' must not be higher than defined in VF level",
+
+ "=========== SERVICE PATH SELECTOR ===========": "",
+ "SERVICE_PATH_SELECTOR_HIDE_ALL_VALUE" : "⚊ Hide all ⚊",
+ "SERVICE_PATH_SELECTOR_SHOW_ALL_VALUE" : "⚊ Show all ⚊"
}
diff --git a/catalog-ui/src/assets/styles/app.less b/catalog-ui/src/assets/styles/app.less
index 8042c0e7b7..f48fd864ef 100644
--- a/catalog-ui/src/assets/styles/app.less
+++ b/catalog-ui/src/assets/styles/app.less
@@ -14,6 +14,8 @@
@import 'sprite.less';
@import 'sprite-resource-icons.less';
@import 'sprite-services-icons.less';
+@import 'sprite-group-icons.less';
+@import 'sprite-policy-icons.less';
@import 'animation.less';
@import 'buttons.less';
@@ -35,6 +37,7 @@
@import 'welcome-sprite.less';
@import 'welcome-style.less';
@import 'notification-template.less';
+@import 'tables.less';
// Less insides specific files.
@import '../../app/directives/ecomp-header/ecomp-header.less';
diff --git a/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding.svg b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding.svg
new file mode 100644
index 0000000000..1a9a507948
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding.svg
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="44px" height="44px" viewBox="0 0 44 44" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 12</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <filter x="-79.5%" y="-65.9%" width="259.1%" height="259.1%" filterUnits="objectBoundingBox" id="filter-1">
+ <feOffset dx="0" dy="3" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>
+ <feGaussianBlur stdDeviation="5" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" type="matrix" in="shadowBlurOuter1" result="shadowMatrixOuter1"></feColorMatrix>
+ <feMerge>
+ <feMergeNode in="shadowMatrixOuter1"></feMergeNode>
+ <feMergeNode in="SourceGraphic"></feMergeNode>
+ </feMerge>
+ </filter>
+ <linearGradient x1="0%" y1="0%" x2="104.899315%" y2="128.265625%" id="linearGradient-2">
+ <stop stop-color="#009E98" offset="0%"></stop>
+ <stop stop-color="#97D648" offset="100%"></stop>
+ </linearGradient>
+ <path d="M3,0 L19,0 C20.6568542,-3.04359188e-16 22,1.34314575 22,3 L22,19 C22,20.6568542 20.6568542,22 19,22 L3,22 C1.34314575,22 2.02906125e-16,20.6568542 0,19 L0,3 C-2.02906125e-16,1.34314575 1.34314575,3.04359188e-16 3,0 Z" id="path-3"></path>
+ <filter x="-11.4%" y="-11.4%" width="122.7%" height="122.7%" filterUnits="objectBoundingBox" id="filter-4">
+ <feGaussianBlur stdDeviation="1.5" in="SourceAlpha" result="shadowBlurInner1"></feGaussianBlur>
+ <feOffset dx="0" dy="0" in="shadowBlurInner1" result="shadowOffsetInner1"></feOffset>
+ <feComposite in="shadowOffsetInner1" in2="SourceAlpha" operator="arithmetic" k2="-1" k3="1" result="shadowInnerInner1"></feComposite>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0.478431373 0 0 0 0 0.243137255 0 0 0 1 0" type="matrix" in="shadowInnerInner1"></feColorMatrix>
+ </filter>
+ <path d="M6,4 L6,1 C6,0.4 5.6,0 5,0 C4.4,0 4,0.4 4,1 L4,4 L1,4 C0.4,4 0,4.4 0,5 C0,5.6 0.4,6 1,6 L4,6 L4,9 C4,9.6 4.4,10 5,10 C5.6,10 6,9.6 6,9 L6,6 L9,6 C9.6,6 10,5.6 10,5 C10,4.4 9.6,4 9,4 L6,4 Z" id="path-5"></path>
+ </defs>
+ <g id="sdc" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Group-12" transform="translate(11.000000, 8.000000)">
+ <g id="Group-4-Copy">
+ <g id="Group-3" filter="url(#filter-1)">
+ <g id="Rectangle-15-Copy-5">
+ <use fill="url(#linearGradient-2)" fill-rule="evenodd" xlink:href="#path-3"></use>
+ <use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-3"></use>
+ <use stroke="#FFFFFF" stroke-width="2" xlink:href="#path-3"></use>
+ </g>
+ </g>
+ </g>
+ <g id="color-/-gray-#5A5A5A-/-idle--Copy-34" transform="translate(6.000000, 6.000000)">
+ <mask id="mask-6" fill="white">
+ <use xlink:href="#path-5"></use>
+ </mask>
+ <use id="Mask" fill="#FFFFFF" xlink:href="#path-5"></use>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_group.svg b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_group.svg
new file mode 100644
index 0000000000..90920e9001
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_group.svg
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="28px" height="28px" viewBox="0 0 28 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 12 Copy</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <filter x="-22.7%" y="-13.6%" width="145.5%" height="145.5%" filterUnits="objectBoundingBox" id="filter-1">
+ <feOffset dx="0" dy="2" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>
+ <feGaussianBlur stdDeviation="1" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" type="matrix" in="shadowBlurOuter1" result="shadowMatrixOuter1"></feColorMatrix>
+ <feMerge>
+ <feMergeNode in="shadowMatrixOuter1"></feMergeNode>
+ <feMergeNode in="SourceGraphic"></feMergeNode>
+ </feMerge>
+ </filter>
+ <path d="M6,4 L6,1 C6,0.4 5.6,0 5,0 C4.4,0 4,0.4 4,1 L4,4 L1,4 C0.4,4 0,4.4 0,5 C0,5.6 0.4,6 1,6 L4,6 L4,9 C4,9.6 4.4,10 5,10 C5.6,10 6,9.6 6,9 L6,6 L9,6 C9.6,6 10,5.6 10,5 C10,4.4 9.6,4 9,4 L6,4 Z" id="path-2"></path>
+ </defs>
+ <g id="sdc" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Group-12-Copy" transform="translate(3.000000, 1.000000)">
+ <g id="Group-4-Copy" filter="url(#filter-1)" fill="#009FDB" stroke="#FFFFFF">
+ <g id="Group-3">
+ <path d="M3,0 L19,0 C20.6568542,-3.04359188e-16 22,1.34314575 22,3 L22,19 C22,20.6568542 20.6568542,22 19,22 L3,22 C1.34314575,22 2.02906125e-16,20.6568542 0,19 L0,3 C-2.02906125e-16,1.34314575 1.34314575,3.04359188e-16 3,0 Z" id="Rectangle-15-Copy-5"></path>
+ </g>
+ </g>
+ <g id="color-/-gray-#5A5A5A-/-idle--Copy-34" transform="translate(6.000000, 6.000000)">
+ <mask id="mask-3" fill="white">
+ <use xlink:href="#path-2"></use>
+ </mask>
+ <use id="Mask" fill="#FFFFFF" xlink:href="#path-2"></use>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_policy.svg b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_policy.svg
new file mode 100644
index 0000000000..217d92c654
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/adding_policy.svg
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="28px" height="28px" viewBox="0 0 28 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 12 Copy</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <filter x="-22.7%" y="-13.6%" width="145.5%" height="145.5%" filterUnits="objectBoundingBox" id="filter-1">
+ <feOffset dx="0" dy="2" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>
+ <feGaussianBlur stdDeviation="1" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" type="matrix" in="shadowBlurOuter1" result="shadowMatrixOuter1"></feColorMatrix>
+ <feMerge>
+ <feMergeNode in="shadowMatrixOuter1"></feMergeNode>
+ <feMergeNode in="SourceGraphic"></feMergeNode>
+ </feMerge>
+ </filter>
+ <path d="M6,4 L6,1 C6,0.4 5.6,0 5,0 C4.4,0 4,0.4 4,1 L4,4 L1,4 C0.4,4 0,4.4 0,5 C0,5.6 0.4,6 1,6 L4,6 L4,9 C4,9.6 4.4,10 5,10 C5.6,10 6,9.6 6,9 L6,6 L9,6 C9.6,6 10,5.6 10,5 C10,4.4 9.6,4 9,4 L6,4 Z" id="path-2"></path>
+ </defs>
+ <g id="sdc" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Group-12-Copy" transform="translate(3.000000, 1.000000)">
+ <g id="Group-4-Copy" filter="url(#filter-1)" fill="#0568AE" stroke="#FFFFFF">
+ <g id="Group-3">
+ <path d="M3,0 L19,0 C20.6568542,-3.04359188e-16 22,1.34314575 22,3 L22,19 C22,20.6568542 20.6568542,22 19,22 L3,22 C1.34314575,22 2.02906125e-16,20.6568542 0,19 L0,3 C-2.02906125e-16,1.34314575 1.34314575,3.04359188e-16 3,0 Z" id="Rectangle-15-Copy-5"></path>
+ </g>
+ </g>
+ <g id="color-/-gray-#5A5A5A-/-idle--Copy-34" transform="translate(6.000000, 6.000000)">
+ <mask id="mask-3" fill="white">
+ <use xlink:href="#path-2"></use>
+ </mask>
+ <use id="Mask" fill="#FFFFFF" xlink:href="#path-2"></use>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/images/canvas-tagging-icons/group_added.svg b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/group_added.svg
new file mode 100644
index 0000000000..d88e7ca343
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/group_added.svg
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 13</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <path d="M3,0 L15,0 C16.6568542,-3.04359188e-16 18,1.34314575 18,3 L18,15 C18,16.6568542 16.6568542,18 15,18 L3,18 C1.34314575,18 -6.85272294e-16,16.6568542 -8.8817842e-16,15 L0,3 C-2.02906125e-16,1.34314575 1.34314575,-5.83819232e-16 3,-8.8817842e-16 Z" id="path-1"></path>
+ <filter x="-25.0%" y="-13.9%" width="150.0%" height="150.0%" filterUnits="objectBoundingBox" id="filter-2">
+ <feMorphology radius="0.5" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
+ <feOffset dx="0" dy="2" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
+ <feGaussianBlur stdDeviation="1" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
+ <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
+ </filter>
+ <path d="M12.6603086,4.57405469 L8.30209375,11.5833406 L5.57568359,9.20957266 C5.13068359,8.77957266 4.46368359,8.77957266 4.01968359,9.20957266 C3.57568359,9.64057266 3.57568359,10.2865727 4.01968359,10.7175727 L7.52409375,13.8453406 C7.74609375,14.0603406 7.96809375,14.1683406 8.30209375,14.1683406 C8.63509375,14.1683406 8.85809375,14.0603406 9.07909375,13.8453406 L14.2163086,6.08105469 C14.6603086,5.65105469 14.6603086,5.00505469 14.2163086,4.57405469 C13.7723086,4.14305469 13.1053086,4.14305469 12.6603086,4.57405469 Z" id="path-3"></path>
+ </defs>
+ <g id="sdc" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Group-13" transform="translate(3.000000, 1.000000)">
+ <g id="Group-4-Copy-9">
+ <g id="Group-3">
+ <g id="Rectangle-15-Copy-5">
+ <use fill="black" fill-opacity="1" filter="url(#filter-2)" xlink:href="#path-1"></use>
+ <use stroke="#FFFFFF" stroke-width="1" fill="#009FDB" fill-rule="evenodd" xlink:href="#path-1"></use>
+ </g>
+ </g>
+ </g>
+ <mask id="mask-4" fill="white">
+ <use xlink:href="#path-3"></use>
+ </mask>
+ <use id="Mask" fill="#FFFFFF" xlink:href="#path-3"></use>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/images/canvas-tagging-icons/indication.svg b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/indication.svg
new file mode 100644
index 0000000000..7581d0447e
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/indication.svg
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="28px" height="28px" viewBox="0 0 28 28" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 4 Copy 10</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <path d="M3,0 L15,0 C16.6568542,-3.04359188e-16 18,1.34314575 18,3 L18,15 C18,16.6568542 16.6568542,18 15,18 L3,18 C1.34314575,18 -6.85272294e-16,16.6568542 -8.8817842e-16,15 L0,3 C-2.02906125e-16,1.34314575 1.34314575,-5.83819232e-16 3,-8.8817842e-16 Z" id="path-1"></path>
+ <filter x="-41.7%" y="-30.6%" width="183.3%" height="183.3%" filterUnits="objectBoundingBox" id="filter-2">
+ <feMorphology radius="0.5" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
+ <feOffset dx="0" dy="2" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
+ <feGaussianBlur stdDeviation="2" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
+ <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
+ </filter>
+ </defs>
+ <g id="sdc" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Group-4-Copy-10" transform="translate(5.000000, 3.000000)">
+ <g id="Group-3">
+ <g id="Rectangle-15-Copy-5">
+ <use fill="black" fill-opacity="1" filter="url(#filter-2)" xlink:href="#path-1"></use>
+ <use stroke="#FFFFFF" stroke-width="1" fill-opacity="0.3" fill="#009FDB" fill-rule="evenodd" xlink:href="#path-1"></use>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/images/canvas-tagging-icons/policy_added.svg b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/policy_added.svg
new file mode 100644
index 0000000000..9ff39019c7
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/canvas-tagging-icons/policy_added.svg
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 48.2 (47327) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 13 Copy</title>
+ <desc>Created with Sketch.</desc>
+ <defs>
+ <path d="M3,0 L15,0 C16.6568542,-3.04359188e-16 18,1.34314575 18,3 L18,15 C18,16.6568542 16.6568542,18 15,18 L3,18 C1.34314575,18 -6.85272294e-16,16.6568542 -8.8817842e-16,15 L0,3 C-2.02906125e-16,1.34314575 1.34314575,-5.83819232e-16 3,-8.8817842e-16 Z" id="path-1"></path>
+ <filter x="-25.0%" y="-13.9%" width="150.0%" height="150.0%" filterUnits="objectBoundingBox" id="filter-2">
+ <feMorphology radius="0.5" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
+ <feOffset dx="0" dy="2" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
+ <feGaussianBlur stdDeviation="1" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
+ <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
+ <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
+ </filter>
+ <path d="M12.6603086,4.57405469 L8.30209375,11.5833406 L5.57568359,9.20957266 C5.13068359,8.77957266 4.46368359,8.77957266 4.01968359,9.20957266 C3.57568359,9.64057266 3.57568359,10.2865727 4.01968359,10.7175727 L7.52409375,13.8453406 C7.74609375,14.0603406 7.96809375,14.1683406 8.30209375,14.1683406 C8.63509375,14.1683406 8.85809375,14.0603406 9.07909375,13.8453406 L14.2163086,6.08105469 C14.6603086,5.65105469 14.6603086,5.00505469 14.2163086,4.57405469 C13.7723086,4.14305469 13.1053086,4.14305469 12.6603086,4.57405469 Z" id="path-3"></path>
+ </defs>
+ <g id="sdc" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Group-13-Copy" transform="translate(3.000000, 1.000000)">
+ <g id="Group-4-Copy-9">
+ <g id="Group-3">
+ <g id="Rectangle-15-Copy-5">
+ <use fill="black" fill-opacity="1" filter="url(#filter-2)" xlink:href="#path-1"></use>
+ <use stroke="#FFFFFF" stroke-width="1" fill="#0568AE" fill-rule="evenodd" xlink:href="#path-1"></use>
+ </g>
+ </g>
+ </g>
+ <mask id="mask-4" fill="white">
+ <use xlink:href="#path-3"></use>
+ </mask>
+ <use id="Mask" fill="#FFFFFF" xlink:href="#path-3"></use>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/images/resource-icons/monitoring_template.png b/catalog-ui/src/assets/styles/images/resource-icons/monitoring_template.png
new file mode 100644
index 0000000000..f5b73989a6
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/resource-icons/monitoring_template.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/sprites/sprite-policy-groups-icons.png b/catalog-ui/src/assets/styles/images/sprites/sprite-policy-groups-icons.png
new file mode 100644
index 0000000000..fe1723e2fa
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-policy-groups-icons.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/sprite-group-icons.less b/catalog-ui/src/assets/styles/sprite-group-icons.less
new file mode 100644
index 0000000000..47340adbb3
--- /dev/null
+++ b/catalog-ui/src/assets/styles/sprite-group-icons.less
@@ -0,0 +1,11 @@
+.sprite-group-icons {
+ background-image: url('images/sprites/sprite-policy-groups-icons.png');
+ display: inline-block;
+}
+
+.sprite-group-icons.disable { opacity:0.5;}
+.sprite-group-icons.group { background-position: -43px -42px; width: 40px; height: 40px;}
+.sprite-group-icons.group-border { background-position: -123px -36px; width: 55px; height: 55px;}
+
+sprite-group-icons.group-empty { background-position: -40px -274px; width: 47px; height: 47px;}
+sprite-group-icons.group-empty-border { background-position: -123px -270px; width: 55px; height: 55px;} \ No newline at end of file
diff --git a/catalog-ui/src/assets/styles/sprite-policy-icons.less b/catalog-ui/src/assets/styles/sprite-policy-icons.less
new file mode 100644
index 0000000000..154cf0b6a3
--- /dev/null
+++ b/catalog-ui/src/assets/styles/sprite-policy-icons.less
@@ -0,0 +1,12 @@
+.sprite-policy-icons {
+ background-image: url('images/sprites/sprite-policy-groups-icons.png');
+ display: inline-block;
+}
+
+.sprite-policy-icons.disable { opacity:0.5;}
+
+.sprite-policy-icons.policy { background-position: -42px -130px; width: 40px; height: 40px;}
+.sprite-policy-icons.policy-border { background-position: -123px -123px; width: 55px; height: 55px;}
+
+.sprite-policy-icons.policy-empty { background-position: -40px -546px; width: 47px; height: 47px;}
+.sprite-policy-icons.policy-empty-border { background-position: -123px -542px; width: 55px; height: 55px;}
diff --git a/catalog-ui/src/assets/styles/sprite-resource-icons.less b/catalog-ui/src/assets/styles/sprite-resource-icons.less
index 96993d5171..2f542d661c 100644
--- a/catalog-ui/src/assets/styles/sprite-resource-icons.less
+++ b/catalog-ui/src/assets/styles/sprite-resource-icons.less
@@ -195,10 +195,10 @@
.sprite-resource-icons.ucpe.medium { background-position: -141px -3137px; width: 41px; height: 41px;}
.sprite-resource-icons.ucpe.large { background-position: -70px -3119px; width: 60px; height: 60px;}
-.sprite-resource-icons.vrouter { background-position: -282px -3066px; width: 69px; height: 43px;}
-.sprite-resource-icons.vrouter.small { background-position: -210px -3080px; width: 29px; height: 29px;}
-.sprite-resource-icons.vrouter.medium { background-position: -141px -3068px; width: 41px; height: 41px;}
-.sprite-resource-icons.vrouter.large { background-position: -70px -3049px; width: 60px; height: 60px;}
+.sprite-resource-icons.vRouter { background-position: -282px -3066px; width: 69px; height: 43px;}
+.sprite-resource-icons.vRouter.small { background-position: -210px -3080px; width: 29px; height: 29px;}
+.sprite-resource-icons.vRouter.medium { background-position: -141px -3068px; width: 41px; height: 41px;}
+.sprite-resource-icons.vRouter.large { background-position: -70px -3049px; width: 60px; height: 60px;}
.sprite-resource-icons.wanx { background-position: -283px -2992px; width: 58px; height: 47px;}
.sprite-resource-icons.wanx.small { background-position: -210px -3009px; width: 30px; height: 30px;}
diff --git a/catalog-ui/src/assets/styles/sprite.less b/catalog-ui/src/assets/styles/sprite.less
index 107cb815ee..aaf4f5529a 100644
--- a/catalog-ui/src/assets/styles/sprite.less
+++ b/catalog-ui/src/assets/styles/sprite.less
@@ -231,8 +231,8 @@
.asc{background-position: -924px -71px; width: 8px; height: 12px;}
.desc{background-position: -924px -101px; width: 8px; height: 12px;}
-.delete-item-icon { background-position: -140px -1119px; width: 11px; height: 15px; }
-.delete-item-icon:hover { background-position: -167px -1119px; width: 11px; height: 15px; }
+.delete-item-icon { background-position: -140px -1118px; width: 11px; height: 15px; }
+.delete-item-icon:hover { background-position: -167px -1118px; width: 11px; height: 15px; }
.filter-icon { background-position: -48px -1040px; width: 19px; height: 20px;}
.filter-icon:hover { background-position: -99px -1040px; width: 19px; height: 20px;}
.filled-checkbox-icon { background-position: -100px -1079px; width: 14px; height: 14px;}
diff --git a/catalog-ui/src/assets/styles/tables.less b/catalog-ui/src/assets/styles/tables.less
new file mode 100644
index 0000000000..6bac2588a4
--- /dev/null
+++ b/catalog-ui/src/assets/styles/tables.less
@@ -0,0 +1,54 @@
+.generic-table {
+ border: solid 1px @main_color_o;
+ color: @main_color_m;
+ background-color: @func_color_r;
+ font-size: 13px;
+ font-family: @font-opensans-regular;
+ overflow-y: auto;
+
+ .cell {
+ flex: 1;
+ padding: 10px;
+ border-right: @main_color_o solid 1px;
+ &:last-child {
+ margin: 0;
+ flex: 0.1;
+ border: none;
+ }
+ }
+
+ .header-row {
+ display: flex;
+ flex-basis: 100%;
+ background-color: @func_color_r;
+ color: @func_color_s;
+ font-weight: bold;
+ border-bottom: @main_color_o solid 1px;
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ .header-cell {
+ padding: 10px;
+ }
+ }
+
+ .data-row {
+ display: flex;
+ flex-basis: 100%;
+ border-bottom: @main_color_o solid 1px;
+ background-color: @main_color_p;
+ &:last-child {
+ border-bottom: none;
+ }
+ }
+
+ .no-row-text {
+ color: @main_color_m;
+ display: flex;
+ flex-basis: 100%;
+ background-color: @main_color_p;
+ padding: 20px;
+ justify-content: center;
+ font-size: 14px;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/webpack.server.js b/catalog-ui/webpack.server.js
index e53d79f533..608063aa02 100644
--- a/catalog-ui/webpack.server.js
+++ b/catalog-ui/webpack.server.js
@@ -4,84 +4,78 @@ const mockApis = require('./configurations/mock.json').sdcConfig;
const proxy = require('http-proxy-middleware');
const devPort = 9000;
const fePort = 8181;
+const loclahost = "192.168.33.10"; // "localhost"
module.exports = function(env) {
- // Set default role
- if (!env) {
- env = {
- role: "designer"
- };
- }
- console.log("Starting dev server with role: " + env.role);
+ // Set default role
+ if (!env) {
+ env = {
+ role: "designer"
+ };
+ }
+ console.log("Starting dev server with role: " + env.role);
- const ServerConfig = {
- port: devPort,
- historyApiFallback: true,
- inline: true,
- stats: {
- colors: true,
- exclude: ['node_modules']
- },
- setup: server => {
- let userType = mockApis.userTypes[env.role];
+ const ServerConfig = {
+ port: devPort,
+ historyApiFallback: true,
+ inline: true,
+ stats: {
+ colors: true,
+ exclude: ['node_modules']
+ },
+ setup: server => {
+ let userType = mockApis.userTypes[env.role];
- let middlewares = [
- (req, res, next) => {
- res.cookie(mockApis.cookie.userIdSuffix, req.headers[mockApis.cookie.userIdSuffix] || userType.userId);
- res.cookie(mockApis.cookie.userEmail, req.headers[mockApis.cookie.userEmail] || userType.email);
- res.cookie(mockApis.cookie.userFirstName, req.headers[mockApis.cookie.userFirstName] || userType.firstName);
- res.cookie(mockApis.cookie.userLastName, req.headers[mockApis.cookie.userLastName] || userType.lastName);
- next();
- }
- ];
-
- // Redirect all '/sdc1/feProxy/rest' to feHost
- middlewares.push(
- proxy(['/sdc1/feProxy/rest'],{
- target: 'http://localhost:' + fePort,
- changeOrigin: true,
- secure: false
- }));
-
- middlewares.push(
- proxy(['/sdc1/rest'],{
- target: 'http://localhost:' + fePort,
- changeOrigin: true,
- secure: false
- }));
+ let middlewares = [
+ (req, res, next) => {
+ res.cookie(mockApis.cookie.userIdSuffix, req.headers[mockApis.cookie.userIdSuffix] || userType.userId);
+ res.cookie(mockApis.cookie.userEmail, req.headers[mockApis.cookie.userEmail] || userType.email);
+ res.cookie(mockApis.cookie.userFirstName, req.headers[mockApis.cookie.userFirstName] || userType.firstName);
+ res.cookie(mockApis.cookie.userLastName, req.headers[mockApis.cookie.userLastName] || userType.lastName);
+ next();
+}
+];
- // Redirect dcae urls to feHost
- middlewares.push(
- proxy(['/dcae','/sdc1/feProxy/dcae-api'],{
- target: 'http://localhost:' + fePort,
- changeOrigin: true,
- secure: false,
- onProxyRes: (proxyRes, req, res) => {
- let setCookie = proxyRes.headers['set-cookie'];
- if (setCookie) {
- setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, '');
- }
- }
- }));
+ // Redirect all '/sdc1/feProxy/rest' to feHost
+ middlewares.push(
+ proxy(['/sdc1/feProxy/rest'],{
+ target: 'http://' + loclahost + ':' + fePort,
+ changeOrigin: true,
+ secure: false
+ }));
- // Redirect onboarding urls to feHost
- middlewares.push(
- proxy(['/onboarding','/sdc1/feProxy/onboarding-api'],{
- target: 'http://localhost:' + fePort,
- changeOrigin: true,
- secure: false,
- onProxyRes: (proxyRes, req, res) => {
- let setCookie = proxyRes.headers['set-cookie'];
- if (setCookie) {
- setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, '');
- }
- }
- }));
+ // Redirect dcae urls to feHost
+ middlewares.push(
+ proxy(['/dcae','/sdc1/feProxy/dcae-api'],{
+ target: 'http://' + loclahost + ':' + fePort,
+ changeOrigin: true,
+ secure: false,
+ onProxyRes: (proxyRes, req, res) => {
+ let setCookie = proxyRes.headers['set-cookie'];
+ if (setCookie) {
+ setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, '');
+ }
+}
+}));
- server.use(middlewares);
- }
- };
+ // Redirect onboarding urls to feHost
+ middlewares.push(
+ proxy(['/onboarding','/sdc1/feProxy/onboarding-api'],{
+ target: 'http://' + loclahost + ':' + fePort,
+ changeOrigin: true,
+ secure: false,
+ onProxyRes: (proxyRes, req, res) => {
+ let setCookie = proxyRes.headers['set-cookie'];
+ if (setCookie) {
+ setCookie[0] = setCookie[0].replace(/\bSecure\b(; )?/, '');
+ }
+}
+}));
- return ServerConfig;
+ server.use(middlewares);
}
+};
+
+ return ServerConfig;
+} \ No newline at end of file
diff --git a/common-app-api/pom.xml b/common-app-api/pom.xml
index 30577653ff..9d23ead5f9 100644
--- a/common-app-api/pom.xml
+++ b/common-app-api/pom.xml
@@ -11,6 +11,9 @@
<version>1.2.0-SNAPSHOT</version>
</parent>
+ <properties>
+ <sonar.skip>true</sonar.skip>
+ </properties>
<dependencies>
<dependency>
<groupId>org.openecomp.sdc</groupId>
@@ -27,13 +30,6 @@
</dependency>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
@@ -148,13 +144,6 @@
<version>${logback.version}</version>
<scope>provided</scope>
</dependency>
-
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- <scope>provided</scope>
- </dependency>
<!-- logging end -->
<dependency>
@@ -181,7 +170,6 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java
index d2675ac0c0..3cb7974c06 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/BeEcompErrorManager.java
@@ -42,8 +42,10 @@ public class BeEcompErrorManager extends AbsEcompErrorManager {
public static BeEcompErrorManager getInstance() {
if (instance == null) {
-
- instance = init();
+ synchronized (BeEcompErrorManager.class){
+ if (instance == null)
+ instance = init();
+ }
}
return instance;
}
@@ -81,6 +83,14 @@ public class BeEcompErrorManager extends AbsEcompErrorManager {
processEcompError(context, EcompErrorEnum.BeHealthCheckUebClusterRecovery);
}
+ public void logDmaapHealthCheckError(String context) {
+ processEcompError(context, EcompErrorEnum.DmaapHealthCheckError);
+ }
+
+ public void logDmaapHealthCheckRecovery(String context) {
+ processEcompError(context, EcompErrorEnum.DmaapHealthCheckRecovery);
+ }
+
public void logFeHealthCheckRecovery(String context) {
processEcompError(context, EcompErrorEnum.FeHealthCheckRecovery);
}
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 0a0d6e505e..14b02b4ff9 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
@@ -20,16 +20,15 @@
package org.openecomp.sdc.be.config;
-import static java.lang.String.format;
+import org.openecomp.sdc.common.api.BasicConfiguration;
import java.util.Date;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import static java.lang.String.format;
-import org.openecomp.sdc.common.api.BasicConfiguration;
-
+import static java.util.Collections.emptyMap;
public class Configuration extends BasicConfiguration {
private List<String> identificationHeaderFields;
@@ -74,15 +73,19 @@ public class Configuration extends BasicConfiguration {
private int startMigrationFrom;
private Long titanLockTimeout;
private Long titanReconnectIntervalInSeconds;
+ private List<String> healthStatusExclude;
private Long titanHealthCheckReadTimeout;
private Long esReconnectIntervalInSeconds;
private Long uebHealthCheckReconnectIntervalInSeconds;
private Long uebHealthCheckReadTimeout;
- private LinkedList<Map<String, Map<String, String>>> defaultImports;
+ private List<Map<String, Map<String, String>>> defaultImports;
private List<String> resourceTypes;
private List<String> excludeResourceCategory;
private List<String> excludeResourceType;
+ private Map<String, Set<String>> excludedPolicyTypesMapping;
+
+ private Map<String, Set<String>> excludedGroupTypesMapping;
private Map<String, Object> deploymentResourceArtifacts;
private Map<String, Object> deploymentResourceInstanceArtifacts;
private Map<String, Object> toscaArtifacts;
@@ -147,16 +150,28 @@ public class Configuration extends BasicConfiguration {
}
private String autoHealingOwner;
-
- private Map<String, List<String>> resourcesForUpgrade;
- private boolean skipUpgradeFailedVfs;
-
- private boolean skipUpgradeVSPs;
+ private Map<String, List<String>> resourcesForUpgrade;
+ private DmaapConsumerConfiguration dmaapConsumerConfiguration;
+ private boolean skipUpgradeFailedVfs;
+ private boolean skipUpgradeVSPs;
+ private DmeConfiguration dmeConfiguration;
+ public DmaapConsumerConfiguration getDmaapConsumerConfiguration() {
+ return dmaapConsumerConfiguration;
+ }
+ public void setDmaapConsumerConfiguration(DmaapConsumerConfiguration dmaapConsumerConfiguration) {
+ this.dmaapConsumerConfiguration = dmaapConsumerConfiguration;
+ }
+ public DmeConfiguration getDmeConfiguration() {
+ return dmeConfiguration;
+ }
+ public void setDmeConfiguration(DmeConfiguration dmeConfiguration) {
+ this.dmeConfiguration = dmeConfiguration;
+ }
public void setSkipUpgradeVSPs(boolean skipUpgradeVSPs) { this.skipUpgradeVSPs = skipUpgradeVSPs; }
public boolean getSkipUpgradeVSPsFlag() { return skipUpgradeVSPs; }
@@ -427,6 +442,21 @@ public class Configuration extends BasicConfiguration {
this.excludeResourceType = excludeResourceType;
}
+ public Map<String, Set<String>> getExcludedPolicyTypesMapping() {
+ return safeGetMap(excludedPolicyTypesMapping);
+ }
+
+ public void setExcludedPolicyTypesMapping(Map<String, Set<String>> excludedPolicyTypesMapping) {
+ this.excludedPolicyTypesMapping = excludedPolicyTypesMapping;
+ }
+
+ public Map<String, Set<String>> getExcludedGroupTypesMapping() {
+ return safeGetMap(excludedGroupTypesMapping);
+ }
+
+ public void setExcludedGroupTypesMapping(Map<String, Set<String>> excludedGroupTypesMapping) {
+ this.excludedGroupTypesMapping = excludedGroupTypesMapping;
+ }
public Map<String, Object> getToscaArtifacts() {
return toscaArtifacts;
@@ -1282,31 +1312,31 @@ public class Configuration extends BasicConfiguration {
@Override
public String toString() {
- return new StringBuilder().append(format("backend host: %s\n", beFqdn))
- .append(format("backend http port: %s\n", beHttpPort))
- .append(format("backend ssl port: %s\n", beSslPort)).append(format("backend context: %s\n", beContext))
- .append(format("backend protocol: %s\n", beProtocol)).append(format("Version: %s\n", version))
- .append(format("Released: %s\n", released)).append(format("Supported protocols: %s\n", protocols))
- .append(format("Users: %s\n", users)).append(format("Neo4j: %s\n", neo4j))
- .append(format("ElasticSearch: %s\n", elasticSearch))
- .append(format("Titan Cfg File: %s\n", titanCfgFile))
- .append(format("Titan In memory: %s\n", titanInMemoryGraph))
- .append(format("Titan lock timeout: %s\n", titanLockTimeout))
- .append(format("Titan reconnect interval seconds: %s\n", titanReconnectIntervalInSeconds))
- .append(format("excludeResourceCategory: %s\n", excludeResourceCategory))
- .append(format("informationalResourceArtifacts: %s\n", informationalResourceArtifacts))
- .append(format("deploymentResourceArtifacts: %s\n", deploymentResourceArtifacts))
- .append(format("informationalServiceArtifacts: %s\n", informationalServiceArtifacts))
- .append(format("Supported artifacts types: %s\n", artifactTypes))
- .append(format("Supported license types: %s\n", licenseTypes))
- .append(format("Additional information Maximum number of preoperties: %s\n",
+ return new StringBuilder().append(format("backend host: %s%n", beFqdn))
+ .append(format("backend http port: %s%n", beHttpPort))
+ .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext))
+ .append(format("backend protocol: %s%n", beProtocol)).append(format("Version: %s%n", version))
+ .append(format("Released: %s%n", released)).append(format("Supported protocols: %s%n", protocols))
+ .append(format("Users: %s%n", users)).append(format("Neo4j: %s%n", neo4j))
+ .append(format("ElasticSearch: %s%n", elasticSearch))
+ .append(format("Titan Cfg File: %s%n", titanCfgFile))
+ .append(format("Titan In memory: %s%n", titanInMemoryGraph))
+ .append(format("Titan lock timeout: %s%n", titanLockTimeout))
+ .append(format("Titan reconnect interval seconds: %s%n", titanReconnectIntervalInSeconds))
+ .append(format("excludeResourceCategory: %s%n", excludeResourceCategory))
+ .append(format("informationalResourceArtifacts: %s%n", informationalResourceArtifacts))
+ .append(format("deploymentResourceArtifacts: %s%n", deploymentResourceArtifacts))
+ .append(format("informationalServiceArtifacts: %s%n", informationalServiceArtifacts))
+ .append(format("Supported artifacts types: %s%n", artifactTypes))
+ .append(format("Supported license types: %s%n", licenseTypes))
+ .append(format("Additional information Maximum number of preoperties: %s%n",
additionalInformationMaxNumberOfKeys))
- .append(format("Default Heat Artifact Timeout in Minutes: %s\n", defaultHeatArtifactTimeoutMinutes))
- .append(format("URLs For HTTP Requests that will not be automatically logged : %s\n", unLoggedUrls))
- .append(format("Service Api Artifacts: %s\n", serviceApiArtifacts))
- .append(format("heat env artifact header: %s\n", heatEnvArtifactHeader))
- .append(format("heat env artifact footer: %s\n", heatEnvArtifactFooter))
- .append(format("onboarding: %s\n", onboarding)).toString();
+ .append(format("Default Heat Artifact Timeout in Minutes: %s%n", defaultHeatArtifactTimeoutMinutes))
+ .append(format("URLs For HTTP Requests that will not be automatically logged : %s%n", unLoggedUrls))
+ .append(format("Service Api Artifacts: %s%n", serviceApiArtifacts))
+ .append(format("heat env artifact header: %s%n", heatEnvArtifactHeader))
+ .append(format("heat env artifact footer: %s%n", heatEnvArtifactFooter))
+ .append(format("onboarding: %s%n", onboarding)).toString();
}
public List<String> getUnLoggedUrls() {
@@ -1487,11 +1517,11 @@ public class Configuration extends BasicConfiguration {
}
}
- public LinkedList<Map<String, Map<String, String>>> getDefaultImports() {
+ public List<Map<String, Map<String, String>>> getDefaultImports() {
return defaultImports;
}
- public void setDefaultImports(LinkedList<Map<String, Map<String, String>>> defaultImports) {
+ public void setDefaultImports(List<Map<String, Map<String, String>>> defaultImports) {
this.defaultImports = defaultImports;
}
@@ -1502,5 +1532,18 @@ public class Configuration extends BasicConfiguration {
public void setResourcesForUpgrade(Map<String, List<String>> resourcesForUpgrade) {
this.resourcesForUpgrade = resourcesForUpgrade;
}
-
+
+ private <K,V> Map<K,V> safeGetMap(Map<K,V> map) {
+ return map == null ? emptyMap() : map;
+ }
+
+
+ public List<String> getHealthStatusExclude() {
+ return healthStatusExclude;
+ }
+
+ public void setHealthStatusExclude(List<String> healthStatusExclude) {
+ this.healthStatusExclude = healthStatusExclude;
+ }
+
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java
index 1bef188d0d..eeeca5b9bb 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DistributionEngineConfiguration.java
@@ -27,6 +27,7 @@ import java.util.Map;
import java.util.Set;
import org.openecomp.sdc.common.api.BasicConfiguration;
+import org.openecomp.sdc.common.http.config.ExternalServiceConfig;
public class DistributionEngineConfiguration extends BasicConfiguration {
@@ -44,10 +45,6 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
private ComponentArtifactTypesConfig distribNotifResourceArtifactTypes;
- // private List<String> distribNotifServiceInfoArtifactTypes;
-
- // private List<String> distribNotifResourceLifecycleArtifactTypes;
-
private String uebPublicKey;
private String uebSecretKey;
@@ -63,13 +60,25 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
private DistributionNotificationTopicConfig distributionNotificationTopic;
private Integer defaultArtifactInstallationTimeout = 60;
+
+ private Integer currentArtifactInstallationTimeout = 120;
private boolean useHttpsWithDmaap;
+ private ExternalServiceConfig aaiConfig;
+
+ private ExternalServiceConfig msoConfig;
+
+ private Integer opEnvRecoveryIntervalSec;
+
+ private Integer allowedTimeBeforeStaleSec;
+
public static class DistribNotifServiceArtifacts {
Map<String, Object> service;
Map<String, Object> resource;
+
+
public Map<String, Object> getService() {
return service;
@@ -118,7 +127,7 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
}
- public static enum ArtifcatTypeEnum {
+ public enum ArtifcatTypeEnum {
MURANO_PKG("MURANO-PKG"), HEAT("HEAT"), DG_XML("DG_XML");
@@ -204,10 +213,10 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
public void setEnvironments(List<String> environments) {
- Set<String> set = new HashSet<String>();
+ Set<String> set = new HashSet<>();
if (environments != null) {
set.addAll(environments);
- this.environments = new ArrayList<String>(set);
+ this.environments = new ArrayList<>(set);
} else {
this.environments = null;
}
@@ -261,6 +270,14 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
public void setDefaultArtifactInstallationTimeout(int defaultArtifactInstallationTimeout) {
this.defaultArtifactInstallationTimeout = defaultArtifactInstallationTimeout;
}
+
+ public int getCurrentArtifactInstallationTimeout() {
+ return currentArtifactInstallationTimeout;
+ }
+
+ public void setCurrentArtifactInstallationTimeout(int currentArtifactInstallationTimeout) {
+ this.currentArtifactInstallationTimeout = currentArtifactInstallationTimeout;
+ }
public boolean isUseHttpsWithDmaap() {
return useHttpsWithDmaap;
@@ -440,4 +457,35 @@ public class DistributionEngineConfiguration extends BasicConfiguration {
}
+ public Integer getOpEnvRecoveryIntervalSec() {
+ return opEnvRecoveryIntervalSec;
+ }
+
+ public void setOpEnvRecoveryIntervalSec(Integer opEnvRecoveryIntervalSec) {
+ this.opEnvRecoveryIntervalSec = opEnvRecoveryIntervalSec;
+ }
+
+ public Integer getAllowedTimeBeforeStaleSec() {
+ return allowedTimeBeforeStaleSec;
+ }
+
+ public void setAllowedTimeBeforeStaleSec(Integer allowedTimeBeforeStaleSec) {
+ this.allowedTimeBeforeStaleSec = allowedTimeBeforeStaleSec;
+ }
+
+ public ExternalServiceConfig getAaiConfig() {
+ return aaiConfig;
+ }
+
+ public void setAaiConfig(ExternalServiceConfig aaiConfig) {
+ this.aaiConfig = aaiConfig;
+ }
+
+ public ExternalServiceConfig getMsoConfig() {
+ return msoConfig;
+ }
+
+ public void setMsoConfig(ExternalServiceConfig msoConfig) {
+ this.msoConfig = msoConfig;
+ }
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java
new file mode 100644
index 0000000000..1ba539b942
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmaapConsumerConfiguration.java
@@ -0,0 +1,269 @@
+package org.openecomp.sdc.be.config;
+/**
+ * Contains DMAAP Client configuration parameters
+ */
+public class DmaapConsumerConfiguration {
+
+ private String hosts;
+ private String consumerGroup;
+ private String consumerId;
+ private Integer timeoutMs;
+ private Integer limit;
+ private Integer pollingInterval;
+ private String topic;
+ private Double latitude;
+ private Double longitude;
+ private String version;
+ private String serviceName;
+ private String environment;
+ private String partner;
+ private String routeOffer;
+ private String protocol;
+ private String contenttype;
+ private Boolean dme2TraceOn;
+ private String aftEnvironment;
+ private Integer aftDme2ConnectionTimeoutMs;
+ private Integer aftDme2RoundtripTimeoutMs;
+ private Integer aftDme2ReadTimeoutMs;
+ private String dme2preferredRouterFilePath;
+ private Credential credential;
+ private Integer timeLimitForNotificationHandleMs;
+
+ public String getHosts() {
+ return hosts;
+ }
+
+ public void setHosts(String hosts) {
+ this.hosts = hosts;
+ }
+
+ public String getConsumerGroup() {
+ return consumerGroup;
+ }
+
+ public void setConsumerGroup(String consumerGroup) {
+ this.consumerGroup = consumerGroup;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public Integer getTimeoutMs() {
+ return timeoutMs;
+ }
+
+ public void setTimeoutMs(Integer timeoutMs) {
+ this.timeoutMs = timeoutMs;
+ }
+
+ public Integer getLimit() {
+ return limit;
+ }
+
+ public void setLimit(Integer limit) {
+ this.limit = limit;
+ }
+
+ public Integer getPollingInterval() {
+ return pollingInterval;
+ }
+
+ public void setPollingInterval(Integer pollingInterval) {
+ this.pollingInterval = pollingInterval;
+ }
+
+ public String getTopic() {
+ return topic;
+ }
+
+ public void setTopic(String topic) {
+ this.topic = topic;
+ }
+
+ public Double getLatitude() {
+ return latitude;
+ }
+
+ public void setLatitude(Double latitude) {
+ this.latitude = latitude;
+ }
+
+ public Double getLongitude() {
+ return longitude;
+ }
+
+ public void setLongitude(Double longitude) {
+ this.longitude = longitude;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ public String getEnvironment() {
+ return environment;
+ }
+
+ public void setEnvironment(String environment) {
+ this.environment = environment;
+ }
+
+ public String getPartner() {
+ return partner;
+ }
+
+ public void setPartner(String partner) {
+ this.partner = partner;
+ }
+
+ public String getRouteOffer() {
+ return routeOffer;
+ }
+
+ public void setRouteOffer(String routeOffer) {
+ this.routeOffer = routeOffer;
+ }
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public void setProtocol(String protocol) {
+ this.protocol = protocol;
+ }
+
+ public String getContenttype() {
+ return contenttype;
+ }
+
+ public void setContenttype(String contenttype) {
+ this.contenttype = contenttype;
+ }
+
+ public Boolean isDme2TraceOn() {
+ return dme2TraceOn;
+ }
+
+ public Boolean getDme2TraceOn() {
+ return dme2TraceOn;
+ }
+
+ public void setDme2TraceOn(Boolean dme2TraceOn) {
+ this.dme2TraceOn = dme2TraceOn;
+ }
+
+ public String getAftEnvironment() {
+ return aftEnvironment;
+ }
+
+ public void setAftEnvironment(String aftEnvironment) {
+ this.aftEnvironment = aftEnvironment;
+ }
+
+ public Integer getAftDme2ConnectionTimeoutMs() {
+ return aftDme2ConnectionTimeoutMs;
+ }
+
+ public void setAftDme2ConnectionTimeoutMs(Integer aftDme2ConnectionTimeoutMs) {
+ this.aftDme2ConnectionTimeoutMs = aftDme2ConnectionTimeoutMs;
+ }
+
+ public Integer getAftDme2RoundtripTimeoutMs() {
+ return aftDme2RoundtripTimeoutMs;
+ }
+
+ public void setAftDme2RoundtripTimeoutMs(Integer aftDme2RoundtripTimeoutMs) {
+ this.aftDme2RoundtripTimeoutMs = aftDme2RoundtripTimeoutMs;
+ }
+
+ public Integer getAftDme2ReadTimeoutMs() {
+ return aftDme2ReadTimeoutMs;
+ }
+
+ public void setAftDme2ReadTimeoutMs(Integer aftDme2ReadTimeoutMs) {
+ this.aftDme2ReadTimeoutMs = aftDme2ReadTimeoutMs;
+ }
+
+ public String getDme2preferredRouterFilePath() {
+ return dme2preferredRouterFilePath;
+ }
+
+ public void setDme2preferredRouterFilePath(String dme2preferredRouterFilePath) {
+ this.dme2preferredRouterFilePath = dme2preferredRouterFilePath;
+ }
+
+ public Credential getCredential() {
+ return credential;
+ }
+
+ public void setCredential(Credential credential) {
+ this.credential = credential;
+ }
+
+ /**
+ * Contains Dmaap Client credential parameters: username and password
+ */
+ public static class Credential{
+
+ private String username;
+ private String password;
+
+ 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;
+ }
+ @Override
+ public String toString() {
+ return "Credential [username=" + username + ", password=" + password + "]";
+ }
+
+ }
+
+ @Override
+ public String toString() {
+ return "DmaapConsumerConfiguration [hosts=" + hosts + ", consumerGroup=" + consumerGroup + ", consumerId="
+ + consumerId + ", timeoutMs=" + timeoutMs + ", limit=" + limit + ", pollingInterval=" + pollingInterval
+ + ", topic=" + topic + ", latitude=" + latitude + ", longitude=" + longitude + ", version=" + version
+ + ", serviceName=" + serviceName + ", environment=" + environment + ", partner=" + partner
+ + ", routeOffer=" + routeOffer + ", protocol=" + protocol + ", contenttype=" + contenttype
+ + ", dme2TraceOn=" + dme2TraceOn + ", aftEnvironment=" + aftEnvironment
+ + ", aftDme2ConnectionTimeoutMs=" + aftDme2ConnectionTimeoutMs + ", aftDme2RoundtripTimeoutMs="
+ + aftDme2RoundtripTimeoutMs + ", aftDme2ReadTimeoutMs=" + aftDme2ReadTimeoutMs
+ + ", dme2preferredRouterFilePath=" + dme2preferredRouterFilePath
+ + ", timeLimitForNotificationHandleMs=" + timeLimitForNotificationHandleMs+ ", credential=" + credential + "]";
+ }
+
+ public Integer getTimeLimitForNotificationHandleMs() {
+ return timeLimitForNotificationHandleMs;
+ }
+
+ public void setTimeLimitForNotificationHandleMs(Integer timeLimitForNotificationHandleMs) {
+ this.timeLimitForNotificationHandleMs = timeLimitForNotificationHandleMs;
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java
new file mode 100644
index 0000000000..82eb0a2f32
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/DmeConfiguration.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.config;
+
+public class DmeConfiguration {
+ private String dme2Search = "DME2SEARCH";
+ private String dme2Resolve = "DME2RESOLVE";
+
+ public String getDme2Search() {
+ return dme2Search;
+ }
+
+ public void setDme2Search(String dme2Search) {
+ this.dme2Search = dme2Search;
+ }
+
+ public String getDme2Resolve() {
+ return dme2Resolve;
+ }
+
+ public void setDme2Resolve(String dme2Resolve) {
+ this.dme2Resolve = dme2Resolve;
+ }
+
+ @Override
+ public String toString() {
+ return "DmeConfiguration [dme2Search=" + dme2Search + ", dme2Resolve=" + dme2Resolve + "]";
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java
index 40daf96d36..6751e3cfe2 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ErrorInfo.java
@@ -70,7 +70,6 @@ public class ErrorInfo {
this.errorInfoType = ErrorInfoType.POLICY_EXCEPTION;
} else {
// unexpected - should it fail the startup?
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.ErrorConfigFileFormat, "Error Info");
BeEcompErrorManager.getInstance().logErrorConfigFileFormat("Error Info",
"Could not set error info type for message id " + messageId);
log.debug("Error: unexpected error message ID {}, should start with {} or {}", messageId, SVC_PREFIX,
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java
index ac7391d8cc..f2438fcbfc 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/monitoring/BeMonitoringService.java
@@ -20,27 +20,24 @@
package org.openecomp.sdc.be.monitoring;
-import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
import org.openecomp.sdc.be.config.Configuration;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.openecomp.sdc.common.http.config.Timeouts;
import org.openecomp.sdc.common.monitoring.MonitoringEvent;
import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher;
import org.slf4j.Logger;
@@ -93,48 +90,22 @@ public class BeMonitoringService {
}
private void processMonitoringEvent(MonitoringEvent monitoringMetrics) {
- CloseableHttpClient httpClient = null;
try {
Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
.getConfiguration();
String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeFqdn(),
config.getBeHttpPort());
- httpClient = getHttpClient(config);
- HttpPost httpPost = new HttpPost(redirectedUrl);
+
+ final int timeout = 3000;
String monitoringMetricsJson = gson.toJson(monitoringMetrics);
- HttpEntity myEntity = new StringEntity(monitoringMetricsJson);
- httpPost.setEntity(myEntity);
- httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
- int beResponseStatus;
- CloseableHttpResponse beResponse;
- try {
- beResponse = httpClient.execute(httpPost);
- beResponseStatus = beResponse.getStatusLine().getStatusCode();
- if (beResponseStatus != HttpStatus.SC_OK) {
- monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus);
- }
- } catch (Exception e) {
- monitoringLogger.error("Monitoring error when trying to connect to BE", e);
- }
+ HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON);
+ HttpResponse<String> httpResponse = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout)));
+ int beResponseStatus = httpResponse.getStatusCode();
+ if (beResponseStatus != HttpStatus.SC_OK) {
+ monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus);
+ }
} catch (Exception e) {
- monitoringLogger.error("Unexpected monitoring error", e);
- } finally {
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- }
- }
+ monitoringLogger.error("Monitoring BE failed with exception ", e);
}
}
-
- private CloseableHttpClient getHttpClient(Configuration config) {
- int timeout = 3000;
- RequestConfig.Builder requestBuilder = RequestConfig.custom();
- requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout);
-
- HttpClientBuilder builder = HttpClientBuilder.create();
- builder.setDefaultRequestConfig(requestBuilder.build());
- return builder.build();
- }
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java
index 691b8ea159..5d33e9918f 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java
@@ -20,7 +20,7 @@
package org.openecomp.sdc.common.api;
-public interface Constants {
+public final class Constants {
public static final String APPLICATION_NAME = "application-name";
public static final String APPLICATION_VERSION = "application-version";
@@ -48,24 +48,20 @@ public interface Constants {
public static final String X_ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID";
public static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID";
public static final String X_ECOMP_SERVICE_ID_HEADER = "X-ECOMP-ServiceID";
+ public static final String X_TRANSACTION_ID_HEADER = "X-TransactionId";
+ public static final String X_FROM_APP_ID = "X-FromAppId";
public static final String HTTP = "http";
public static final String HTTPS = "https";
public static final String HTTP_IV_USER = "HTTP_IV_USER";
public static final String A4C_CSAR_CONTEXT = "/rest/csars/";
public static final String WEB_APPLICATION_CONTEXT_WRAPPER_ATTR = "web-application-context-wrapper";
public static final String CATALOG_BE = "catalog-be";
- public static final String HTTP_CSP_FIRSTNAME = "HTTP_CSP_FIRSTNAME";
- public static final String HTTP_CSP_LASTNAME = "HTTP_CSP_LASTNAME";
- public static final String HTTP_IV_REMOTE_ADDRESS = "HTTP_IV_REMOTE_ADDRESS";
- public static final String HTTP_CSP_TYPE = "HTTP_CSP_WSTYPE";
public static final String RESOURCE_SUPPORTED_VERSION = "0.0.1";
public static final String ARTIFACT_ID_FORMAT = "%s:%s:%s"; // resourceName:resourceVersion:artifactName
public static final String SERVICE_ARTIFACT_ID_FORMAT = "%s:%s:%s:%s"; // serviceName:serviceVersion:nodeTemplateName:artifactName
public static final String CONTENT_DISPOSITION = "content-disposition";
public static final String DOWNLOAD_ARTIFACT_LOGIC_ATTR = "downloadArtifactLogic";
public static final String ASDC_RELEASE_VERSION_ATTR = "SDC-Version";
- // public static final String AUDITING_MANAGER = "auditingManager";
- // public static final String USER_ADMIN_MANAGER = "userAdminManager";
public static final String YEAR = "year";
public static final String MONTH = "month";
public static final String DAY = "day";
@@ -83,7 +79,6 @@ public interface Constants {
public static final String ACCEPT_HEADER = "Accept";
public static final String STANDARD_INTERFACE_TYPE = "standard";
public static final String MURANO_PKG_ARTIFACT_TYPE = "MURANO-PKG";
- public static final String ARTIFACT_GROUP_TYPE_FIELD = "artifactGroupType";
// TOSCA
public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
@@ -92,6 +87,8 @@ public interface Constants {
public static final String IS_BASE = "isBase";
public static final String HEAT_FILE_PROPS = "heat_file";
+ public static final String GROUP_POLICY_NAME_DELIMETER = "..";
+ public static final String POLICY_UID_POSTFIX = ".policy";
public static final String MODULE_NAME_FORMAT = "%s..%s..module-%s";
public static final String MODULE_DESC_PATTERN = "[\\_\\-\\.a-zA-Z0-9]+";
public static final String MODULE_OLD_NAME_PATTERN = "([\\w\\_\\-\\.\\s]+)(::module-)(\\d+)";
@@ -99,6 +96,7 @@ public interface Constants {
public static final String MODULE_NAME_DELIMITER = "module-";
public static final String IMPORT_STRUCTURE = "importStructure";
public static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule";
+ public static final String GROUP_TOSCA_HEAT = "org.openecomp.groups.heat.HeatStack";
public static final String ARTIFACT_GROUP_TYPE = "artifactGroupType";
public static final String ARTIFACT_LABEL = "artifactLabel";
@@ -107,6 +105,7 @@ public interface Constants {
public static final String ARTIFACT_DESCRIPTION = "description";
public static final String ARTIFACT_TYPE = "artifactType";
public static final String ARTIFACT_NAME = "artifactName";
+ public static final String IS_FROM_CSAR = "isFromCsar";
public static final String ARTIFACT_ID = "uniqueId";
public static final String REQUIRED_ARTIFACTS = "requiredArtifacts";
public static final String ARTIFACT_HEAT_PARAMS = "heatParameters";
@@ -134,8 +133,10 @@ public interface Constants {
public static final String HC_COMPONENT_FE = "FE";
public static final String HC_COMPONENT_BE = "BE";
public static final String HC_COMPONENT_TITAN = "TITAN";
+ public static final String HC_COMPONENT_ES = "ES";
public static final String HC_COMPONENT_CASSANDRA = "CASSANDRA";
public static final String HC_COMPONENT_DISTRIBUTION_ENGINE = "DE";
+ public static final String HC_COMPONENT_DMAAP_ENGINE = "DMAPP";
//external HealthCheck components
public static final String HC_COMPONENT_ON_BOARDING = "ON_BOARDING";
@@ -143,4 +144,6 @@ public interface Constants {
//Plugin BL
public static final String PLUGIN_BL_COMPONENT = "pluginStatusBL";
+
+ private Constants(){}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java
index 8afd2fb4c9..7a22495643 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java
@@ -51,7 +51,7 @@ public class HealthCheckInfo {
this.version = version;
this.description = description;
this.componentsInfo = componentsInfo;
- }
+}
public HealthCheckInfo() {
super();
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java
index 6a54071f42..49f04d2ee1 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/AbsEcompErrorManager.java
@@ -20,98 +20,15 @@
package org.openecomp.sdc.common.config;
-import java.util.Formatter;
-import java.util.IllegalFormatException;
-import java.util.Locale;
-
-import org.apache.commons.lang3.StringUtils;
-import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompAlarmSeverity;
-import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompErrorSeverity;
-import org.openecomp.sdc.common.config.EcompErrorConfiguration.EcompErrorType;
-
import com.jcabi.aspects.Loggable;
@Loggable(prepend = true, value = Loggable.TRACE, trim = false)
-public abstract class AbsEcompErrorManager implements IEcompErrorManager {
+public abstract class AbsEcompErrorManager {
public static final String PARAM_STR = "%s";
public abstract IEcompConfigurationManager getConfigurationManager();
- @Deprecated
- @Override
- public void processEcompError(EcompErrorName ecompErrorName, String ecompErrorContext,
- String... descriptionParams) {
-
- /*
- * //Getting the relevant config manager IEcompConfigurationManager
- * configurationManager = getConfigurationManager();
- *
- * //Getting the error by name EcompErrorInfo ecompErrorInfo =
- * configurationManager.getEcompErrorConfiguration().getEcompErrorInfo(
- * ecompErrorName.name());
- *
- * if (ecompErrorInfo != null){ ecompErrorInfo =
- * setDescriptionParams(ecompErrorInfo, ecompErrorName.name(),
- * descriptionParams); EcompErrorLogUtil.logEcompError(ecompErrorName,
- * ecompErrorInfo, ecompErrorContext); } else {
- * EcompErrorLogUtil.logEcompError(EcompErrorName.EcompErrorNotFound,
- * getErrorInfoForUnknownErrorName(ecompErrorName.name()),
- * ecompErrorContext); }
- */
-
- }
-
- private EcompErrorInfo setDescriptionParams(EcompErrorInfo ecompErrorInfo, String ecompErrorName,
- String... descriptionParams) {
- String description = ecompErrorInfo.getDescription();
- // Counting number of params in description
- int countMatches = StringUtils.countMatches(description, PARAM_STR);
- // Catching cases when there are more params passed than there are in
- // the description (formatter will ignore extra params and won't throw
- // exception)
- if (countMatches != descriptionParams.length) {
- return getErrorInfoForDescriptionParamsMismatch(ecompErrorName);
- }
- // Setting params of the description if any
- StringBuilder sb = new StringBuilder();
- Formatter formatter = new Formatter(sb, Locale.US);
- try {
- formatter.format(description, (Object[]) descriptionParams).toString();
- ecompErrorInfo.setDescription(formatter.toString());
- } catch (IllegalFormatException e) {
- // Number of passed params doesn't match number of params in config
- // file
- return getErrorInfoForDescriptionParamsMismatch(ecompErrorName);
- } finally {
- formatter.close();
- }
- return ecompErrorInfo;
- }
-
- private EcompErrorInfo getErrorInfoForUnknownErrorName(String ecompErrorName) {
- EcompErrorInfo ecompErrorInfo = new EcompErrorInfo();
- ecompErrorInfo.setCode(EcompErrorConfiguration.ECODE_PREFIX + "3001");
- ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name());
- ecompErrorInfo.setSeverity(EcompErrorSeverity.ERROR.name());
- ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.MAJOR.name());
- ecompErrorInfo.setDescription(new StringBuilder().append("Ecomp error element not found in YAML, name: ")
- .append(ecompErrorName).toString());
- return ecompErrorInfo;
- }
-
- private EcompErrorInfo getErrorInfoForDescriptionParamsMismatch(String ecompErrorName) {
- EcompErrorInfo ecompErrorInfo = new EcompErrorInfo();
- ecompErrorInfo.setCode(EcompErrorConfiguration.ECODE_PREFIX + "3002");
- ecompErrorInfo.setType(EcompErrorType.CONFIG_ERROR.name());
- ecompErrorInfo.setSeverity(EcompErrorSeverity.ERROR.name());
- ecompErrorInfo.setAlarmSeverity(EcompAlarmSeverity.MAJOR.name());
- ecompErrorInfo.setDescription(new StringBuilder()
- .append("Ecomp error description params mismatch between code and YAML or wrong format, name: ")
- .append(ecompErrorName).toString());
- return ecompErrorInfo;
- }
-
public void processEcompError(String context, EcompErrorEnum ecompErrorEnum, String... descriptionParams) {
EcompErrorLogUtil.logEcompError(context, ecompErrorEnum, descriptionParams);
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java
index aaee26004f..aabd6d9305 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java
@@ -44,8 +44,9 @@ public enum EcompErrorCode {
"Connection problem towards U-EB server. Cannot reach host %s",
"Please check that that parameter uebServers in distribution-configuration.yaml points to a valid UEB Cluster."), E_212(
"Couldn't resolve hostIP. Desciption: %s"), E_213(
- "Site switch over was done. Site is now in %s mode"), E_299(
- "Internal Connection problem. Description: %s"),
+ "Site switch over was done. Site is now in %s mode"), E_214(
+ "Dmaap Connection problem."), E_299(
+ "Internal Connection problem. Description: %s"),
// [resource/service/product]
E_300("Mandatory %s Component %s cannot be found in repository"),
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java
index c79677a9ef..575cbe9e7e 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorEnum.java
@@ -22,9 +22,14 @@ package org.openecomp.sdc.common.config;
public enum EcompErrorEnum {
+
BeUebAuthenticationError(EcompErrorCode.E_100, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MAJOR,
EcompClassification.ERROR),
+
+ DmaapHealthCheckError(EcompErrorCode.E_214, ErrorType.CONNECTION_PROBLEM, AlarmSeverity.MAJOR,
+ EcompClassification.ERROR),
+
InternalAuthenticationInfo(EcompErrorCode.E_199, ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.INFORMATIONAL,
EcompClassification.INFORMATION), InternalAuthenticationWarning(EcompErrorCode.E_199,
ErrorType.AUTHENTICATION_PROBLEM, AlarmSeverity.MINOR,
@@ -43,7 +48,9 @@ public enum EcompErrorEnum {
AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION,
null), FeHealthCheckRecovery(EcompErrorCode.E_209, ErrorType.RECOVERY,
AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION,
- null), BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR,
+ null),DmaapHealthCheckRecovery( EcompErrorCode.E_210, ErrorType.RECOVERY,
+ AlarmSeverity.INFORMATIONAL, EcompClassification.INFORMATION,
+ null), BeHealthCheckError(EcompErrorCode.E_200, ErrorType.SYSTEM_ERROR,
AlarmSeverity.CRITICAL, EcompClassification.ERROR,
BeHealthCheckRecovery),
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java
index 6bd139bb28..5da7808376 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorName.java
@@ -37,5 +37,7 @@ public enum EcompErrorName {
// BeRepositoryQueryError,
BeDaoSystemError, BeSystemError, BeInvalidConfigurationError, BeMissingConfigurationError, BeUebConnectionError, BeUebObjectNotFoundError, BeUebSystemError, BeDistributionEngineSystemError, BeDistributionEngineInvalidArtifactType, BeConfigurationInvalidListSizeError, BeUebAuthenticationError, BeUebUnkownHostError, BeInvalidTypeError, BeInvalidValueError, BeFailedLockObjectError, BeInvalidJsonInput, BeDistributionMissingError, ErrorConfigFileFormat,
// model
- BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError;
+ BeFailedCreateNodeError, BeFailedUpdateNodeError, BeFailedDeleteNodeError, BeFailedRetrieveNodeError, BeExecuteRollbackError, BeFailedFindParentError, BeFailedFindAllNodesError, BeFailedFindAssociationError, BeFailedToAssociateError, BeComponentCleanerSystemError,
+ //dmaap
+ DmaapHealthCheckRecovery , DmaapHealthCheckError;
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java
deleted file mode 100644
index 7b9aa8e730..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/IEcompErrorManager.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.config;
-
-public interface IEcompErrorManager {
-
- public void processEcompError(EcompErrorName ecompErrorName, String ecompErrorContext, String... descriptionParams);
-
-}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java
index 53aa2391d5..0dd15073da 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/AuditingFieldsKeysEnum.java
@@ -68,6 +68,9 @@ public enum AuditingFieldsKeysEnum {
AUDIT_DISTRIBUTION_RESOURCE_URL(String.class, "RESOURCE_URL"),
AUDIT_DISTRIBUTION_STATUS_TIME(String.class, "STATUS_TIME"),
AUDIT_DISTRIBUTION_STATUS_DESC(String.class, "STATUS_DESC"),
+ AUDIT_DISTRIBUTION_ENVIRONMENT_ID(String.class, "ENV_ID"),
+ AUDIT_DISTRIBUTION_VNF_WORKLOAD_CONTEXT(String.class, "VNF_WORKLOAD_CONTEXT"),
+ AUDIT_DISTRIBUTION_TENANT(String.class, "TENANT"),
// category
AUDIT_CATEGORY_NAME(String.class, "CATEGORY_NAME"),
@@ -75,6 +78,13 @@ public enum AuditingFieldsKeysEnum {
AUDIT_GROUPING_NAME(String.class, "GROUPING_NAME"),
AUDIT_DETAILS(String.class, "DETAILS"),
+ //operational environment
+ AUDIT_OPERATIONAL_ENVIRONMENT_ID(String.class, "OPERATIONAL_ENVIRONMENT_ID"),
+ AUDIT_OPERATIONAL_ENVIRONMENT_NAME(String.class, "OPERATIONAL_ENVIRONMENT_NAME"),
+ AUDIT_OPERATIONAL_ENVIRONMENT_TYPE(String.class, "OPERATIONAL_ENVIRONMENT_TYPE"),
+ AUDIT_OPERATIONAL_ENVIRONMENT_ACTION(String.class, "OPERATIONAL_ENVIRONMENT_ACTION"),
+ AUDIT_TENANT_CONTEXT(String.class, "TENANT_CONTEXT"),
+
// authentication
AUDIT_AUTH_URL(String.class, "URL"),
AUDIT_AUTH_USER(String.class, "USER"),
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java
index de94358ab4..64266f5985 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/datastructure/FunctionalInterfaces.java
@@ -21,10 +21,25 @@
package org.openecomp.sdc.common.datastructure;
import java.io.Serializable;
+import java.util.Arrays;
import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
import java.util.function.Function;
+import java.util.function.Predicate;
import java.util.function.Supplier;
+import org.apache.commons.lang3.math.NumberUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.F;
import fj.data.Either;
/**
@@ -36,14 +51,16 @@ import fj.data.Either;
public class FunctionalInterfaces {
private static final int DEFAULT_REDO_INTERVAL_TIME_MS = 50;
private static final int DEFAULT_MAX_WAIT_TIME_MS = 10000;
-
+ private static final Logger LOGGER = LoggerFactory.getLogger(FunctionalInterfaces.class);
+
/**
* This is an interface of a List that implements Serializable
+ *
* @author mshitrit
*
* @param <T>
*/
- public interface SerializableList<T> extends List<T> , Serializable {
+ public interface SerializableList<T> extends List<T>, Serializable {
}
/**
@@ -94,6 +111,17 @@ public class FunctionalInterfaces {
R apply(T t) throws E;
}
+ public interface FunctionTwoParamThrows<T1, T2, R, E extends Exception> {
+ /**
+ * Same apply method, but throws an exception
+ *
+ * @param t1
+ * @param t2
+ * @return
+ */
+ R apply(T1 t1, T2 t2) throws E;
+ }
+
/**
* @author mshitrit Supplier that throws an exception
* @param <R>
@@ -264,6 +292,80 @@ public class FunctionalInterfaces {
/**
* Runs the given method.<br>
+ * Verify the method result against the resultVerifier.<br>
+ * If verification passed returns the result.<br>
+ * If Verification failed keeps retrying until maxRetries reached.<br>
+ * If Exception Occurred keeps retrying until it passes or until maxRetries
+ * reached,<br>
+ * If last retry result caused an exception - it is thrown.
+ *
+ * @param methodToRun
+ * given Method
+ * @param resultVerifier
+ * verifier for the method result
+ * @param maxRetries
+ * @return
+ */
+ public static <R> R retryMethodOnResult(Supplier<R> methodToRun, Function<R, Boolean> resultVerifier,
+ long maxRetries) {
+ boolean stopSearch = false;
+ R ret = null;
+ int retriesCount = 0;
+ FunctionalAttException functionalExceotion = null;
+ boolean isExceptionInLastTry = false;
+ while (!stopSearch) {
+ try {
+ ret = methodToRun.get();
+ stopSearch = resultVerifier.apply(ret);
+ isExceptionInLastTry = false;
+ } catch (Exception e) {
+ functionalExceotion = new FunctionalAttException(e);
+ isExceptionInLastTry = true;
+ } finally {
+ if (++retriesCount >= maxRetries) {
+ stopSearch = true;
+ }
+ }
+ }
+ if (isExceptionInLastTry) {
+ throw functionalExceotion;
+ } else {
+ return ret;
+ }
+ }
+
+ public static <R> R retryMethodOnException(SupplierThrows<R, Exception> methodToRun,
+ Function<Exception, Boolean> exceptionVerifier, long maxRetries) throws Exception {
+ boolean stopSearch = false;
+ R ret = null;
+ int retriesCount = 0;
+ Exception exception = null;
+ while (!stopSearch) {
+ try {
+ exception = null;
+ ret = methodToRun.get();
+ stopSearch = true;
+ }
+ catch (Exception e) {
+ exception = e;
+ stopSearch = exceptionVerifier.apply(e);
+ }
+ finally {
+ if (++retriesCount >= maxRetries) {
+ stopSearch = true;
+ }
+ }
+ }
+ if (exception != null) {
+ throw exception;
+ }
+ else {
+ return ret;
+ }
+ }
+
+ /**
+ * Runs the given method.<br>
* In case exception occurred runs the method again either until succeed or
* until 10 seconds pass.
*
@@ -312,17 +414,15 @@ public class FunctionalInterfaces {
* @param eitherToConvert
* @return
*/
- public static <T1,T2,T3> Either<T1,T2> convertEitherRight(Either<T3,T2> eitherToConvert){
- if( eitherToConvert.isLeft() ){
+ public static <T1, T2, T3> Either<T1, T2> convertEitherRight(Either<T3, T2> eitherToConvert) {
+ if (eitherToConvert.isLeft()) {
throw new UnsupportedOperationException("Can not convert either right value because it has left value");
- }
- else{
+ } else {
return Either.right(eitherToConvert.right().value());
}
-
-
+
}
-
+
/**
* Converts Either containing left value to another either with different
* type of right value and the same type of left value.
@@ -330,14 +430,95 @@ public class FunctionalInterfaces {
* @param eitherToConvert
* @return
*/
- public static <T1,T2,T3> Either<T1,T2> convertEitherLeft(Either<T1,T3> eitherToConvert){
- if( eitherToConvert.isLeft() ){
+ public static <T1, T2, T3> Either<T1, T2> convertEitherLeft(Either<T1, T3> eitherToConvert) {
+ if (eitherToConvert.isLeft()) {
throw new UnsupportedOperationException("Can not convert either left value because it has right value");
+ } else {
+ return Either.left(eitherToConvert.left().value());
+ }
+
+ }
+
+ /**
+ * Returns enum value for a field <br>
+ *
+ * @param fieldValue
+ * @param values
+ * @param enumValueGetter
+ * @return
+ */
+ public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values,
+ Function<T, String> enumValueGetter, T defaultValue) {
+ return getEnumValueByFieldValue(fieldValue, values, enumValueGetter, defaultValue, true);
+
+ }
+
+
+ public static <T extends Enum<T>> T getEnumValueByFieldValue(String fieldValue, T[] values,
+ Function<T, String> enumValueGetter, T defaultValue, boolean isCaseSensetive ){
+
+ final Predicate<? super T> predicate;
+ if( isCaseSensetive ){
+ predicate = e -> fieldValue.equals(enumValueGetter.apply(e));
}
else{
- return Either.left(eitherToConvert.left().value());
+ predicate = e -> fieldValue.equalsIgnoreCase(enumValueGetter.apply(e));
+ }
+ Optional<T> optionalFound =
+ // Stream of values of enum
+ Arrays.asList(values).stream().
+ // Filter in the one that match the field
+ filter(predicate).
+ // collect
+ findAny();
+ T ret;
+ ret = optionalFound.isPresent() ? optionalFound.get() : defaultValue;
+ return ret;
+
+ }
+
+ /**
+ * This method runs the given method.<br>
+ * In case given method finished running within timeoutInMs limit it returns
+ * Either which left value is the result of the method that ran.<br>
+ * In case given method did not finish running within timeoutInMs limit it
+ * returns Either which right value is false. <br>
+ *
+ * @param supplier
+ * @param timeoutInMs
+ * - if 0 or lower no timeout is used
+ * @return
+ */
+ public static <T> Either<T, Boolean> runMethodWithTimeOut(Supplier<T> supplier, long timeoutInMs) {
+ Either<T, Boolean> result;
+ if (timeoutInMs <= NumberUtils.LONG_ZERO) {
+ result = Either.left(supplier.get());
+ } else {
+ ExecutorService pool = Executors.newSingleThreadExecutor();
+ Future<T> future = pool.submit(supplier::get);
+ try {
+ T calcValue = future.get(timeoutInMs, TimeUnit.MILLISECONDS);
+ result = Either.left(calcValue);
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ LOGGER.debug("method run was canceled because it has passed its time limit of {} MS", timeoutInMs, e);
+ result = Either.right(false);
+ } finally {
+ pool.shutdownNow();
+ }
}
-
+ return result;
+ }
+
+ public static <T> F<T, Boolean> convertToFunction(Consumer<T> consumer) {
+ F<T, Boolean> func = t -> {
+ try {
+ consumer.accept(t);
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ };
+ return func;
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java
new file mode 100644
index 0000000000..e5f5fc99dd
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerAudit.java
@@ -0,0 +1,184 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ALERT_SEVERITY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_CLASS_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_INSTANCE_UUID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD1;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD2;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD3;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD4;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PROCESS_KEY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_REMOTE_HOST;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_DESC;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_STATUS_CODE;
+
+import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode;
+import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers;
+import org.openecomp.sdc.common.ecomplog.Enums.Severity;
+import org.openecomp.sdc.common.ecomplog.Enums.StatusCode;
+import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper;
+import org.slf4j.MDC;
+import org.slf4j.MarkerFactory;
+
+public class EcompLoggerAudit extends EcompLoggerBase{
+ private static EcompLoggerAudit instanceLoggerAudit = EcompLoggerFactory.getLogger(EcompLoggerAudit.class);
+
+ EcompLoggerAudit(IEcompMdcWrapper ecompMdcWrapper) {
+ super (ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.AUDIT_MARKER.text()));
+ }
+
+ public static EcompLoggerAudit getInstance() {
+ return instanceLoggerAudit;
+ }
+
+ @Override
+ public EcompLoggerAudit startTimer() {
+ return (EcompLoggerAudit) super.startTimer();
+ }
+
+ public EcompLoggerAudit stopTimer() {
+ ecompMdcWrapper.stopTimer();
+ return this;
+ }
+
+ // automatic parameter this is optional
+ public EcompLoggerAudit setAutoServerFQDN(String serverFQDN) {
+ ecompMdcWrapper.setAutoServerFQDN(serverFQDN);
+ return this;
+ }
+
+ // automatic parameter this is optional
+ public EcompLoggerAudit setAutoServerIPAddress(String serverIPAddress) {
+ ecompMdcWrapper.setAutoServerIPAddress(serverIPAddress);
+ return this;
+ }
+
+ public EcompLoggerAudit setInstanceUUID(String instanceUUID) {
+ ecompMdcWrapper.setInstanceUUID(instanceUUID);
+ return this;
+ }
+
+ public EcompLoggerAudit setOptClassName(String className) {
+ MDC.put("ClassName", className);
+ return this;
+ }
+
+ public EcompLoggerAudit setOptProcessKey(String processKey) {
+ ecompMdcWrapper.setProcessKey(processKey);
+ return this;
+ }
+
+ public EcompLoggerAudit setOptAlertSeverity(Severity alertSeverity) {
+ ecompMdcWrapper.setAlertSeverity(alertSeverity);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerAudit setOptCustomField1(String customField1) {
+ ecompMdcWrapper.setOptCustomField1(customField1);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerAudit setOptCustomField2(String customField2) {
+ ecompMdcWrapper.setOptCustomField2(customField2);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerAudit setOptCustomField3(String customField3) {
+ ecompMdcWrapper.setOptCustomField3(customField3);
+ return this;
+ }
+
+ public EcompLoggerAudit setOptCustomField4(String customField4) {
+ ecompMdcWrapper.setOptCustomField4(customField4);
+ return this;
+ }
+
+ @Override
+ public EcompLoggerAudit setKeyRequestId(String keyRequestId) {
+ return (EcompLoggerAudit) super.setKeyRequestId(keyRequestId);
+ }
+
+ public EcompLoggerAudit setRemoteHost(String remoteHost) {
+ ecompMdcWrapper.setRemoteHost(remoteHost);
+ return this;
+ }
+
+ public EcompLoggerAudit setServiceName(String serviceName) {
+ ecompMdcWrapper.setServiceName(serviceName);
+ return this;
+ }
+
+ public EcompLoggerAudit setStatusCode(String statusCode) {
+ // status code is either success (COMPLETE) or failure (ERROR) of the request.
+ String respStatus = Integer.parseInt(statusCode) / 100 == 2 ? StatusCode.COMPLETE.getStatusCodeEnum() : StatusCode.ERROR.getStatusCodeEnum();
+ ecompMdcWrapper.setStatusCode(respStatus);
+ return this;
+ }
+
+ public EcompLoggerAudit setPartnerName(String partnerName) {
+ ecompMdcWrapper.setPartnerName(partnerName);
+ return this;
+ }
+
+ public EcompLoggerAudit setResponseCode(EcompLoggerErrorCode responseCode) {
+ ecompMdcWrapper.setResponseCode(responseCode.getErrorCode());
+ return this;
+ }
+
+ public EcompLoggerAudit setResponseDesc(String responseDesc) {
+ ecompMdcWrapper.setResponseDesc(responseDesc);
+ return this;
+ }
+
+ public EcompLoggerAudit setOptServiceInstanceId(String serviceInstanceId) {
+ ecompMdcWrapper.setServiceInstanceId(serviceInstanceId);
+ return this;
+ }
+
+ @Override
+ public EcompLoggerAudit clear() {
+ return (EcompLoggerAudit) super.clear();
+ }
+
+ @Override
+ public void initializeMandatoryFields() {
+
+ ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP);
+ ecompMdcWrapper.setMandatoryField(MDC_END_TIMESTAMP);
+ ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVICE_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_PARTNER_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_STATUS_CODE);
+ ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_CODE);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVICE_INSTANCE_ID);
+ ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_DESC);
+ ecompMdcWrapper.setMandatoryField(MDC_ELAPSED_TIME);
+
+ //Theoretically Optional, but practically Mandatory
+ ecompMdcWrapper.setMandatoryField(MDC_SERVER_IP_ADDRESS);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVER_FQDN);
+
+ ecompMdcWrapper.setOptionalField(MDC_INSTANCE_UUID);
+ ecompMdcWrapper.setOptionalField(MDC_ALERT_SEVERITY);
+ ecompMdcWrapper.setOptionalField(MDC_REMOTE_HOST);
+ ecompMdcWrapper.setOptionalField(MDC_CLASS_NAME);
+ ecompMdcWrapper.setOptionalField(MDC_PROCESS_KEY);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD1);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD2);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD3);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD4);
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java
new file mode 100644
index 0000000000..535e8a4204
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerBase.java
@@ -0,0 +1,79 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS;
+
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+import org.openecomp.sdc.common.ecomplog.api.IEcompLogger;
+import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.slf4j.Marker;
+
+
+/**
+ * Created by mm288v on 12/27/2017.
+ * This class holds the common behavior of all Loger-Typed classes.
+ * The Concrete loggers shoudl derive from this one.
+ */
+public abstract class EcompLoggerBase implements IEcompLogger{
+ private static Logger myLogger = LoggerFactory.getLogger(IEcompLogger.class.getName());
+ private Marker myMarker;
+ IEcompMdcWrapper ecompMdcWrapper;
+
+ EcompLoggerBase(IEcompMdcWrapper ecompMdcWrapper, Marker marker) {
+ this.ecompMdcWrapper = ecompMdcWrapper;
+ initializeMandatoryFields();
+ this.myMarker = marker;
+ }
+
+ @Override
+ public void log(LogLevel errorLevel, String message) {
+
+ ecompMdcWrapper.validateMandatoryFields();
+
+ if (this instanceof EcompLoggerAudit || this instanceof EcompLoggerMetric) {
+ MDC.put(MDC_SERVER_IP_ADDRESS, EcompMDCWrapper.getInstance().getHostAddress());
+ MDC.put(MDC_SERVER_FQDN, EcompMDCWrapper.getInstance().getFqdn());
+ }
+
+ if (errorLevel.equals(LogLevel.ERROR)) {
+ myLogger.error(myMarker, message);
+ return;
+ }
+
+ if (errorLevel.equals(LogLevel.WARN)) {
+ myLogger.warn(myMarker, message);
+ return;
+ }
+
+ if (errorLevel.equals(LogLevel.INFO)) {
+ myLogger.info(myMarker, message);
+ return;
+ }
+
+ if (errorLevel.equals(LogLevel.DEBUG)) {
+ myLogger.info(myMarker, message);
+ }
+ }
+
+ @Override
+ public IEcompLogger clear() {
+ ecompMdcWrapper.clear();
+ return this;
+ }
+
+ @Override
+ public IEcompLogger startTimer() {
+ ecompMdcWrapper.startTimer();
+ return this;
+ }
+
+ @Override
+ public IEcompLogger setKeyRequestId(String keyRequestId) {
+ ecompMdcWrapper.setKeyRequestId(keyRequestId);
+ return this;
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java
new file mode 100644
index 0000000000..aecb487e24
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerDebug.java
@@ -0,0 +1,51 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID;
+
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers;
+import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper;
+import org.slf4j.MarkerFactory;
+
+public class EcompLoggerDebug extends EcompLoggerBase {
+
+ private static EcompLoggerDebug instanceLoggerDebug = EcompLoggerFactory.getLogger(EcompLoggerDebug.class);
+
+ protected final String endOfRecordDelimiter = "|^\\n";
+
+ EcompLoggerDebug(IEcompMdcWrapper ecompMdcWrapper) {
+ super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.DEBUG_MARKER.text()));
+ }
+
+ public static EcompLoggerDebug getInstance() {
+ return instanceLoggerDebug;
+ }
+
+ @Override
+ public void log(LogLevel errorLevel, String message) {
+ String formattedMessage = String.format("%s%s", message, endOfRecordDelimiter);
+ super.log(errorLevel, formattedMessage);
+ }
+
+ @Override
+ public void initializeMandatoryFields() {
+ ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP);
+ ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID);
+ }
+
+ @Override
+ public EcompLoggerDebug clear() {
+ return (EcompLoggerDebug) super.clear();
+ }
+
+ @Override
+ public EcompLoggerDebug startTimer() {
+ return (EcompLoggerDebug) super.startTimer();
+ }
+
+ @Override
+ public EcompLoggerDebug setKeyRequestId(String keyRequestId) {
+ return (EcompLoggerDebug) super.setKeyRequestId(keyRequestId);
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java
new file mode 100644
index 0000000000..92a495fda7
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerError.java
@@ -0,0 +1,77 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_CATEGORY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_DESC;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_ENTITY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_SERVICE_NAME;
+
+import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode;
+import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers;
+import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper;
+import org.slf4j.MarkerFactory;
+
+public class EcompLoggerError extends EcompLoggerBase{
+ private static EcompLoggerError instanceLoggerError = EcompLoggerFactory.getLogger(EcompLoggerError.class);
+
+ EcompLoggerError(IEcompMdcWrapper ecompMdcWrapper) {
+ super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.ERROR_MARKER.text()));
+ }
+
+ public static EcompLoggerError getInstance() {
+ return instanceLoggerError;
+ }
+
+ @Override
+ public void initializeMandatoryFields() {
+ ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP);
+ ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVICE_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_PARTNER_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_ERROR_CATEGORY);
+ ecompMdcWrapper.setMandatoryField(MDC_ERROR_CODE);
+ ecompMdcWrapper.setMandatoryField(MDC_ERROR_DESC);
+
+ ecompMdcWrapper.setOptionalField(MDC_TARGET_ENTITY);
+ ecompMdcWrapper.setOptionalField(MDC_TARGET_SERVICE_NAME);
+ }
+
+ @Override
+ public EcompLoggerError startTimer() {
+ return (EcompLoggerError) super.startTimer();
+ }
+
+ @Override
+ public EcompLoggerError setKeyRequestId(String keyRequestId) {
+ return (EcompLoggerError) super.setKeyRequestId(keyRequestId);
+ }
+
+ public EcompLoggerError setServiceName(String serviceName) {
+ ecompMdcWrapper.setServiceName(serviceName);
+ return this;
+ }
+
+ public EcompLoggerError setTargetEntity(String targetEntity) {
+ ecompMdcWrapper.setTargetEntity(targetEntity);
+ return this;
+ }
+
+ public EcompLoggerError setErrorCode(EcompLoggerErrorCode errorCode) {
+ ecompMdcWrapper.setErrorCode(errorCode.getErrorCode());
+ return this;
+ }
+
+ public EcompLoggerError setErrorDescription(String errorDescription) {
+ ecompMdcWrapper.setErrorDescription(errorDescription);
+ return this;
+ }
+
+ public EcompLoggerError clear() {
+ return (EcompLoggerError) super.clear();
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java
new file mode 100644
index 0000000000..2ea1280f48
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerFactory.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.common.ecomplog;
+
+/**
+ * Created by dd4296 on 12/26/2017.
+ * this factory helps decouple the classes for Stopwatch and EcompMDCWrapper from
+ * the EcompLogger classes
+ */
+public class EcompLoggerFactory {
+
+ private EcompLoggerFactory() {
+ }
+
+ @SuppressWarnings("unchecked")
+ static public <T, V> V getLogger(Class<T> type) {
+
+ if (type.getName().equals(EcompLoggerAudit.class.getName())) {
+ return (V) new EcompLoggerAudit(new EcompMDCWrapper(new Stopwatch()));
+ }
+
+ if (type.getName().equals(EcompLoggerDebug.class.getName())) {
+ return (V) new EcompLoggerDebug(new EcompMDCWrapper(new Stopwatch()));
+ }
+
+ if (type.getName().equals(EcompLoggerMetric.class.getName())) {
+ return (V) new EcompLoggerMetric(new EcompMDCWrapper(new Stopwatch()));
+ }
+
+ if (type.getName().equals(EcompLoggerError.class.getName())) {
+ return (V) new EcompLoggerError(new EcompMDCWrapper(new Stopwatch()));
+ }
+
+ return null;
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java
new file mode 100644
index 0000000000..2405a0eadf
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompLoggerMetric.java
@@ -0,0 +1,207 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ALERT_SEVERITY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_CLASS_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_INSTANCE_UUID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD1;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD2;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD3;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD4;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PROCESS_KEY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_REMOTE_HOST;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_DESC;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_STATUS_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_ENTITY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_SERVICE_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_VIRTUAL_ENTITY;
+
+import org.openecomp.sdc.common.ecomplog.Enums.LogMarkers;
+import org.openecomp.sdc.common.ecomplog.Enums.Severity;
+import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper;
+import org.slf4j.MarkerFactory;
+
+
+public class EcompLoggerMetric extends EcompLoggerBase{
+ private static EcompLoggerMetric instanceLoggerMetric = (EcompLoggerMetric) EcompLoggerFactory.getLogger(EcompLoggerMetric.class);
+
+ EcompLoggerMetric(IEcompMdcWrapper ecompMdcWrapper) {
+ super(ecompMdcWrapper, MarkerFactory.getMarker(LogMarkers.METRIC_MARKER.text()));
+ }
+
+ public static EcompLoggerMetric getInstance() {
+ return instanceLoggerMetric;
+ }
+
+ @Override
+ public EcompLoggerMetric startTimer() {
+ return (EcompLoggerMetric) super.startTimer();
+ }
+
+ @Override
+ public EcompLoggerMetric setKeyRequestId(String keyRequestId) {
+ return (EcompLoggerMetric) super.setKeyRequestId(keyRequestId);
+ }
+
+ public EcompLoggerMetric stopTimer() {
+ ecompMdcWrapper.stopTimer();
+ return this;
+ }
+
+ // automatic parameter this is optional
+ public EcompLoggerMetric setAutoServerFQDN(String serverFQDN) {
+ ecompMdcWrapper.setAutoServerFQDN(serverFQDN);
+ return this;
+ }
+
+ // automatic parameter this is optional
+ public EcompLoggerMetric setAutoServerIPAddress(String serverIPAddress) {
+ ecompMdcWrapper.setAutoServerIPAddress(serverIPAddress);
+ return this;
+ }
+
+ public EcompLoggerMetric setInstanceUUID(String instanceUUID) {
+ ecompMdcWrapper.setInstanceUUID(instanceUUID);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerMetric setOptProcessKey(String processKey) {
+ ecompMdcWrapper.setProcessKey(processKey);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerMetric setOptAlertSeverity(Severity alertSeverity) {
+ ecompMdcWrapper.setAlertSeverity(alertSeverity);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerMetric setOptCustomField1(String customField1) {
+ ecompMdcWrapper.setOptCustomField1(customField1);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerMetric setOptCustomField2(String customField2) {
+ ecompMdcWrapper.setOptCustomField2(customField2);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerMetric setOptCustomField3(String customField3) {
+ ecompMdcWrapper.setOptCustomField3(customField3);
+ return this;
+ }
+
+ // ecomplog optional parameter
+ public EcompLoggerMetric setOptCustomField4(String customField4) {
+ ecompMdcWrapper.setOptCustomField4(customField4);
+ return this;
+ }
+
+ public EcompLoggerMetric setRemoteHost(String remoteHost) {
+ ecompMdcWrapper.setRemoteHost(remoteHost);
+ return this;
+ }
+
+ public EcompLoggerMetric setServiceName(String serviceName) {
+ ecompMdcWrapper.setServiceName(serviceName);
+ return this;
+ }
+
+ public EcompLoggerMetric setStatusCode(String statusCode) {
+ ecompMdcWrapper.setStatusCode(statusCode);
+ return this;
+ }
+
+ public EcompLoggerMetric setPartnerName(String partnerName) {
+ ecompMdcWrapper.setPartnerName(partnerName);
+ return this;
+ }
+
+ public EcompLoggerMetric setResponseCode(int responseCode) {
+ ecompMdcWrapper.setResponseCode(responseCode);
+ return this;
+ }
+
+ public EcompLoggerMetric setResponseDesc(String responseDesc) {
+ ecompMdcWrapper.setResponseDesc(responseDesc);
+ return this;
+ }
+
+ public EcompLoggerMetric setOptServiceInstanceId(String serviceInstanceId) {
+ ecompMdcWrapper.setServiceInstanceId(serviceInstanceId);
+ return this;
+ }
+
+ public EcompLoggerMetric setOptClassName(String className) {
+ ecompMdcWrapper.setClassName(className);
+ return this;
+ }
+
+ public EcompLoggerMetric setTargetEntity(String targetEntity) {
+ ecompMdcWrapper.setTargetEntity(targetEntity);
+ return this;
+ }
+
+ public EcompLoggerMetric setTargetServiceName(String targetServiceName) {
+ ecompMdcWrapper.setTargetServiceName(targetServiceName);
+ return this;
+ }
+
+ public EcompLoggerMetric setTargetVirtualEntity(String targetVirtualEntity) {
+ ecompMdcWrapper.setTargetVirtualEntity(targetVirtualEntity);
+ return this;
+ }
+
+ @Override
+ public EcompLoggerMetric clear () {
+ return (EcompLoggerMetric) super.clear();
+ }
+
+
+ @Override
+ public void initializeMandatoryFields() {
+
+ ecompMdcWrapper.setMandatoryField(MDC_BEGIN_TIMESTAMP);
+ ecompMdcWrapper.setMandatoryField(MDC_END_TIMESTAMP);
+ ecompMdcWrapper.setMandatoryField(MDC_KEY_REQUEST_ID);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVICE_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_PARTNER_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_STATUS_CODE);
+ ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_CODE);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVICE_INSTANCE_ID);
+ ecompMdcWrapper.setMandatoryField(MDC_RESPONSE_DESC);
+ ecompMdcWrapper.setMandatoryField(MDC_ELAPSED_TIME);
+ ecompMdcWrapper.setMandatoryField(MDC_TARGET_ENTITY);
+ ecompMdcWrapper.setMandatoryField(MDC_TARGET_SERVICE_NAME);
+ ecompMdcWrapper.setMandatoryField(MDC_TARGET_VIRTUAL_ENTITY);
+
+ //Theoretically Optional, but practically Mandatory
+ ecompMdcWrapper.setMandatoryField(MDC_SERVER_IP_ADDRESS);
+ ecompMdcWrapper.setMandatoryField(MDC_SERVER_FQDN);
+
+ ecompMdcWrapper.setOptionalField(MDC_INSTANCE_UUID);
+ ecompMdcWrapper.setOptionalField(MDC_ALERT_SEVERITY);
+ ecompMdcWrapper.setOptionalField(MDC_REMOTE_HOST);
+ ecompMdcWrapper.setOptionalField(MDC_CLASS_NAME);
+ ecompMdcWrapper.setOptionalField(MDC_PROCESS_KEY);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD1);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD2);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD3);
+ ecompMdcWrapper.setOptionalField(MDC_OPT_FIELD4);
+
+
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java
new file mode 100644
index 0000000000..1d833ec6f9
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/EcompMDCWrapper.java
@@ -0,0 +1,290 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static java.lang.Integer.valueOf;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ALERT_SEVERITY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_CLASS_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ERROR_DESC;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_INSTANCE_UUID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_KEY_REQUEST_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD1;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD2;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD3;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_OPT_FIELD4;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PARTNER_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_PROCESS_KEY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_REMOTE_HOST;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_RESPONSE_DESC;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_FQDN;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVER_IP_ADDRESS;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_INSTANCE_ID;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_SERVICE_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_STATUS_CODE;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_ENTITY;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_SERVICE_NAME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_TARGET_VIRTUAL_ENTITY;
+
+import java.net.InetAddress;
+import java.util.ArrayList;
+
+import org.openecomp.sdc.common.ecomplog.Enums.Severity;
+import org.openecomp.sdc.common.ecomplog.api.IEcompMdcWrapper;
+import org.openecomp.sdc.common.ecomplog.api.IStopWatch;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+public class EcompMDCWrapper implements IEcompMdcWrapper {
+
+ private static EcompMDCWrapper instanceMdcWrapper = new EcompMDCWrapper(new Stopwatch());
+
+ public static EcompMDCWrapper getInstance() {
+ return instanceMdcWrapper;
+ }
+
+ private IStopWatch stopWatch;
+ protected static Logger log = LoggerFactory.getLogger(EcompMDCWrapper.class.getName());
+ protected ArrayList<String> mandatoryFields = new ArrayList<>();
+ protected ArrayList<String> optionalFields = new ArrayList<>();
+ protected static String hostAddress;
+ protected static String fqdn;
+
+ // in package classes can instantiate this class
+ // to use directly from outside the package usr the getInstance() Method
+ EcompMDCWrapper(IStopWatch stopwatch) {
+ this.stopWatch = stopwatch;
+ }
+
+ static {
+ try {
+ hostAddress = InetAddress.getLocalHost().getHostAddress();
+ fqdn = InetAddress.getByName(hostAddress).getCanonicalHostName();
+ } catch (Exception ex) {
+ log.error("failed to get machine parameters", ex);
+ }
+ }
+
+ @Override
+ public EcompMDCWrapper startTimer() {
+ stopWatch.start();
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper stopTimer() {
+ try {
+ stopWatch.stop();
+ } catch (Exception ex) {
+ log.error("StopWatch failed; probably start was not called before Stopwatch", ex);
+ }
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setClassName(String className) {
+ MDC.put(MDC_CLASS_NAME, className);
+ return this;
+ }
+
+ // automatic parameter this is optional
+ @Override
+ public EcompMDCWrapper setAutoServerFQDN(String serverFQDN) {
+ MDC.put(MDC_SERVER_FQDN, serverFQDN);
+ return this;
+ }
+
+ // automatic parameter this is optional
+ @Override
+ public EcompMDCWrapper setAutoServerIPAddress(String serverIPAddress) {
+ MDC.put(MDC_SERVER_IP_ADDRESS, serverIPAddress);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setInstanceUUID(String instanceUUID) {
+ MDC.put(MDC_INSTANCE_UUID, instanceUUID);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setProcessKey(String processKey) {
+ MDC.put(MDC_PROCESS_KEY, processKey);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setAlertSeverity(Severity alertSeverity) {
+ MDC.put(MDC_ALERT_SEVERITY, String.valueOf(alertSeverity.getSeverityType()));
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setOptCustomField1(String customField1) {
+ MDC.put(MDC_OPT_FIELD1, customField1);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setOptCustomField2(String customField2) {
+ MDC.put(MDC_OPT_FIELD2, customField2);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setOptCustomField3(String customField3) {
+ MDC.put(MDC_OPT_FIELD3, customField3);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setOptCustomField4(String customField4) {
+ MDC.put(MDC_OPT_FIELD4, customField4);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setKeyRequestId(String keyRequestId) {
+ MDC.put(MDC_KEY_REQUEST_ID, keyRequestId); // eg. servletRequest.getSession().getId()
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setRemoteHost(String remoteHost) {
+ MDC.put(MDC_REMOTE_HOST, remoteHost);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setServiceName(String serviceName) {
+ MDC.put(MDC_SERVICE_NAME, serviceName);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setStatusCode(String statusCode) {
+ MDC.put(MDC_STATUS_CODE, statusCode);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setPartnerName(String partnerName) {
+ MDC.put(MDC_PARTNER_NAME, partnerName);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setResponseCode(int responseCode) {
+ MDC.put(MDC_RESPONSE_CODE, Integer.toString(responseCode));
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setResponseDesc(String responseDesc) {
+ MDC.put(MDC_RESPONSE_DESC, responseDesc);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setServiceInstanceId(String serviceInstanceId) {
+ MDC.put(MDC_SERVICE_INSTANCE_ID, serviceInstanceId);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setTargetEntity(String targetEntity) {
+ MDC.put(MDC_TARGET_ENTITY, targetEntity);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setTargetServiceName(String targetServiceName) {
+ MDC.put(MDC_TARGET_SERVICE_NAME, targetServiceName);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setTargetVirtualEntity(String targetVirtualEntity) {
+ MDC.put(MDC_TARGET_VIRTUAL_ENTITY, targetVirtualEntity);
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setErrorCode(int errorCode) {
+ MDC.put(MDC_ERROR_CODE, valueOf(errorCode).toString());
+ return this;
+ }
+
+ @Override
+ public EcompMDCWrapper setErrorDescription(String errorDescription) {
+ MDC.put(MDC_ERROR_DESC, errorDescription);
+ return this;
+ }
+
+ @Override
+ public void validateMandatoryFields() {
+ // this method only checks if the mandatory fields have been initialized
+ String filedNameThatHasNotBeenInitialized = checkMandatoryFieldsExistInMDC();
+
+ if (MDC.getCopyOfContextMap() == null || MDC.getCopyOfContextMap().isEmpty()) {
+ writeLogMDCEmptyError();
+ return;
+ }
+
+ if (!"".equalsIgnoreCase(filedNameThatHasNotBeenInitialized)) {
+ writeLogMissingFieldsError(filedNameThatHasNotBeenInitialized);
+ }
+ }
+
+ protected void writeLogMissingFieldsError(String FiledNameThatHasNotBeenInitialized) {
+ log.error("mandatory parameters for EELF logging, missing fields: %s", FiledNameThatHasNotBeenInitialized);
+ }
+
+ protected void writeLogMDCEmptyError() {
+ log.error("write to log when MDC is empty error");
+ }
+
+ @Override
+ public EcompMDCWrapper clear() {
+ mandatoryFields.forEach(MDC::remove);
+ optionalFields.forEach(MDC::remove);
+ return this;
+ }
+
+ protected String checkMandatoryFieldsExistInMDC() {
+ // this method returns a String of uninitialised fields
+ StringBuilder missingFields = new StringBuilder();
+ mandatoryFields.forEach(field -> {
+ if (isMDCParamEmpty(field)) {
+ missingFields.append(field).append(" ");
+ }
+ });
+ return missingFields.toString();
+ }
+
+ @Override
+ public void setMandatoryField(String parameterName) {
+ mandatoryFields.add(parameterName);
+ }
+
+ @Override
+ public void setOptionalField(String parameterName) {
+ optionalFields.add(parameterName);
+ }
+
+ @Override
+ public boolean isMDCParamEmpty(String mdcKeyName) {
+ String val = MDC.get(mdcKeyName);
+ return (val == null || val.trim().length() == 0);
+ }
+
+ @Override
+ public String getFqdn() {
+ return fqdn;
+ }
+
+ @Override
+ public String getHostAddress() {
+ return hostAddress;
+ }
+} \ No newline at end of file
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java
new file mode 100644
index 0000000000..c6862656bb
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/EcompLoggerErrorCode.java
@@ -0,0 +1,24 @@
+package org.openecomp.sdc.common.ecomplog.Enums;
+
+/**
+ * Created by dd4296 on 12/26/2017.
+ */
+public enum EcompLoggerErrorCode {
+ SUCCESS(0),
+ PERMISSION_ERROR(100),
+ AVAILABILITY_TIMEOUTS_ERROR(200),
+ DATA_ERROR(300),
+ SCHEMA_ERROR(400),
+ BUSINESS_PROCESS_ERROR(500),
+ UNKNOWN_ERROR(900);
+
+ int errorCode;
+
+ EcompLoggerErrorCode(int errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ public int getErrorCode() {
+ return errorCode;
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java
new file mode 100644
index 0000000000..2fc7d7f26f
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogLevel.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.common.ecomplog.Enums;
+
+/**
+ * Created by dd4296 on 12/14/2017.
+ */
+public enum LogLevel {
+ INFO,
+ WARN,
+ DEBUG,
+ ERROR,
+ FATAL
+}
+
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java
new file mode 100644
index 0000000000..b26e8c105d
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/LogMarkers.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.common.ecomplog.Enums;
+
+/**
+ * Created by mm288v on 12/27/2017.
+ * This enum reflects the Marker text in logback.xml file per each ecomp marker
+ */
+public enum LogMarkers {
+ DEBUG_MARKER("DEBUG_MARKER"),
+ ERROR_MARKER("ERROR_MARKER"),
+ AUDIT_MARKER("AUDIT_MARKER"),
+ METRIC_MARKER("METRICS");
+
+ private String text;
+
+ LogMarkers (String text){
+ this.text = text;
+ }
+
+ public String text(){
+ return text;
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java
new file mode 100644
index 0000000000..f842927af2
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/Severity.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.common.ecomplog.Enums;
+
+/**
+ * Created by dd4296 on 12/14/2017.
+ */
+public enum Severity {
+ OK(0),
+ WARNING(1),
+ CRITICAL(2),
+ DOWN(3),
+ UNREACHABLE(4);
+
+ int severityType;
+
+ Severity(int serveryType) {
+ this.severityType = serveryType;
+ }
+
+ public int getSeverityType() {
+ return severityType;
+ }
+}
+
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java
new file mode 100644
index 0000000000..2fdd96f11b
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Enums/StatusCode.java
@@ -0,0 +1,14 @@
+package org.openecomp.sdc.common.ecomplog.Enums;
+
+public enum StatusCode {
+ ERROR("ERROR"),
+ COMPLETE("COMPLETE");
+
+ String statusCode;
+
+ StatusCode(String statusCode){this.statusCode = statusCode;}
+
+ public String getStatusCodeEnum(){
+ return statusCode;
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java
new file mode 100644
index 0000000000..76262e7815
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/Stopwatch.java
@@ -0,0 +1,61 @@
+package org.openecomp.sdc.common.ecomplog;
+
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_BEGIN_TIMESTAMP;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_ELAPSED_TIME;
+import static org.openecomp.sdc.common.ecomplog.api.IEcompLogConfiguration.MDC_END_TIMESTAMP;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.LocalDateTime;
+
+import org.openecomp.sdc.common.ecomplog.api.IStopWatch;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Created by dd4296 on 12/13/2017.
+ * this is local implementation of the stopwatch class from EELF standard with the same interface
+ * can be replaced if needed with EELF lib
+ */
+public class Stopwatch implements IStopWatch {
+
+ private static Logger log = LoggerFactory.getLogger(Stopwatch.class.getName());
+
+ public Stopwatch() {
+ }
+
+ public void start() {
+ if (MDC.get(MDC_BEGIN_TIMESTAMP) == null || MDC.get(MDC_BEGIN_TIMESTAMP).trim().length() == 0)
+ MDC.put(MDC_BEGIN_TIMESTAMP, generatedTimeNow());
+ }
+
+ public void stop() {
+ if (MDC.get(MDC_BEGIN_TIMESTAMP) == null) {
+ log.error("call to stop without calling start first, this is not compliant with EELF format");
+ }
+ MDC.put(MDC_END_TIMESTAMP, generatedTimeNow());
+ setElapsedTime();
+ }
+
+ private void setElapsedTime() {
+
+ try {
+
+ final LocalDateTime startTime = LocalDateTime.parse(MDC.get(MDC_BEGIN_TIMESTAMP));
+ final LocalDateTime endTime = LocalDateTime.parse(MDC.get(MDC_END_TIMESTAMP));
+
+ final Duration timeDifference = Duration.between(startTime, endTime);
+
+ MDC.put(MDC_ELAPSED_TIME, String.valueOf(timeDifference.toMillis()));
+
+ } catch(Exception ex) {
+ log.error("failed to calculate elapsed time",ex);
+ }
+ }
+
+ private String generatedTimeNow() {
+ return String.valueOf(LocalDateTime.now(Clock.systemUTC()));
+ }
+
+} \ No newline at end of file
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java
new file mode 100644
index 0000000000..6521ea78e1
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogConfiguration.java
@@ -0,0 +1,42 @@
+package org.openecomp.sdc.common.ecomplog.api;
+
+public interface IEcompLogConfiguration {
+ String PROPERTY_LOGGING_FILE_NAME = "com.att.ecomplog.logging.file";
+ String PROPERTY_LOGGING_FILE_PATH = "com.att.ecomplog.logging.path";
+ String GENERAL_LOGGER_NAME = "com.att.ecomplog";
+ String METRICS_LOGGER_NAME = "com.att.ecomplog.metrics";
+ String PERF_LOGGER_NAME = "com.att.ecomplog.perf";
+ String POLICY_LOGGER_NAME = "com.att.ecomplog.policy";
+ String SECURITY_LOGGER_NAME = "com.att.ecomplog.security";
+ String SERVER_LOGGER_NAME = "com.att.ecomplog.server";
+ String AUDIT_LOGGER_NAME = "com.att.ecomplog.audit";
+ String ERROR_LOGGER_NAME = "com.att.ecomplog.error";
+ String DEBUG_LOGGER_NAME = "com.att.ecomplog.debug";
+ String MDC_KEY_REQUEST_ID = "RequestId";
+ String MDC_SERVICE_INSTANCE_ID = "ServiceInstanceId";
+ String MDC_SERVICE_NAME = "ServiceName";
+ String MDC_INSTANCE_UUID = "InstanceUUID";
+ String MDC_SERVER_IP_ADDRESS = "ServerIPAddress";
+ String MDC_SERVER_FQDN = "ServerFQDN";
+ String MDC_REMOTE_HOST = "RemoteHost";
+ String MDC_ALERT_SEVERITY = "AlertSeverity";
+ String MDC_BEGIN_TIMESTAMP = "BeginTimestamp";
+ String MDC_END_TIMESTAMP = "EndTimestamp";
+ String MDC_PARTNER_NAME = "PartnerName";
+ String MDC_STATUS_CODE = "StatusCode";
+ String MDC_RESPONSE_CODE = "ResponseCode";
+ String MDC_RESPONSE_DESC = "ResponseDescription";
+ String MDC_ELAPSED_TIME = "ElapsedTime";
+ String MDC_PROCESS_KEY = "ProcessKey";
+ String MDC_TARGET_ENTITY = "TargetEntity";
+ String MDC_TARGET_SERVICE_NAME = "TargetServiceName";
+ String MDC_TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity";
+ String MDC_ERROR_CATEGORY = "ErrorCategory";
+ String MDC_ERROR_CODE = "ErrorCode";
+ String MDC_ERROR_DESC = "ErrorDescription";
+ String MDC_CLASS_NAME = "ClassName";
+ String MDC_OPT_FIELD1 = "CustomField1";
+ String MDC_OPT_FIELD2 = "CustomField2";
+ String MDC_OPT_FIELD3 = "CustomField3";
+ String MDC_OPT_FIELD4 = "CustomField4";
+} \ No newline at end of file
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java
new file mode 100644
index 0000000000..569343eaf6
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompLogger.java
@@ -0,0 +1,14 @@
+package org.openecomp.sdc.common.ecomplog.api;
+
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+
+/**
+ * Created by dd4296 on 12/24/2017.
+ */
+public interface IEcompLogger {
+ void log(LogLevel errorLevel, String message);
+ void initializeMandatoryFields();
+ IEcompLogger clear();
+ IEcompLogger startTimer();
+ IEcompLogger setKeyRequestId(String keyRequestId);
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java
new file mode 100644
index 0000000000..37d77fd6c5
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IEcompMdcWrapper.java
@@ -0,0 +1,75 @@
+package org.openecomp.sdc.common.ecomplog.api;
+
+import org.openecomp.sdc.common.ecomplog.EcompMDCWrapper;
+import org.openecomp.sdc.common.ecomplog.Enums.Severity;
+
+/**
+ * Created by dd4296 on 12/25/2017.
+ */
+public interface IEcompMdcWrapper {
+ EcompMDCWrapper startTimer();
+
+ EcompMDCWrapper stopTimer();
+
+ EcompMDCWrapper setClassName(String className);
+
+ // automatic parameter this is optional
+ EcompMDCWrapper setAutoServerFQDN(String serverFQDN);
+
+ // automatic parameter this is optional
+ EcompMDCWrapper setAutoServerIPAddress(String serverIPAddress);
+
+ EcompMDCWrapper setInstanceUUID(String instanceUUID);
+
+ EcompMDCWrapper setProcessKey(String processKey);
+
+ EcompMDCWrapper setAlertSeverity(Severity alertSeverity);
+
+ EcompMDCWrapper setOptCustomField1(String customField1);
+
+ EcompMDCWrapper setOptCustomField2(String customField2);
+
+ EcompMDCWrapper setOptCustomField3(String customField3);
+
+ EcompMDCWrapper setOptCustomField4(String customField4);
+
+ EcompMDCWrapper setKeyRequestId(String keyRequestId);
+
+ EcompMDCWrapper setRemoteHost(String remoteHost);
+
+ EcompMDCWrapper setServiceName(String serviceName);
+
+ EcompMDCWrapper setStatusCode(String statusCode);
+
+ EcompMDCWrapper setPartnerName(String partnerName);
+
+ EcompMDCWrapper setResponseCode(int responseCode);
+
+ EcompMDCWrapper setResponseDesc(String responseDesc);
+
+ EcompMDCWrapper setServiceInstanceId(String serviceInstanceId);
+
+ EcompMDCWrapper setTargetEntity(String targetEntity);
+
+ EcompMDCWrapper setTargetServiceName(String targetServiceName);
+
+ EcompMDCWrapper setTargetVirtualEntity(String targetVirtualEntity);
+
+ EcompMDCWrapper setErrorCode(int errorCode);
+
+ EcompMDCWrapper setErrorDescription(String errorDescription);
+
+ EcompMDCWrapper clear();
+
+ void validateMandatoryFields();
+
+ void setMandatoryField(String mdcKeyRequestId);
+
+ void setOptionalField(String mdcKeyRequestId);
+
+ boolean isMDCParamEmpty(String mdcKeyName);
+
+ String getFqdn();
+
+ String getHostAddress();
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java
new file mode 100644
index 0000000000..4f1649cef1
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplog/api/IStopWatch.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.common.ecomplog.api;
+
+/**
+ * Created by dd4296 on 12/14/2017.
+ *
+ * stop watch interface compliant with ecomplog stop watch class
+ */
+public interface IStopWatch {
+ void start();
+ void stop();
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java
new file mode 100644
index 0000000000..57499b340d
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcAudit.java
@@ -0,0 +1,92 @@
+package org.openecomp.sdc.common.ecomplogwrapper;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.ecomplog.EcompLoggerAudit;
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+import org.openecomp.sdc.common.ecomplog.Enums.Severity;
+import org.slf4j.MDC;
+
+
+/**
+ * Created by dd4296 on 12/19/2017.
+ *
+ * audit log for asdc using the ecomplog library
+ * this is adapted for filter classes
+ */
+public class EcompLoggerSdcAudit extends EcompLoggerSdcUtilBase {
+
+ private static String AUDIT_ON = "auditOn";
+ private String className;
+
+ public EcompLoggerSdcAudit(String className) {
+ this.className = className;
+ }
+
+ public void startLog() {
+ EcompLoggerAudit
+ .getInstance()
+ .clear()
+ .startTimer();
+ MDC.put(AUDIT_ON, "true");
+ }
+
+ public static boolean isFlowBeingTakenCare(){
+ try
+ {
+ if (MDC.get(AUDIT_ON).equals("true")){
+ return true;
+ }
+ return false;
+ }
+ catch (Exception E)
+ {
+ return false;
+ }
+ }
+
+ public void log(HttpServletRequest sr,
+ ContainerRequestContext requestContext,
+ Response.StatusType statusInfo,
+ MultivaluedMap<String, Object> responseHeaders,
+ LogLevel errorLevel,
+ Severity securityLevel,
+ String message) {
+
+ try {
+ EcompLoggerAudit.getInstance()
+ .stopTimer()
+ .setRemoteHost(sr.getRemoteAddr())
+ .setServiceName(getServiceName(requestContext))
+ .setResponseCode(convertHttpCodeToErrorCode(statusInfo.getStatusCode()))
+ .setStatusCode(Integer.toString(statusInfo.getStatusCode()))
+ .setResponseDesc(statusInfo.getReasonPhrase())
+ .setKeyRequestId(getRequestIDfromHeaders(responseHeaders.get(Constants.X_ECOMP_REQUEST_ID_HEADER)))
+
+ .setPartnerName(getPartnerName(
+ requestContext.getHeaderString("user-agent"),
+ requestContext.getHeaderString("USER_ID"),
+ getUrl(requestContext)))
+
+ .setInstanceUUID(requestContext.getHeaderString(Constants.X_ECOMP_INSTANCE_ID_HEADER))
+
+ .setOptServiceInstanceId(requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER))
+ .setOptClassName(className)
+ .setOptAlertSeverity(securityLevel)
+ .setOptCustomField1(requestContext.getMethod() + ": " + getUrl(requestContext))
+ .setOptCustomField2(Integer.toString(statusInfo.getStatusCode()))
+ .log(errorLevel, message);
+ }
+ catch (Exception E)
+ {
+ log.warn("Faild to write to Audit Log. Original Message: {}", message);
+ }
+ finally {
+ MDC.put(AUDIT_ON,"false");
+ }
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java
new file mode 100644
index 0000000000..57e9e8c5a0
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcDebug.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.common.ecomplogwrapper;
+
+import java.util.Arrays;
+
+import org.openecomp.sdc.common.ecomplog.EcompLoggerDebug;
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+
+public class EcompLoggerSdcDebug {
+
+ public void log(LogLevel errorLevel,
+ String uuid,
+ String message,
+ Exception ex) {
+
+ StringBuilder stackTrack = new StringBuilder();
+ Arrays.asList(ex.getStackTrace()).forEach(item -> stackTrack.append(item.toString()).append("\n"));
+
+ EcompLoggerDebug.getInstance()
+ .clear()
+ .startTimer()
+ .setKeyRequestId(uuid)
+ .log(errorLevel, String.format("%s %s", message, stackTrack.toString()));
+ }
+
+ public void log(LogLevel errorLevel,
+ String uuid,
+ String message) {
+
+ EcompLoggerDebug.getInstance()
+ .clear()
+ .startTimer()
+ .setKeyRequestId(uuid)
+ .log(errorLevel, message);
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java
new file mode 100644
index 0000000000..a2478c40eb
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcError.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.common.ecomplogwrapper;
+
+import org.openecomp.sdc.common.ecomplog.EcompLoggerError;
+import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode;
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+
+public class EcompLoggerSdcError {
+
+ public void log(LogLevel errorLevel,
+ EcompLoggerErrorCode errorCodeEnum,
+ String uuid,
+ String errorDescription,
+ String partnerName,
+ String targetEntity,
+ String message) {
+
+ EcompLoggerError.getInstance()
+ .clear()
+ .startTimer()
+ .setErrorDescription(errorDescription)
+ .setErrorCode(errorCodeEnum)
+ .setKeyRequestId(uuid)
+ .setServiceName(partnerName)
+ .setTargetEntity(targetEntity)
+ .log(errorLevel, message);
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java
new file mode 100644
index 0000000000..8603a77d08
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcMetric.java
@@ -0,0 +1,71 @@
+package org.openecomp.sdc.common.ecomplogwrapper;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Response;
+
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.ecomplog.EcompLoggerAudit;
+import org.openecomp.sdc.common.ecomplog.EcompLoggerMetric;
+import org.openecomp.sdc.common.ecomplog.Enums.LogLevel;
+import org.openecomp.sdc.common.ecomplog.Enums.Severity;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+
+/**
+ * Created by dd4296 on 12/20/2017.
+ *
+ * METRIC log for asdc using the ecomplog library
+ */
+public class EcompLoggerSdcMetric extends EcompLoggerSdcUtilBase {
+
+ private String className;
+
+ public EcompLoggerSdcMetric(String className) {
+ this.className = className;
+ }
+
+ public void startLog() {
+ EcompLoggerAudit
+ .getInstance()
+ .clear()
+ .startTimer();
+ }
+
+ public void writeToLog(HttpServletRequest sr,
+ ContainerRequestContext requestContext,
+ Response.StatusType statusInfo,
+ LogLevel errorLevel,
+ Severity securityLevel,
+ String targetEntity,
+ String targetServiceName,
+ String targetVirtualEntity,
+ String message) {
+
+ EcompLoggerMetric.getInstance()
+ .stopTimer()
+ .setRemoteHost(sr.getRemoteAddr())
+ .setServiceName(getServiceName(requestContext))
+ .setResponseCode(statusInfo.getStatusCode())
+ .setStatusCode(Integer.toString(statusInfo.getStatusCode()))
+ .setResponseDesc(statusInfo.getReasonPhrase())
+ .setKeyRequestId(ThreadLocalsHolder.getUuid())
+
+ .setPartnerName(getPartnerName(
+ requestContext.getHeaderString("user-agent"),
+ requestContext.getHeaderString("USER_ID"),
+ getUrl(requestContext)))
+
+ .setInstanceUUID(requestContext.getHeaderString(Constants.X_ECOMP_INSTANCE_ID_HEADER))
+
+ .setOptServiceInstanceId(requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER))
+ .setOptClassName(className)
+ .setOptAlertSeverity(securityLevel)
+ .setOptCustomField1(getUrl(requestContext) + "/" + requestContext.getMethod())
+
+ .setTargetEntity(targetEntity)
+ .setTargetServiceName(targetServiceName)
+ .setTargetVirtualEntity(targetVirtualEntity)
+
+ .log(errorLevel, message);
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java
new file mode 100644
index 0000000000..3fe49c17e6
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/ecomplogwrapper/EcompLoggerSdcUtilBase.java
@@ -0,0 +1,198 @@
+package org.openecomp.sdc.common.ecomplogwrapper;
+
+import static java.net.HttpURLConnection.HTTP_BAD_METHOD;
+import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
+import static java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT;
+import static java.net.HttpURLConnection.HTTP_CONFLICT;
+import static java.net.HttpURLConnection.HTTP_ENTITY_TOO_LARGE;
+import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
+import static java.net.HttpURLConnection.HTTP_GONE;
+import static java.net.HttpURLConnection.HTTP_LENGTH_REQUIRED;
+import static java.net.HttpURLConnection.HTTP_NOT_ACCEPTABLE;
+import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
+import static java.net.HttpURLConnection.HTTP_PAYMENT_REQUIRED;
+import static java.net.HttpURLConnection.HTTP_PRECON_FAILED;
+import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;
+import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG;
+import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
+import static java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE;
+
+import java.util.List;
+import java.util.StringTokenizer;
+
+import javax.ws.rs.container.ContainerRequestContext;
+
+import org.openecomp.sdc.common.ecomplog.Enums.EcompLoggerErrorCode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by dd4296 on 12/20/2017.
+ *
+ * base class for metric and audit ecomplog logging
+ * holding the specific logic for data extraction
+ */
+public class EcompLoggerSdcUtilBase {
+
+ protected static Logger log = LoggerFactory.getLogger(EcompLoggerSdcUtilBase.class.getName());
+
+ String getRequestIDfromHeaders(List<Object> requestHeader) {
+ // this method gets list of type object.
+ // toString method returns the RequestId with brackets.
+ String requestHeaderString = requestHeader.toString();
+ return requestHeaderString.replace("[","").replace("]","");
+ }
+
+
+ // this method translates http error code to ECOMP Logger Error code
+ // this is a naive translation and is not a result of any documented format ECOMP specification
+ protected EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) {
+ if (isSuccessError(httpResponseCode))
+ return EcompLoggerErrorCode.SUCCESS;
+
+ if (isSchemaError(httpResponseCode))
+ return EcompLoggerErrorCode.SCHEMA_ERROR;
+
+ if (isDataError(httpResponseCode))
+ return EcompLoggerErrorCode.DATA_ERROR;
+
+ if (isPermissionsError(httpResponseCode))
+ return EcompLoggerErrorCode.PERMISSION_ERROR;
+
+ if (isTimeoutOrAvailabilityError(httpResponseCode))
+ return EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR;
+
+ if (isBusinessProcessError(httpResponseCode))
+ return EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
+
+
+ return EcompLoggerErrorCode.UNKNOWN_ERROR;
+ }
+
+ private boolean isTimeoutOrAvailabilityError(int httpResponseCode) {
+
+ switch (httpResponseCode) {
+ case HTTP_BAD_REQUEST:
+ case HTTP_UNAUTHORIZED:
+ case HTTP_NOT_FOUND:
+ case HTTP_CLIENT_TIMEOUT:
+ case HTTP_GONE:
+ return true;
+ }
+
+ return false;
+ }
+
+ private boolean isPermissionsError(int httpResponseCode) {
+
+ switch (httpResponseCode) {
+ case HTTP_PAYMENT_REQUIRED:
+ case HTTP_FORBIDDEN:
+ case HTTP_BAD_METHOD:
+ case HTTP_PROXY_AUTH:
+ return true;
+ }
+
+ return false;
+ }
+
+ private boolean isDataError(int httpResponseCode) {
+
+ switch (httpResponseCode) {
+ case HTTP_NOT_ACCEPTABLE:
+ case HTTP_LENGTH_REQUIRED:
+ case HTTP_PRECON_FAILED:
+ case HTTP_REQ_TOO_LONG:
+ case HTTP_ENTITY_TOO_LARGE:
+ case HTTP_UNSUPPORTED_TYPE:
+ return true;
+ }
+
+ return false;
+ }
+
+ private boolean isSchemaError(int httpResponseCode) {
+ return HTTP_CONFLICT == httpResponseCode;
+ }
+
+ private boolean isSuccessError(int httpResponseCode) {
+ return httpResponseCode < 399;
+ }
+
+ private boolean isBusinessProcessError(int httpResponseCode) {
+ return httpResponseCode > 499;
+ }
+
+ protected String getPartnerName(String userAgent, String userId, String url) {
+
+ if (!isNullOrEmpty(userId)) {
+ return userId;
+ }
+
+ String urlUser = getUserIdFromUrl(url);
+
+ if (!isNullOrEmpty(urlUser))
+ return urlUser;
+
+ String userAgentName = getUserIdFromUserAgent(userAgent);
+
+ if (!isNullOrEmpty(userAgentName))
+ return userAgentName;
+
+ return "";
+ }
+
+ private String getUserIdFromUserAgent(String userAgent) {
+ if (userAgent != null && userAgent.length() > 0) {
+ if (userAgent.toLowerCase().contains("firefox")) {
+ return "fireFox_FE";
+ }
+
+ if (userAgent.toLowerCase().contains("msie")) {
+ return "explorer_FE";
+ }
+
+ if (userAgent.toLowerCase().contains("chrome")) {
+ return "chrome_FE";
+ }
+
+ return userAgent;
+ }
+ return null;
+ }
+
+ private String getUserIdFromUrl(String url) {
+ if (url != null && url.toLowerCase().contains("user")) {
+ StringTokenizer st = new StringTokenizer(url, "/");
+ while (st.hasMoreElements()) {
+ if ("user".equalsIgnoreCase(st.nextToken())) {
+ return st.nextToken();
+ }
+ }
+ }
+ return null;
+ }
+
+ protected String getUrl(ContainerRequestContext requestContext) {
+ String url = "";
+
+ try {
+ if (requestContext.getUriInfo() != null && requestContext.getUriInfo().getRequestUri() != null) {
+ url = requestContext.getUriInfo().getRequestUri().toURL().toString();
+ }
+ } catch (Exception ex) {
+ log.error("failed to get url from request context ", ex);
+ }
+
+ return url;
+ }
+
+ private boolean isNullOrEmpty(String str) {
+ return (str == null || str.isEmpty());
+ }
+
+ protected String getServiceName(ContainerRequestContext requestContext) {
+ return (requestContext.getUriInfo().getRequestUri().toString())
+ .replace(requestContext.getUriInfo().getBaseUri().toString(), "/");
+ }
+} \ No newline at end of file
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java
new file mode 100644
index 0000000000..1f25d31944
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/ComparableHttpRequestRetryHandler.java
@@ -0,0 +1,8 @@
+package org.openecomp.sdc.common.http.client.api;
+import org.apache.http.client.HttpRequestRetryHandler;
+
+public interface ComparableHttpRequestRetryHandler extends HttpRequestRetryHandler {
+ public default <T extends HttpRequestRetryHandler> boolean compare(T handler) {
+ return (handler != null && getClass() == handler.getClass());
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java
new file mode 100644
index 0000000000..26518a6456
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClient.java
@@ -0,0 +1,147 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.Properties;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHeaders;
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScheme;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.AuthCache;
+import org.apache.http.client.CredentialsProvider;
+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.HttpPatch;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.auth.BasicScheme;
+import org.apache.http.impl.client.BasicAuthCache;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpClient {
+ private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);
+
+ private final CloseableHttpClient client;
+ private final HttpClientConfigImmutable configImmutable;
+
+ HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) {
+ this.client = client;
+ this.configImmutable = configImmutable;
+ }
+
+ <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
+ HttpGet httpGet = new HttpGet(url);
+ return execute(httpGet, headers, responseBuilder);
+ }
+
+ <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
+ HttpPut httpPut = new HttpPut(url);
+ httpPut.setEntity(entity);
+ return execute(httpPut, headers, responseBuilder);
+ }
+
+ <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
+ HttpPost httpPost = new HttpPost(url);
+ httpPost.setEntity(entity);
+ return execute(httpPost, headers, responseBuilder);
+ }
+
+ <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
+ HttpPatch httpPatch = new HttpPatch(url);
+ httpPatch.setEntity(entity);
+ return execute(httpPatch, headers, responseBuilder);
+ }
+
+ <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
+ HttpDelete httpDelete = new HttpDelete(url);
+ return execute(httpDelete, headers, responseBuilder);
+ }
+
+ void close() {
+ try {
+ client.close();
+ }
+ catch (IOException e) {
+ logger.debug("Close http client failed with exception ", e);
+ }
+ }
+
+ private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
+ if(configImmutable.getHeaders() != null) {
+ configImmutable.getHeaders().forEach((k, v) -> request.addHeader(k, v));
+ }
+
+ if (headers != null) {
+ headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString()));
+ }
+
+ HttpClientContext httpClientContext = null;
+ if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) {
+ httpClientContext = createHttpContext(request.getURI());
+ }
+
+ logger.debug("Execute request {}", request.getRequestLine());
+ try (CloseableHttpResponse response = client.execute(request, httpClientContext)) {
+ return responseBuilder.apply(response);
+ }
+ catch (Exception e) {
+ String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage());
+ BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR);
+ logger.debug("{}: ",description, e);
+
+ throw new HttpExecuteException(description, e);
+ }
+ }
+
+ private HttpClientContext createHttpContext(URI uri) {
+ if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) {
+ return null;
+ }
+
+ CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ int port = getPort(uri);
+ credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port),
+ new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword()));
+
+ HttpClientContext localContext = HttpClientContext.create();
+ localContext.setCredentialsProvider(credentialsProvider);
+
+ AuthCache authCache = new BasicAuthCache();
+ authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme());
+ localContext.setAuthCache(authCache);
+
+ return localContext;
+ }
+
+ private int getPort(URI uri) {
+ int port = uri.getPort();
+ if(port < 0) {
+ if(Constants.HTTPS.equals(uri.getScheme())) {
+ port = 443;
+ }
+ else
+ if (Constants.HTTP.equals(uri.getScheme())) {
+ port = 80;
+ }
+ else {
+ port = AuthScope.ANY_PORT;
+ logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port);
+ }
+ }
+ return port;
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java
new file mode 100644
index 0000000000..bfd3b473b4
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientConfigImmutable.java
@@ -0,0 +1,154 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.common.http.config.BasicAuthorization;
+import org.openecomp.sdc.common.http.config.ClientCertificate;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.openecomp.sdc.common.http.config.Timeouts;
+
+final class HttpClientConfigImmutable {
+
+ private final Map<String, String> headers;
+ private final BasicAuthorization basicAuthorization;
+ private final ClientCertificate clientCertificate;
+ private final Timeouts timeouts;
+ /*
+ * use ComparableHttpRequestRetryHandler.compare instead of default generated equals
+ */
+ private final ComparableHttpRequestRetryHandler retryHandler;
+ private final int numOfRetries;
+
+ static HttpClientConfigImmutable getOrCreate(HttpClientConfig httpClientConfig) {
+ // TODO: retrive from a pool if exist, otherwise create new
+ return new HttpClientConfigImmutable(httpClientConfig);
+ }
+
+ HttpClientConfigImmutable(HttpClientConfig httpClientConfig) {
+ timeouts = httpClientConfig.getTimeouts() != null ? new Timeouts(httpClientConfig.getTimeouts()) : null;
+ basicAuthorization = httpClientConfig.getBasicAuthorization() != null ? new BasicAuthorization(httpClientConfig.getBasicAuthorization()) : null;
+ clientCertificate = httpClientConfig.getClientCertificate() != null ? new ClientCertificate(httpClientConfig.getClientCertificate()) : null;
+ headers = httpClientConfig.getHeaders() != null ? Collections.unmodifiableMap(new HashMap<>(httpClientConfig.getHeaders())) : null;
+ retryHandler = httpClientConfig.getRetryHandler();
+ numOfRetries = httpClientConfig.getNumOfRetries();
+ }
+
+ Map<String, String> getHeaders() {
+ return headers;
+ }
+
+ int getNumOfRetries() {
+ return numOfRetries;
+ }
+
+ String getBasicAuthPassword() {
+ return basicAuthorization != null ? basicAuthorization.getPassword() : null;
+ }
+
+ String getBasicAuthUserName() {
+ return basicAuthorization != null ? basicAuthorization.getUserName() : null;
+ }
+
+ String getClientCertKeyStore() {
+ return clientCertificate != null ? clientCertificate.getKeyStore() : null;
+ }
+
+ String getClientCertKeyPassword() {
+ return clientCertificate != null ? clientCertificate.getKeyStorePassword() : null;
+ }
+
+ ClientCertificate getClientCertificate() {
+ return clientCertificate != null ? new ClientCertificate(clientCertificate) : null;
+ }
+
+ int getReadTimeoutMs() {
+ return timeouts.getReadTimeoutMs();
+ }
+
+ int getConnectTimeoutMs() {
+ return timeouts.getConnectTimeoutMs();
+ }
+
+ int getConnectPoolTimeoutMs() {
+ return timeouts.getConnectPoolTimeoutMs();
+ }
+
+ ComparableHttpRequestRetryHandler getRetryHandler() {
+ return retryHandler;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((basicAuthorization == null) ? 0 : basicAuthorization.hashCode());
+ result = prime * result + ((clientCertificate == null) ? 0 : clientCertificate.hashCode());
+ result = prime * result + ((headers == null) ? 0 : headers.hashCode());
+ result = prime * result + ((retryHandler == null) ? 0 : retryHandler.hashCode());
+ result = prime * result + ((timeouts == null) ? 0 : timeouts.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ HttpClientConfigImmutable other = (HttpClientConfigImmutable) obj;
+ if (basicAuthorization == null) {
+ if (other.basicAuthorization != null)
+ return false;
+ }
+ else if (!basicAuthorization.equals(other.basicAuthorization))
+ return false;
+ if (clientCertificate == null) {
+ if (other.clientCertificate != null)
+ return false;
+ }
+ else if (!clientCertificate.equals(other.clientCertificate))
+ return false;
+ if (headers == null) {
+ if (other.headers != null)
+ return false;
+ }
+ else if (!headers.equals(other.headers))
+ return false;
+ if (retryHandler == null) {
+ if (other.retryHandler != null)
+ return false;
+ }
+ else if (!retryHandler.compare(other.retryHandler))
+ return false;
+ if (timeouts == null) {
+ if (other.timeouts != null)
+ return false;
+ }
+ else if (!timeouts.equals(other.timeouts))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("HttpClientConfigImmutable [basicAuthorization=");
+ builder.append(basicAuthorization);
+ builder.append(", clientCertificate=");
+ builder.append(clientCertificate);
+ builder.append(", retryHandler=");
+ builder.append(retryHandler);
+ builder.append(", timeouts=");
+ builder.append(timeouts);
+ builder.append(", headers=");
+ builder.append(headers);
+ builder.append(", numOfRetries=");
+ builder.append(numOfRetries);
+ builder.append("]");
+ return builder.toString();
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java
new file mode 100644
index 0000000000..c52880cb96
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java
@@ -0,0 +1,51 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import org.apache.http.client.HttpRequestRetryHandler;
+import org.apache.http.client.UserTokenHandler;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.conn.HttpClientConnectionManager;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.http.config.ClientCertificate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpClientFactory {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientFactory.class);
+ private static final UserTokenHandler userTokenHandler = context -> null;
+ private final HttpConnectionMngFactory connectionMngFactory;
+
+ HttpClientFactory(HttpConnectionMngFactory connectionMngFactory) {
+ this.connectionMngFactory = connectionMngFactory;
+ }
+
+ HttpClient createClient(String protocol, HttpClientConfigImmutable config) {
+ LOGGER.debug("Create {} client based on {}", protocol, config);
+
+ ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null;
+ HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate);
+ RequestConfig requestConfig = createClientTimeoutConfiguration(config);
+ CloseableHttpClient client = HttpClients.custom()
+ .setDefaultRequestConfig(requestConfig)
+ .setConnectionManager(connectionManager)
+ .setUserTokenHandler(userTokenHandler)
+ .setRetryHandler(resolveRetryHandler(config))
+ .build();
+
+ return new HttpClient(client, config);
+ }
+
+ private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) {
+ return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null;
+ }
+
+ private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) {
+ return RequestConfig.custom()
+ .setConnectTimeout(config.getConnectTimeoutMs())
+ .setSocketTimeout(config.getReadTimeoutMs())
+ .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs())
+ .build();
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java
new file mode 100644
index 0000000000..6a408c92cd
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpConnectionMngFactory.java
@@ -0,0 +1,117 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.HttpClientConnectionManager;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.ssl.SSLContextBuilder;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.http.config.ClientCertificate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HttpConnectionMngFactory {
+
+ private static final String P12_KEYSTORE_EXTENTION = ".p12";
+ private static final String PFX_KEYSTORE_EXTENTION = ".pfx";
+ private static final String JKS_KEYSTORE_EXTENTION = ".jks";
+
+ private static final String P12_KEYSTORE_TYPE = "pkcs12";
+ private static final String JKS_KEYSTORE_TYPE = "jks";
+
+ private static final Logger logger = LoggerFactory.getLogger(HttpConnectionMngFactory.class);
+ private static final int DEFAULT_CONNECTION_POOL_SIZE = 30;
+ private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5;
+ private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000;
+
+ private Map<ClientCertificate, HttpClientConnectionManager> sslClientConnectionManagers = new ConcurrentHashMap<>();
+ private HttpClientConnectionManager plainClientConnectionManager;
+
+ HttpConnectionMngFactory() {
+ plainClientConnectionManager = createConnectionMng(null);
+ }
+
+ HttpClientConnectionManager getOrCreate(ClientCertificate clientCertificate) {
+ if(clientCertificate == null) {
+ return plainClientConnectionManager;
+ }
+ return sslClientConnectionManagers.computeIfAbsent(clientCertificate, k -> createConnectionMng(clientCertificate));
+ }
+
+ private HttpClientConnectionManager createConnectionMng(ClientCertificate clientCertificate) {
+
+ SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
+ SSLConnectionSocketFactory sslsf = null;
+ try {
+ sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());
+
+ if(clientCertificate != null) {
+ setClientSsl(clientCertificate, sslContextBuilder);
+ }
+ sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
+ }
+ catch (GeneralSecurityException e) {
+ logger.debug("Create SSL connection socket factory failed with exception, use default SSL factory ", e);
+ sslsf = SSLConnectionSocketFactory.getSocketFactory();
+ }
+
+ Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
+ .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory())
+ .register(Constants.HTTPS, sslsf).build();
+
+ PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
+
+ manager.setMaxTotal(DEFAULT_CONNECTION_POOL_SIZE);
+ manager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION_PER_ROUTE);
+ manager.setValidateAfterInactivity(VALIDATE_CONNECTION_AFTER_INACTIVITY_MS);
+
+ return manager;
+ }
+
+ private void setClientSsl(ClientCertificate clientCertificate, SSLContextBuilder sslContextBuilder) {
+ try {
+ char[] keyStorePassword = clientCertificate.getKeyStorePassword().toCharArray();
+ KeyStore clientKeyStore = createClientKeyStore(clientCertificate.getKeyStore(), keyStorePassword);
+ sslContextBuilder.loadKeyMaterial(clientKeyStore, keyStorePassword);
+ logger.debug("#setClientSsl - Set Client Certificate authentication");
+ }
+ catch (IOException | GeneralSecurityException e) {
+ logger.debug("#setClientSsl - Set Client Certificate authentication failed with exception, diasable client SSL authentication ", e);
+ }
+ }
+
+ private KeyStore createClientKeyStore(String keyStorePath, char[] keyStorePassword) throws IOException, GeneralSecurityException {
+ KeyStore keyStore = null;
+ try (InputStream stream = new FileInputStream(keyStorePath)) {
+ keyStore = KeyStore.getInstance(getKeyStoreType(keyStorePath));
+ keyStore.load(stream, keyStorePassword);
+ }
+ return keyStore;
+ }
+
+ private String getKeyStoreType(String keyStore) {
+ if(!StringUtils.isEmpty(keyStore)) {
+ if(keyStore.endsWith(P12_KEYSTORE_EXTENTION) || keyStore.endsWith(PFX_KEYSTORE_EXTENTION)) {
+ return P12_KEYSTORE_TYPE;
+ }
+ else if(keyStore.endsWith(JKS_KEYSTORE_EXTENTION)) {
+ return JKS_KEYSTORE_TYPE;
+ }
+ }
+ return KeyStore.getDefaultType();
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java
new file mode 100644
index 0000000000..6f3638ef2d
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpExecuteException.java
@@ -0,0 +1,24 @@
+package org.openecomp.sdc.common.http.client.api;
+
+public class HttpExecuteException extends Exception {
+
+ private static final long serialVersionUID = 1L;
+
+ public HttpExecuteException(String message) {
+ super (message);
+ }
+
+ public HttpExecuteException(String message, Throwable cause) {
+ super (message, cause);
+ }
+
+ public HttpExecuteException(Throwable cause) {
+ super(cause);
+ }
+
+ @Override
+ public Throwable getCause() {
+ Throwable cause = super.getCause();
+ return cause != null ? cause : this;
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java
new file mode 100644
index 0000000000..57911144a1
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequest.java
@@ -0,0 +1,136 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import org.apache.http.HttpEntity;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+
+import java.util.Properties;
+
+//TODO- remove all static and use instance methods for better testing
+public abstract class HttpRequest {
+
+ static final Properties defaultHeaders = null;
+ static final HttpClientConfig defaultConfig = new HttpClientConfig();
+
+
+
+ private HttpRequest() {
+ }
+
+ /*
+ * GET response as string
+ */
+ public static HttpResponse<String> get(String url) throws HttpExecuteException {
+ return get(url, defaultHeaders, defaultConfig);
+ }
+
+ public static HttpResponse<String> get(String url, Properties headers) throws HttpExecuteException {
+ return get(url, headers, defaultConfig);
+ }
+
+ public static HttpResponse<String> get(String url, HttpClientConfig config) throws HttpExecuteException {
+ return get(url, defaultHeaders, config);
+ }
+
+ public static HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
+ return HttpRequestHandler.get().get(url, headers, config);
+ }
+
+ /*
+ * GET response as byte array
+ */
+ public static HttpResponse<byte[]> getAsByteArray(String url) throws HttpExecuteException {
+ return getAsByteArray(url, defaultHeaders, defaultConfig);
+ }
+
+ public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers) throws HttpExecuteException {
+ return getAsByteArray(url, headers, defaultConfig);
+ }
+
+ public static HttpResponse<byte[]> getAsByteArray(String url, HttpClientConfig config) throws HttpExecuteException {
+ return getAsByteArray(url, defaultHeaders, config);
+ }
+
+ public static HttpResponse<byte[]> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
+ return HttpRequestHandler.get().getAsByteArray(url, headers, config);
+ }
+
+ /*
+ * PUT
+ */
+ public static HttpResponse<String> put(String url, HttpEntity entity) throws HttpExecuteException {
+ return put(url, defaultHeaders, entity, defaultConfig);
+ }
+
+ public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity) throws HttpExecuteException {
+ return put(url, headers, entity, defaultConfig);
+ }
+
+ public static HttpResponse<String> put(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ return put(url, defaultHeaders, entity, config);
+ }
+
+ public static HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ return HttpRequestHandler.get().put(url, headers, entity, config);
+ }
+
+ /*
+ * POST
+ */
+ public static HttpResponse<String> post(String url, HttpEntity entity) throws HttpExecuteException {
+ return post(url, defaultHeaders, entity, defaultConfig);
+ }
+
+ public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity) throws HttpExecuteException {
+ return post(url, headers, entity, defaultConfig);
+ }
+
+ public static HttpResponse<String> post(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ return post(url, defaultHeaders, entity, config);
+ }
+
+ public static HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ return HttpRequestHandler.get().post(url, headers, entity, config);
+ }
+
+ /*
+ * PATCH
+ */
+ public static HttpResponse<String> patch(String url, HttpEntity entity) throws HttpExecuteException {
+ return patch(url, defaultHeaders, entity, defaultConfig);
+ }
+
+ public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity) throws HttpExecuteException {
+ return patch(url, headers, entity, defaultConfig);
+ }
+
+ public static HttpResponse<String> patch(String url, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ return patch(url, defaultHeaders, entity, config);
+ }
+
+ public static HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ return HttpRequestHandler.get().patch(url, headers, entity, config);
+ }
+
+ /*
+ * DELETE
+ */
+ public static HttpResponse<String> delete(String url) throws HttpExecuteException {
+ return delete(url, defaultHeaders, defaultConfig);
+ }
+
+ public static HttpResponse<String> delete(String url, Properties headers) throws HttpExecuteException {
+ return delete(url, headers, defaultConfig);
+ }
+
+ public static HttpResponse<String> delete(String url, HttpClientConfig config) throws HttpExecuteException {
+ return delete(url, defaultHeaders, config);
+ }
+
+ public static HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
+ return HttpRequestHandler.get().delete(url, headers, config);
+ }
+
+ public static void destroy() {
+ HttpRequestHandler.get().destroy();
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java
new file mode 100644
index 0000000000..5722fc9c4e
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpRequestHandler.java
@@ -0,0 +1,114 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.util.EntityUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+
+public enum HttpRequestHandler {
+ HANDLER;
+ private static final String HTTPS_PREFIX = "https://";
+ private static final String HTTP_PREFIX = "http://";
+
+ private Map<HttpClientConfigImmutable, HttpClient> clients = new ConcurrentHashMap<>();
+ private HttpClientFactory clientFactory;
+
+ private FunctionThrows<CloseableHttpResponse, HttpResponse<byte[]>, Exception> byteResponseBuilder = (CloseableHttpResponse httpResponse) -> {
+ HttpEntity entity = httpResponse.getEntity();
+ byte[] response = null;
+ if (entity != null) {
+ InputStream content = entity.getContent();
+ if (content != null) {
+ response = IOUtils.toByteArray(content);
+ }
+ }
+ return new HttpResponse<>(response,
+ httpResponse.getStatusLine().getStatusCode(),
+ httpResponse.getStatusLine().getReasonPhrase());
+ };
+
+ private FunctionThrows<CloseableHttpResponse, HttpResponse<String>, Exception> stringResponseBuilder = (CloseableHttpResponse httpResponse) -> {
+ HttpEntity entity = httpResponse.getEntity();
+ String response = null;
+ if (entity != null) {
+ response = EntityUtils.toString(entity);
+ }
+ return new HttpResponse<>(response,
+ httpResponse.getStatusLine().getStatusCode(),
+ httpResponse.getStatusLine().getReasonPhrase());
+ };
+
+ HttpRequestHandler() {
+ HttpConnectionMngFactory connectionMngFactory = new HttpConnectionMngFactory();
+ clientFactory = new HttpClientFactory(connectionMngFactory);
+ }
+
+ static HttpRequestHandler get() {
+ return HANDLER;
+ }
+
+ public HttpResponse<String> get(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
+ HttpClient client = getOrCreateClient(url, config);
+ return client.<String>get(url, headers, stringResponseBuilder);
+ }
+
+ public HttpResponse<byte []> getAsByteArray(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
+ HttpClient client = getOrCreateClient(url, config);
+ return client.<byte[]>get(url, headers, byteResponseBuilder);
+ }
+
+ public HttpResponse<String> put(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ HttpClient client = getOrCreateClient(url, config);
+ return client.<String>put(url, headers, entity, stringResponseBuilder);
+ }
+
+ public HttpResponse<String> post(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ HttpClient client = getOrCreateClient(url, config);
+ return client.<String>post(url, headers, entity, stringResponseBuilder);
+ }
+
+ public HttpResponse<String> patch(String url, Properties headers, HttpEntity entity, HttpClientConfig config) throws HttpExecuteException {
+ HttpClient client = getOrCreateClient(url, config);
+ return client.<String>patch(url, headers, entity, stringResponseBuilder);
+ }
+
+ public HttpResponse<String> delete(String url, Properties headers, HttpClientConfig config) throws HttpExecuteException {
+ HttpClient client = getOrCreateClient(url, config != null ? config : HttpRequest.defaultConfig);
+ return client.<String>delete(url, headers, stringResponseBuilder);
+ }
+
+ public void destroy() {
+ clients.forEach((k, v) -> v.close());
+ clients.clear();
+ }
+
+ private HttpClient getOrCreateClient(String url, HttpClientConfig config) throws HttpExecuteException {
+ String protocol = getProtocol(url);
+ HttpClientConfigImmutable httpClientConfigImmutable = HttpClientConfigImmutable.getOrCreate(config);
+ return clients.computeIfAbsent(httpClientConfigImmutable, k -> createClient(protocol, httpClientConfigImmutable));
+ }
+
+ private HttpClient createClient(String protocol, HttpClientConfigImmutable config) {
+ return clientFactory.createClient(protocol, config);
+ }
+
+ private String getProtocol(String url) throws HttpExecuteException {
+ if (url.startsWith(HTTPS_PREFIX)) {
+ return Constants.HTTPS;
+ }
+ else if (url.startsWith(HTTP_PREFIX)) {
+ return Constants.HTTP;
+ }
+ else {
+ throw new HttpExecuteException(String.format("Failed to create http client. Requested protocol is not supported \"%s\"", url));
+ }
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java
new file mode 100644
index 0000000000..c67345c813
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java
@@ -0,0 +1,48 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import org.apache.commons.lang3.StringUtils;
+
+public class HttpResponse<T> {
+ private final T response;
+ private final int statusCode;
+ private final String description;
+
+ public HttpResponse(T response, int statusCode) {
+ this.response = response;
+ this.statusCode = statusCode;
+ this.description = StringUtils.EMPTY;
+ }
+
+ public HttpResponse(T response, int statusCode, String description) {
+ this.response = response;
+ this.statusCode = statusCode;
+ this.description = description;
+ }
+
+ public T getResponse() {
+ return response;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("HttpResponse [response=");
+ builder.append(response);
+ builder.append(", statusCode=");
+ builder.append(statusCode);
+ builder.append(", description=");
+ builder.append(description);
+ builder.append("]");
+ return builder.toString();
+ }
+
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java
new file mode 100644
index 0000000000..6f34f80071
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/Responses.java
@@ -0,0 +1,10 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import org.apache.http.HttpStatus;
+
+public final class Responses {
+ public static final HttpResponse<String> INTERNAL_SERVER_ERROR = new HttpResponse<>("Internal server error", HttpStatus.SC_INTERNAL_SERVER_ERROR);
+
+ private Responses() {
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java
new file mode 100644
index 0000000000..7776c53035
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RestUtils.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.HttpHeaders;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Properties;
+
+public class RestUtils {
+
+ public static void addBasicAuthHeader(Properties headers, String username, String password) {
+ byte[] credentials = Base64.encodeBase64((username + ":" + password).getBytes(StandardCharsets.UTF_8));
+ headers.setProperty(HttpHeaders.AUTHORIZATION, "Basic " + new String(credentials, StandardCharsets.UTF_8));
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java
new file mode 100644
index 0000000000..3e3b61f0f1
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/RetryHandlers.java
@@ -0,0 +1,24 @@
+package org.openecomp.sdc.common.http.client.api;
+
+import org.apache.http.protocol.HttpContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+public class RetryHandlers {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(RetryHandlers.class);
+
+ private RetryHandlers(){}
+
+ public static ComparableHttpRequestRetryHandler getDefault(int numOfRetries) {
+ return (IOException exception, int executionCount, HttpContext context) -> {
+ LOGGER.debug("failed sending request with exception", exception);
+ LOGGER.debug("try request number: {}", executionCount);
+ return executionCount <= numOfRetries;
+ };
+ }
+
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java
new file mode 100644
index 0000000000..4fb8fadce4
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/BasicAuthorization.java
@@ -0,0 +1,101 @@
+package org.openecomp.sdc.common.http.config;
+
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.security.SecurityUtil;
+
+import fj.data.Either;
+
+public class BasicAuthorization {
+ private String userName;
+ private String password;
+
+ public BasicAuthorization() {
+ }
+
+ public BasicAuthorization(BasicAuthorization basicAuthorization) {
+ setUserName(basicAuthorization.userName);
+ setPassword(basicAuthorization.password, false);
+ }
+
+ public void setUserName(String userName) {
+ validate(userName);
+ this.userName = userName;
+ }
+
+ public void setPassword(String password) {
+ setPassword(password, true);
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+
+ private void setPassword(String password, boolean isEncoded) {
+ validate(password);
+ if(isEncoded) {
+ Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(password);
+ if(passkey.isLeft()) {
+ this.password = passkey.left().value();
+ }
+ else {
+ throw new IllegalArgumentException(passkey.right().value());
+ }
+ }
+ else {
+ this.password = password;
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((password == null) ? 0 : password.hashCode());
+ result = prime * result + ((userName == null) ? 0 : userName.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ BasicAuthorization other = (BasicAuthorization) obj;
+ if (password == null) {
+ if (other.password != null)
+ return false;
+ }
+ else if (!password.equals(other.password))
+ return false;
+ if (userName == null) {
+ if (other.userName != null)
+ return false;
+ }
+ else if (!userName.equals(other.userName))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("BasicAuthentication [userName=");
+ builder.append(userName);
+ builder.append("]");
+ return builder.toString();
+ }
+
+ private void validate(String str) {
+ if(StringUtils.isEmpty(str)) {
+ throw new IllegalArgumentException("BasicAuthorization username and/or password cannot be empty");
+ }
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java
new file mode 100644
index 0000000000..972a4178e0
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ClientCertificate.java
@@ -0,0 +1,100 @@
+package org.openecomp.sdc.common.http.config;
+
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.security.SecurityUtil;
+
+import fj.data.Either;
+
+public class ClientCertificate {
+ private String keyStore;
+ private String keyStorePassword;
+
+ public ClientCertificate() {
+ }
+
+ public ClientCertificate(ClientCertificate clientCertificate) {
+ setKeyStore(clientCertificate.getKeyStore());
+ setKeyStorePassword(clientCertificate.getKeyStorePassword(), false);
+ }
+
+ public void setKeyStore(String keyStore) {
+ validate(keyStore);
+ this.keyStore = keyStore;
+ }
+
+ public void setKeyStorePassword(String keyStorePassword) {
+ setKeyStorePassword(keyStorePassword, true);
+ }
+
+ private void setKeyStorePassword(String keyStorePassword, boolean isEncoded) {
+ validate(keyStorePassword);
+ if(isEncoded) {
+ Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(keyStorePassword);
+ if (passkey.isLeft()) {
+ this.keyStorePassword = passkey.left().value();
+ }
+ else {
+ throw new IllegalArgumentException(passkey.right().value());
+ }
+ }
+ else {
+ this.keyStorePassword = keyStorePassword;
+ }
+ }
+
+ public String getKeyStore() {
+ return keyStore;
+ }
+
+ public String getKeyStorePassword() {
+ return keyStorePassword;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((keyStore == null) ? 0 : keyStore.hashCode());
+ result = prime * result + ((keyStorePassword == null) ? 0 : keyStorePassword.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ClientCertificate other = (ClientCertificate) obj;
+ if (keyStore == null) {
+ if (other.keyStore != null)
+ return false;
+ }
+ else if (!keyStore.equals(other.keyStore))
+ return false;
+ if (keyStorePassword == null) {
+ if (other.keyStorePassword != null)
+ return false;
+ }
+ else if (!keyStorePassword.equals(other.keyStorePassword))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("ClientCertificate [keyStore=");
+ builder.append(keyStore);
+ builder.append("]");
+ return builder.toString();
+ }
+
+ private void validate(String str) {
+ if(StringUtils.isEmpty(str)) {
+ throw new IllegalArgumentException("ClientCertificate keystore and/or kestorePassword cannot be empty");
+ }
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java
new file mode 100644
index 0000000000..d1e1733565
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/ExternalServiceConfig.java
@@ -0,0 +1,35 @@
+package org.openecomp.sdc.common.http.config;
+
+public class ExternalServiceConfig {
+
+ private HttpRequestConfig httpRequestConfig;
+ private HttpClientConfig httpClientConfig;
+
+ public HttpRequestConfig getHttpRequestConfig() {
+ return httpRequestConfig;
+ }
+
+ public void setHttpRequestConfig(HttpRequestConfig httpRequestConfig) {
+ this.httpRequestConfig = httpRequestConfig;
+ }
+
+ public HttpClientConfig getHttpClientConfig() {
+ return httpClientConfig;
+ }
+
+ public void setHttpClientConfig(HttpClientConfig httpClientConfig) {
+ this.httpClientConfig = httpClientConfig;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("ExternalServiceConfig [httpRequestConfig=");
+ builder.append(httpRequestConfig);
+ builder.append(", httpClientConfig=");
+ builder.append(httpClientConfig);
+ builder.append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java
new file mode 100644
index 0000000000..69789957b4
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpClientConfig.java
@@ -0,0 +1,99 @@
+package org.openecomp.sdc.common.http.config;
+
+import java.util.Map;
+
+import org.openecomp.sdc.common.http.client.api.ComparableHttpRequestRetryHandler;
+
+public class HttpClientConfig {
+
+ private BasicAuthorization basicAuthorization;
+ private ClientCertificate clientCertificate;
+ private ComparableHttpRequestRetryHandler retryHandler;
+ private Timeouts timeouts = Timeouts.DEFAULT;
+ private Map<String, String> headers;
+ private int numOfRetries;
+
+ public HttpClientConfig() {
+ }
+
+ public HttpClientConfig(Timeouts timeouts) {
+ setTimeouts(timeouts);
+ }
+
+ public HttpClientConfig(Timeouts timeouts, ClientCertificate clientCertificate) {
+ setTimeouts(timeouts);
+ setClientCertificate(clientCertificate);
+ }
+
+ public HttpClientConfig(Timeouts timeouts, BasicAuthorization basicAuthorization) {
+ setTimeouts(timeouts);
+ setBasicAuthorization(basicAuthorization);
+ }
+
+ public ComparableHttpRequestRetryHandler getRetryHandler() {
+ return retryHandler;
+ }
+
+ public void setRetryHandler(ComparableHttpRequestRetryHandler retryHandler) {
+ this.retryHandler = retryHandler;
+ }
+
+ public Timeouts getTimeouts() {
+ return timeouts;
+ }
+
+ public void setTimeouts(Timeouts timeouts) {
+ this.timeouts = timeouts;
+ }
+
+ public BasicAuthorization getBasicAuthorization() {
+ return basicAuthorization;
+ }
+
+ public void setBasicAuthorization(BasicAuthorization basicAuthorization) {
+ this.basicAuthorization = basicAuthorization;
+ }
+
+ public ClientCertificate getClientCertificate() {
+ return clientCertificate;
+ }
+
+ public void setClientCertificate(ClientCertificate clientCertificate) {
+ this.clientCertificate = clientCertificate;
+ }
+
+ public Map<String, String> getHeaders() {
+ return headers;
+ }
+
+ public void setHeaders(Map<String, String> headers) {
+ this.headers = headers;
+ }
+
+ public int getNumOfRetries() {
+ return numOfRetries;
+ }
+
+ public void setNumOfRetries(int numOfRetries) {
+ this.numOfRetries = numOfRetries;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("HttpClientConfig [basicAuthorization=");
+ builder.append(basicAuthorization);
+ builder.append(", clientCertificate=");
+ builder.append(clientCertificate);
+ builder.append(", retryHandler=");
+ builder.append(retryHandler);
+ builder.append(", timeouts=");
+ builder.append(timeouts);
+ builder.append(", headers=");
+ builder.append(headers);
+ builder.append(", numOfRetries=");
+ builder.append(numOfRetries);
+ builder.append("]");
+ return builder.toString();
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java
new file mode 100644
index 0000000000..8ea8e1f600
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/HttpRequestConfig.java
@@ -0,0 +1,40 @@
+package org.openecomp.sdc.common.http.config;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpRequestConfig {
+
+ private String serverRootUrl;
+ private Map<String, String> resourceNamespaces;
+
+ public String getServerRootUrl() {
+ return serverRootUrl;
+ }
+
+ public void setServerRootUrl(String serverRootUrl) {
+ this.serverRootUrl = serverRootUrl;
+ }
+
+ public Map<String, String> getResourceNamespaces() {
+ if(resourceNamespaces == null) {
+ resourceNamespaces = new HashMap<>();
+ }
+ return resourceNamespaces;
+ }
+
+ public void setResourceNamespaces(Map<String, String> resourceNamespaces) {
+ this.resourceNamespaces = resourceNamespaces;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("HttpRequestConfig [serverRootUrl=");
+ builder.append(serverRootUrl);
+ builder.append(", resourceNamespaces=");
+ builder.append(resourceNamespaces);
+ builder.append("]");
+ return builder.toString();
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java
new file mode 100644
index 0000000000..d759b3eef4
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/config/Timeouts.java
@@ -0,0 +1,102 @@
+package org.openecomp.sdc.common.http.config;
+
+public class Timeouts {
+
+ private static final int DEFAULT_TIMEOUT_MS = 15000;
+ private int connectTimeoutMs = DEFAULT_TIMEOUT_MS;
+ private int readTimeoutMs = DEFAULT_TIMEOUT_MS;
+ private int connectPoolTimeoutMs = DEFAULT_TIMEOUT_MS;
+
+ public static final Timeouts DEFAULT;
+ static {
+ DEFAULT = new Timeouts();
+ }
+
+ private Timeouts() {
+ }
+
+ public Timeouts(int connectTimeoutMs, int readTimeoutMs) {
+ setConnectTimeoutMs(connectTimeoutMs);
+ setReadTimeoutMs(readTimeoutMs);
+ }
+
+ public Timeouts(Timeouts timeouts) {
+ setReadTimeoutMs(timeouts.readTimeoutMs);
+ setConnectTimeoutMs(timeouts.connectTimeoutMs);
+ setConnectPoolTimeoutMs(timeouts.connectPoolTimeoutMs);
+ }
+
+ public int getConnectTimeoutMs() {
+ return connectTimeoutMs;
+ }
+
+ public void setConnectTimeoutMs(int connectTimeoutMs) {
+ validate(connectTimeoutMs);
+ this.connectTimeoutMs = connectTimeoutMs;
+ }
+
+ public int getReadTimeoutMs() {
+ return readTimeoutMs;
+ }
+
+ public void setReadTimeoutMs(int readTimeoutMs) {
+ validate(readTimeoutMs);
+ this.readTimeoutMs = readTimeoutMs;
+ }
+
+ public int getConnectPoolTimeoutMs() {
+ return connectPoolTimeoutMs;
+ }
+
+ public void setConnectPoolTimeoutMs(int connectPoolTimeoutMs) {
+ validate(connectPoolTimeoutMs);
+ this.connectPoolTimeoutMs = connectPoolTimeoutMs;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + connectPoolTimeoutMs;
+ result = prime * result + connectTimeoutMs;
+ result = prime * result + readTimeoutMs;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Timeouts other = (Timeouts) obj;
+ if (connectPoolTimeoutMs != other.connectPoolTimeoutMs)
+ return false;
+ if (connectTimeoutMs != other.connectTimeoutMs)
+ return false;
+ if (readTimeoutMs != other.readTimeoutMs)
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("Timeouts [connectTimeoutMs=");
+ builder.append(connectTimeoutMs);
+ builder.append(", readTimeoutMs=");
+ builder.append(readTimeoutMs);
+ builder.append(", connectPoolTimeoutMs=");
+ builder.append(connectPoolTimeoutMs);
+ builder.append("]");
+ return builder.toString();
+ }
+
+ private void validate(int timeout) {
+ if(timeout <= 0) {
+ throw new IllegalArgumentException("Timeout values cannot be less than zero");
+ }
+ }
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java
deleted file mode 100644
index 8deb3d7d64..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/IRestClient.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.rest.api;
-
-import java.util.Properties;
-
-/**
- * This interface describe the methods of the REST generic client. Each method
- * will receive the destination URI and specific list of headers. With this
- * information the REST Client will create a request to the specific REST Web
- * server. Error from the REST Web server will be return by proprietary
- * exception object.
- *
- * @author esofer
- *
- */
-public interface IRestClient {
-
- /**
- * This method will return resource according to the given URI.
- *
- * @param uri
- * Full URL path to the desire resource.
- * @param headers
- * - list of headers in format of name and value, to be add as
- * part of the HTTP request.
- * @return JSON representation of the requested resource.
- */
- public RestResponse doGET(String uri, Properties headers);
-
- /**
- * This method will CREATE resource according to the given URI.
- *
- * @param uri
- * Full URL path to the desire resource.
- * @param headers
- * - list of headers in format of name and value, to be add as
- * part of the HTTP request.
- * @param objectToCreate
- * - JSON representation of the resource.
- */
- public RestResponse doPOST(String uri, Properties headers, Object objectToCreate);
-
- /**
- * This method will UPDATE resource according to the given URI.
- *
- * @param uri
- * Full URL path to the desire resource.
- * @param headers
- * - list of headers in format of name and value, to be add as
- * part of the HTTP request.
- * @param objectToUpdate
- * - JSON representation of the resource.
- */
- public RestResponse doPUT(String uri, Properties headers, Object objectToUpdate);
-
- /**
- * This method will return resource according to the given URI.
- *
- * @param uri
- * Full URL path to the desire resource.
- * @param headers
- * - list of headers in format of name and value, to be add as
- * part of the HTTP request.
- *
- */
- public RestResponse doDELETE(String uri, Properties headers);
-
- /**
- * initialize the rest client instance. The timeout is infinite.
- */
- public boolean init() throws Exception;
-
- /**
- * initialize the rest client instance with a given timeout in milliseconds.
- *
- * @param restConfigurationInfo
- */
- public boolean init(RestConfigurationInfo restConfigurationInfo);
-
- /**
- * destroy the connections
- */
- public void destroy();
-}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java
deleted file mode 100644
index 6f652cc8a4..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestClientServiceExeption.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.rest.api;
-
-public class RestClientServiceExeption extends Exception {
-
- private static final long serialVersionUID = 8258477052369440242L;
-
- /**
- * Default Constructor.
- */
- public RestClientServiceExeption() {
- super();
- }
-
- /**
- * Constructor.
- *
- * @param msg
- * String
- */
- public RestClientServiceExeption(String msg) {
- super(msg);
- }
-
- /**
- * Constructor.
- *
- * @param cause
- * Throwable
- */
- public RestClientServiceExeption(Throwable cause) {
- super(cause);
- }
-
- /**
- * Constructor.
- *
- * @param msg
- * String
- * @param cause
- * Throwable
- */
- public RestClientServiceExeption(String msg, Throwable cause) {
- super(msg, cause);
- }
-
- /**
- *
- * @param response
- *
- * public RSClientServiceExeption(ClientResponse response) { super(); this.response = response; }
- *
- * public ClientResponse getResponse() { return response; }
- *
- * public void setResponse(ClientResponse response) { this.response = response; }
- */
-}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java
deleted file mode 100644
index b08cf7332b..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponse.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.rest.api;
-
-public class RestResponse {
-
- private String response;
-
- private String statusDescription;
-
- private int httpStatusCode = 0;
-
- public RestResponse(String response, String statusDescription, int httpStatusCode) {
- super();
- this.response = response;
- this.statusDescription = statusDescription;
- this.httpStatusCode = httpStatusCode;
- }
-
- /**
- * @return the response
- */
- public String getResponse() {
- return response;
- }
-
- /**
- * @param response
- * the response to set
- */
- public void setResponse(String response) {
- this.response = response;
- }
-
- /**
- * @return the httpStatusCode
- */
- public int getHttpStatusCode() {
- return httpStatusCode;
- }
-
- /**
- * @param httpStatusCode
- * the httpStatusCode to set
- */
- public void setHttpStatusCode(int httpStatusCode) {
- this.httpStatusCode = httpStatusCode;
- }
-
- /**
- * @return the statusDescription
- */
- public String getStatusDescription() {
- return statusDescription;
- }
-
- /**
- * @param statusDescription
- * the statusDescription to set
- */
- public void setStatusDescription(String statusDescription) {
- this.statusDescription = statusDescription;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- *
- * ERROR: Error from Rest Server:Status: 400 Message: Bad Request Body:
- * Invalid cell: Cell with cell name dmgrCell22 does not exist!
- *
- */
- public String toString() {
-
- StringBuilder stringBuilder = new StringBuilder();
-
- stringBuilder.append("Status: ");
- stringBuilder.append(httpStatusCode);
- stringBuilder.append("\n");
- stringBuilder.append("Message: ");
- stringBuilder.append(statusDescription);
- stringBuilder.append("\n");
- stringBuilder.append("Body: ");
- stringBuilder.append(response);
-
- return stringBuilder.toString();
-
- }
-}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java
deleted file mode 100644
index 7a4d8ee4cb..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArray.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.rest.api;
-
-import java.util.Arrays;
-
-import org.apache.http.HttpStatus;
-
-public class RestResponseAsByteArray {
-
- private byte[] response;
-
- private String statusDescription;
-
- private int httpStatusCode = 0;
-
- public RestResponseAsByteArray(byte[] response, String statusDescription, int httpStatusCode) {
- super();
- this.response = response;
- this.statusDescription = statusDescription;
- this.httpStatusCode = httpStatusCode;
- }
-
- /**
- * @return the response
- */
- public byte[] getResponse() {
- return response;
- }
-
- /**
- * @param response
- * the response to set
- */
- public void setResponse(byte[] response) {
- this.response = response;
- }
-
- /**
- * @return the httpStatusCode
- */
- public int getHttpStatusCode() {
- return httpStatusCode;
- }
-
- /**
- * @param httpStatusCode
- * the httpStatusCode to set
- */
- public void setHttpStatusCode(int httpStatusCode) {
- this.httpStatusCode = httpStatusCode;
- }
-
- /**
- * @return the statusDescription
- */
- public String getStatusDescription() {
- return statusDescription;
- }
-
- /**
- * @param statusDescription
- * the statusDescription to set
- */
- public void setStatusDescription(String statusDescription) {
- this.statusDescription = statusDescription;
- }
-
- public String toString() {
-
- StringBuilder stringBuilder = new StringBuilder();
-
- stringBuilder.append("Status: ");
- stringBuilder.append(httpStatusCode);
- stringBuilder.append("\n");
- stringBuilder.append("Message: ");
- stringBuilder.append(statusDescription);
- stringBuilder.append("\n");
- stringBuilder.append("Body length: ");
- stringBuilder.append(response == null ? 0 : response.length);
-
- return stringBuilder.toString();
-
- }
-
- public String toPrettyString() {
-
- int maxBytesToDisplay = 200;
-
- StringBuilder stringBuilder = new StringBuilder();
-
- stringBuilder.append("Status: ");
- stringBuilder.append(httpStatusCode);
- stringBuilder.append("\n");
- stringBuilder.append("Message: ");
- stringBuilder.append(statusDescription);
- stringBuilder.append("\n");
- if (httpStatusCode != HttpStatus.SC_OK) {
- stringBuilder.append("Body(maximum " + maxBytesToDisplay + " bytes): ");
- if (response != null) {
- byte[] subArray = Arrays.copyOfRange(response, 0, Math.min(maxBytesToDisplay, response.length));
- if (subArray != null && subArray.length > 0) {
- String responseStr = new String(subArray);
- stringBuilder.append(responseStr);
- }
- }
- } else {
- stringBuilder.append("Body length: ");
- stringBuilder.append(response == null ? 0 : response.length);
- }
-
- return stringBuilder.toString();
-
- }
-}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java
deleted file mode 100644
index eed083ab68..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/HttpRestClientServiceImpl.java
+++ /dev/null
@@ -1,427 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.rest.impl;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-import java.util.Map.Entry;
-import java.util.Properties;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.TrustManager;
-
-import org.apache.http.ConnectionReuseStrategy;
-import org.apache.http.HeaderElement;
-import org.apache.http.HeaderElementIterator;
-import org.apache.http.HeaderIterator;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-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.client.methods.HttpPut;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.conn.ConnectionKeepAliveStrategy;
-import org.apache.http.conn.scheme.Scheme;
-import org.apache.http.conn.ssl.SSLSocketFactory;
-import org.apache.http.conn.ssl.X509HostnameVerifier;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.conn.PoolingClientConnectionManager;
-import org.apache.http.message.BasicHeaderElementIterator;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.CoreConnectionPNames;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.HTTP;
-import org.apache.http.protocol.HttpContext;
-import org.apache.http.util.EntityUtils;
-import org.openecomp.sdc.common.rest.api.IRestClient;
-import org.openecomp.sdc.common.rest.api.RestClientServiceExeption;
-import org.openecomp.sdc.common.rest.api.RestConfigurationInfo;
-import org.openecomp.sdc.common.rest.api.RestResponse;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HttpRestClientServiceImpl implements IRestClient {
-
- private Logger log = LoggerFactory.getLogger(HttpRestClientServiceImpl.class.getName());
-
- public final static int DEFAULT_CONNECTION_POOL_SIZE = 10;
-
- public final static int DEFAULT_CONNECT_TIMEOUT = 10;
-
- private DefaultHttpClient httpClient;
-
- private SSLSocketFactory sslFactory;
-
- private Logger logger = LoggerFactory.getLogger(HttpRestClientServiceImpl.class.getName());
-
- PoolingClientConnectionManager cm = null;
-
- public boolean init() {
-
- return init(new RestConfigurationInfo());
-
- }
-
- public boolean init(RestConfigurationInfo restConfigurationInfo) {
-
- boolean initialized = false;
-
- logger.debug("HttpRestClientServiceImpl::init - start. restConfigurationInfo= {}", restConfigurationInfo);
-
- try {
- createHttpClient(restConfigurationInfo);
-
- initialized = true;
- } catch (KeyManagementException e) {
- String msg = "Failed creating client config for rest. " + e.getMessage();
- logger.error(msg, e);
- // throw new RestClientServiceExeption(e.getMessage());
- } catch (NoSuchAlgorithmException e) {
- String msg = "Failed creating client config for rest. " + e.getMessage();
- logger.error(msg, e);
- // throw new RestClientServiceExeption(msg);
- }
-
- logger.debug("HttpRestClientServiceImpl::init - finish successfully");
-
- return initialized;
- }
-
- public void destroy() {
-
- if (this.httpClient != null) {
- this.httpClient.getConnectionManager().shutdown();
- logger.info("After closing connection Manager of rest Client.");
- }
-
- }
-
- private void createHttpClient(RestConfigurationInfo restConfigurationInfo) throws KeyManagementException, NoSuchAlgorithmException {
-
- PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
-
- Integer connPoolSizeObj = restConfigurationInfo.getConnectionPoolSize();
- int connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
- if (connPoolSizeObj != null) {
- connPoolSize = connPoolSizeObj.intValue();
- if (connPoolSize <= 0) {
- connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
- }
- }
- cm.setMaxTotal(connPoolSize);
-
- this.httpClient = new DefaultHttpClient(cm);
-
- int timeoutInSec = restConfigurationInfo.getReadTimeoutInSec() == null ? 0 : restConfigurationInfo.getReadTimeoutInSec();
- int connectTimeoutInSec = restConfigurationInfo.getConnectTimeoutInSec() == null ? DEFAULT_CONNECT_TIMEOUT : restConfigurationInfo.getConnectTimeoutInSec();
- HttpParams params = new BasicHttpParams();
- params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutInSec * 1000);
- params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutInSec * 1000);
-
- this.httpClient.setParams(params);
-
- Boolean ignoreCertificateObj = restConfigurationInfo.getIgnoreCertificate();
- boolean ignoreCertificate = false;
- if (ignoreCertificateObj != null) {
- ignoreCertificate = ignoreCertificateObj.booleanValue();
- }
- if (ignoreCertificate == true) {
-
- this.sslFactory = createSSLSocketFactory();
-
- Scheme scheme = new Scheme("https", 9443, sslFactory);
- this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
- }
-
- // addKeepAlive();
-
- this.cm = cm;
- }
-
- private void addKeepAlive() {
-
- this.httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
-
- public boolean keepAlive(HttpResponse response, HttpContext context) {
- // TODO Auto-generated method stub
- return true;
- }
-
- });
-
- this.httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
-
- public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
- log.debug("============ In getKeepAliveDuration ================= ");
-
- HeaderIterator headerIterator = response.headerIterator(HTTP.CONN_KEEP_ALIVE);
- if (headerIterator != null) {
- HeaderElementIterator it = new BasicHeaderElementIterator(headerIterator);
- while (it.hasNext()) {
- HeaderElement he = it.nextElement();
- String param = he.getName();
- String value = he.getValue();
- if (value != null && param.equalsIgnoreCase("timeout")) {
- try {
- log.debug("============ In getKeepAliveDuration ================= {}", value);
-
- return Long.parseLong(value) * 1000;
- } catch (NumberFormatException ignore) {
- log.error("Failed parsing retrieved value of timeout header.", ignore);
- }
- }
- }
- }
- return 20;
- }
- });
-
- }
-
- protected SSLSocketFactory createSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
- TrustManager easyTrustManager = new javax.net.ssl.X509TrustManager() {
-
- public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
- // TODO Auto-generated method stub
-
- }
-
- public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
- // TODO Auto-generated method stub
-
- }
-
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- // TODO Auto-generated method stub
- return null;
- }
-
- };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
- SSLSocketFactory sslFactory = new SSLSocketFactory(sslContext);
-
- sslFactory.setHostnameVerifier(new X509HostnameVerifier() {
-
- public boolean verify(String arg0, SSLSession arg1) {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void verify(String host, SSLSocket ssl) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public void verify(String host, java.security.cert.X509Certificate cert) throws SSLException {
- // TODO Auto-generated method stub
-
- }
-
- public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
- // TODO Auto-generated method stub
-
- }
-
- });
- return sslFactory;
- }
-
- /**
- * Executes RS-GET to perform FIND.
- *
- * @param headerParameterKey
- * String
- * @param headerParameterValue
- * String
- * @return String
- */
- public RestResponse doGET(String uri, Properties headers) {
- logger.debug("Before executing uri {}. headers = {}", uri, headers);
-
- HttpGet httpGet = new HttpGet(uri);
-
- RestResponse response = execute(httpGet, headers);
-
- return response;
- }
-
- private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {
-
- if (headers != null) {
- for (Entry<Object, Object> entry : headers.entrySet()) {
- httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
- }
- }
-
- }
-
- public RestResponse doPOST(String uri, Properties headers, Object objectToCreate) {
-
- logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers);
-
- HttpPost httpPost = new HttpPost(uri);
-
- if (objectToCreate != null) {
- StringEntity se;
- try {
- se = new StringEntity(objectToCreate.toString());
-
- // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
- // "application/json"));
- httpPost.setEntity(se);
- } catch (UnsupportedEncodingException e) {
- String msg = "Failed creating Entity for post request." + e.getMessage();
- log.error(msg, e);
- return null;
- // throw new RestClientServiceExeption(msg);
- }
- }
-
- RestResponse response = execute(httpPost, headers);
-
- return response;
-
- }
-
- public RestResponse doPUT(String uri, Properties headers, Object objectToCreate) {
-
- logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers);
-
- HttpPut httpPut = new HttpPut(uri);
-
- if (objectToCreate != null) {
- StringEntity se;
- try {
- se = new StringEntity(objectToCreate.toString());
-
- // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
- // "application/json"));
- httpPut.setEntity(se);
- } catch (UnsupportedEncodingException e) {
- String msg = "Failed creating Entity for post request." + e.getMessage();
- // throw new RestClientServiceExeption(msg);
- log.error(msg, e);
- return null;
- }
- }
-
- RestResponse response = execute(httpPut, headers);
-
- return response;
- }
-
- private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) {
-
- String response = null;
- String statusDesc = null;
- int statusCode = HttpStatus.SC_OK;
-
- try {
-
- addHeadersToRequest(httpRequestBase, headers);
-
- HttpResponse httpResponse = this.httpClient.execute(httpRequestBase);
-
- statusCode = httpResponse.getStatusLine().getStatusCode();
- statusDesc = httpResponse.getStatusLine().getReasonPhrase();
-
- HttpEntity entity = httpResponse.getEntity();
- if (entity != null) {
- response = EntityUtils.toString(entity);
- }
- // ensure the connection gets released to the manager
- EntityUtils.consume(entity);
-
- logResponse(response, httpRequestBase.getMethod());
-
- } catch (Exception exception) {
- httpRequestBase.abort();
- log.error("Failed to execute the {} request {}", httpRequestBase.getMethod(), httpRequestBase.getURI(), exception);
- // processAndThrowException(exception);
- return null;
- }
-
- RestResponse restResponse = new RestResponse(response, statusDesc, statusCode);
-
- if (logger.isDebugEnabled()) {
- URI uri = httpRequestBase.getURI();
- String url = uri.toString();
- logger.debug("After executing uri {}. response = {}", url, restResponse);
- }
-
- return restResponse;
- }
-
- public RestResponse doDELETE(String uri, Properties headers) {
-
- if (logger.isDebugEnabled()) {
- logger.debug("Before executing uri {}. headers = {}", uri, headers);
- }
-
- HttpDelete httpDelete = new HttpDelete(uri);
-
- RestResponse restResponse = execute(httpDelete, headers);
-
- return restResponse;
-
- }
-
- /**
- * This method print the JSON response from the REST Server
- *
- * @param response
- * the JSON response from the REST server
- * @param method
- * name of method
- */
- private void logResponse(String response, String method) {
- logger.debug("{} response = {}", method, response);
- }
-
- /**
- * Exception during client invocation usually it happens when status code starting with 400 or 500 is returned
- *
- * @param exception
- * Exception
- * @throws RSClientServiceExeption
- */
- private void processAndThrowException(Exception exception) throws RestClientServiceExeption {
-
- logger.debug("\n------------------------");
- logger.debug("FAILURE: {}", exception.getMessage());
-
- throw new RestClientServiceExeption(exception);
-
- }
-
-}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java
deleted file mode 100644
index 5bf250f59c..0000000000
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/rest/impl/RestClientServiceFactory.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.common.rest.impl;
-
-import org.openecomp.sdc.common.rest.api.IRestClient;
-import org.openecomp.sdc.common.rest.api.RestConfigurationInfo;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RestClientServiceFactory {
-
- private static Logger log = LoggerFactory.getLogger(RestClientServiceFactory.class.getName());
-
- public static IRestClient createRestClientService(RestConfigurationInfo restConfigurationInfo) {
-
- log.trace("Enter createRestClientService");
-
- HttpRestClientServiceImpl restClientServiceImpl = new HttpRestClientServiceImpl();
-
- boolean result = restClientServiceImpl.init(restConfigurationInfo);
- if (result == false) {
- return null;
- }
-
- log.trace("Exit createRestClientService");
-
- return restClientServiceImpl;
- }
-
-}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java
index ad5471e852..2e31eebd23 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/BaseConfDependentTest.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/test/BaseConfDependent.java
@@ -18,24 +18,24 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.be.components;
+package org.openecomp.sdc.common.test;
import java.io.File;
-import org.junit.BeforeClass;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
-public class BaseConfDependentTest {
+public class BaseConfDependent {
protected static ConfigurationManager configurationManager;
-
- @BeforeClass
- public static void setupBeforeClass() {
-
- ExternalConfiguration.setAppName("catalog-be");
- ExternalConfiguration.setConfigDir("src/test/resources/config");
+ protected static String componentName;
+ protected static String confPath;
+
+
+ protected static void setUp(){
+ ExternalConfiguration.setAppName(componentName);
+ ExternalConfiguration.setConfigDir(confPath);
ExternalConfiguration.listenForChanges();
ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), ExternalConfiguration.getConfigDir() + File.separator + ExternalConfiguration.getAppName());
@@ -43,6 +43,7 @@ public class BaseConfDependentTest {
configurationManager = new ConfigurationManager(configurationSource);
configurationManager.getConfiguration().setTitanInMemoryGraph(true);
-
+
}
+
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java
new file mode 100644
index 0000000000..44f0d251c2
--- /dev/null
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/EitherPair.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.common.util;
+
+import fj.data.Either;
+
+import java.util.function.BiFunction;
+import java.util.function.Function;
+
+public class EitherPair<L, M, R> {
+
+ private Either<L, R> firstEither;
+ private Either<M, R> secondEither;
+
+ private EitherPair(Either<L, R> firstEither, Either<M, R> secondEither) {
+ this.firstEither = firstEither;
+ this.secondEither = secondEither;
+ }
+
+ public static <L, M, R> EitherPair<L, M, R> from(Either<L, R> firstEither,
+ Either<M, R> secondEither) {
+ return new EitherPair<>(firstEither, secondEither);
+ }
+
+ public <X> X either(BiFunction<L, M, X> onLeft, Function<R, X > onRight) {
+ if (firstEither.isRight()) {
+ return onRight.apply(firstEither.right().value());
+ }
+ if (secondEither.isRight()) {
+ return onRight.apply(secondEither.right().value());
+ }
+ return onLeft.apply(firstEither.left().value(), secondEither.left().value());
+ }
+
+
+}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java
index e0d5206066..91222a049c 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java
@@ -1,21 +1,24 @@
package org.openecomp.sdc.common.util;
-import java.util.List;
-
+import org.apache.commons.collections.CollectionUtils;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class HealthCheckUtil {
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
- private static Logger log = LoggerFactory.getLogger(HealthCheckUtil.class.getName());
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
- public static boolean getAggregateStatus(List<HealthCheckInfo> healthCheckInfos) {
+public class HealthCheckUtil {
+ private static Logger log = LoggerFactory.getLogger(HealthCheckUtil.class.getName());
+ public boolean getAggregateStatus(List<HealthCheckInfo> healthCheckInfos, Collection<String> excludes) {
boolean status = true;
-
+ excludes = CollectionUtils.isEmpty(excludes) ? new ArrayList<>() : excludes;
for (HealthCheckInfo healthCheckInfo : healthCheckInfos) {
- if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckInfo.HealthCheckStatus.DOWN)) {
+ if (!excludes.contains(healthCheckInfo.getHealthCheckComponent()) && healthCheckInfo.getHealthCheckStatus().equals(DOWN)) {
log.debug("Component {} is reported as DOWN - Aggregated HC will be DOWN", healthCheckInfo.getHealthCheckComponent());
status = false;
break;
@@ -25,18 +28,16 @@ public class HealthCheckUtil {
return status;
}
- public static String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos, String parentDescription) {
+ public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos, String parentDescription) {
StringBuilder sb = new StringBuilder();
healthCheckInfos.forEach(x -> {
- if (x.getHealthCheckStatus() == HealthCheckInfo.HealthCheckStatus.DOWN) {
+ if (x.getHealthCheckStatus() == DOWN) {
sb.append("Component ").append(x.getHealthCheckComponent()).append(" is Down, ");
}
});
return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
-
-// return description;
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java
index 9022e7246e..1f60632f1b 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java
@@ -54,8 +54,9 @@ public class JsonUtils {
public static boolean isEmptyJson(JsonElement json) {
return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject());
}
-
+
public static boolean isJsonNullOrEmpty(JsonObject json) {
return json.isJsonNull() || isEmptyJson(json);
}
+
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java
index 6c47659dad..004c2d0a67 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.common.util;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Pattern;
-
+import com.google.common.base.CharMatcher;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
@@ -36,7 +30,12 @@ import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.safety.Whitelist;
-import com.google.common.base.CharMatcher;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.regex.Pattern;
public class ValidationUtils {
public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024;
@@ -126,6 +125,12 @@ public class ValidationUtils {
public final static Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4;
public final static Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100;
+ public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100;
+ public final static Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH-1) + "}$");
+
+ public final static Integer POLICY_MAX_LENGTH = 1024;
+ public final static Pattern POLICY_NAME_PATTERN = Pattern
+ .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH-1) + "}$");
public static boolean validateArtifactLabel(String label) {
return ARTIFACT_LABEL_PATTERN.matcher(label).matches();
@@ -367,7 +372,7 @@ public class ValidationUtils {
}
public static String normalizeComponentInstanceName(String name) {
- String[] split = splitComponentInctanceName(name);
+ String[] split = splitComponentInstanceName(name);
StringBuffer sb = new StringBuffer();
for (String splitElement : split) {
sb.append(splitElement);
@@ -383,7 +388,7 @@ public class ValidationUtils {
return split;
}
- private static String[] splitComponentInctanceName(String name) {
+ private static String[] splitComponentInstanceName(String name) {
String normalizedName = name.toLowerCase();
normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
String[] split = normalizedName.split(" ");
@@ -527,5 +532,8 @@ public class ValidationUtils {
String stripped = HtmlCleaner.stripHtml(htmlText, false);
return stripped;
}
-
+
+ public static boolean validateForwardingPathNamePattern(String forwardingPathName) {
+ return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches();
+ }
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java
index 203609aee3..322725b032 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java
@@ -271,6 +271,7 @@ public class YamlToObjectConverter {
Iterable<Object> mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents));
for (Object o : mappedToscaTemplateIt) {
+ System.out.println("Loaded object type:" + o.getClass());
Map<String, Object> map = (Map<String, Object>) o;
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java
index 9ee8fc6be0..7267bd148c 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/Configuration.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,394 +20,401 @@
package org.openecomp.sdc.fe.config;
-import static java.lang.String.format;
+import org.openecomp.sdc.common.api.BasicConfiguration;
import java.util.Date;
import java.util.List;
-import org.openecomp.sdc.common.api.BasicConfiguration;
+import static java.lang.String.format;
public class Configuration extends BasicConfiguration {
- /**
- * fe FQDN
- */
- private String feFqdn;
- /**
- * backend host
- */
- private String beHost;
- /**
- * backend http port
- */
- private Integer beHttpPort;
- /**
- * backend http secured port
- */
- private Integer beSslPort;
-
- private Integer healthCheckSocketTimeoutInMs;
-
- private Integer healthCheckIntervalInSeconds;
-
- private FeMonitoringConfig systemMonitoring;
-
- private String kibanaHost;
-
- private Integer kibanaPort;
-
- private String kibanaProtocol;
-
- private String onboardingForwardContext;
-
- private OnboardingConfig onboarding;
-
- private DcaeConfig dcae;
-
- public String getKibanaProtocol() {
- return kibanaProtocol;
- }
-
- public void setKibanaProtocol(String kibanaProtocol) {
- this.kibanaProtocol = kibanaProtocol;
- }
-
- public String getKibanaHost() {
- return kibanaHost;
- }
-
- public void setKibanaHost(String kibanaHost) {
- this.kibanaHost = kibanaHost;
- }
-
- public Integer getKibanaPort() {
- return kibanaPort;
- }
-
- public void setKibanaPort(Integer kibanaPort) {
- this.kibanaPort = kibanaPort;
- }
-
- public FeMonitoringConfig getSystemMonitoring() {
- return systemMonitoring;
- }
-
- public void setSystemMonitoring(FeMonitoringConfig systemMonitoring) {
- this.systemMonitoring = systemMonitoring;
- }
-
- public Integer getHealthCheckSocketTimeoutInMs() {
- return healthCheckSocketTimeoutInMs;
- }
-
- public Integer getHealthCheckSocketTimeoutInMs(int defaultVal) {
- return healthCheckSocketTimeoutInMs == null ? defaultVal : healthCheckSocketTimeoutInMs;
- }
-
- public void setHealthCheckSocketTimeoutInMs(Integer healthCheckSocketTimeout) {
- this.healthCheckSocketTimeoutInMs = healthCheckSocketTimeout;
- }
-
- public Integer getHealthCheckIntervalInSeconds() {
- return healthCheckIntervalInSeconds;
- }
-
- public Integer getHealthCheckIntervalInSeconds(int defaultVal) {
- return healthCheckIntervalInSeconds == null ? defaultVal : healthCheckIntervalInSeconds;
- }
-
- public void setHealthCheckIntervalInSeconds(Integer healthCheckInterval) {
- this.healthCheckIntervalInSeconds = healthCheckInterval;
- }
-
- /**
- * be http context
- */
- private String beContext;
- /**
- * backend protocol. http | https
- */
- private String beProtocol = "http";
-
- private Date released;
- private String version = "1111";
- private Connection connection;
- private List<String> protocols;
-
- private int threadpoolSize;
- private int requestTimeout;
-
- private List<List<String>> identificationHeaderFields;
- private List<List<String>> optionalHeaderFields;
- private List<String> forwardHeaderFields;
-
- public Date getReleased() {
- return released;
- }
-
- public String getVersion() {
- return version;
- }
-
- public void setReleased(Date released) {
- this.released = released;
- }
-
- public void setVersion(String version) {
- this.version = version;
- }
-
- public Connection getConnection() {
- return connection;
- }
-
- public void setConnection(Connection connection) {
- this.connection = connection;
- }
-
- public List<String> getProtocols() {
- return protocols;
- }
-
- public void setProtocols(List<String> protocols) {
- this.protocols = protocols;
- }
-
- public String getBeHost() {
- return beHost;
- }
-
- public void setBeHost(String beHost) {
- this.beHost = beHost;
- }
-
- public Integer getBeHttpPort() {
- return beHttpPort;
- }
-
- public void setBeHttpPort(Integer beHttpPort) {
- this.beHttpPort = beHttpPort;
- }
-
- public Integer getBeSslPort() {
- return beSslPort;
- }
-
- public void setBeSslPort(Integer beSslPort) {
- this.beSslPort = beSslPort;
- }
-
- public String getBeContext() {
- return beContext;
- }
-
- public void setBeContext(String beContext) {
- this.beContext = beContext;
- }
-
- public String getBeProtocol() {
- return beProtocol;
- }
-
- public void setBeProtocol(String beProtocol) {
- this.beProtocol = beProtocol;
- }
-
- public int getThreadpoolSize() {
- return threadpoolSize;
- }
-
- public void setThreadpoolSize(int threadpoolSize) {
- this.threadpoolSize = threadpoolSize;
- }
-
- public int getRequestTimeout() {
- return requestTimeout;
- }
-
- public void setRequestTimeout(int requestTimeout) {
- this.requestTimeout = requestTimeout;
- }
-
- public List<List<String>> getIdentificationHeaderFields() {
- return identificationHeaderFields;
- }
-
- public void setIdentificationHeaderFields(List<List<String>> identificationHeaderFields) {
- this.identificationHeaderFields = identificationHeaderFields;
- }
-
- public List<List<String>> getOptionalHeaderFields() {
- return optionalHeaderFields;
- }
-
- public void setOptionalHeaderFields(List<List<String>> optionalHeaderFields) {
- this.optionalHeaderFields = optionalHeaderFields;
- }
-
- public List<String> getForwardHeaderFields() {
- return forwardHeaderFields;
- }
+ /**
+ * fe FQDN
+ */
+ private String feFqdn;
+ /**
+ * backend host
+ */
+ private String beHost;
+ /**
+ * backend http port
+ */
+ private Integer beHttpPort;
+ /**
+ * backend http secured port
+ */
+ private Integer beSslPort;
+
+ private Integer healthCheckSocketTimeoutInMs;
+
+ private Integer healthCheckIntervalInSeconds;
+
+ private List<String> healthStatusExclude;
+
+ private FeMonitoringConfig systemMonitoring;
+
+ private String kibanaHost;
+
+ private Integer kibanaPort;
+
+ private String kibanaProtocol;
+
+ private String onboardingForwardContext;
+
+ private OnboardingConfig onboarding;
+
+ private DcaeConfig dcae;
+ /**
+ * be http context
+ */
+ private String beContext;
+ /**
+ * backend protocol. http | https
+ */
+ private String beProtocol = "http";
+ private Date released;
+ private String version = "1111";
+ private Connection connection;
+ private List<String> protocols;
+ private int threadpoolSize;
+ private int requestTimeout;
+ private List<List<String>> identificationHeaderFields;
+ private List<List<String>> optionalHeaderFields;
+ private List<String> forwardHeaderFields;
+
+ public String getKibanaProtocol() {
+ return kibanaProtocol;
+ }
+
+ public void setKibanaProtocol(String kibanaProtocol) {
+ this.kibanaProtocol = kibanaProtocol;
+ }
+
+ public String getKibanaHost() {
+ return kibanaHost;
+ }
+
+ public void setKibanaHost(String kibanaHost) {
+ this.kibanaHost = kibanaHost;
+ }
+
+ public Integer getKibanaPort() {
+ return kibanaPort;
+ }
+
+ public void setKibanaPort(Integer kibanaPort) {
+ this.kibanaPort = kibanaPort;
+ }
+
+ public FeMonitoringConfig getSystemMonitoring() {
+ return systemMonitoring;
+ }
+
+ public void setSystemMonitoring(FeMonitoringConfig systemMonitoring) {
+ this.systemMonitoring = systemMonitoring;
+ }
+
+ public Integer getHealthCheckSocketTimeoutInMs() {
+ return healthCheckSocketTimeoutInMs;
+ }
+
+ public void setHealthCheckSocketTimeoutInMs(Integer healthCheckSocketTimeout) {
+ this.healthCheckSocketTimeoutInMs = healthCheckSocketTimeout;
+ }
+
+ public Integer getHealthCheckSocketTimeoutInMs(int defaultVal) {
+ return healthCheckSocketTimeoutInMs == null ? defaultVal : healthCheckSocketTimeoutInMs;
+ }
+
+ public Integer getHealthCheckIntervalInSeconds() {
+ return healthCheckIntervalInSeconds;
+ }
+
+ public void setHealthCheckIntervalInSeconds(Integer healthCheckInterval) {
+ this.healthCheckIntervalInSeconds = healthCheckInterval;
+ }
+
+ public Integer getHealthCheckIntervalInSeconds(int defaultVal) {
+ return healthCheckIntervalInSeconds == null ? defaultVal : healthCheckIntervalInSeconds;
+ }
- public void setForwardHeaderFields(List<String> forwardHeaderFields) {
- this.forwardHeaderFields = forwardHeaderFields;
- }
+ public Date getReleased() {
+ return released;
+ }
- public String getFeFqdn() {
- return feFqdn;
- }
+ public void setReleased(Date released) {
+ this.released = released;
+ }
- public void setFeFqdn(String feFqdn) {
- this.feFqdn = feFqdn;
- }
+ public String getVersion() {
+ return version;
+ }
- public static class FeMonitoringConfig {
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public Connection getConnection() {
+ return connection;
+ }
+
+ public void setConnection(Connection connection) {
+ this.connection = connection;
+ }
+
+ public List<String> getProtocols() {
+ return protocols;
+ }
+
+ public void setProtocols(List<String> protocols) {
+ this.protocols = protocols;
+ }
+
+ public String getBeHost() {
+ return beHost;
+ }
+
+ public void setBeHost(String beHost) {
+ this.beHost = beHost;
+ }
- Boolean enabled;
- Boolean isProxy;
- Integer probeIntervalInSeconds;
+ public Integer getBeHttpPort() {
+ return beHttpPort;
+ }
- public Boolean getEnabled() {
- return enabled;
- }
+ public void setBeHttpPort(Integer beHttpPort) {
+ this.beHttpPort = beHttpPort;
+ }
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
+ public Integer getBeSslPort() {
+ return beSslPort;
+ }
+
+ public void setBeSslPort(Integer beSslPort) {
+ this.beSslPort = beSslPort;
+ }
+
+ public String getBeContext() {
+ return beContext;
+ }
+
+ public void setBeContext(String beContext) {
+ this.beContext = beContext;
+ }
+
+ public String getBeProtocol() {
+ return beProtocol;
+ }
+
+ public void setBeProtocol(String beProtocol) {
+ this.beProtocol = beProtocol;
+ }
+
+ public int getThreadpoolSize() {
+ return threadpoolSize;
+ }
+
+ public void setThreadpoolSize(int threadpoolSize) {
+ this.threadpoolSize = threadpoolSize;
+ }
+
+ public int getRequestTimeout() {
+ return requestTimeout;
+ }
+
+ public void setRequestTimeout(int requestTimeout) {
+ this.requestTimeout = requestTimeout;
+ }
+
+ public List<List<String>> getIdentificationHeaderFields() {
+ return identificationHeaderFields;
+ }
+
+ public void setIdentificationHeaderFields(List<List<String>> identificationHeaderFields) {
+ this.identificationHeaderFields = identificationHeaderFields;
+ }
+
+ public List<List<String>> getOptionalHeaderFields() {
+ return optionalHeaderFields;
+ }
+
+ public void setOptionalHeaderFields(List<List<String>> optionalHeaderFields) {
+ this.optionalHeaderFields = optionalHeaderFields;
+ }
+
+ public List<String> getForwardHeaderFields() {
+ return forwardHeaderFields;
+ }
+
+ public void setForwardHeaderFields(List<String> forwardHeaderFields) {
+ this.forwardHeaderFields = forwardHeaderFields;
+ }
+
+ public String getFeFqdn() {
+ return feFqdn;
+ }
+
+ public void setFeFqdn(String feFqdn) {
+ this.feFqdn = feFqdn;
+ }
+
+ public String getOnboardingForwardContext() {
+ return onboardingForwardContext;
+ }
+
+ public void setOnboardingForwardContext(String onboardingForwardContext) {
+ this.onboardingForwardContext = onboardingForwardContext;
+ }
+
+ public OnboardingConfig getOnboarding() {
+ return onboarding;
+ }
+
+ public void setOnboarding(OnboardingConfig onboarding) {
+ this.onboarding = onboarding;
+ }
+
+ public DcaeConfig getDcae() {
+ return dcae;
+ }
+
+ public void setDcae(DcaeConfig dcae) {
+ this.dcae = dcae;
+ }
+
+ @Override
+ public String toString() {
+ return new StringBuilder().append(format("backend host: %s%n", beHost))
+ .append(format("backend http port: %s%n", beHttpPort))
+ .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext))
+ .append(format("backend protocol: %s%n", beProtocol))
+ .append(format("onboarding forward context: %s%n", onboardingForwardContext))
+ .append(format("Version: %s%n", version)).append(format("Released: %s%n", released))
+ .append(format("Connecting to database: %s%n", connection))
+ .append(format("Supported protocols: %s%n", protocols)).toString();
+ }
+
+ public static class FeMonitoringConfig {
+
+ Boolean enabled;
+ Boolean isProxy;
+ Integer probeIntervalInSeconds;
+
+ public Boolean getEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(Boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ public Boolean getIsProxy() {
+ return isProxy;
+ }
+
+ public void setIsProxy(Boolean isProxy) {
+ this.isProxy = isProxy;
+ }
+
+ public Integer getProbeIntervalInSeconds() {
+ return probeIntervalInSeconds;
+ }
+
+ public void setProbeIntervalInSeconds(Integer probeIntervalInSeconds) {
+ this.probeIntervalInSeconds = probeIntervalInSeconds;
+ }
+
+ public Integer getProbeIntervalInSeconds(int defaultVal) {
+ return probeIntervalInSeconds == null ? defaultVal : probeIntervalInSeconds;
+ }
+ }
+
+ public static class OnboardingConfig {
+
+ String protocol = "http";
+ String host;
+ Integer port;
+ String healthCheckUri;
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public void setProtocol(String protocol) {
+ this.protocol = protocol;
+ }
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public Integer getPort() {
+ return port;
+ }
+
+ public void setPort(Integer port) {
+ this.port = port;
+ }
+
+ public String getHealthCheckUri() {
+ return healthCheckUri;
+ }
+
+ public void setHealthCheckUri(String healthCheckUri) {
+ this.healthCheckUri = healthCheckUri;
+ }
+ }
+
+ public static class DcaeConfig {
+
+ String protocol = "http";
+ String host;
+ Integer port;
+ String healthCheckUri;
+
+ public String getProtocol() {
+ return protocol;
+ }
+
+ public void setProtocol(String protocol) {
+ this.protocol = protocol;
+ }
+
+ public String getHost() {
+ return host;
+ }
- public Boolean getIsProxy() {
- return isProxy;
- }
+ public void setHost(String host) {
+ this.host = host;
+ }
- public void setIsProxy(Boolean isProxy) {
- this.isProxy = isProxy;
- }
+ public Integer getPort() {
+ return port;
+ }
- public Integer getProbeIntervalInSeconds() {
- return probeIntervalInSeconds;
- }
+ public void setPort(Integer port) {
+ this.port = port;
+ }
- public Integer getProbeIntervalInSeconds(int defaultVal) {
- return probeIntervalInSeconds == null ? defaultVal : probeIntervalInSeconds;
- }
+ public String getHealthCheckUri() {
+ return healthCheckUri;
+ }
- public void setProbeIntervalInSeconds(Integer probeIntervalInSeconds) {
- this.probeIntervalInSeconds = probeIntervalInSeconds;
- }
- }
+ public void setHealthCheckUri(String healthCheckUri) {
+ this.healthCheckUri = healthCheckUri;
+ }
+ }
- public String getOnboardingForwardContext() {
- return onboardingForwardContext;
- }
+ public List<String> getHealthStatusExclude() {
+ return healthStatusExclude;
+ }
- public void setOnboardingForwardContext(String onboardingForwardContext) {
- this.onboardingForwardContext = onboardingForwardContext;
- }
+ public void setHealthStatusExclude(List<String> healthStatusExclude) {
+ this.healthStatusExclude = healthStatusExclude;
+ }
- public OnboardingConfig getOnboarding() {
- return onboarding;
- }
-
- public void setOnboarding(OnboardingConfig onboarding) {
- this.onboarding = onboarding;
- }
-
- public static class OnboardingConfig {
-
- String protocol = "http";
- String host;
- Integer port;
- String healthCheckUri;
-
- public String getProtocol() {
- return protocol;
- }
-
- public void setProtocol(String protocol) {
- this.protocol = protocol;
- }
-
- public String getHost() {
- return host;
- }
-
- public void setHost(String host) {
- this.host = host;
- }
-
- public Integer getPort() {
- return port;
- }
-
- public void setPort(Integer port) {
- this.port = port;
- }
-
- public String getHealthCheckUri() {
- return healthCheckUri;
- }
-
- public void setHealthCheckUri(String healthCheckUri) {
- this.healthCheckUri = healthCheckUri;
- }
- }
-
- public DcaeConfig getDcae() {
- return dcae;
- }
-
- public void setDcae(DcaeConfig dcae) {
- this.dcae = dcae;
- }
-
- public static class DcaeConfig {
-
- String protocol = "http";
- String host;
- Integer port;
- String healthCheckUri;
-
- public String getProtocol() {
- return protocol;
- }
-
- public void setProtocol(String protocol) {
- this.protocol = protocol;
- }
-
- public String getHost() {
- return host;
- }
-
- public void setHost(String host) {
- this.host = host;
- }
-
- public Integer getPort() {
- return port;
- }
-
- public void setPort(Integer port) {
- this.port = port;
- }
-
- public String getHealthCheckUri() {
- return healthCheckUri;
- }
-
- public void setHealthCheckUri(String healthCheckUri) {
- this.healthCheckUri = healthCheckUri;
- }
- }
-
- @Override
- public String toString() {
- return new StringBuilder().append(format("backend host: %s%n", beHost))
- .append(format("backend http port: %s%n", beHttpPort))
- .append(format("backend ssl port: %s%n", beSslPort)).append(format("backend context: %s%n", beContext))
- .append(format("backend protocol: %s%n", beProtocol))
- .append(format("onboarding forward context: %s%n", onboardingForwardContext))
- .append(format("Version: %s%n", version)).append(format("Released: %s%n", released))
- .append(format("Connecting to database: %s%n", connection))
- .append(format("Supported protocols: %s%n", protocols)).toString();
- }
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java
index 482be7697d..68078071f3 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/monitoring/FeMonitoringService.java
@@ -20,25 +20,22 @@
package org.openecomp.sdc.fe.monitoring;
-import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.openecomp.sdc.common.http.config.Timeouts;
import org.openecomp.sdc.common.monitoring.MonitoringEvent;
import org.openecomp.sdc.common.monitoring.MonitoringMetricsFetcher;
import org.openecomp.sdc.fe.config.Configuration;
@@ -93,48 +90,22 @@ public class FeMonitoringService {
}
private void processMonitoringEvent(MonitoringEvent monitoringMetrics) {
- CloseableHttpClient httpClient = null;
try {
Configuration config = ((ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR))
.getConfiguration();
String redirectedUrl = String.format(URL, config.getBeProtocol(), config.getBeHost(),
- config.getBeHttpPort());
- httpClient = getHttpClient(config);
- HttpPost httpPost = new HttpPost(redirectedUrl);
+ Constants.HTTPS.equals(config.getBeProtocol()) ? config.getBeSslPort() : config.getBeHttpPort());
+
+ int timeout = 3000;
String monitoringMetricsJson = gson.toJson(monitoringMetrics);
- HttpEntity myEntity = new StringEntity(monitoringMetricsJson);
- httpPost.setEntity(myEntity);
- httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
- int beResponseStatus;
- CloseableHttpResponse beResponse;
- try {
- beResponse = httpClient.execute(httpPost);
- beResponseStatus = beResponse.getStatusLine().getStatusCode();
- if (beResponseStatus != HttpStatus.SC_OK) {
- monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus);
- }
- } catch (Exception e) {
- monitoringLogger.error("Monitoring error when trying to connect to BE", e);
- }
+ HttpEntity myEntity = new StringEntity(monitoringMetricsJson, ContentType.APPLICATION_JSON);
+ HttpResponse<String> resposne = HttpRequest.post(redirectedUrl, myEntity, new HttpClientConfig(new Timeouts(timeout, timeout)));
+ int beResponseStatus = resposne.getStatusCode();
+ if (beResponseStatus != HttpStatus.SC_OK) {
+ monitoringLogger.error("Unexpected HTTP response from BE : {}", beResponseStatus);
+ }
} catch (Exception e) {
- monitoringLogger.error("Unexpected monitoring error", e);
- } finally {
- if (httpClient != null) {
- try {
- httpClient.close();
- } catch (IOException e) {
- }
- }
+ monitoringLogger.error("Monitoring BE failed with exception ", e);
}
}
-
- private CloseableHttpClient getHttpClient(Configuration config) {
- int timeout = 3000;
- RequestConfig.Builder requestBuilder = RequestConfig.custom();
- requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout);
-
- HttpClientBuilder builder = HttpClientBuilder.create();
- builder.setDefaultRequestConfig(requestBuilder.build());
- return builder.build();
- }
}
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java
index 15508c540f..0604e80ffc 100644
--- a/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java
+++ b/common-app-api/src/test/java/org/openecomp/sdc/be/config/ConfigurationTest.java
@@ -1433,7 +1433,7 @@ public class ConfigurationTest {
@Test
public void testGetDefaultImports() throws Exception {
Configuration testSubject;
- LinkedList<Map<String, Map<String, String>>> result;
+ List<Map<String, Map<String, String>>> result;
// default test
testSubject = createTestSubject();
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArrayTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArrayTest.java
deleted file mode 100644
index c1bcae31cd..0000000000
--- a/common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseAsByteArrayTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package org.openecomp.sdc.common.rest.api;
-
-import org.junit.Test;
-
-
-public class RestResponseAsByteArrayTest {
-
- private RestResponseAsByteArray createTestSubject() {
- return new RestResponseAsByteArray(null, "", 0);
- }
-
-
- @Test
- public void testGetResponse() throws Exception {
- RestResponseAsByteArray testSubject;
- byte[] result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getResponse();
- }
-
-
- @Test
- public void testSetResponse() throws Exception {
- RestResponseAsByteArray testSubject;
- byte[] response = new byte[] { ' ' };
-
- // default test
- testSubject = createTestSubject();
- testSubject.setResponse(response);
- }
-
-
- @Test
- public void testGetHttpStatusCode() throws Exception {
- RestResponseAsByteArray testSubject;
- int result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getHttpStatusCode();
- }
-
-
- @Test
- public void testSetHttpStatusCode() throws Exception {
- RestResponseAsByteArray testSubject;
- int httpStatusCode = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setHttpStatusCode(httpStatusCode);
- }
-
-
- @Test
- public void testGetStatusDescription() throws Exception {
- RestResponseAsByteArray testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getStatusDescription();
- }
-
-
- @Test
- public void testSetStatusDescription() throws Exception {
- RestResponseAsByteArray testSubject;
- String statusDescription = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setStatusDescription(statusDescription);
- }
-
-
- @Test
- public void testToString() throws Exception {
- RestResponseAsByteArray testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.toString();
- }
-
-
- @Test
- public void testToPrettyString() throws Exception {
- RestResponseAsByteArray testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.toPrettyString();
- }
-} \ No newline at end of file
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseTest.java
deleted file mode 100644
index 1ca37b16df..0000000000
--- a/common-app-api/src/test/java/org/openecomp/sdc/common/rest/api/RestResponseTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.openecomp.sdc.common.rest.api;
-
-import org.junit.Test;
-
-
-public class RestResponseTest {
-
- private RestResponse createTestSubject() {
- return new RestResponse("", "", 0);
- }
-
-
- @Test
- public void testGetResponse() throws Exception {
- RestResponse testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getResponse();
- }
-
-
- @Test
- public void testSetResponse() throws Exception {
- RestResponse testSubject;
- String response = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setResponse(response);
- }
-
-
- @Test
- public void testGetHttpStatusCode() throws Exception {
- RestResponse testSubject;
- int result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getHttpStatusCode();
- }
-
-
- @Test
- public void testSetHttpStatusCode() throws Exception {
- RestResponse testSubject;
- int httpStatusCode = 0;
-
- // default test
- testSubject = createTestSubject();
- testSubject.setHttpStatusCode(httpStatusCode);
- }
-
-
- @Test
- public void testGetStatusDescription() throws Exception {
- RestResponse testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getStatusDescription();
- }
-
-
- @Test
- public void testSetStatusDescription() throws Exception {
- RestResponse testSubject;
- String statusDescription = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setStatusDescription(statusDescription);
- }
-
-
- @Test
- public void testToString() throws Exception {
- RestResponse testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.toString();
- }
-} \ No newline at end of file
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/E2EHttpClientTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/E2EHttpClientTest.java
new file mode 100644
index 0000000000..9dbb146d5a
--- /dev/null
+++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/E2EHttpClientTest.java
@@ -0,0 +1,83 @@
+package org.openecomp.sdc.common.test;
+
+import java.net.MalformedURLException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.sdc.common.http.client.api.HttpExecuteException;
+import org.openecomp.sdc.common.http.client.api.HttpRequest;
+import org.openecomp.sdc.common.http.client.api.HttpResponse;
+import org.openecomp.sdc.common.http.config.HttpClientConfig;
+import org.openecomp.sdc.common.http.config.Timeouts;
+
+public class E2EHttpClientTest {
+
+ @Ignore
+ @Test
+ public void testSsl() throws MalformedURLException {
+
+ String url = "https://135.76.210.29:2443/certificate-manager-fe/v1";
+// String url = "http://135.76.123.110:1111//aai/v1/aai/cloud-infrastructure/operational-environments/operational-environment/12345";
+ try {
+ HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(10000, 5000));
+
+ HttpResponse<String> response = HttpRequest.get(url, httpClientConfig);
+ System.out.println(response);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Ignore
+ @Test
+ public void testSslMutliThread() throws MalformedURLException {
+
+ String url = "https://135.76.210.29:2443/certificate-manager-fe/v1";
+// String url = "http://135.76.210.29:2080/certificate-manager-fe/v1";
+ String url2 = "http://135.76.123.110:1111//aai/v1/aai/cloud-infrastructure/operational-environments/operational-environment/12345";
+
+ HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(1000, 5000));
+
+ int threadCount = 10;
+ ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+ for (int i = 0; i < threadCount; i++) {
+ Runnable worker = new Runnable() {
+ @Override
+ public void run() {
+ int count = 10;
+ try {
+ int i = 0;
+ while (i < count) {
+ if(i%2==0) {
+ HttpResponse<String> response = HttpRequest.get(url, httpClientConfig);
+ System.out.println("Thead id=" + Thread.currentThread() + " Count = " + ++i + " " + response);
+ }
+ else {
+ HttpResponse<String> response = HttpRequest.get(url2, httpClientConfig);
+ System.out.println("Thead id=" + Thread.currentThread() + " Count = " + ++i + " " + response);
+ }
+ }
+ }
+ catch (HttpExecuteException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ executor.execute(worker);
+ }
+
+ try {
+ executor.awaitTermination(1, TimeUnit.SECONDS);
+ }
+ catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ executor.shutdown();
+ while (!executor.isTerminated())
+ ;
+ }
+}
diff --git a/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml b/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml
index a4ce7cc08c..b4aaef59c7 100644
--- a/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml
+++ b/common-app-api/src/test/resources/config/common/distribution-engine-configuration.yaml
@@ -33,3 +33,35 @@ distributionStatusTopic:
createTopic:
partitionCount: 1
replicationCount: 1
+
+aaiConfig:
+ httpRequestConfig:
+ serverRootUrl: https://127.0.0.1/aai/v1
+ resourceNamespaces:
+ operationalEnvironments: /aai/cloud-infrastructure/operational-environments
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 5000
+ connectTimeoutMs: 1000
+ clientCertificate:
+ keyStore: /opt/app/jetty/base/be/etc/non-prod.jks
+ keyStorePassword: hmXYcznAljMSisdy8zgcag==
+ headers:
+ X-FromAppId: asdc
+ numOfRetries: 3
+
+msoConfig:
+ httpRequestConfig:
+ serverRootUrl: http://127.0.0.1:8080/onap/so/infra/modelDistributions/v1
+ resourceNamespaces:
+ distributions: /distributions
+
+ httpClientConfig:
+ timeouts:
+ readTimeoutMs: 2000
+ connectTimeoutMs: 500
+ basicAuthorization:
+ userName: asdc
+ password: OTLEp5lfVhYdyw5EAtTUBQ==
+ numOfRetries: 3
diff --git a/common-be/pom.xml b/common-be/pom.xml
index 970f533ae5..6a10d8476a 100644
--- a/common-be/pom.xml
+++ b/common-be/pom.xml
@@ -28,27 +28,6 @@
</dependency>
<dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- <version>${codehaus.jackson.core}</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
@@ -61,7 +40,13 @@
<scope>provided</scope>
</dependency>
- <!-- TEST -->
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>${jackson.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@@ -74,33 +59,6 @@
<build>
<pluginManagement>
<plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings
- only. It has no influence on the Maven build itself. -->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>fr.fastconnect</groupId>
- <artifactId>plantuml-maven-plugin</artifactId>
- <versionRange>[1.0.0,)</versionRange>
- <goals>
- <goal>plant</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
-
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
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 5fecac429a..9499529f03 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
@@ -557,4 +557,9 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio
return true;
}
+ /**
+ * Return the type of the actual component - e.g. for a Resource, return the actual VF/CR
+ * @return
+ */
+ public abstract String getActualComponentType();
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java
index 8dac7ea4c4..da432ca971 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.components;
-import java.io.Serializable;
-
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import java.io.Serializable;
+
public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinition implements Serializable {
/**
@@ -192,4 +192,9 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
return super.equals(obj);
}
+ @Override
+ public String getActualComponentType() {
+ return getResourceType().getValue();
+ }
+
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java
index 7a85a763f6..c36c7f053d 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java
@@ -169,4 +169,10 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
return super.equals(obj);
}
+ @Override
+ public String getActualComponentType() {
+
+ return componentType.getValue();
+ }
+
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterDataDefinition.java
index f618458edf..ea47342ce3 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterDataDefinition.java
@@ -20,11 +20,11 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.List;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class AdditionalInfoParameterDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java
index cdfe75d156..94aea6d321 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AdditionalInfoParameterInfo.java
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import java.io.Serializable;
+
public class AdditionalInfoParameterInfo extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ArtifactDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ArtifactDataDefinition.java
index 49c13a09cd..b42ceab945 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ArtifactDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ArtifactDataDefinition.java
@@ -20,15 +20,15 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-
//import com.google.gson.reflect.TypeToken;
public class ArtifactDataDefinition extends ToscaDataDefinition implements Serializable {
@@ -86,6 +86,7 @@ public class ArtifactDataDefinition extends ToscaDataDefinition implements Seria
if (a.getHeatParameters() != null)
this.setHeatParameters(new ArrayList<>(a.getHeatParameters()));
this.setGeneratedFromId( a.getGeneratedFromId());
+ this.setIsFromCsar(a.getIsFromCsar());
}
@@ -350,6 +351,13 @@ public class ArtifactDataDefinition extends ToscaDataDefinition implements Seria
public String getGeneratedFromId() {
return (String) getToscaPresentationValue(JsonPresentationFields.GENERATED_FROM_ID);
}
+ public boolean getIsFromCsar(){
+ Boolean isFromCsar = (Boolean) getToscaPresentationValue(JsonPresentationFields.IS_FROM_CSAR);
+ return isFromCsar == null ? Boolean.FALSE: isFromCsar;
+ }
+ public void setIsFromCsar(Boolean isFromCsar) {
+ setToscaPresentationValue(JsonPresentationFields.IS_FROM_CSAR, isFromCsar);
+ }
public void setGeneratedFromId(String generatedFromId) {
setToscaPresentationValue(JsonPresentationFields.GENERATED_FROM_ID, generatedFromId);
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java
index 5baed964c7..9327499981 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityDataDefinition.java
@@ -20,14 +20,13 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
+import com.google.common.collect.Lists;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import com.google.common.collect.Lists;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
/**
* Represents the capability of the component or component instance
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityTypeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityTypeDataDefinition.java
index 110e08852b..cecb4f1bf9 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityTypeDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CapabilityTypeDataDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-import java.util.List;
-
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import java.io.Serializable;
+import java.util.List;
+
public class CapabilityTypeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java
index be21a70bbc..57270f6eaa 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ComponentInstanceDataDefinition.java
@@ -20,13 +20,13 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.common.util.ValidationUtils;
+import java.io.Serializable;
+
public class ComponentInstanceDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java
index 853e7cf261..590cdb8a5a 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/CompositionDataDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.HashMap;
-import java.util.Map;
-
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import java.util.HashMap;
+import java.util.Map;
+
public class CompositionDataDefinition extends ToscaDataDefinition {
public Map<String, ComponentInstanceDataDefinition> getComponentInstances() {
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/DataTypeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/DataTypeDataDefinition.java
index a048ceb096..923c47de58 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/DataTypeDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/DataTypeDataDefinition.java
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import java.io.Serializable;
+
public class DataTypeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathDataDefinition.java
new file mode 100644
index 0000000000..bf63e20d38
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathDataDefinition.java
@@ -0,0 +1,94 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.DESCRIPTION;
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.PATH_DESTINATION_PORT_NUMBER;
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.PATH_ELEMENT_LIST;
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.PATH_NAME;
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.PATH_PROTOCOL;
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.TOSCA_RESOURCE_NAME;
+import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.UNIQUE_ID;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import java.io.Serializable;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+public class ForwardingPathDataDefinition extends ToscaDataDefinition implements Serializable {
+
+ @JsonCreator
+ public ForwardingPathDataDefinition() {
+ super();
+ }
+
+ public ForwardingPathDataDefinition(String name) {
+ super();
+ setName(name);
+
+ }
+
+ public ForwardingPathDataDefinition(ForwardingPathDataDefinition path) {
+ super();
+ setName(path.getName());
+ setDestinationPortNumber(path.getDestinationPortNumber());
+ setUniqueId(path.getUniqueId());
+ setPathElements(path.getPathElements());
+ setProtocol(path.getProtocol());
+ setDescription(path.getDescription());
+ setToscaResourceName(path.getToscaResourceName());
+ }
+
+ public String getName() {
+ return (String) getToscaPresentationValue(PATH_NAME);
+ }
+
+ public void setName(String name) {
+ setToscaPresentationValue(PATH_NAME, name);
+ }
+
+ public ListDataDefinition<ForwardingPathElementDataDefinition> getPathElements() {
+ return (ListDataDefinition<ForwardingPathElementDataDefinition>) getToscaPresentationValue(PATH_ELEMENT_LIST);
+ }
+
+ public void setPathElements(ListDataDefinition<ForwardingPathElementDataDefinition> pathElements) {
+ setToscaPresentationValue(PATH_ELEMENT_LIST, pathElements);
+ }
+
+ public String getUniqueId() {
+ return (String) getToscaPresentationValue(UNIQUE_ID);
+ }
+
+ public void setUniqueId(String uid) {
+ setToscaPresentationValue(UNIQUE_ID, uid);
+ }
+
+ public String getProtocol() {
+ return (String) getToscaPresentationValue(PATH_PROTOCOL);
+ }
+
+ public void setProtocol(String protocol) {
+ setToscaPresentationValue(PATH_PROTOCOL, protocol);
+ }
+
+ public String getDestinationPortNumber() {
+ return (String) getToscaPresentationValue(PATH_DESTINATION_PORT_NUMBER);
+ }
+
+ public void setDestinationPortNumber(String destinationPortNumber) {
+ setToscaPresentationValue(PATH_DESTINATION_PORT_NUMBER, destinationPortNumber);
+ }
+
+ public String getDescription() {
+ return (String) getToscaPresentationValue(DESCRIPTION);
+ }
+
+ public void setDescription(String description) {
+ setToscaPresentationValue(DESCRIPTION, description);
+ }
+
+ public String getToscaResourceName() {
+ return (String) getToscaPresentationValue(TOSCA_RESOURCE_NAME);
+ }
+
+ public void setToscaResourceName(String toscaResourceName) {
+ setToscaPresentationValue(TOSCA_RESOURCE_NAME, toscaResourceName);
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathElementDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathElementDataDefinition.java
new file mode 100644
index 0000000000..3bbe9cae70
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ForwardingPathElementDataDefinition.java
@@ -0,0 +1,107 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.google.common.base.MoreObjects;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+public class ForwardingPathElementDataDefinition extends ToscaDataDefinition implements Serializable {
+ @JsonCreator
+ public ForwardingPathElementDataDefinition() {
+ super();
+ }
+
+ public ForwardingPathElementDataDefinition(String fromNode, String toNode, String fromCPName, String toCPName , String fromCPOriginId, String toCPOriginId) {
+ super();
+ setFromNode(fromNode);
+ setToNode(toNode);
+ setFromCP(fromCPName);
+ setToCP(toCPName);
+ setFromCPOriginId(fromCPOriginId);
+ setToCPOriginId(toCPOriginId);
+
+ }
+
+ public ForwardingPathElementDataDefinition(ForwardingPathElementDataDefinition pathElement) {
+ super();
+ setFromNode(pathElement.getFromNode());
+ setToNode(pathElement.getToNode());
+ setFromCP(pathElement.getFromCP());
+ setToCP(pathElement.getToCP());
+ setFromCPOriginId(pathElement.getFromCPOriginId());
+ setToCPOriginId(pathElement.getToCPOriginId());
+ }
+
+ public String getFromNode() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.FROM_NODE);
+ }
+
+ public void setFromNode(String fromNode) {
+ setToscaPresentationValue(JsonPresentationFields.FROM_NODE, fromNode);
+ }
+
+ public String getToNode() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TO_NODE);
+ }
+
+ public void setToNode(String toNode) {
+ setToscaPresentationValue(JsonPresentationFields.TO_NODE, toNode);
+ }
+
+ public String getFromCP() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.PATH_FROM_CP);
+ }
+
+ public void setFromCP(String fromCP) {
+ setToscaPresentationValue(JsonPresentationFields.PATH_FROM_CP, fromCP);
+ }
+
+ public String getToCP() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.PATH_TO_CP);
+ }
+
+ public void setToCP(String toCP) {
+ setToscaPresentationValue(JsonPresentationFields.PATH_TO_CP, toCP);
+ }
+
+ public String getToCPOriginId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.PATH_TO_CP_ORIGIN);
+ }
+
+ public void setToCPOriginId(String toCPOriginId) {
+ setToscaPresentationValue(JsonPresentationFields.PATH_TO_CP_ORIGIN, toCPOriginId);
+ }
+
+ public String getFromCPOriginId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.PATH_FROM_CP_ORIGIN);
+ }
+
+ public void setFromCPOriginId(String fromCPOriginId) {
+ setToscaPresentationValue(JsonPresentationFields.PATH_FROM_CP_ORIGIN, fromCPOriginId);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ ForwardingPathElementDataDefinition that = (ForwardingPathElementDataDefinition) o;
+ return Objects.equals(getFromNode(), that.getFromNode()) && Objects.equals(getToNode(), that.getToNode())
+ && Objects.equals(getFromCPOriginId(), that.getFromCPOriginId()) && Objects.equals(getToCPOriginId(), that.getToCPOriginId());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getFromNode(), getToNode(), getFromCP(),getToCP(), getFromCPOriginId(), getToCPOriginId());
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("fromNode", getFromNode()).add("toNode", getToNode())
+ .add("fromCPOriginId", getFromCPOriginId()).add("toCPOriginId", getToCPOriginId())
+ .add("fromCPName", getFromCP()).add("toCPName", getToCP()).toString();
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetInputValueDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetInputValueDataDefinition.java
index c913eaf0cb..131d41a06a 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetInputValueDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetInputValueDataDefinition.java
@@ -20,11 +20,11 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class GetInputValueDataDefinition extends ToscaDataDefinition implements Serializable{
/**
*
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java
index d4981a72ae..c46e21166c 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupDataDefinition.java
@@ -20,15 +20,15 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class GroupDataDefinition extends ToscaDataDefinition implements Serializable {
@@ -188,8 +188,8 @@ public class GroupDataDefinition extends ToscaDataDefinition implements Serializ
+ super.toString() + "]";
}
-
-
-
+ public boolean containsInstanceAsMember(String instanceId) {
+ return getMembers() != null && getMembers().values().contains(instanceId);
+ }
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java
index 03e8cc34bb..04cac38e47 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupInstanceDataDefinition.java
@@ -20,14 +20,14 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class GroupInstanceDataDefinition extends ToscaDataDefinition implements Serializable {
private static final long serialVersionUID = -4231181556686542208L;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupTypeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupTypeDataDefinition.java
index a250ac4308..18e594e0ce 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupTypeDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GroupTypeDataDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class GroupTypeDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/HeatParameterDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/HeatParameterDataDefinition.java
index 33091473cf..a2440610ae 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/HeatParameterDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/HeatParameterDataDefinition.java
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import java.io.Serializable;
+
public class HeatParameterDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java
index 301d888bd2..7afae8a799 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class InterfaceDataDefinition extends ToscaDataDefinition implements Serializable {
/**
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 0ea3e64f28..b705be49e0 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
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.List;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
+import java.util.List;
public class ListCapabilityDataDefinition extends ListDataDefinition<CapabilityDataDefinition> {
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 e9969d73de..ab886fa41f 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
@@ -20,6 +20,11 @@
package org.openecomp.sdc.be.datatypes.elements;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -27,11 +32,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
-public class ListDataDefinition<T extends ToscaDataDefinition> extends ToscaDataDefinition {
+public class ListDataDefinition<T extends ToscaDataDefinition> extends ToscaDataDefinition implements Serializable {
protected List<T> listToscaDataDefinition;
@@ -41,14 +42,15 @@ public class ListDataDefinition<T extends ToscaDataDefinition> extends ToscaData
}
- @JsonCreator
public ListDataDefinition(List<T> listToscaDataDefinition) {
super();
this.listToscaDataDefinition = listToscaDataDefinition;
}
+ @JsonCreator
public ListDataDefinition() {
super();
+ this.listToscaDataDefinition = new ArrayList<>();
}
public List<T> getListToscaDataDefinition() {
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java
index f6c0c491f5..368ed1bdc4 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListMapPropertiesDataDefinition.java
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.List;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
+import java.util.List;
public class ListMapPropertiesDataDefinition extends ListDataDefinition<MapPropertiesDataDefinition> {
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 dee3a8a1f3..652ab335c6 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
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.List;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
+import java.util.List;
public class ListRequirementDataDefinition extends ListDataDefinition<RequirementDataDefinition> {
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java
index db32d56c3a..6629d10802 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapArtifactDataDefinition.java
@@ -20,10 +20,10 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.Map;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
+import java.util.Map;
public class MapArtifactDataDefinition extends MapDataDefinition<ArtifactDataDefinition>{
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java
index 6814d41914..5f22e6b401 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapCapabiltyProperty.java
@@ -20,10 +20,11 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.Map;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+import java.util.Map;
public class MapCapabiltyProperty extends MapDataDefinition<MapPropertiesDataDefinition> {
@JsonCreator
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapComponentInstanceExternalRefs.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapComponentInstanceExternalRefs.java
new file mode 100644
index 0000000000..0900f44cea
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapComponentInstanceExternalRefs.java
@@ -0,0 +1,83 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+import java.io.Serializable;
+import java.util.*;
+
+/**
+ * Maps an object type (e.g. "monitoring", "workflows" etc) to a list of external references.
+ *
+ * "monitoring" -> { "ref1", "ref2" },
+ * "workflows" -> { "ref1", "ref2" }
+ *
+ */
+public class MapComponentInstanceExternalRefs extends ToscaDataDefinition implements Serializable {
+
+ private static final long serialVersionUID = 7788408255736272985L;
+
+ //Constructor
+ public MapComponentInstanceExternalRefs() {
+ this.setComponentInstanceExternalRefs(new HashMap<String, List<String>>());
+ }
+
+ public Map<String, List<String>> getComponentInstanceExternalRefs() {
+ return (Map<String, List<String>>) getToscaPresentationValue(JsonPresentationFields.EXTERNAL_REF);
+ }
+
+ public List<String> getExternalRefsByObjectType(String objectType) {
+ List<String> externalRefsByObjectType = ((Map<String, List<String>>) getToscaPresentationValue(JsonPresentationFields.EXTERNAL_REF)).get(objectType);
+ return externalRefsByObjectType;
+ }
+
+ public void setComponentInstanceExternalRefs(Map<String, List<String>> componentInstanceExternalRefs) {
+ setToscaPresentationValue(JsonPresentationFields.EXTERNAL_REF, componentInstanceExternalRefs);
+ }
+
+ /**
+ * Adds a reference to the given object type. Will do nothing if already exist.
+ *
+ * @param objectType object type to associate reference to
+ * @param ref to add
+ */
+ public boolean addExternalRef(String objectType, String ref){
+
+ List<String> refList = this.getExternalRefsByObjectType(objectType);
+
+ if (refList == null) {
+ //Create list if does not exist and add it to map
+ refList = new ArrayList<String>();
+ this.getComponentInstanceExternalRefs().put(objectType, refList);
+ }
+
+ //Add reference to list if does not exist
+ if (!refList.contains(ref)){
+ return refList.add(ref);
+ }
+
+ return false;
+
+ }
+
+ public boolean deleteExternalRef(String objectType, String ref){
+ List<String> refList = this.getExternalRefsByObjectType(objectType);
+
+ if (refList != null) {
+ return refList.remove(ref);
+ } else {
+ return false;
+ }
+ }
+
+ public boolean replaceExternalRef(String objectType, String oldRef, String newRef) {
+ List<String> refList = this.getExternalRefsByObjectType(objectType);
+
+ if (refList != null && !refList.contains(newRef)) {
+ return Collections.replaceAll(refList, oldRef, newRef);
+ } else {
+ return false;
+ }
+ }
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
index 597e640165..1ca067e047 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
@@ -20,15 +20,17 @@
package org.openecomp.sdc.be.datatypes.elements;
+
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
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 MapDataDefinition <T extends ToscaDataDefinition> extends ToscaDataDefinition {
protected Map<String, T > mapToscaDataDefinition;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java
index 983f1434c5..cdb48336a7 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapGroupsDataDefinition.java
@@ -20,10 +20,13 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.util.Map;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
+
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+import java.util.Map;
public class MapGroupsDataDefinition extends MapDataDefinition<GroupInstanceDataDefinition>{
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java
index 37703df631..f56b59934a 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListCapabiltyDataDefinition.java
@@ -20,12 +20,15 @@
package org.openecomp.sdc.be.datatypes.elements;
+
+
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
import java.util.HashMap;
import java.util.Map;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
-
public class MapListCapabiltyDataDefinition extends MapDataDefinition<ListCapabilityDataDefinition> {
public MapListCapabiltyDataDefinition(MapListCapabiltyDataDefinition cdt) {
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java
index 2144dcac69..d4fecb70e3 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapListRequirementDataDefinition.java
@@ -20,12 +20,15 @@
package org.openecomp.sdc.be.datatypes.elements;
+
+
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
import java.util.HashMap;
import java.util.Map;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
-
public class MapListRequirementDataDefinition extends MapDataDefinition<ListRequirementDataDefinition> {
public MapListRequirementDataDefinition(MapListRequirementDataDefinition cdt) {
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java
index 87a7c60d92..eec5bc1fb8 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapPropertiesDataDefinition.java
@@ -20,12 +20,15 @@
package org.openecomp.sdc.be.datatypes.elements;
+
+
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
import java.util.HashMap;
import java.util.Map;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
-
public class MapPropertiesDataDefinition extends MapDataDefinition<PropertyDataDefinition>{
private String parentName;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java
index 09370f8311..cb09411337 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java
@@ -20,11 +20,11 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class OperationDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyDataDefinition.java
new file mode 100644
index 0000000000..fd34428855
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyDataDefinition.java
@@ -0,0 +1,204 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * public class representing the component policy,
+ * described by the next properties:
+ *
+ * name
+ * uniqueId
+ * type (policy type name)
+ * typeUid (policy type uniqueId)
+ * version (version)
+ * derivedFrom (policy type derivedFrom)
+ * description
+ * policyUUID
+ * invariantUUID
+ * members
+ * metadata
+ * properties
+ * targets
+ * isFromCsar
+ */
+public class PolicyDataDefinition extends ToscaDataDefinition implements Serializable{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4705371580363581255L;
+
+ /**
+ * public constructor by default
+ */
+ public PolicyDataDefinition() {
+ super();
+ }
+
+ /**
+ * public constructor from superclass
+ * @param policy
+ */
+ public PolicyDataDefinition(Map<String, Object> policy) {
+ super(policy);
+ }
+
+ /**
+ * public copy constructor
+ * @param other
+ */
+ public PolicyDataDefinition(PolicyDataDefinition other){
+ this.setName(other.getName());
+ this.setUniqueId(other.getUniqueId());
+ this.setPolicyTypeName(other.getPolicyTypeName());
+ this.setPolicyTypeUid(other.getPolicyTypeUid());
+ this.setVersion(other.getVersion());
+ this.setDerivedFrom(other.getDerivedFrom());
+ this.setDescription(other.getDescription());
+ this.setPolicyUUID(other.getPolicyUUID());
+ this.setInvariantUUID(other.getInvariantUUID());
+ this.setInvariantName(other.getInvariantName());
+ this.setComponentName(other.getComponentName());
+ this.setIsFromCsar(other.getIsFromCsar());
+ if (other.getProperties() != null) {
+ this.setProperties(other.getProperties());
+ }
+ if (other.getTargets() != null) {
+ this.setTargets(other.getTargets());
+ }
+ }
+
+ private void setIsFromCsar(Boolean isFromCsar) {
+ if(isFromCsar == null){
+ setToscaPresentationValue(JsonPresentationFields.IS_FROM_CSAR, false);
+ } else {
+ setToscaPresentationValue(JsonPresentationFields.IS_FROM_CSAR, isFromCsar);
+ }
+ }
+
+ public Boolean getIsFromCsar() {
+ Boolean isFromCsar = (Boolean) getToscaPresentationValue(JsonPresentationFields.IS_FROM_CSAR);
+ return ( isFromCsar != null ) ? isFromCsar : false;
+ }
+
+ public String getComponentName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_NAME);
+ }
+
+ public void setComponentName(String componentName) {
+ setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_NAME, componentName);
+ }
+
+ public String getInvariantName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.CI_INVARIANT_NAME);
+ }
+
+ public void setInvariantName(Object invariantName) {
+ setToscaPresentationValue(JsonPresentationFields.CI_INVARIANT_NAME, invariantName);
+ }
+
+ public String getName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.NAME);
+ }
+
+ public void setName(String name) {
+ setToscaPresentationValue(JsonPresentationFields.NAME, name);
+ }
+
+ public String getUniqueId() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID);
+ }
+
+ public void setUniqueId(String uniqueId) {
+ setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId);
+ }
+
+ public String getPolicyTypeName() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE);
+ }
+
+ public void setPolicyTypeName(String policyTypeName) {
+ setToscaPresentationValue(JsonPresentationFields.TYPE, policyTypeName);
+ }
+
+ public String getPolicyTypeUid() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.TYPE_UNIQUE_ID);
+ }
+
+ public void setPolicyTypeUid(String policyTypeUid) {
+ setToscaPresentationValue(JsonPresentationFields.TYPE_UNIQUE_ID, policyTypeUid);
+ }
+
+ public String getVersion() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.VERSION);
+ }
+
+ public void setVersion(String version) {
+ setToscaPresentationValue(JsonPresentationFields.VERSION, version);
+ }
+
+ public String getDerivedFrom() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.DERIVED_FROM);
+ }
+
+ public void setDerivedFrom(String derivedFrom) {
+ setToscaPresentationValue(JsonPresentationFields.DERIVED_FROM, derivedFrom);
+ }
+
+ public String getDescription() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION);
+ }
+
+ public void setDescription(String description) {
+ setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description);
+ }
+
+ public String getPolicyUUID() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.UUID);
+ }
+
+ public void setPolicyUUID(String policyUUID) {
+ setToscaPresentationValue(JsonPresentationFields.UUID, policyUUID);
+ }
+ public String getInvariantUUID() {
+ return (String) getToscaPresentationValue(JsonPresentationFields.INVARIANT_UUID);
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ setToscaPresentationValue(JsonPresentationFields.INVARIANT_UUID, invariantUUID);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<PropertyDataDefinition> getProperties() {
+ return (List<PropertyDataDefinition> ) getToscaPresentationValue(JsonPresentationFields.PROPERTIES);
+ }
+
+ public void setProperties(List<PropertyDataDefinition> properties) {
+ setToscaPresentationValue(JsonPresentationFields.PROPERTIES, properties);
+ }
+
+ @SuppressWarnings("unchecked")
+ public Map<PolicyTargetType, List<String>> getTargets() {
+ return (Map<PolicyTargetType, List<String>>) getToscaPresentationValue(JsonPresentationFields.TARGETS);
+ }
+
+ public void setTargets(Map<PolicyTargetType, List<String>> metadata) {
+ setToscaPresentationValue(JsonPresentationFields.TARGETS, metadata);
+ }
+
+ public List<String> resolveComponentInstanceTargets() {
+ Map<PolicyTargetType, List<String>> targets = getTargets();
+ return targets == null ? null: targets.get(PolicyTargetType.COMPONENT_INSTANCES);
+ }
+
+ public boolean containsCmptInstanceAsTarget(String cmptInstId) {
+ List<String> componentInstanceTargets = resolveComponentInstanceTargets();
+ return componentInstanceTargets != null && componentInstanceTargets.contains(cmptInstId);
+ }
+
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTargetType.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTargetType.java
new file mode 100644
index 0000000000..3cf8ce1266
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTargetType.java
@@ -0,0 +1,29 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+
+public enum PolicyTargetType {
+
+ GROUPS("GROUPS"),
+ COMPONENT_INSTANCES("COMPONENT_INSTANCES"),
+ TYPE_DOES_NOT_EXIST("TYPE_DOES_NOT_EXIST");
+
+ private String name;
+
+ PolicyTargetType(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+ public static PolicyTargetType getByNameIgnoreCase(String name) {
+ for (PolicyTargetType inst : PolicyTargetType.values()) {
+ if (inst.getName().equalsIgnoreCase(name)) {
+ return inst;
+ }
+ }
+ return null;
+ }
+}
+
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTypeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTypeDataDefinition.java
index 8f73764234..38cb4da1ca 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTypeDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PolicyTypeDataDefinition.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,146 +20,147 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class PolicyTypeDataDefinition extends ToscaDataDefinition implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -3783390539788578388L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -3783390539788578388L;
- private String uniqueId;
+ private String uniqueId;
- private String type;
+ private String type;
- private String version;
+ private String version;
- private String derivedFrom;
+ private String derivedFrom;
- private List<String> targets;
+ private List<String> targets;
- private Map<String, String> metadata;
+ private Map<String, String> metadata;
- private String description;
+ private String description;
- /**
- * Timestamp of data type creation
- */
- private Long creationTime;
+ /**
+ * Timestamp of data type creation
+ */
+ private Long creationTime;
- /**
- * Timestamp of the data type last update
- */
- private Long modificationTime;
+ /**
+ * Timestamp of the data type last update
+ */
+ private Long modificationTime;
- private boolean highestVersion;
+ private boolean highestVersion;
- public PolicyTypeDataDefinition() {
+ public PolicyTypeDataDefinition() {
- }
+ }
- public PolicyTypeDataDefinition(PolicyTypeDataDefinition p) {
- this.uniqueId = p.uniqueId;
- this.type = p.type;
- this.version = p.version;
- this.targets = p.targets;
- this.metadata = p.metadata;
- // this.derivedFromName = p.derivedFromName;
- this.description = p.description;
- this.creationTime = p.creationTime;
- this.modificationTime = p.modificationTime;
- }
+ public PolicyTypeDataDefinition(PolicyTypeDataDefinition p) {
+ this.uniqueId = p.uniqueId;
+ this.type = p.type;
+ this.version = p.version;
+ this.targets = p.targets;
+ this.metadata = p.metadata;
+ this.derivedFrom = p.derivedFrom;
+ this.description = p.description;
+ this.creationTime = p.creationTime;
+ this.modificationTime = p.modificationTime;
+ this.highestVersion = p.highestVersion;
+ }
- public String getType() {
- return type;
- }
+ public String getType() {
+ return type;
+ }
- public void setType(String type) {
- this.type = type;
- }
+ public void setType(String type) {
+ this.type = type;
+ }
- public String getVersion() {
- return version;
- }
+ public String getVersion() {
+ return version;
+ }
- public void setVersion(String version) {
- this.version = version;
- }
+ public void setVersion(String version) {
+ this.version = version;
+ }
- public List<String> getTargets() {
- return targets;
- }
+ public List<String> getTargets() {
+ return targets;
+ }
- public void setTargets(List<String> members) {
- this.targets = members;
- }
+ public void setTargets(List<String> members) {
+ this.targets = members;
+ }
- public Map<String, String> getMetadata() {
- return metadata;
- }
+ public Map<String, String> getMetadata() {
+ return metadata;
+ }
- public void setMetadata(Map<String, String> metadata) {
- this.metadata = metadata;
- }
+ public void setMetadata(Map<String, String> metadata) {
+ this.metadata = metadata;
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- public String getUniqueId() {
- return uniqueId;
- }
+ public String getUniqueId() {
+ return uniqueId;
+ }
- public void setUniqueId(String uniqueId) {
- this.uniqueId = uniqueId;
- }
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
- public Long getCreationTime() {
- return creationTime;
- }
+ public Long getCreationTime() {
+ return creationTime;
+ }
- public void setCreationTime(Long creationTime) {
- this.creationTime = creationTime;
- }
+ public void setCreationTime(Long creationTime) {
+ this.creationTime = creationTime;
+ }
- public Long getModificationTime() {
- return modificationTime;
- }
+ public Long getModificationTime() {
+ return modificationTime;
+ }
- public void setModificationTime(Long modificationTime) {
- this.modificationTime = modificationTime;
- }
+ public void setModificationTime(Long modificationTime) {
+ this.modificationTime = modificationTime;
+ }
- @Override
- public String toString() {
- return "PolicyTypeDataDefinition [uniqueId=" + uniqueId + ", type=" + type + ", version=" + version
- + ", targets=" + targets + ", metadata=" + metadata + ", description=" + description + ", creationTime="
- + creationTime + ", modificationTime=" + modificationTime + "]";
- }
-
- public String getDerivedFrom() {
- return derivedFrom;
- }
-
- public void setDerivedFrom(String derivedFrom) {
- this.derivedFrom = derivedFrom;
- }
-
- public boolean isHighestVersion() {
- return highestVersion;
- }
-
- public void setHighestVersion(boolean isLatestVersion) {
- this.highestVersion = isLatestVersion;
- }
+ @Override
+ public String toString() {
+ return "PolicyTypeDataDefinition [uniqueId=" + uniqueId + ", type=" + type + ", version=" + version
+ + ", targets=" + targets + ", metadata=" + metadata + ", description=" + description + ", creationTime="
+ + creationTime + ", modificationTime=" + modificationTime + "]";
+ }
+
+ public String getDerivedFrom() {
+ return derivedFrom;
+ }
+
+ public void setDerivedFrom(String derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+
+ public boolean isHighestVersion() {
+ return highestVersion;
+ }
+
+ public void setHighestVersion(boolean isLatestVersion) {
+ this.highestVersion = isLatestVersion;
+ }
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java
index 3f044c1d46..d3855b5b1d 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ProductMetadataDataDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
+
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
-import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
-
public class ProductMetadataDataDefinition extends ComponentMetadataDataDefinition implements Serializable {
/**
@@ -123,4 +123,9 @@ public class ProductMetadataDataDefinition extends ComponentMetadataDataDefiniti
return false;
return super.equals(obj);
}
+
+ @Override
+ public String getActualComponentType() {
+ return getComponentType().getValue();
+ }
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertiesOwner.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertiesOwner.java
new file mode 100644
index 0000000000..cee3384a13
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertiesOwner.java
@@ -0,0 +1,11 @@
+package org.openecomp.sdc.be.datatypes.elements;
+
+public interface PropertiesOwner {
+
+ String getUniqueId();
+
+ String getName();
+
+ String getNormalizedName();
+
+}
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 c338597f40..1092b8f24e 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
@@ -20,13 +20,13 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class PropertyDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java
index 639c6dd118..a23ecfee05 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/PropertyRule.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.List;
-import org.codehaus.jackson.annotate.JsonIgnore;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
public class PropertyRule extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
index 0017567031..f1fe93f6ba 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-import java.util.List;
-
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import java.io.Serializable;
+import java.util.List;
+
public class RelationshipInstDataDefinition extends ToscaDataDefinition implements Serializable {
/**
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
index 75f4b857c5..42b828634d 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
@@ -20,14 +20,13 @@
package org.openecomp.sdc.be.datatypes.elements;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
+import com.google.common.collect.Lists;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import com.google.common.collect.Lists;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
/**
* Represents the requirement of the component or component instance
*/
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/SchemaDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/SchemaDefinition.java
index 8d8e518049..e8bd775e78 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/SchemaDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/SchemaDefinition.java
@@ -20,12 +20,12 @@
package org.openecomp.sdc.be.datatypes.elements;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+
import java.io.Serializable;
import java.util.List;
import java.util.Map;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-
/**
* Schema allows to create new types that can be used along TOSCA definitions.
*/
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java
index 9bef5ce887..dfbb7a7c37 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java
@@ -44,7 +44,9 @@ public enum ComponentFieldsEnum {
SERVICE_API_ARTIFACTS("serviceApiArtifacts"),
METADATA("metadata"),
CATEGORIES("categories"),
- INSTANCE_CAPABILTY_PROPERTIES("instanceCapabiltyProperties");
+ INSTANCE_CAPABILTY_PROPERTIES("instanceCapabiltyProperties"),
+ FORWARDING_PATHS("forwardingPaths"),
+ POLICIES("policies");
private String value;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ConnectionPointEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ConnectionPointEnum.java
new file mode 100644
index 0000000000..fd49e29822
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ConnectionPointEnum.java
@@ -0,0 +1,25 @@
+package org.openecomp.sdc.be.datatypes.enums;
+
+import java.util.Arrays;
+import java.util.List;
+
+public enum ConnectionPointEnum {
+
+ CAPABILITY("capability"), REQUIREMENT("requirement");
+
+ private String data;
+ private static List<ConnectionPointEnum> connectionPointEnums = Arrays.asList(values());
+
+ ConnectionPointEnum(String inData) {
+ this.data = inData;
+ }
+
+ @Override
+ public String toString() {
+ return data;
+ }
+
+ public static ConnectionPointEnum getConnectionPointEnum(String data) {
+ return connectionPointEnums.stream().filter(cp -> cp.toString().equals(data)).findAny().orElse(null);
+ }
+}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/EnvironmentStatusEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/EnvironmentStatusEnum.java
new file mode 100644
index 0000000000..ef78ea8fdc
--- /dev/null
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/EnvironmentStatusEnum.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.be.datatypes.enums;
+
+public enum EnvironmentStatusEnum {
+ UNKNOWN("unknown"),
+ IN_PROGRESS("in_progress"),
+ FAILED("failed"),
+ COMPLETED("completed");
+
+ private final String name;
+
+ private EnvironmentStatusEnum(String name){
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+ public static EnvironmentStatusEnum getByName(final String name){
+ switch(name){
+ case ("in_progress") : return IN_PROGRESS;
+ case ("failed") : return FAILED;
+ case ("completed") : return COMPLETED;
+ default: return UNKNOWN;
+ }
+ }
+
+}
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 bb65e7e7a9..083f8dd544 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
@@ -19,12 +19,8 @@
*/
package org.openecomp.sdc.be.datatypes.enums;
-
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
-
-
-//@JsonDeserialize(using = MyDeserializer.class)
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
public enum JsonPresentationFields {
UNIQUE_ID ("uniqueId", GraphPropertyEnum.UNIQUE_ID),
@@ -75,6 +71,7 @@ public enum JsonPresentationFields {
USER_ID_LAST_UPDATER ("userIdLastUpdater", null),
CREATOR_FULL_NAME ("creatorFullName", null),
UPDATER_FULL_NAME ("updaterFullName", null),
+ IS_FROM_CSAR ("isFromCsar", null),
ES_ID ("esId", null),
ARTIFACT_LABEL ("artifactLabel", null),
@@ -136,6 +133,7 @@ public enum JsonPresentationFields {
VALID_SOURCE_TYPES ("validSourceTypes", null),
REQUIREMENT_ID ("requirementId", null),
PARENT_NAME ("parentName", null),
+
//Relation
CAPABILTY_OWNER_ID ("capabilityOwnerId", null),
REQUIREMENT_OWNER_ID ("requirementOwnerId", null),
@@ -144,7 +142,6 @@ public enum JsonPresentationFields {
REQUIREMENT ("requirement", null),
//Groups
-
GROUP_INVARIANT_UUID ("invariantUUID", null),
GROUP_UUID ("groupUUID", null),
GROUP_MEMBER ("members", null),
@@ -162,7 +159,6 @@ public enum JsonPresentationFields {
GROUP_INSTANCE_PROPERTIES ("groupInstancesProperties", null),
//Component instance
-
CI_COMPONENT_UID ("componentUid", null),
CI_POS_X ("posX", null),
CI_POS_Y ("posY", null),
@@ -180,7 +176,27 @@ public enum JsonPresentationFields {
CI_SOURCE_MODEL_INVARIANT ("sourceModelInvariant", null),
CI_SOURCE_MODEL_NAME ("sourceModelName", null),
CI_IS_PROXY ("isProxy", null),
+
+ //path
+ FORWARDING_PATH ("forwardingPath", null),
+ FROM_NODE ("fromNode", null),
+ TO_NODE ("toNode", null),
+ PATH_FROM_CP ("fromCP", null),
+ PATH_TO_CP ("toCP", null),
+ PATH_TO_CP_ORIGIN ("toCPOrigin", null),
+ PATH_FROM_CP_ORIGIN ("fromCPOrigin", null),
+ PATH_NAME ("pathName", null),
+ PATH_PROTOCOL ("pathProtocol", null),
+ PATH_DESTINATION_PORT_NUMBER ("destinationPortNumber", null),
+ PATH_ELEMENT_LIST ("pathElementList", null),
+
+ TYPE_UNIQUE_ID ("typeUniqueId", null),
+ METADATA ("metadata", null),
+ TARGETS ("targets", null),
+ //External Refs
+ EXTERNAL_REF ("externalRef", null),
+
//Workflow Operation
WO_TYPE ("operationType",null),
WO_INPUT_PARAMETERS ("inputParams",null),
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java
index 714e3c6c0a..b295ef7a82 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java
@@ -21,17 +21,18 @@
package org.openecomp.sdc.be.datatypes.enums;
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),
- Configuration("Configuration", "Configuration ()", "resource instance", ComponentTypeEnum.RESOURCE),
- VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE),
- CVFC("CVFC", "CVFC (Complex Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE),
- PNF("PNF", "PNF (Physical Network Function)", "resource instance", ComponentTypeEnum.RESOURCE),
- ServiceProxy("Service Proxy", "Service Proxy", "service proxy", ComponentTypeEnum.RESOURCE)
+ PRODUCT("Product", "Product", "product instance", ComponentTypeEnum.PRODUCT, false),
+ SERVICE("Service", "Service", "service instance", ComponentTypeEnum.SERVICE, false),
+ VF("VF", "VF (Virtual Function)", "resource instance", ComponentTypeEnum.RESOURCE, false),
+ VFC("VFC", "VFC (Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE, true),
+ CP("CP", "CP (Connection Point)", "resource instance", ComponentTypeEnum.RESOURCE, true),
+ VL("VL", "VL (Virtual Link)", "resource instance", ComponentTypeEnum.RESOURCE, true),
+ Configuration("Configuration", "Configuration ()", "resource instance", ComponentTypeEnum.RESOURCE, true),
+ VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE, true),
+ CVFC("CVFC", "CVFC (Complex Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE, false),
+ PNF("PNF", "PNF (Physical Network Function)", "resource instance", ComponentTypeEnum.RESOURCE, false),
+ CR("CR", "CR (Complex Resource)", "resource instance", ComponentTypeEnum.RESOURCE, false),
+ ServiceProxy("Service Proxy", "Service Proxy", "service proxy", ComponentTypeEnum.RESOURCE, false)
;
private String value;
@@ -39,7 +40,7 @@ public enum OriginTypeEnum {
private String instanceType;
private ComponentTypeEnum componentType;
- private OriginTypeEnum(String value, String displayValue, String instanceType, ComponentTypeEnum componentType) {
+ private OriginTypeEnum(String value, String displayValue, String instanceType, ComponentTypeEnum componentType, boolean isAtomicType) {
this.value = value;
this.displayValue = displayValue;
this.instanceType = instanceType;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
index a4efafbf75..8e026b146e 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
@@ -27,27 +27,34 @@ package org.openecomp.sdc.be.datatypes.enums;
*/
public enum ResourceTypeEnum {
- VFC("VFC (Virtual Function Component)"),
- VF("VF"/* (Virtual Function)" */),
- CP("CP (Connection Point)"),
- PNF("PNF"/* (Physical Network Function)" */),
- CVFC("CVFC"/*Complex Virtual Function Component*/),
- VL( "VL (Virtual Link)"),
- VFCMT("VFCMT (VFC Monitoring Template)"),
- Configuration("Configuration ()"),
- ServiceProxy("ServiceProxy ()"),
- ABSTRACT("Abstract (Generic VFC/VF/PNF/Service Type)");
+ VFC("VFC"/* (Virtual Function Component)"*/, true),
+ VF("VF"/* (Virtual Function)" */, false),
+ CR("CR"/* (Complex Resource"*/, false),
+ CP("CP"/* (Connection Point)"*/, true),
+ PNF("PNF"/* (Physical Network Function)" */, false),
+ CVFC("CVFC"/* Complex Virtual Function Component*/, false),
+ VL("VL"/* (Virtual Link)"*/, true),
+ VFCMT("VFCMT"/* (VFC Monitoring Template)"*/, true),
+ Configuration("Configuration ()", true),
+ ServiceProxy("ServiceProxy ()", true),
+ ABSTRACT("Abstract (Generic VFC/VF/PNF/Service Type)", true);
private String value;
+ private boolean isAtomicType;
- private ResourceTypeEnum(String value) {
+ private ResourceTypeEnum(String value, boolean isAtomicType) {
this.value = value;
+ this.isAtomicType = isAtomicType;
}
public String getValue() {
return value;
}
-
+
+ public boolean isAtomicType() {
+ return isAtomicType;
+ }
+
public static ResourceTypeEnum getType(String type) {
for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
if (e.name().equals(type)) {
@@ -56,7 +63,7 @@ public enum ResourceTypeEnum {
}
return null;
}
-
+
public static ResourceTypeEnum getTypeByName(String type) {
for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
if (e.name().equalsIgnoreCase(type)) {
@@ -65,11 +72,13 @@ public enum ResourceTypeEnum {
}
return null;
}
-/**
- * Returns ResourceTypeEnum matching to received String ignore case
- * @param type
- * @return
- */
+
+ /**
+ * Returns ResourceTypeEnum matching to received String ignore case
+ *
+ * @param type
+ * @return
+ */
public static ResourceTypeEnum getTypeIgnoreCase(String type) {
for (ResourceTypeEnum e : ResourceTypeEnum.values()) {
if (e.name().toLowerCase().equals(type.toLowerCase())) {
@@ -78,8 +87,10 @@ public enum ResourceTypeEnum {
}
return null;
}
+
/**
* Checks if enum exist with given type
+ *
* @param type
* @return
*/
@@ -92,8 +103,10 @@ public enum ResourceTypeEnum {
}
return false;
}
+
/**
* Checks if enum exist with given type ignore case
+ *
* @param type
* @return
*/
@@ -106,4 +119,5 @@ public enum ResourceTypeEnum {
}
return false;
}
-}
+
+} \ No newline at end of file
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 31ca6bb1cd..8be36e526a 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
@@ -20,6 +20,11 @@
package org.openecomp.sdc.be.datatypes.tosca;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
+
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -27,18 +32,12 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
-import org.codehaus.jackson.annotate.JsonCreator;
-import org.codehaus.jackson.annotate.JsonValue;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-
-import fj.data.Either;
-
public abstract class ToscaDataDefinition {
protected Map<String, Object> toscaPresentation;
public ToscaDataDefinition() {
- toscaPresentation = new HashMap<String, Object>();
+ toscaPresentation = new HashMap<>();
}
@JsonCreator
diff --git a/common/pom.xml b/common/pom.xml
index 046cada0cf..092c8994a8 100644
--- a/common/pom.xml
+++ b/common/pom.xml
@@ -70,7 +70,7 @@
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
- <version>2.0-m10</version>
+ <version>${ws.rs.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
diff --git a/mvn-be.cmd b/mvn-be.cmd
new file mode 100644
index 0000000000..8ecbe75cb6
--- /dev/null
+++ b/mvn-be.cmd
@@ -0,0 +1 @@
+mvn clean install -Pcatalog -pl catalog-be -am %* \ No newline at end of file
diff --git a/openecomp-ui/yarn.lock b/openecomp-ui/yarn.lock
index db25f0ee40..fe991f31be 100644
--- a/openecomp-ui/yarn.lock
+++ b/openecomp-ui/yarn.lock
@@ -2826,14 +2826,6 @@ create-hmac@^1.1.0, create-hmac@^1.1.2, create-hmac@^1.1.4:
safe-buffer "^5.0.1"
sha.js "^2.4.8"
-create-react-class@^15.5.1:
- version "15.6.3"
- resolved "https://registry.yarnpkg.com/create-react-class/-/create-react-class-15.6.3.tgz#2d73237fb3f970ae6ebe011a9e66f46dbca80036"
- dependencies:
- fbjs "^0.8.9"
- loose-envify "^1.3.1"
- object-assign "^4.1.1"
-
create-react-class@^15.5.2, create-react-class@^15.6.0, create-react-class@^15.6.2:
version "15.6.2"
resolved "https://registry.yarnpkg.com/create-react-class/-/create-react-class-15.6.2.tgz#cf1ed15f12aad7f14ef5f2dfe05e6c42f91ef02a"
@@ -3261,7 +3253,7 @@ d3-zoom@1.7.1:
d3-selection "1"
d3-transition "1"
-d3@^4.10.0, d3@^4.9.1:
+d3@^4.10.0:
version "4.13.0"
resolved "https://registry.yarnpkg.com/d3/-/d3-4.13.0.tgz#ab236ff8cf0cfc27a81e69bf2fb7518bc9b4f33d"
dependencies:
@@ -3634,16 +3626,16 @@ dotenv@^4.0.0:
"dox-sequence-diagram-ui@file:../dox-sequence-diagram-ui":
version "1.0.0"
dependencies:
- d3 "^4.9.1"
+ d3 "^4.10.0"
lodash "^4.12.0"
prop-types "^15.6.0"
- react "^15.1.0"
- react-dnd "^2.1.2"
- react-dnd-html5-backend "^2.1.2"
- react-dom "^15.1.0"
- react-redux "^4.4.5"
- react-select "1.0.0-rc.5"
- redux "^3.5.2"
+ react "^15.6.2"
+ react-dnd "^2.5.4"
+ react-dnd-html5-backend "^2.5.4"
+ react-dom "^15.6.2"
+ react-redux "^5.0.6"
+ react-select "1.2.1"
+ redux "^3.7.2"
duplexer2@0.0.2:
version "0.0.2"
@@ -5080,7 +5072,7 @@ hoek@4.x.x:
version "4.2.0"
resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.0.tgz#72d9d0754f7fe25ca2d01ad8f8f9a9449a89526d"
-hoist-non-react-statics@1.x.x, hoist-non-react-statics@^1.0.3, hoist-non-react-statics@^1.2.0:
+hoist-non-react-statics@1.x.x, hoist-non-react-statics@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-1.2.0.tgz#aa448cf0986d55cc40773b17174b7dd066cb7cfb"
@@ -8392,13 +8384,13 @@ react-deep-force-update@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/react-deep-force-update/-/react-deep-force-update-2.1.1.tgz#8ea4263cd6455a050b37445b3f08fd839d86e909"
-react-dnd-html5-backend@^2.1.2, react-dnd-html5-backend@^2.5.4:
+react-dnd-html5-backend@^2.5.4:
version "2.5.4"
resolved "https://registry.yarnpkg.com/react-dnd-html5-backend/-/react-dnd-html5-backend-2.5.4.tgz#974ad083f67b12d56977a5b171f5ffeb29d78352"
dependencies:
lodash "^4.2.0"
-react-dnd@^2.1.2, react-dnd@^2.5.4:
+react-dnd@^2.5.4:
version "2.5.4"
resolved "https://registry.yarnpkg.com/react-dnd/-/react-dnd-2.5.4.tgz#0b6dc5e9d0dfc2909f4f4fe736e5534f3afd1bd9"
dependencies:
@@ -8434,7 +8426,7 @@ react-dom@16.x.x:
object-assign "^4.1.1"
prop-types "^15.6.0"
-react-dom@^15.1.0, react-dom@^15.5.4, react-dom@^15.6.2:
+react-dom@^15.5.4, react-dom@^15.6.2:
version "15.6.2"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-15.6.2.tgz#41cfadf693b757faf2708443a1d1fd5a02bef730"
dependencies:
@@ -8493,13 +8485,6 @@ react-icons@^2.2.7:
dependencies:
react-icon-base "2.1.0"
-react-input-autosize@^1.1.3:
- version "1.2.0"
- resolved "https://registry.yarnpkg.com/react-input-autosize/-/react-input-autosize-1.2.0.tgz#87241071159f742123897691da6796ec33b57d05"
- dependencies:
- create-react-class "^15.5.2"
- prop-types "^15.5.8"
-
react-input-autosize@^2.1.2, react-input-autosize@^2.2.0:
version "2.2.1"
resolved "https://registry.yarnpkg.com/react-input-autosize/-/react-input-autosize-2.2.1.tgz#ec428fa15b1592994fb5f9aa15bb1eb6baf420f8"
@@ -8586,17 +8571,6 @@ react-proxy@^3.0.0-alpha.0:
dependencies:
lodash "^4.6.1"
-react-redux@^4.4.5:
- version "4.4.8"
- resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-4.4.8.tgz#e7bc1dd100e8b64e96ac8212db113239b9e2e08f"
- dependencies:
- create-react-class "^15.5.1"
- hoist-non-react-statics "^1.0.3"
- invariant "^2.0.0"
- lodash "^4.2.0"
- loose-envify "^1.1.0"
- prop-types "^15.5.4"
-
react-redux@^5.0.6:
version "5.0.6"
resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-5.0.6.tgz#23ed3a4f986359d68b5212eaaa681e60d6574946"
@@ -8608,15 +8582,6 @@ react-redux@^5.0.6:
loose-envify "^1.1.0"
prop-types "^15.5.10"
-react-select@1.0.0-rc.5:
- version "1.0.0-rc.5"
- resolved "https://registry.yarnpkg.com/react-select/-/react-select-1.0.0-rc.5.tgz#9d316f252b1adc372ddb5cdf1f119c6b7cfdb5d6"
- dependencies:
- classnames "^2.2.4"
- create-react-class "^15.5.2"
- prop-types "^15.5.8"
- react-input-autosize "^1.1.3"
-
react-select@1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/react-select/-/react-select-1.2.1.tgz#a2fe58a569eb14dcaa6543816260b97e538120d1"
@@ -8725,7 +8690,7 @@ react@16.x.x:
object-assign "^4.1.1"
prop-types "^15.6.0"
-react@^15.1.0, react@^15.4.1, react@^15.5.4, react@^15.6.2:
+react@^15.4.1, react@^15.5.4, react@^15.6.2:
version "15.6.2"
resolved "https://registry.yarnpkg.com/react/-/react-15.6.2.tgz#dba0434ab439cfe82f108f0f511663908179aa72"
dependencies:
diff --git a/pom.xml b/pom.xml
index 985d1e17d3..dae9bf5db1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -24,11 +24,12 @@
<guava.version>18.0</guava.version>
<titan.version>1.0.0</titan.version>
<spring-boot.version>1.1.6.RELEASE</spring-boot.version>
- <spring.version>4.3.4.RELEASE</spring.version>
+ <spring.version>4.3.13.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<spring.ldap.version>2.0.1.RELEASE</spring.ldap.version>
- <jersey-bom.version>2.24</jersey-bom.version>
+ <jersey-bom.version>2.26</jersey-bom.version>
<servlet-api.version>2.5</servlet-api.version>
+ <wire-mock.version>2.11.0</wire-mock.version>
<artifact-generator-api.version>${project.version}</artifact-generator-api.version>
<artifact-generator-core.version>${project.version}</artifact-generator-core.version>
@@ -36,13 +37,15 @@
<dox-common-lib.version>${project.version}</dox-common-lib.version>
<!-- Elastic Search mapper (reference the elastic search version actually). -->
- <elastic-search.version>2.1.0</elastic-search.version>
+ <elastic-search.version>2.4.0</elastic-search.version>
+ <catalog-artifacts.version>1.0.0-SNAPSHOT</catalog-artifacts.version>
+ <catalog-builders.version>1.0.0-SNAPSHOT</catalog-builders.version>
<jetty.version>9.2.10.v20150310</jetty.version>
<!-- JSON and YAML Parsing -->
- <jackson.version>2.6.2</jackson.version>
+ <jackson.version>2.8.4</jackson.version>
<jackson.yaml.version>2.8.1</jackson.yaml.version>
- <jackson.annotations.version>2.6.0</jackson.annotations.version>
+ <jackson.annotations.version>2.8.4</jackson.annotations.version>
<!-- Yaml for properties -->
<snakeyaml.version>1.14</snakeyaml.version>
@@ -73,8 +76,6 @@
<regex.version>3.0.3</regex.version>
- <codehaus.jackson.core>1.9.2</codehaus.jackson.core>
-
<!--GSON-->
<gson.version>2.3.1</gson.version>
@@ -84,36 +85,24 @@
<!--TESTING-->
<mockito.version>2.12.0</mockito.version>
<junit.version>4.12</junit.version>
+ <assertj.version>3.8.0</assertj.version>
<testng.version>6.9.10</testng.version>
<extentreports.version>3.0.3</extentreports.version>
-
+ <cucumber.version>2.3.1</cucumber.version>
+
<!-- parser-->
<sdc-tosca-parser.version>1.2.3-SNAPSHOT</sdc-tosca-parser.version>
-
+
<!--JaCoCO -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
- <sonar.jacoco.reportPath>${project.basedir}/target/jacoco.exec</sonar.jacoco.reportPath>
- <sonar.jacoco.itReportPath>${project.basedir}/target/it-jacoco.exec</sonar.jacoco.itReportPath>
+ <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
+ <sonar.jacoco.itReportPath>${project.basedir}/../target/it-jacoco.exec</sonar.jacoco.itReportPath>
<sonar.language>java</sonar.language>
<!-- Sonar properties -->
<sonar.sourceEncoding>${project.build.sourceEncoding}</sonar.sourceEncoding>
<sonar.projectBaseDir>${project.basedir}</sonar.projectBaseDir>
- <sonar.sources>.</sonar.sources>
- <sonar.exclusions>**/scripts/**/*</sonar.exclusions>
- <sonar.test.exclusions>**/test/**/*,**/tests/**/*</sonar.test.exclusions>
- <sonar.inclusions>app/**/*.js,server-mock/**/*.js,src/**/*.js,src/main/**/*.java</sonar.inclusions>
<sonar.branch>${project.version}</sonar.branch>
- <assertj.version>3.8.0</assertj.version>
-
- <!--cassandra -->
- <cassandra.driver.version>3.0.0</cassandra.driver.version>
- <!-- maven central (Nexus) -->
- <nexus.id.release>nexus</nexus.id.release>
- <nexus.id.snapshot>nexus</nexus.id.snapshot>
-
- <assertj.version>3.8.0</assertj.version>
-
<!--cassandra -->
<cassandra.driver.version>3.0.0</cassandra.driver.version>
<!-- maven central (Nexus) -->
@@ -126,12 +115,60 @@
<staging.profile.id>176c31dfe190a</staging.profile.id>
<!--maven-->
<maven.build.timestamp.format>yyyyMMdd'T'HHmm</maven.build.timestamp.format>
+ <!--io.fabric8-->
+ <fabric8.version>0.23.0</fabric8.version>
<!--docker tags-->
<docker.tag>${project.version}-${maven.build.timestamp}</docker.tag>
<docker.latest.tag>${project.version}-latest</docker.latest.tag>
</properties>
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.glassfish.jersey.ext</groupId>
+ <artifactId>jersey-bean-validation</artifactId>
+ <version>${jersey-bom.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.glassfish.hk2.external</groupId>
+ <artifactId>asm-all-repackaged</artifactId>
+ <version>2.4.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <version>${assertj.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>${mockito.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock</artifactId>
+ <version>${wire-mock.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>io.cucumber</groupId>
+ <artifactId>cucumber-java</artifactId>
+ <version>${cucumber.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>io.cucumber</groupId>
+ <artifactId>cucumber-junit</artifactId>
+ <version>${cucumber.version}</version>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
<reporting>
<plugins>
<plugin>
@@ -293,6 +330,54 @@
</execution>
</executions>
</plugin>
+
+ <!-- license plugin -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>license-maven-plugin</artifactId>
+ <version>1.10</version>
+ <configuration>
+ <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
+ <processStartTag>============LICENSE_START=======================================================</processStartTag>
+ <processEndTag>============LICENSE_END=========================================================</processEndTag>
+ <sectionDelimiter>================================================================================</sectionDelimiter>
+ <licenseName>apache_v2</licenseName>
+ <inceptionYear>2017</inceptionYear>
+ <organizationName>AT&amp;T Intellectual Property. All rights
+ reserved.</organizationName>
+ <projectName>SDC</projectName>
+ <canUpdateCopyright>true</canUpdateCopyright>
+ <canUpdateDescription>true</canUpdateDescription>
+ <canUpdateLicense>true</canUpdateLicense>
+ <emptyLineAfterHeader>true</emptyLineAfterHeader>
+ <verbose>false</verbose>
+ <includes>
+ <include>**/*.java</include>
+ <include>**/*.ts</include>
+ </includes>
+ <excludes>
+ <exclude>**/*.d.ts</exclude>
+ </excludes>
+ <roots>
+ <root>src</root>
+ <root>app</root>
+ <root>server-mock</root>
+ <root>typings</root>
+ </roots>
+ <extraExtensions>
+ <ts>java</ts>
+ </extraExtensions>
+ </configuration>
+ <executions>
+ <execution>
+ <id>first</id>
+ <goals>
+ <goal>update-file-header</goal>
+ </goals>
+ <!--phase>process-sources</phase -->
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
@@ -314,7 +399,6 @@
<module>asdctool</module>
<module>catalog-ui</module>
<module>catalog-fe</module>
- <module>asdc-tests</module>
<module>test-apis-ci</module>
<module>ui-ci</module>
<module>sdc-os-chef</module>
@@ -337,18 +421,17 @@
<module>asdctool</module>
<module>catalog-ui</module>
<module>catalog-fe</module>
- <module>asdc-tests</module>
<module>test-apis-ci</module>
<module>ui-ci</module>
</modules>
<properties>
<ecomp.version>1.2.7</ecomp.version>
- <artifact-generator-api.version>1710.0.0</artifact-generator-api.version>
- <artifact-generator-core.version>1710.0.0</artifact-generator-core.version>
- <dox-common-lib.version>1710.0.0</dox-common-lib.version>
+ <artifact-generator-api.version>1802.0.1.167</artifact-generator-api.version>
+ <artifact-generator-core.version>1802.0.1.167</artifact-generator-core.version>
+ <dox-common-lib.version>1802.0.1.167</dox-common-lib.version>
<sdc-tosca-parser.version>1.1.32</sdc-tosca-parser.version>
- </properties>
+ </properties>
</profile>
<profile>
@@ -357,24 +440,9 @@
<activeByDefault>false</activeByDefault>
</activation>
<modules>
- <module>build-tools</module>
<module>onboarding</module>
</modules>
</profile>
-
- <profile>
- <id>dev-integ</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- <dependencies>
- <dependency>
- <groupId>org.togglz</groupId>
- <artifactId>togglz-console</artifactId>
- <version>${togglz.version}</version>
- </dependency>
- </dependencies>
- </profile>
</profiles>
<repositories>
@@ -403,7 +471,6 @@
</repositories>
<distributionManagement>
-
<repository>
<id>ecomp-releases</id>
<name>Release Repository</name>
@@ -420,4 +487,3 @@
</site>
</distributionManagement>
</project>
-
diff --git a/sdc-os-chef/pom.xml b/sdc-os-chef/pom.xml
index c796b2d9dd..8b6337205d 100644
--- a/sdc-os-chef/pom.xml
+++ b/sdc-os-chef/pom.xml
@@ -146,7 +146,7 @@
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
- <version>0.23.0</version>
+ <version>${fabric8.version}</version>
<configuration>
<verbose>true</verbose>
diff --git a/sdc-os-chef/scripts/docker_run.sh b/sdc-os-chef/scripts/docker_run.sh
index f7f1ad5632..61a2434819 100755
--- a/sdc-os-chef/scripts/docker_run.sh
+++ b/sdc-os-chef/scripts/docker_run.sh
@@ -17,7 +17,7 @@ function cleanup {
echo "performing old dockers cleanup"
if [ "$1" == "all" ] ; then
- docker_ids=`docker ps -a | egrep -v "openecomp/sdc-simulator" | egrep "ecomp-nexus:${PORT}/sdc|sdc|Exit" | awk '{print $1}'`
+ docker_ids=`docker ps -a | egrep -v "onap/sdc-simulator" | egrep "ecomp-nexus:${PORT}/sdc|sdc|Exit" | awk '{print $1}'`
for X in ${docker_ids}
do
docker rm -f ${X}
@@ -106,6 +106,7 @@ if [ -n "$MATCH" ]; then
match_result=true
fi
}
+
function monitor_docker {
echo monitor $1 Docker
@@ -229,10 +230,9 @@ fi
echo ""
-
+#Elastic-Search
function sdc-es {
-
-# Elastic-Search
+dir_perms
echo "docker run sdc-elasticsearch..."
if [ ${LOCAL} = false ]; then
echo "pulling code"
@@ -244,8 +244,10 @@ echo "please wait while ES is starting..."
monitor_docker sdc-es
}
+
+#Init-Elastic-Search
function sdc-init-es {
-# Init-Elastic-Search
+dir_perms
echo "docker run sdc-init-elasticsearch..."
if [ ${LOCAL} = false ]; then
echo "pulling code"
@@ -258,8 +260,9 @@ if [[ $rc != 0 ]]; then exit $rc; fi
}
+#Cassandra
function sdc-cs {
-# Cassandra
+dir_perms
echo "docker run sdc-cassandra..."
if [ ${LOCAL} = false ]; then
docker pull ${PREFIX}/sdc-cassandra:${RELEASE}
@@ -271,8 +274,8 @@ echo "please wait while CS is starting..."
monitor_docker sdc-cs
}
+#Cassandra-init
function sdc-cs-init {
-# cassandra-init
echo "docker run sdc-cassandra-init..."
if [ ${LOCAL} = false ]; then
docker pull ${PREFIX}/sdc-cassandra-init:${RELEASE}
@@ -283,21 +286,19 @@ docker_logs sdc-cs-init
if [[ $rc != 0 ]]; then exit $rc; fi
}
+#Kibana
function sdc-kbn {
-# kibana
+dir_perms
echo "docker run sdc-kibana..."
if [ ${LOCAL} = false ]; then
docker pull ${PREFIX}/sdc-kibana:${RELEASE}
docker run --detach --name sdc-kbn --env ENVNAME="${DEP_ENV}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 5601:5601 ${PREFIX}/sdc-kibana:${RELEASE}
fi
-
}
-
+#Back-End
function sdc-BE {
-
dir_perms
-# Back-End
echo "docker run sdc-backend..."
if [ ${LOCAL} = false ]; then
docker pull ${PREFIX}/sdc-backend:${RELEASE}
@@ -310,10 +311,9 @@ echo "please wait while BE is starting..."
monitor_docker sdc-BE
}
+# Back-End-Init
function sdc-BE-init {
-
dir_perms
-# Back-End-Init
echo "docker run sdc-backend-init..."
if [ ${LOCAL} = false ]; then
docker pull ${PREFIX}/sdc-backend-init:${RELEASE}
@@ -324,9 +324,10 @@ docker_logs sdc-BE-init
if [[ $rc != 0 ]]; then exit $rc; fi
}
+
+# Front-End
function sdc-FE {
dir_perms
-# Front-End
echo "docker run sdc-frontend..."
if [ ${LOCAL} = false ]; then
docker pull ${PREFIX}/sdc-frontend:${RELEASE}
@@ -338,9 +339,8 @@ monitor_docker sdc-FE
}
-
-function sdc-sanity {
# sanityDocker
+function sdc-sanity {
if [[ (${RUNTESTS} = true) && (${healthCheck_http_code} == 200) ]]; then
echo "docker run sdc-sanity..."
echo "Triger sanity docker, please wait..."
diff --git a/sdc-os-chef/scripts/docker_run_csit.sh b/sdc-os-chef/scripts/docker_run_csit.sh
new file mode 100644
index 0000000000..2981afa49d
--- /dev/null
+++ b/sdc-os-chef/scripts/docker_run_csit.sh
@@ -0,0 +1,386 @@
+#!/bin/bash
+
+CS_PASSWORD="onap123#@!"
+SDC_USER="asdc_user"
+SDC_PASSWORD="Aa1234%^!"
+JETTY_BASE="/var/lib/jetty"
+BE_JAVA_OPTIONS="-Xdebug -agentlib:jdwp=transport=dt_socket,address=4000,server=y,suspend=n -Xmx2g -Xms2g"
+FE_JAVA_OPTIONS="-Xdebug -agentlib:jdwp=transport=dt_socket,address=6000,server=y,suspend=n -Xmx512m -Xms512m"
+
+
+function usage {
+ echo "usage: docker_run.sh [ -r|--release <RELEASE-NAME> ] [ -e|--environment <ENV-NAME> ] [ -p|--port <Docker-hub-port>] [ -l|--local <Run-without-pull>] [ -t|--runTests <Run-with-sanityDocker>] [ -h|--help ]"
+}
+
+
+function cleanup {
+ echo "performing old dockers cleanup"
+
+ if [ "$1" == "all" ] ; then
+ docker_ids=`docker ps -a | egrep -v "openecomp/sdc-simulator" | egrep "ecomp-nexus:${PORT}/sdc|sdc|Exit" | awk '{print $1}'`
+ for X in ${docker_ids}
+ do
+ docker rm -f ${X}
+ done
+ else
+ echo "performing $1 docker cleanup"
+ tmp=`docker ps -a -q --filter="name=$1"`
+ if [[ ! -z "$tmp" ]]; then
+ docker rm -f ${tmp}
+ fi
+ fi
+}
+
+
+function dir_perms {
+ mkdir -p ${WORKSPACE}/data/logs/BE/SDC/SDC-BE
+ mkdir -p ${WORKSPACE}/data/logs/FE/SDC/SDC-FE
+ chmod -R 777 ${WORKSPACE}/data/logs
+}
+function probe_cs {
+
+cs_stat=false
+docker exec -it $1 /var/lib/ready-probe.sh > /dev/null 2>&1
+rc=$?
+if [[ $rc == 0 ]]; then
+ echo DOCKER start finished in $2 seconds
+ cs_stat=true
+fi
+
+}
+
+function probe_be {
+
+be_stat=false
+docker exec -it $1 /var/lib/ready-probe.sh > /dev/null 2>&1
+rc=$?
+if [[ $rc == 200 ]]; then
+ echo DOCKER start finished in $2 seconds
+ be_stat=true
+fi
+
+}
+
+function probe_fe {
+
+fe_stat=false
+docker exec -it $1 /var/lib/ready-probe.sh > /dev/null 2>&1
+rc=$?
+if [[ $rc == 200 ]]; then
+ echo DOCKER start finished in $2 seconds
+ fe_stat=true
+fi
+
+}
+
+function probe_es {
+
+es_stat=false
+health_Check_http_code=$(curl -o /dev/null -w '%{http_code}' http://${IP}:9200/_cluster/health?wait_for_status=yellow&timeout=120s)
+if [[ "$health_Check_http_code" -eq 200 ]]
+ then
+ echo DOCKER start finished in $2 seconds
+ es_stat=true
+ fi
+
+}
+
+function probe_docker {
+
+match_result=false
+MATCH=`docker logs --tail 30 $1 | grep "DOCKER STARTED"`
+echo MATCH is -- $MATCH
+
+if [ -n "$MATCH" ]; then
+ echo DOCKER start finished in $2 seconds
+ match_result=true
+fi
+}
+function monitor_docker {
+
+ echo monitor $1 Docker
+ sleep 5
+ TIME_OUT=900
+ INTERVAL=20
+ TIME=0
+ while [ "$TIME" -lt "$TIME_OUT" ]; do
+ if [ "$1" == "sdc-cs" ]; then
+ probe_cs $1 $TIME
+ if [[ $cs_stat == true ]]; then break; fi
+ elif [ "$1" == "sdc-es" ]; then
+ probe_es $1 $TIME
+ if [[ $es_stat == true ]]; then break; fi
+ elif [ "$1" == "sdc-BE" ]; then
+ probe_be $1 $TIME
+ if [[ $be_stat == true ]]; then break; fi
+ elif [ "$1" == "sdc-FE" ]; then
+ probe_fe $1 $TIME
+ if [[ $fe_stat == true ]]; then break; fi
+ else
+ probe_docker $1 $TIME
+ if [[ $match_result == true ]]; then break; fi
+ fi
+ echo Sleep: $INTERVAL seconds before testing if $1 DOCKER is up. Total wait time up now is: $TIME seconds. Timeout is: $TIME_OUT seconds
+ sleep $INTERVAL
+ TIME=$(($TIME+$INTERVAL))
+ done
+
+ if [ "$TIME" -ge "$TIME_OUT" ]; then
+ echo -e "\e[1;31mTIME OUT: DOCKER was NOT fully started in $TIME_OUT seconds... Could cause problems ...\e[0m"
+ fi
+
+}
+
+function healthCheck {
+ curl ${IP}:9200/_cluster/health?pretty=true
+
+ echo "BE health-Check:"
+ curl http://${IP}:8080/sdc2/rest/healthCheck
+
+ echo ""
+ echo ""
+ echo "FE health-Check:"
+ curl http://${IP}:8181/sdc1/rest/healthCheck
+
+
+ echo ""
+ echo ""
+ healthCheck_http_code=$(curl -o /dev/null -w '%{http_code}' -H "Accept: application/json" -H "Content-Type: application/json" -H "USER_ID: jh0003" http://${IP}:8080/sdc2/rest/v1/user/demo;)
+ if [[ ${healthCheck_http_code} != 200 ]]
+ then
+ echo "Error [${healthCheck_http_code}] while user existance check"
+ return ${healthCheck_http_code}
+ fi
+ echo "check user existance: OK"
+ return ${healthCheck_http_code}
+}
+
+function elasticHealthCheck {
+ echo "Elastic Health-Check:"
+
+ COUNTER=0
+ while [ $COUNTER -lt 20 ]; do
+ echo "Waiting ES docker to start"
+ health_Check_http_code=$(curl -o /dev/null -w '%{http_code}' http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=120s)
+ if [[ "$health_Check_http_code" -eq 200 ]]
+ then
+ break
+ fi
+ let COUNTER=COUNTER+1
+ sleep 4
+ done
+
+ healthCheck_http_code=$(curl -o /dev/null -w '%{http_code}' http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=120s)
+ if [[ "$health_Check_http_code" != 200 ]]
+ then
+ echo "Error [${healthCheck_http_code}] ES NOT started correctly"
+ exit ${healthCheck_http_code}
+ fi
+ echo "ES started correctly"
+ curl ${IP}:9200/_cluster/health?pretty=true
+ return ${healthCheck_http_code}
+}
+
+RELEASE=latest
+LOCAL=false
+RUNTESTS=false
+DEBUG_PORT="--publish 4000:4000"
+
+while [ $# -gt 0 ]; do
+ case $1 in
+ # -r | --release - The specific docker version to pull and deploy
+ -r | --release )
+ shift 1 ;
+ RELEASE=$1;
+ shift 1;;
+ # -e | --environment - The environment name you want to deploy
+ -e | --environment )
+ shift 1;
+ DEP_ENV=$1;
+ shift 1 ;;
+ # -p | --port - The port from which to connect to the docker nexus
+ -p | --port )
+ shift 1 ;
+ PORT=$1;
+ shift 1 ;;
+ # -l | --local - Use this for deploying your local dockers without pulling them first
+ -l | --local )
+ LOCAL=true;
+ shift 1;;
+ # -t | --runTests - Use this for running the sanity tests docker after all other dockers have been deployed
+ -t | --runTests )
+ RUNTESTS=true;
+ shift 1 ;;
+ # -d | --docker - The init specified docker
+ -d | --docker )
+ shift 1 ;
+ DOCKER=$1;
+ shift 1 ;;
+ # -h | --help - Display the help message with all the available run options
+ -h | --help )
+ usage;
+ exit 0;;
+ * )
+ usage;
+ exit 1;;
+ esac
+done
+
+
+[ -f /opt/config/env_name.txt ] && DEP_ENV=$(cat /opt/config/env_name.txt) || echo ${DEP_ENV}
+[ -f /opt/config/nexus_username.txt ] && NEXUS_USERNAME=$(cat /opt/config/nexus_username.txt) || NEXUS_USERNAME=release
+[ -f /opt/config/nexus_password.txt ] && NEXUS_PASSWD=$(cat /opt/config/nexus_password.txt) || NEXUS_PASSWD=sfWU3DFVdBr7GVxB85mTYgAW
+[ -f /opt/config/nexus_docker_repo.txt ] && NEXUS_DOCKER_REPO=$(cat /opt/config/nexus_docker_repo.txt) || NEXUS_DOCKER_REPO=nexus3.onap.org:${PORT}
+[ -f /opt/config/nexus_username.txt ] && docker login -u $NEXUS_USERNAME -p $NEXUS_PASSWD $NEXUS_DOCKER_REPO
+
+export IP=`ip route get 8.8.8.8 | awk '/src/{ print $7 }'`
+export PREFIX=${NEXUS_DOCKER_REPO}'/onap'
+
+if [ ${LOCAL} = true ]; then
+ PREFIX='onap'
+fi
+
+echo ""
+
+
+
+function sdc-es {
+
+# Elastic-Search
+echo "docker run sdc-elasticsearch..."
+if [ ${LOCAL} = false ]; then
+ echo "pulling code"
+ docker pull ${PREFIX}/sdc-elasticsearch:${RELEASE}
+fi
+docker run -dit --name sdc-es --env ENVNAME="${DEP_ENV}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --env ES_JAVA_OPTS="-Xms512m -Xmx512m" --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --env ES_HEAP_SIZE=1024M --volume ${WORKSPACE}/data/ES:/usr/share/elasticsearch/data --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 9200:9200 --publish 9300:9300 ${PREFIX}/sdc-elasticsearch:${RELEASE} /bin/sh
+
+echo "please wait while ES is starting..."
+monitor_docker sdc-es
+}
+
+function sdc-init-es {
+# Init-Elastic-Search
+echo "docker run sdc-init-elasticsearch..."
+if [ ${LOCAL} = false ]; then
+ echo "pulling code"
+ docker pull ${PREFIX}/sdc-init-elasticsearch:${RELEASE}
+fi
+docker run --name sdc-init-es --env ENVNAME="${DEP_ENV}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments ${PREFIX}/sdc-init-elasticsearch:${RELEASE}
+rc=$?
+if [[ $rc != 0 ]]; then exit $rc; fi
+
+}
+
+function sdc-cs {
+# Cassandra
+echo "docker run sdc-cassandra..."
+if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-cassandra:${RELEASE}
+fi
+docker run -dit --name sdc-cs --env RELEASE="${RELEASE}" --env CS_PASSWORD="${CS_PASSWORD}" --env ENVNAME="${DEP_ENV}" --env HOST_IP=${IP} --env MAX_HEAP_SIZE="2024M" --env HEAP_NEWSIZE="512M" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/CS:/var/lib/cassandra --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 9042:9042 --publish 9160:9160 ${PREFIX}/sdc-cassandra:${RELEASE} /bin/sh
+
+
+echo "please wait while CS is starting..."
+monitor_docker sdc-cs
+}
+
+function sdc-cs-init {
+# cassandra-init
+echo "docker run sdc-cassandra-init..."
+if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-cassandra-init:${RELEASE}
+fi
+docker run --name sdc-cs-init --env RELEASE="${RELEASE}" --env SDC_USER="${SDC_USER}" --env SDC_PASSWORD="${SDC_PASSWORD}" --env CS_PASSWORD="${CS_PASSWORD}" --env ENVNAME="${DEP_ENV}" --env HOST_IP=${IP} --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/CS:/var/lib/cassandra --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --volume ${WORKSPACE}/data/CS-Init:/root/chef-solo/cache ${PREFIX}/sdc-cassandra-init:${RELEASE}
+rc=$?
+if [[ $rc != 0 ]]; then exit $rc; fi
+}
+
+function sdc-kbn {
+# kibana
+echo "docker run sdc-kibana..."
+if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-kibana:${RELEASE}
+docker run --detach --name sdc-kbn --env ENVNAME="${DEP_ENV}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 5601:5601 ${PREFIX}/sdc-kibana:${RELEASE}
+fi
+
+}
+
+
+function sdc-BE {
+
+dir_perms
+# Back-End
+echo "docker run sdc-backend..."
+if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-backend:${RELEASE}
+else
+ ADDITIONAL_ARGUMENTS=${DEBUG_PORT}
+fi
+docker run --detach --name sdc-BE --env HOST_IP=${IP} --env ENVNAME="${DEP_ENV}" --env http_proxy=${http_proxy} --env https_proxy=${https_proxy} --env no_proxy=${no_proxy} --env JAVA_OPTIONS="${BE_JAVA_OPTIONS}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/logs/BE/:/var/lib/jetty/logs --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 8443:8443 --publish 8080:8080 ${ADDITIONAL_ARGUMENTS} ${PREFIX}/sdc-backend:${RELEASE}
+
+echo "please wait while BE is starting..."
+monitor_docker sdc-BE
+}
+
+function sdc-BE-init {
+
+dir_perms
+# Back-End-Init
+echo "docker run sdc-backend-init..."
+if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-backend-init:${RELEASE}
+fi
+docker run --name sdc-BE-init --env HOST_IP=${IP} --env ENVNAME="${DEP_ENV}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/logs/BE/:/var/lib/jetty/logs --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments ${PREFIX}/sdc-backend-init:${RELEASE}
+rc=$?
+if [[ $rc != 0 ]]; then exit $rc; fi
+}
+
+function sdc-FE {
+dir_perms
+# Front-End
+echo "docker run sdc-frontend..."
+if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-frontend:${RELEASE}
+fi
+docker run --detach --name sdc-FE --env HOST_IP=${IP} --env ENVNAME="${DEP_ENV}" --env http_proxy=${http_proxy} --env https_proxy=${https_proxy} --env no_proxy=${no_proxy} --env JAVA_OPTIONS="${FE_JAVA_OPTIONS}" --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/logs/FE/:/var/lib/jetty/logs --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 9443:9443 --publish 8181:8181 ${PREFIX}/sdc-frontend:${RELEASE}
+
+echo "please wait while FE is starting....."
+monitor_docker sdc-FE
+}
+
+
+
+function sdc-sanity {
+# sanityDocker
+if [[ (${RUNTESTS} = true) && (${healthCheck_http_code} == 200) ]]; then
+ echo "docker run sdc-sanity..."
+ echo "Triger sanity docker, please wait..."
+
+ if [ ${LOCAL} = false ]; then
+ docker pull ${PREFIX}/sdc-sanity:${RELEASE}
+ fi
+
+docker run --detach --name sdc-sanity --env HOST_IP=${IP} --env ENVNAME="${DEP_ENV}" --env http_proxy=${http_proxy} --env https_proxy=${https_proxy} --env no_proxy=${no_proxy} --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/logs/sdc-sanity/target:/var/lib/tests/target --volume ${WORKSPACE}/data/logs/sdc-sanity/ExtentReport:/var/lib/tests/ExtentReport --volume ${WORKSPACE}/data/logs/sdc-sanity/outputCsar:/var/lib/tests/outputCsar --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 9560:9560 ${PREFIX}/sdc-sanity:${RELEASE}
+echo "please wait while SANITY is starting....."
+monitor_docker sdc-sanity
+
+fi
+}
+
+if [ -z "${DOCKER}" ]; then
+ cleanup all
+ sdc-es
+ sdc-init-es
+ sdc-cs
+ sdc-cs-init
+ sdc-kbn
+ sdc-BE
+ sdc-BE-init
+ sdc-FE
+else
+ cleanup ${DOCKER}
+ ${DOCKER}
+fi
+
+# healthCheck
+healthCheck
diff --git a/sdc-os-chef/scripts/sanity_run.sh b/sdc-os-chef/scripts/sanity_run.sh
index 17d1642c73..4aea3bb410 100644
--- a/sdc-os-chef/scripts/sanity_run.sh
+++ b/sdc-os-chef/scripts/sanity_run.sh
@@ -2,116 +2,176 @@
function usage {
- echo "usage: docker_run.sh [ -r|--release <RELEASE-NAME> ] [ -e|--environment <ENV-NAME> ] [ -p|--port <Docker-hub-port>] [ -l|--local <Run-without-pull>] [ -s|--skipTests <Run-without-sanityDocker>] [ -h|--help ]"
+ echo "usage: sanity_run.sh [ -r|--release <RELEASE-NAME> ] [ -e|--environment <ENV-NAME> ] [ -p|--port <Docker-hub-port>] [ -l|--local <Run-without-pull>] [ -t|--runTests <Run-with-sanityDocker>] [ -h|--help ]"
}
-
function cleanup {
- echo "performing old dockers cleanup"
- docker_ids=`docker ps -a | egrep -v "openecomp/sdc-simulator" | egrep "ecomp-nexus:${PORT}/sdc-sanity|sdc-sanity|Exit" | awk '{print $1}'`
- for X in ${docker_ids}
- do
- docker rm -f ${X}
- done
+ echo "performing old dockers cleanup"
+ docker_ids=`docker ps -a | egrep -v "onap/sdc-simulator" | egrep "ecomp-nexus:${PORT}/sdc|sdc-sanity|Exit" | awk '{print $1}'`
+ for X in ${docker_ids}
+ do
+ docker rm -f ${X}
+ done
}
function dir_perms {
- mkdir -p /data/logs/BE/SDC/SDC-BE
- mkdir -p /data/logs/FE/SDC/SDC-FE
- chmod -R 777 /data/logs
+ mkdir -p ${WORKSPACE}/data/logs/BE/SDC/SDC-BE
+ mkdir -p ${WORKSPACE}/data/logs/FE/SDC/SDC-FE
+ chmod -R 777 ${WORKSPACE}/data/logs
}
function monitor_docker {
-echo monitor $1 Docker
-sleep 5
-TIME_OUT=900
-INTERVAL=20
-TIME=0
-while [ "$TIME" -lt "$TIME_OUT" ]; do
-
-MATCH=`docker logs --tail 30 $1 | grep "DOCKER STARTED"`
-echo MATCH is -- $MATCH
-
-if [ -n "$MATCH" ]
- then
- echo DOCKER start finished in $TIME seconds
- break
- fi
-
- echo Sleep: $INTERVAL seconds before testing if $1 DOCKER is up. Total wait time up now is: $TIME seconds. Timeout is: $TIME_OUT seconds
- sleep $INTERVAL
- TIME=$(($TIME+$INTERVAL))
-done
+ echo monitor $1 Docker
+ sleep 5
+ TIME_OUT=900
+ INTERVAL=20
+ TIME=0
+ while [ "$TIME" -lt "$TIME_OUT" ]; do
-if [ "$TIME" -ge "$TIME_OUT" ]
- then
- echo -e "\e[1;31mTIME OUT: DOCKER was NOT fully started in $TIME_OUT seconds... Could cause problems ...\e[0m"
-fi
+ MATCH=`docker logs --tail 30 $1 | grep "DOCKER STARTED"`
+ echo MATCH is -- $MATCH
+
+ if [ -n "$MATCH" ]; then
+ echo DOCKER start finished in $TIME seconds
+ break
+ fi
+
+ echo Sleep: $INTERVAL seconds before testing if $1 DOCKER is up. Total wait time up now is: $TIME seconds. Timeout is: $TIME_OUT seconds
+ sleep $INTERVAL
+ TIME=$(($TIME+$INTERVAL))
+ done
+
+ if [ "$TIME" -ge "$TIME_OUT" ]; then
+ echo -e "\e[1;31mTIME OUT: DOCKER was NOT fully started in $TIME_OUT seconds... Could cause problems ...\e[0m"
+ fi
+}
+
+function healthCheck {
+ curl localhost:9200/_cluster/health?pretty=true
+
+ echo "BE health-Check:"
+ curl http://localhost:8080/sdc2/rest/healthCheck
+
+ echo ""
+ echo ""
+ echo "FE health-Check:"
+ curl http://localhost:8181/sdc1/rest/healthCheck
+
+ echo ""
+ echo ""
+ healthCheck_http_code=$(curl -o /dev/null -w '%{http_code}' -H "Accept: application/json" -H "Content-Type: application/json" -H "USER_ID: jh0003" http://localhost:8080/sdc2/rest/v1/user/demo;)
+ if [[ ${healthCheck_http_code} != 200 ]]
+ then
+ echo "Error [${healthCheck_http_code}] while user existance check"
+ return ${healthCheck_http_code}
+ fi
+ echo "check user existance: OK"
+ return ${healthCheck_http_code}
}
+function elasticHealthCheck {
+ echo "Elastic Health-Check:"
+
+ COUNTER=0
+ while [ $COUNTER -lt 20 ]; do
+ echo "Waiting ES docker to start"
+ health_Check_http_code=$(curl -o /dev/null -w '%{http_code}' http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=120s)
+ if [[ "$health_Check_http_code" -eq 200 ]]
+ then
+ break
+ fi
+ let COUNTER=COUNTER+1
+ sleep 4
+ done
+
+ healthCheck_http_code=$(curl -o /dev/null -w '%{http_code}' http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=120s)
+ if [[ "$health_Check_http_code" != 200 ]]
+ then
+ echo "Error [${healthCheck_http_code}] ES NOT started correctly"
+ exit ${healthCheck_http_code}
+ fi
+ echo "ES started correctly"
+ curl localhost:9200/_cluster/health?pretty=true
+ return ${healthCheck_http_code}
+}
RELEASE=latest
LOCAL=false
-SKIPTESTS=false
+RUNTESTS=true
DEBUG_PORT="--publish 4000:4000"
-[ -f /opt/config/env_name.txt ] && DEP_ENV=$(cat /opt/config/env_name.txt) || DEP_ENV=__ENV-NAME__
-[ -f /opt/config/nexus_username.txt ] && NEXUS_USERNAME=$(cat /opt/config/nexus_username.txt) || NEXUS_USERNAME=release
-[ -f /opt/config/nexus_password.txt ] && NEXUS_PASSWD=$(cat /opt/config/nexus_password.txt) || NEXUS_PASSWD=sfWU3DFVdBr7GVxB85mTYgAW
-[ -f /opt/config/nexus_docker_repo.txt ] && NEXUS_DOCKER_REPO=$(cat /opt/config/nexus_docker_repo.txt) || NEXUS_DOCKER_REPO=ecomp-nexus:${PORT}
-
-while [ "$1" != "" ]; do
+while [ $# -gt 0 ]; do
case $1 in
- -r | --release )
- shift
- RELEASE=${1}
- ;;
- -e | --environment )
- shift
- DEP_ENV=${1}
- ;;
- -p | --port )
- shift
- PORT=${1}
- ;;
- -l | --local )
- shift
- LOCAL=true
- ;;
- -s | --skipTests )
- shift
- SKIPTESTS=true
- ;;
- -h | --help )
- usage
- exit
- ;;
- * )
- usage
- exit 1
+ # -r | --release - The specific docker version to pull and deploy
+ -r | --release )
+ shift 1 ;
+ RELEASE=$1;
+ shift 1;;
+ # -e | --environment - The environment name you want to deploy
+ -e | --environment )
+ shift 1;
+ DEP_ENV=$1;
+ shift 1 ;;
+ # -p | --port - The port from which to connect to the docker nexus
+ -p | --port )
+ shift 1 ;
+ PORT=$1;
+ shift 1 ;;
+ # -l | --local - Use this for deploying your local dockers without pulling them first
+ -l | --local )
+ LOCAL=true;
+ shift 1;;
+ # -t | --runTests - Use this for running the sanity tests docker after all other dockers have been deployed
+ -t | --runTests )
+ RUNTESTS=true;
+ shift 1 ;;
+ # -h | --help - Display the help message with all the available run options
+ -h | --help )
+ usage;
+ exit 0;;
+ * )
+ usage;
+ exit 1;;
esac
- shift
done
+
+[ -f /opt/config/env_name.txt ] && DEP_ENV=$(cat /opt/config/env_name.txt) || DEP_ENV=__ENV-NAME__
+[ -f /opt/config/nexus_username.txt ] && NEXUS_USERNAME=$(cat /opt/config/nexus_username.txt) || NEXUS_USERNAME=release
+[ -f /opt/config/nexus_password.txt ] && NEXUS_PASSWD=$(cat /opt/config/nexus_password.txt) || NEXUS_PASSWD=sfWU3DFVdBr7GVxB85mTYgAW
+[ -f /opt/config/nexus_docker_repo.txt ] && NEXUS_DOCKER_REPO=$(cat /opt/config/nexus_docker_repo.txt) || NEXUS_DOCKER_REPO=nexus3.onap.org:${PORT}
[ -f /opt/config/nexus_username.txt ] && docker login -u $NEXUS_USERNAME -p $NEXUS_PASSWD $NEXUS_DOCKER_REPO
-export IP=`ifconfig eth0 | awk -F: '/inet addr/ {gsub(/ .*/,"",$2); print $2}'`
-export PREFIX=${NEXUS_DOCKER_REPO}'/openecomp'
+
+cleanup
+
+
+export IP=`ip route get 8.8.8.8 | awk '/src/{ print $7 }'`
+export PREFIX=${NEXUS_DOCKER_REPO}'/onap'
if [ ${LOCAL} = true ]; then
- PREFIX='openecomp'
+ PREFIX='onap'
fi
-## sanityDocker
-echo "docker run sdc-sanity..."
-if [ ${SKIPTESTS} = false ]; then
-echo "Triger sanity docker, please wait..."
+echo ""
+
+healthCheck
+
+# sanityDocker
+if [[ (${RUNTESTS} = true) && (${healthCheck_http_code} == 200) ]]; then
+ echo "docker run sdc-sanity..."
+ echo "Triger sanity docker, please wait..."
+
if [ ${LOCAL} = false ]; then
- docker pull ${PREFIX}/sdc-sanity:${RELEASE}
+ docker pull ${PREFIX}/sdc-sanity:${RELEASE}
fi
- docker run --detach --name sdc-sanity --env HOST_IP=${IP} --env ENVNAME="${DEP_ENV}" --env http_proxy=${http_proxy} --env https_proxy=${https_proxy} --env no_proxy=${no_proxy} --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --memory 1g --memory-swap=1g --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume /data/logs/sdc-sanity/target:/var/lib/tests/target --volume /data/logs/sdc-sanity/ExtentReport:/var/lib/tests/ExtentReport --volume /data/logs/sdc-sanity/outputCsar:/var/lib/tests/outputCsar --volume /data/environments:/root/chef-solo/environments --publish 9560:9560 ${PREFIX}/sdc-sanity:${RELEASE}
-fi \ No newline at end of file
+
+docker run --detach --name sdc-sanity --env HOST_IP=${IP} --env ENVNAME="${DEP_ENV}" --env http_proxy=${http_proxy} --env https_proxy=${https_proxy} --env no_proxy=${no_proxy} --log-driver=json-file --log-opt max-size=100m --log-opt max-file=10 --ulimit memlock=-1:-1 --memory 1500m --ulimit nofile=4096:100000 --volume /etc/localtime:/etc/localtime:ro --volume ${WORKSPACE}/data/logs/sdc-sanity/target:/var/lib/tests/target --volume ${WORKSPACE}/data/logs/sdc-sanity/ExtentReport:/var/lib/tests/ExtentReport --volume ${WORKSPACE}/data/logs/sdc-sanity/outputCsar:/var/lib/tests/outputCsar --volume ${WORKSPACE}/data/environments:/root/chef-solo/environments --publish 9560:9560 ${PREFIX}/sdc-sanity:${RELEASE}
+echo "please wait while SANITY is starting....."
+monitor_docker sdc-sanity
+
+fi
diff --git a/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/recipes/sanityTests_3_sanity_execution.rb b/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/recipes/sanityTests_3_sanity_execution.rb
index 517db3d76f..0ffa48d6ed 100644
--- a/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/recipes/sanityTests_3_sanity_execution.rb
+++ b/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/recipes/sanityTests_3_sanity_execution.rb
@@ -1,5 +1,11 @@
tests_base="/var/lib/tests"
-ci_test_suite="pass.xml"
+ci_test_suite="onap.xml"
+
+bash "echo status" do
+ code <<-EOH
+ echo "DOCKER STARTED"
+ EOH
+end
bash "run asdc ci sanity tests" do
cwd "#{tests_base}"
@@ -10,10 +16,4 @@ code <<-EOH
echo "return code from startTest.sh = [$?]"
echo "DOCKER STARTED"
EOH
-timeout 72000
end
-bash "echo status" do
- code <<-EOH
- echo "DOCKER STARTED"
- EOH
-end \ No newline at end of file
diff --git a/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/templates/default/sdc-sanity.yaml.erb b/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/templates/default/sdc-sanity.yaml.erb
index c57269c764..8dde3cdefe 100644
--- a/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/templates/default/sdc-sanity.yaml.erb
+++ b/sdc-os-chef/sdc-sanity/chef-repo/cookbooks/sdc-sanity/templates/default/sdc-sanity.yaml.erb
@@ -18,7 +18,7 @@ errorConfigurationFile: <%= @errorConfigurationFile %>
configurationFile: <%= @ConfigurationFile %>
importTypesConfigDir: <%= @importTypesDir %>
titanPropertiesFile: <%= @titan_file %>
-systemUnderDebug: false
+systemUnderDebug: true
cassandraHost: <%= @CASSANDRA_IP %>
cassandraAuthenticate: true
@@ -30,6 +30,15 @@ cassandraTruststorePassword : Aa123456
cassandraAuditKeySpace: sdcAudit
cassandraArtifactKeySpace: sdcArtifact
+# catalog backend protocol
+<% if node[:disableHttp] -%>
+sdcHttpMethod: https
+<% else %>
+sdcHttpMethod: http
+<% end -%>
+
+localDataCenter: DC-Automate01
+
stopOnClassFailure: false
#List of non-abstract resources to keep during titan cleanup between tests
diff --git a/asdc-tests/src/test/resources/logback-test.xml b/security-utils/logback-test.xml
index 03ce9d1243..4b7eb955c7 100644
--- a/asdc-tests/src/test/resources/logback-test.xml
+++ b/security-utils/logback-test.xml
@@ -1,5 +1,5 @@
<!-- only one line, shut up logback ! -->
-<configuration>
+<configuration >
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>
@@ -7,7 +7,7 @@
</Pattern>
</encoder>
</appender>
- <root level="off">
+ <root level="OFF">
<appender-ref ref="STDOUT" />
</root>
-</configuration> \ No newline at end of file
+</configuration>
diff --git a/security-utils/pom.xml b/security-utils/pom.xml
index ec707c23e4..a6e9befe5d 100644
--- a/security-utils/pom.xml
+++ b/security-utils/pom.xml
@@ -11,13 +11,33 @@
<version>1.2.0-SNAPSHOT</version>
</parent>
+ <properties>
+ <sonar.skip>true</sonar.skip>
+ </properties>
+
<dependencies>
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
+
+ <!-- slf4j + logback -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>${slf4j-api.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!-- functional java -->
+ <dependency>
+ <groupId>org.functionaljava</groupId>
+ <artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
</project>
diff --git a/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java b/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java
index ef424b95de..5f5e00722e 100644
--- a/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java
+++ b/security-utils/src/main/java/org/openecomp/sdc/security/Passwords.java
@@ -20,6 +20,9 @@
package org.openecomp.sdc.security;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -27,8 +30,10 @@ import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
+
public class Passwords {
+ private static Logger log = LoggerFactory.getLogger( Passwords.class.getName());
private static final Random RANDOM = new SecureRandom();
private static final int SALT = 0;
private static final int HASH = 1;
@@ -47,13 +52,14 @@ public class Passwords {
* @return a "salt:hash" value
*/
public static String hashPassword(String password) {
- byte[] salt = getNextSalt();
- byte byteData[] = hash(salt, password.getBytes());
- if (byteData != null) {
- return toHex(salt) + ":" + toHex(byteData);
+ if (password!=null){
+ byte[] salt = getNextSalt();
+ byte byteData[] = hash(salt, password.getBytes());
+ if (byteData != null) {
+ return toHex(salt) + ":" + toHex(byteData);
+ }
}
return null;
-
}
/**
@@ -64,6 +70,15 @@ public class Passwords {
* @return
*/
public static boolean isExpectedPassword(String password, String expectedHash) {
+ if (password==null && expectedHash==null)
+ return true;
+ if (password==null || expectedHash==null) //iff exactly 1 is null
+ return false;
+ if (!expectedHash.contains(":")){
+ log.error("invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" +
+ "\t\t\t");
+ return false;
+ }
String[] params = expectedHash.split(":");
return isExpectedPassword(password, params[SALT], params[HASH]);
}
@@ -78,6 +93,15 @@ public class Passwords {
* @return true if the password matched the hash
*/
public static boolean isExpectedPassword(String password, String salt, String hash) {
+ if ( password == null && hash == null )
+ return true;
+ if ( salt == null ){
+ log.error("salt must be initialized");
+ return false;
+ }
+ //unintialized params
+ if ( password == null || hash == null )
+ return false;
byte[] saltBytes = fromHex(salt);
byte[] hashBytes = fromHex(hash);
@@ -137,6 +161,8 @@ public class Passwords {
* @return the hex string decoded into a byte array
*/
private static byte[] fromHex(String hex) {
+ if ( hex == null )
+ return null;
byte[] binary = new byte[hex.length() / 2];
for (int i = 0; i < binary.length; i++) {
binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
diff --git a/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java b/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java
new file mode 100644
index 0000000000..892c29b88f
--- /dev/null
+++ b/security-utils/src/main/java/org/openecomp/sdc/security/SecurityUtil.java
@@ -0,0 +1,155 @@
+package org.openecomp.sdc.security;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
+import fj.data.*;
+
+public class SecurityUtil {
+
+ private static final Logger LOG = LoggerFactory.getLogger( SecurityUtil.class );
+ private static final byte[] KEY = new byte[]{-64,5,-32 ,-117 ,-44,8,-39, 1, -9, 36,-46,-81, 62,-15,-63,-75};
+ public static final SecurityUtil INSTANCE = new SecurityUtil();
+ public static final String ALGORITHM = "AES" ;
+ public static final String CHARSET = StandardCharsets.UTF_8.name();
+
+ public static Key secKey = null ;
+
+ /**
+ *
+ * cmd commands >$PROGRAM_NAME decrypt "$ENCRYPTED_MSG"
+ * >$PROGRAM_NAME encrypt "message"
+ **/
+ public static void main(String[] args) throws Exception {
+ if ( args!=null && args.length>1){
+ fj.data.Either res = null;
+ final String op = args[0].trim().toLowerCase();
+ try{
+ switch(op) {
+ case "decrypt":
+ res = INSTANCE.decrypt(Base64.getDecoder().decode(args[1]), true);
+ break;
+ case "encrypt":
+ res = INSTANCE.encrypt(args[1]);
+ break;
+ default:
+ LOG.warn("Unfamiliar command please use: \n>aes <encrypt/decrypt> 'message to encrypt/decrypt' ");
+ }
+ }catch(Exception e){
+ LOG.debug( "cannot perform {}:" );
+ throw e;
+ }
+ LOG.debug( "output: {}", res!=null && res.isLeft() ? res.left().value() : "ERROR" );
+ }
+ }
+
+ private SecurityUtil(){ super(); }
+
+ static {
+ try{
+ secKey = generateKey( KEY, ALGORITHM );
+ }
+ catch(Exception e){
+ LOG.warn("cannot generate key for {}", ALGORITHM);
+ }
+ }
+
+
+
+ public static Key generateKey(final byte[] KEY, String algorithm){
+ return new SecretKeySpec(KEY, algorithm);
+ }
+
+ //obfuscates key prefix -> **********
+ public String obfuscateKey(String sensitiveData){
+
+ if (sensitiveData != null){
+ int len = sensitiveData.length();
+ StringBuilder builder = new StringBuilder(sensitiveData);
+ for (int i=0; i<len/2; i++){
+ builder.setCharAt(i, '*');
+ }
+ return builder.toString();
+ }
+ return sensitiveData;
+ }
+
+ /**
+ * @param strDataToEncrypt - plain string to encrypt
+ * Encrypt the Data
+ * a. Declare / Initialize the Data. Here the data is of type String
+ * b. Convert the Input Text to Bytes
+ * c. Encrypt the bytes using doFinal method
+ */
+ public Either<String,String> encrypt(String strDataToEncrypt){
+ if (strDataToEncrypt != null ){
+ try {
+ LOG.debug("Encrypt key -> {}", secKey);
+ Cipher aesCipherForEncryption = Cipher.getInstance("AES"); // Must specify the mode explicitly as most JCE providers default to ECB mode!!
+ aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secKey);
+ byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
+ byte[] byteCipherText = aesCipherForEncryption.doFinal(byteDataToEncrypt);
+ String strCipherText = new String( java.util.Base64.getMimeEncoder().encode(byteCipherText), CHARSET );
+ LOG.debug("Cipher Text generated using AES is {}", strCipherText);
+ return Either.left(strCipherText);
+ } catch( NoSuchAlgorithmException | UnsupportedEncodingException e){
+ LOG.warn( "cannot encrypt data unknown algorithm or missing encoding for {}" ,secKey.getAlgorithm());
+ } catch( InvalidKeyException e){
+ LOG.warn( "invalid key recieved - > {} | {}" , java.util.Base64.getDecoder().decode( secKey.getEncoded() ), e.getMessage() );
+ } catch( IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e){
+ LOG.warn( "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding" , e.getMessage() );
+ }
+ }
+ return Either.right("Cannot encrypt "+strDataToEncrypt);
+ }
+
+ /**
+ * Decrypt the Data
+ * @param byteCipherText - should be valid bae64 input in the length of 16bytes
+ * @param isBase64Decoded - is data already base64 encoded&aligned to 16 bytes
+ * a. Initialize a new instance of Cipher for Decryption (normally don't reuse the same object)
+ * b. Decrypt the cipher bytes using doFinal method
+ */
+ public Either<String,String> decrypt(byte[] byteCipherText , boolean isBase64Decoded){
+ if (byteCipherText != null){
+ byte[] alignedCipherText = byteCipherText;
+ try{
+ if (isBase64Decoded)
+ alignedCipherText = Base64.getDecoder().decode(byteCipherText);
+ LOG.debug("Decrypt key -> "+secKey.getEncoded());
+ Cipher aesCipherForDecryption = Cipher.getInstance("AES"); // Must specify the mode explicitly as most JCE providers default to ECB mode!!
+ aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secKey);
+ byte[] byteDecryptedText = aesCipherForDecryption.doFinal(alignedCipherText);
+ String strDecryptedText = new String(byteDecryptedText);
+ LOG.debug("Decrypted Text message is: {}" , obfuscateKey( strDecryptedText ));
+ return Either.left(strDecryptedText);
+ } catch( NoSuchAlgorithmException e){
+ LOG.warn( "cannot encrypt data unknown algorithm or missing encoding for {}" ,secKey.getAlgorithm());
+ } catch( InvalidKeyException e){
+ LOG.warn( "invalid key recieved - > {} | {}" , java.util.Base64.getDecoder().decode( secKey.getEncoded() ), e.getMessage() );
+ } catch( IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e){
+ LOG.warn( "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding" , e.getMessage() );
+ }
+ }
+ return Either.right("Decrypt FAILED");
+ }
+
+ public Either<String,String> decrypt(String byteCipherText){
+ try {
+ return decrypt(byteCipherText.getBytes(CHARSET),true);
+ } catch( UnsupportedEncodingException e ){
+ LOG.warn( "Missing encoding for {} | {} " ,secKey.getAlgorithm() , e.getMessage());
+ }
+ return Either.right("Decrypt FAILED");
+ }
+}
diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/PasswordTest.java
deleted file mode 100644
index 895806d1b5..0000000000
--- a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordTest.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.security;
-
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class PasswordTest {
-
- @Test
- public void hashtest() {
- String password = "123456";
- String hash = Passwords.hashPassword(password);
- assertTrue(Passwords.isExpectedPassword(password, hash));
- password = "1sdfgsgd23456";
- hash = Passwords.hashPassword(password);
- assertTrue(Passwords.isExpectedPassword(password, hash));
- password = "1sdfgsgd2345((*&%$%6";
- hash = Passwords.hashPassword(password);
- assertTrue(Passwords.isExpectedPassword(password, hash));
- password = "";
- hash = Passwords.hashPassword(password);
- assertTrue(Passwords.isExpectedPassword(password, hash));
- password = " ";
- hash = Passwords.hashPassword(password);
- assertTrue(Passwords.isExpectedPassword(password, hash));
- }
-
-}
diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java
new file mode 100644
index 0000000000..26f04735e5
--- /dev/null
+++ b/security-utils/src/test/java/org/openecomp/sdc/security/PasswordsTest.java
@@ -0,0 +1,75 @@
+package org.openecomp.sdc.security;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class PasswordsTest {
+
+ @Test
+ public void hashPassword() throws Exception {
+ String hash = Passwords.hashPassword("hello1234");
+ assertEquals(true, Passwords.isExpectedPassword("hello1234", hash));
+
+ //test different salt-> result in different hash
+ String hash2 = Passwords.hashPassword("hello1234");
+ assertEquals(false, hash.equals(hash2));
+
+ String hash3 = Passwords.hashPassword("");
+ assertEquals(true, Passwords.isExpectedPassword("", hash3));
+
+ String hash4 = Passwords.hashPassword(null);
+ assertEquals(true, hash4 == null );
+ }
+
+ @Test
+ public void isExpectedPassword() throws Exception {
+ //region isExpectedPassword(String password, String salt, String hash)
+ assertEquals(true, Passwords.isExpectedPassword(null, null , null));
+ //valid hash
+ assertEquals(true, Passwords.isExpectedPassword("hello1234", "e0277df331f4ff8f74752ac4a8fbe03b","6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0"));
+ //invalid salt
+ assertEquals(false, Passwords.isExpectedPassword("hello1234", "c0000df331f4ff8f74752ac4a00be03c","6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0"));
+ assertEquals(false, Passwords.isExpectedPassword("hello1234", null,"6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0"));
+ //exacly 1 param uninitialized
+ assertEquals(false,Passwords.isExpectedPassword("hello1234", "",null));
+ assertEquals(false,Passwords.isExpectedPassword( null, "" , "hello1234"));
+ //no salt & no hash
+ assertEquals(false, Passwords.isExpectedPassword("hello1234", null ,"hello1234"));
+ //endregion
+
+ //region isExpectedPassword(String password, String expectedHash)
+ assertEquals(true, Passwords.isExpectedPassword(null, null));
+ //valid hash
+ assertEquals(true, Passwords.isExpectedPassword("hello1234", "e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0"));
+ //invalid salt
+ assertEquals(false, Passwords.isExpectedPassword("hello1234", "c0000df331f4ff8f74752ac4a00be03c:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0"));
+ //exacly 1 param uninitialized
+ assertEquals(false,Passwords.isExpectedPassword("hello1234", null));
+ assertEquals(false,Passwords.isExpectedPassword( null,"hello1234"));
+ //no salt & no hash
+ assertEquals(false, Passwords.isExpectedPassword("hello1234", "hello1234"));
+ //endregion
+ }
+
+ @Test
+ public void hashtest() {
+ String password = "123456";
+ String hash = Passwords.hashPassword(password);
+ assertTrue(Passwords.isExpectedPassword(password, hash));
+ password = "1sdfgsgd23456";
+ hash = Passwords.hashPassword(password);
+ assertTrue(Passwords.isExpectedPassword(password, hash));
+ password = "1sdfgsgd2345((*&%$%6";
+ hash = Passwords.hashPassword(password);
+ assertTrue(Passwords.isExpectedPassword(password, hash));
+ password = "";
+ hash = Passwords.hashPassword(password);
+ assertTrue(Passwords.isExpectedPassword(password, hash));
+ password = " ";
+ hash = Passwords.hashPassword(password);
+ assertTrue(Passwords.isExpectedPassword(password, hash));
+ }
+
+
+} \ No newline at end of file
diff --git a/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java b/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java
new file mode 100644
index 0000000000..e23c864b77
--- /dev/null
+++ b/security-utils/src/test/java/org/openecomp/sdc/security/SecurityUtilTest.java
@@ -0,0 +1,27 @@
+package org.openecomp.sdc.security;
+
+import org.junit.Test;
+import java.util.Base64;
+import static org.junit.Assert.*;
+
+public class SecurityUtilTest {
+
+ @Test
+ public void encryptDecryptAES128() throws Exception {
+ String data = "decrypt SUCCESS!!";
+ String encrypted = SecurityUtil.INSTANCE.encrypt(data).left().value();
+ assertNotEquals( data, encrypted );
+ byte[] decryptMsg = Base64.getDecoder().decode(encrypted);
+ assertEquals( SecurityUtil.INSTANCE.decrypt( decryptMsg , false ).left().value() ,data );
+ assertEquals( SecurityUtil.INSTANCE.decrypt( encrypted.getBytes() , true ).left().value() ,data );
+ }
+
+ @Test
+ public void obfuscateKey() throws Exception {
+ String key = "abcdefghij123456";
+ String expectedkey = "********ij123456";
+ String obfuscated = SecurityUtil.INSTANCE.obfuscateKey( key );
+ System.out.println( obfuscated );
+ assertEquals( obfuscated , expectedkey );
+ }
+} \ No newline at end of file
diff --git a/test-apis-ci/pom.xml b/test-apis-ci/pom.xml
index 59dc3fd433..ef0eff467c 100644
--- a/test-apis-ci/pom.xml
+++ b/test-apis-ci/pom.xml
@@ -1,359 +1,450 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <modelVersion>4.0.0</modelVersion>
-
- <artifactId>test-apis-ci</artifactId>
-
- <parent>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-main</artifactId>
- <version>1.2.0-SNAPSHOT</version>
- </parent>
-
- <properties>
- <sonar.skip>true</sonar.skip>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>${testng.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.aventstack</groupId>
- <artifactId>extentreports</artifactId>
- <version>3.0.6</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <version>${mockito.version}</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>com.typesafe</groupId>
- <artifactId>config</artifactId>
- <version>1.0.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.jcraft.jsch</groupId>
- <artifactId>com.springsource.com.jcraft.jsch</artifactId>
- <version>0.1.41</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>common-app-api</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>common-be</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- CHECK CATLOG MODEL -->
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>catalog-model</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- catalog dao -->
- <dependency>
- <groupId>org.openecomp.sdc.be</groupId>
- <artifactId>catalog-dao</artifactId>
- <version>${project.version}</version>
- <scope>compile</scope>
- </dependency>
- <!-- functional java -->
- <dependency>
- <groupId>org.functionaljava</groupId>
- <artifactId>functionaljava</artifactId>
- <version>${functionaljava.version}</version>
- <scope>compile</scope>
- </dependency>
- <!-- CASSANDRA -->
- <dependency>
- <groupId>com.datastax.cassandra</groupId>
- <artifactId>cassandra-driver-core</artifactId>
- <version>${cassandra.driver.version}</version>
- <scope>compile</scope>
- </dependency>
- <!-- CASSANDRA END -->
-
- <!-- slf4j + logback -->
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>test-apis-ci</artifactId>
+
+ <parent>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>sdc-main</artifactId>
+ <version>1.2.0-SNAPSHOT</version>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${guava.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${junit.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!--<dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>-->
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-all</artifactId>
+ <version>1.3</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <version>${testng.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.aventstack</groupId>
+ <artifactId>extentreports</artifactId>
+ <version>3.0.6</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
+ <version>1.0.2</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.17</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.jcraft.jsch</groupId>
+ <artifactId>com.springsource.com.jcraft.jsch</artifactId>
+ <version>0.1.41</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- <dependency>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>dmaap-publisher</artifactId>
+ <version>1.0.0</version>
+ <scope>provided</scope>
+ </dependency>-->
+
+ <dependency>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>common-app-api</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.openecomp.sdc.be</groupId>
+ <artifactId>common-be</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- CHECK CATLOG MODEL -->
+ <dependency>
+ <groupId>org.openecomp.sdc.be</groupId>
+ <artifactId>catalog-model</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- catalog dao -->
+ <dependency>
+ <groupId>org.openecomp.sdc.be</groupId>
+ <artifactId>catalog-dao</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!-- functional java -->
+ <dependency>
+ <groupId>org.functionaljava</groupId>
+ <artifactId>functionaljava</artifactId>
+ <version>${functionaljava.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!-- CASSANDRA -->
+ <dependency>
+ <groupId>com.datastax.cassandra</groupId>
+ <artifactId>cassandra-driver-core</artifactId>
+ <version>${cassandra.driver.version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <!-- CASSANDRA END -->
+
+ <!-- slf4j + logback -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
<version>${slf4j-api.version}</version>
- <scope>compile</scope>
- </dependency>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
- <scope>compile</scope>
- </dependency>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
<version>${logback.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.googlecode.json-simple</groupId>
- <artifactId>json-simple</artifactId>
- <version>${json-simple.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- File changes listener -->
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jci-core</artifactId>
- <version>${commons-jci-core.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.googlecode.json-simple</groupId>
+ <artifactId>json-simple</artifactId>
+ <version>${json-simple.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- File changes listener -->
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-jci-core</artifactId>
+ <version>${commons-jci-core.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
<version>${commons-codec}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Gson -->
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>${gson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- Snake Yaml -->
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>${snakeyaml.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- http client -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Gson -->
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>${gson.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Snake Yaml -->
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>${snakeyaml.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- http client -->
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
+ <scope>compile</scope>
+ </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpmime</artifactId>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpmime</artifactId>
<version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.5</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.5</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
<version>${commons-logging}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- http core -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- TITAN -->
- <dependency>
- <groupId>com.thinkaurelius.titan</groupId>
- <artifactId>titan-core</artifactId>
- <version>${titan.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc.sdc-titan-cassandra</groupId>
- <artifactId>sdc-titan-cassandra</artifactId>
- <version>${titan.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.3.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.3.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.ecompsdkos</groupId>
- <artifactId>epsdk-fw</artifactId>
- <version>${ecomp.version}</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <artifactId>slf4j-log4j12</artifactId>
- <groupId>org.slf4j</groupId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20090211</version>
- </dependency>
- <dependency>
- <groupId>org.openecomp.sdc.sdc-tosca</groupId>
- <artifactId>sdc-tosca</artifactId>
- <version>${sdc-tosca-parser.version}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
-
- <!-- ============================================= -->
- <!-- Get the next build number -->
- <!-- ============================================= -->
- <!--<plugin>-->
- <!--<groupId>org.codehaus.mojo</groupId>-->
- <!--<artifactId>properties-maven-plugin</artifactId>-->
- <!--<version>1.0-alpha-1</version>-->
- <!--<inherited>false</inherited>-->
-
- <!--<executions>-->
- <!--<execution>-->
- <!--<id>tests</id>-->
- <!--<phase>initialize</phase>-->
- <!--<goals>-->
- <!--<goal>read-project-properties</goal>-->
- <!--</goals>-->
-
- <!--<configuration>-->
- <!--<files>-->
- <!--<file>../target/FullReleaseVersion.properties</file>-->
- <!--</files>-->
- <!--</configuration>-->
- <!--</execution>-->
- <!--</executions>-->
- <!--</plugin>-->
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-deploy-plugin</artifactId>
- <version>2.7</version>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
-
- <!-- ============================================= -->
- <!-- Create the JAR file with its dependencies -->
- <!-- ============================================= -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>create.jar.with.dependencies</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <archive>
- <manifest>
- <mainClass>org.openecomp.sdc.ci.tests.run.StartTest</mainClass>
- </manifest>
- </archive>
- <descriptorRefs>
- <descriptorRef>jar-with-dependencies</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- http core -->
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpcore</artifactId>
+ <version>${httpcore.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- TITAN -->
+ <dependency>
+ <groupId>com.thinkaurelius.titan</groupId>
+ <artifactId>titan-core</artifactId>
+ <version>${titan.version}</version>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>slf4j-log4j12</artifactId>
+ <groupId>org.slf4j</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>com.thinkaurelius.titan</groupId>
+ <artifactId>titan-cassandra</artifactId>
+ <version>${titan.version}</version>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>slf4j-log4j12</artifactId>
+ <groupId>org.slf4j</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>org.codehaus.jackson</groupId>
+ <artifactId>jackson-mapper-asl</artifactId>
+ <version>1.9.2</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>2.3.1</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>2.3.1</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.openecomp.ecompsdkos</groupId>
+ <artifactId>epsdk-fw</artifactId>
+ <version>${ecomp.version}</version>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>slf4j-log4j12</artifactId>
+ <groupId>org.slf4j</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ <version>20131018</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.openecomp.sdc.sdc-tosca</groupId>
+ <artifactId>sdc-tosca</artifactId>
+ <version>1.2.1-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>info.cukes</groupId>
+ <artifactId>cucumber-junit</artifactId>
+ <version>1.2.4</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>info.cukes</groupId>
+ <artifactId>cucumber-core</artifactId>
+ <version>1.2.4</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>info.cukes</groupId>
+ <artifactId>gherkin</artifactId>
+ <version>2.12.2</version>
+ </dependency>
+ <dependency>
+ <groupId>info.cukes</groupId>
+ <artifactId>cucumber-java</artifactId>
+ <version>1.2.5</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>info.cukes</groupId>
+ <artifactId>cucumber-jvm-deps</artifactId>
+ <version>1.0.5</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mock-server</groupId>
+ <artifactId>mockserver-netty</artifactId>
+ <version>3.10.4</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
+ <artifactId>sdc-distribution-client</artifactId>
+ <version>1.2.2 </version>
+ <scope>test</scope>
+ </dependency>
+
+ <!-- With TestNG -->
+ <dependency>
+ <groupId>info.cukes</groupId>
+ <artifactId>cucumber-testng</artifactId>
+ <version>1.2.5</version>
+ </dependency>
+
+ <!-- spring -->
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ <version>${spring.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- CASSANDRA -->
+ <dependency>
+ <groupId>com.datastax.cassandra</groupId>
+ <artifactId>cassandra-driver-mapping</artifactId>
+ <version>${cassandra.driver.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- CASSANDRA END -->
+ </dependencies>
+
+ <build>
+ <plugins>
+
+ <!-- ============================================= -->
+ <!-- Get the next build number -->
+ <!-- ============================================= -->
+ <!--<plugin> -->
+ <!--<groupId>org.codehaus.mojo</groupId> -->
+ <!--<artifactId>properties-maven-plugin</artifactId> -->
+ <!--<version>1.0-alpha-1</version> -->
+ <!--<inherited>false</inherited> -->
+
+ <!--<executions> -->
+ <!--<execution> -->
+ <!--<id>tests</id> -->
+ <!--<phase>initialize</phase> -->
+ <!--<goals> -->
+ <!--<goal>read-project-properties</goal> -->
+ <!--</goals> -->
+
+ <!--<configuration> -->
+ <!--<files> -->
+ <!--<file>../target/FullReleaseVersion.properties</file> -->
+ <!--</files> -->
+ <!--</configuration> -->
+ <!--</execution> -->
+ <!--</executions> -->
+ <!--</plugin> -->
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.7</version>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+
+ <!-- ============================================= -->
+ <!-- Create the JAR file with its dependencies -->
+ <!-- ============================================= -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>create.jar.with.dependencies</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <archive>
+ <manifest>
+ <mainClass>org.openecomp.sdc.ci.tests.run.StartTest</mainClass>
+ </manifest>
+ </archive>
+ <descriptorRefs>
+ <descriptorRef>jar-with-dependencies</descriptorRef>
+ </descriptorRefs>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
</project>
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
index a49d5c61fe..1d0b4040ca 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
@@ -37,6 +37,7 @@ import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
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;
@@ -66,15 +67,10 @@ 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.Logger;
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 org.testng.annotations.*;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
@@ -85,11 +81,17 @@ 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 Logger logger= LoggerFactory.getLogger(ComponentBaseTest.class);
protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
@@ -127,16 +129,16 @@ public abstract class ComponentBaseTest {
myContext=context;
ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
AtomicOperationUtils.createDefaultConsumer(true);
- openTitanLogic();
+// openTitanLogic();
performClean();
-
-
+
+
}
@BeforeMethod(alwaysRun = true)
public void setupBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
-
+
System.out.println(" method.getName() " + method.getName());
if (!method.getName().equals("onboardVNFShotFlow")) {
// System.out.println("ExtentReport instance started from BeforeMethod...");
@@ -182,7 +184,7 @@ public abstract class ComponentBaseTest {
}
- @AfterClass(alwaysRun = true)
+/* @AfterClass(alwaysRun = true)
public synchronized static void cleanAfterClass() throws Exception{
// System.out.println("<<<<<<<<class name>>>>>"+method.getDeclaringClass());
@@ -190,19 +192,23 @@ public abstract class ComponentBaseTest {
System.out.println("delete components AfterClass");
- deleteCreatedComponents(getCatalogAsMap());
+ if(!config.getSystemUnderDebug()){
+ deleteCreatedComponents(getCatalogAsMap());
+// CassandraUtils.truncateAllKeyspaces();
+ }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 ...");
+ }
// extentReport.flush();
- }
+ }*/
@AfterSuite(alwaysRun = true)
public static void shutdownTitan() throws Exception {
performClean();
- shutdownTitanLogic();
+// shutdownTitanLogic();
}
-
protected static void openTitanLogic() throws Exception {
logger.trace(config.toString());
@@ -234,9 +240,8 @@ public abstract class ComponentBaseTest {
// cleanComponents();
if(!config.getSystemUnderDebug()){
deleteCreatedComponents(getCatalogAsMap());
- CassandraUtils.truncateAllKeyspaces();
+// CassandraUtils.truncateAllKeyspaces();
FileHandling.overWriteExistindDir("outputCsar");
-
}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 ...");
}
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
index 26edee9c7f..b320f4200e 100644
--- 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
@@ -20,19 +20,23 @@
package org.openecomp.sdc.ci.tests.api;
-import java.io.File;
-
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
-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;
+import org.openecomp.sdc.ci.tests.config.Config;
+
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
+import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils;
+import org.testng.ITestContext;
+
+import java.io.File;
public class ExtentManager {
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java
index 045d565a41..2c242d00bd 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java
@@ -20,14 +20,16 @@
package org.openecomp.sdc.ci.tests.api;
-import java.io.File;
-
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;
+import java.io.File;
+import org.openecomp.sdc.ci.tests.api.ExtentTestManager;
+
public class ExtentTestActions {
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
index b525150af4..810f6a6543 100644
--- 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
@@ -20,12 +20,12 @@
package org.openecomp.sdc.ci.tests.api;
-import java.util.HashMap;
-
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
+import java.util.HashMap;
public class ExtentTestManager implements SomeInterface{
+
private static HashMap<Long, ExtentTest> extentTestMap = new HashMap<Long, ExtentTest>();
private static ExtentReports extent = ExtentManager.getReporter();
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
index fd6e9eebc0..b908dddf48 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
@@ -20,220 +20,224 @@
package org.openecomp.sdc.ci.tests.api;
+
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+import java.io.FileNotFoundException;
+
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 static String SDC_HTTP_METHOD = Utils.getConfigHandleException() == null ? "http" : Utils.getConfigHandleException().getSdcHttpMethod();
+ final String AMDOCS_HTTP_METHOD = SDC_HTTP_METHOD;
+
- 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 UPLOAD_ZIP_URL = SDC_HTTP_METHOD + "://%s:%s/sdc1/rest/v1/catalog/resources";
+ final String GET_IMAGE_DATA_FROM_ES = SDC_HTTP_METHOD + "://%s:%s/resources/imagedata/_search?q=resourceName:%s&pretty=true&size=1000";
+ final String GET_SCRIPT_DATA_FROM_ES = SDC_HTTP_METHOD + "://%s:%s/resources/artifactdata/_search?q=resourceName:%s&pretty=true&size=1000";
+ final String GET_ID_LIST_BY_INDEX_FROM_ES = SDC_HTTP_METHOD + "://%s:%s/%s/%s/_search?fields=_id&size=1000";
- final String GET_HEALTH_CHECK_VIA_PROXY = "http://%s:%s/sdc1/rest/healthCheck";
+ final String ES_URL = SDC_HTTP_METHOD + "://%s:%s";
+ final String GET_SERVICE_CSAR_API1 = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/services/%s/%s";
+ final String GET_SERVICE_CSAR_API2 = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/services/%s/%s/csar";
+
+ final String GET_SERVICE_CSAR_FE_PROXY_API1 = SDC_HTTP_METHOD + "://%s:%s/sdc1/portal/rest/services/%s/%s";
+ final String GET_CSAR_USING_SIMULATOR = SDC_HTTP_METHOD + "://%s:%s/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages/%s";
+ final String COPY_CSAR_USING_SIMULATOR = SDC_HTTP_METHOD + "://%s:%s/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages/%s/%s";
+
+ final String GET_HEALTH_CHECK_VIA_PROXY = SDC_HTTP_METHOD + "://%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";
+ final String GET_CONFIG_MANAGER = SDC_HTTP_METHOD + "://%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_RESOURCE_lATEST_VERSION = SDC_HTTP_METHOD + "://%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";
+ final String GET_SERVICE_lATEST_VERSION = SDC_HTTP_METHOD + "://%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";
+ final String GET_RESOURCE_ARTIFACTS_LIST = SDC_HTTP_METHOD + "://%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";
+ final String GET_RESOURCE_ARTIFACT_METADATA = SDC_HTTP_METHOD + "://%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";
+ final String GET_RESOURCE_ARTIFACT_PAYLOAD = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s";
- // 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";
+ final String GET_RESOURCE_ARTIFACT_PAYLOAD_FE_PROXY = SDC_HTTP_METHOD + "://%s:%s/sdc1/portal/rest/v1/catalog/resources/%s/%s/artifacts/%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";
+ final String GET_SERVICE_ARTIFACTS_LIST = SDC_HTTP_METHOD + "://%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";
+ final String GET_SERVICE_METADATA = SDC_HTTP_METHOD + "://%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_SERVICE_ARTIFACT_PAYLOAD = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s";
- final String GET_SEARCH_DATA_FROM_ES = "http://%s:%s/%s";
+ final String GET_SEARCH_DATA_FROM_ES = SDC_HTTP_METHOD + "://%s:%s/%s";
// ****************************************************USER
// URLs********************************************************
- final String GET_USER = "http://%s:%s/sdc2/rest/v1/user/%s";
+ final String GET_USER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/%s";
- final String GET_USER_ROLE = "http://%s:%s/sdc2/rest/v1/user/%s/role";
+ final String GET_USER_ROLE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/%s/role";
- final String CREATE_USER = "http://%s:%s/sdc2/rest/v1/user";
+ final String CREATE_USER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user";
- final String UPDATE_USER = "http://%s:%s/sdc2/rest/v1/user/%s";
+ final String UPDATE_USER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/%s";
- final String UPDATE_USER_ROLE = "http://%s:%s/sdc2/rest/v1/user/%s/role";
+ final String UPDATE_USER_ROLE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/%s/role";
- final String DELETE_USER = "http://%s:%s/sdc2/rest/v1/user/%s";
+ String DELETE_USER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/%s";
- final String GET_ALL_ADMIN_USERS = "http://%s:%s/sdc2/rest/v1/user/admins";
+ String GET_ALL_ADMIN_USERS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/admins";
- final String AUTHORIZE_USER = "http://%s:%s/sdc2/rest/v1/user/authorize";
+ final String AUTHORIZE_USER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/authorize";
- final String GET_ALL_TAGS = "http://%s:%s/sdc2/rest/v1/tags";
+ final String GET_ALL_TAGS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/tags";
- final String AUTH_USER = "http://%s:%s/sdc2/rest/v1/user/authorize";
+ final String AUTH_USER = SDC_HTTP_METHOD + "://%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_NOT_ABSTRACT_RESOURCES = SDC_HTTP_METHOD + "://%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 GET_ALL_ABSTRACT_RESOURCES = SDC_HTTP_METHOD + "://%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 QUERY_NEO4J = SDC_HTTP_METHOD + "://%s:%s/db/data/transaction";
+ final String CHANGE_IN_NEO4J = SDC_HTTP_METHOD + "://%s:%s/db/data/transaction/commit";
- final String GET_ALL_ADMINS = "http://%s:%s/sdc2/rest/v1/user/admins";
+ final String GET_ALL_ADMINS = SDC_HTTP_METHOD + "://%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_USERS_BY_ROLES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/users?roles=%s";
- final String GET_ALL_USERS = "http://%s:%s/sdc2/rest/v1/user/users?roles/";
+ final String GET_ALL_USERS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/user/users?roles/";
// *****************************************ECOMP User
// URL's*****************************************************
- final String ECOMP_PUSH_USER = "http://%s:%s/api/v2/user";
+ final String ECOMP_PUSH_USER = SDC_HTTP_METHOD + "://%s:%s/api/v2/user";
- final String ECOMP_EDIT_USER = "http://%s:%s/api/v2/user/%s";
+ final String ECOMP_EDIT_USER = SDC_HTTP_METHOD + "://%s:%s/api/v2/user/%s";
- final String ECOMP_GET_USER = "http://%s:%s/api/v2/user/%s";
+ final String ECOMP_GET_USER = SDC_HTTP_METHOD + "://%s:%s/api/v2/user/%s";
- final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/v2/users";
+ final String ECOMP_GET_ALL_USERS = SDC_HTTP_METHOD + "://%s:%s/api/v2/users";
- final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/v2/roles";
+ final String ECOMP_GET_ALL_AVAILABLE_ROLES = SDC_HTTP_METHOD + "://%s:%s/api/v2/roles";
- final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/v2/user/%s/roles";
+ final String ECOMP_PUSH_USER_ROLES = SDC_HTTP_METHOD + "://%s:%s/api/v2/user/%s/roles";
- final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/v2/user/%s/roles";
+ final String ECOMP_GET_USER_ROLES = SDC_HTTP_METHOD + "://%s:%s/api/v2/user/%s/roles";
// *****************************************Elements*************************************************************
- final String GET_TAGS_LIST = "http://%s:%s/sdc2/rest/v1/tags";
+ final String GET_TAGS_LIST = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/tags";
- final String GET_PROPERTY_SCOPES_LIST = "http://%s:%s/sdc2/rest/v1/propertyScopes";
+ final String GET_PROPERTY_SCOPES_LIST = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/propertyScopes";
- final String GET_CONFIGURATION = "http://%s:%s/sdc2/rest/v1/configuration/ui";
+ final String GET_CONFIGURATION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/configuration/ui";
- final String GET_ALL_ARTIFACTS = "http://%s:%s/sdc2/rest/v1/artifactTypes";
+ final String GET_ALL_ARTIFACTS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/artifactTypes";
- final String GET_FOLLWED_LIST = "http://%s:%s/sdc2/rest/v1/followed";
+ final String GET_FOLLWED_LIST = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/followed";
- final String GET_CATALOG_DATA = "http://%s:%s/sdc2/rest/v1/screen/?excludeTypes=VFCMT&excludeTypes=Configuration";
+ final String GET_CATALOG_DATA = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/screen/?excludeTypes=VFCMT&excludeTypes=Configuration";
// *****************************************Resources
// **********************************************************************
- final String GET_LIST_CERTIFIED_RESOURCE_TEMPLATES = "http://%s:%s/sdc2/rest/v1/resoourceTemplates";
+ final String GET_LIST_CERTIFIED_RESOURCE_TEMPLATES = SDC_HTTP_METHOD + "://%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 CREATE_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources";
+ final String UPDATE_RESOURCE = SDC_HTTP_METHOD + "://%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_RESOURCE_NORMATIVE = SDC_HTTP_METHOD + "://%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_USER_RESOURCE = SDC_HTTP_METHOD + "://%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";
+ final String IMPORT_CAPABILITY_TYPE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/uploadType/capability";
+ final String IMPORT_CATEGORIES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/uploadType/categories";
+ final String IMPORT_GROUP_TYPE = SDC_HTTP_METHOD + "://%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 GET_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s";
+ final String GET_RESOURCE_BY_NAME_AND_VERSION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/resourceName/%s/resourceVersion/%s";
+ final String GET_RESOURCE_BY_CSAR_UUID = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/csar/%s";
+ final String GET_COMPONENT_REQUIRMENTS_CAPABILITIES = SDC_HTTP_METHOD + "://%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_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s";
+ final String DELETE_RESOURCE_BY_NAME_AND_VERSION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s";
+ final String DELETE_SERVICE_BY_NAME_AND_VERSION = SDC_HTTP_METHOD + "://%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 DELETE_MARKED_RESOURCES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/inactiveComponents/resource";
+ final String DELETE_MARKED_SERVICES = SDC_HTTP_METHOD + "://%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 GET_FOLLOWED_RESOURCES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/followed/resources/%s";
+ final String CHANGE_RESOURCE_LIFECYCLE_STATE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/lifecycleState/%s";
+ final String CHANGE_SERVICE_LIFECYCLE_STATE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/lifecycleState/%s";
+ final String CHANGE_PRODUCT_LIFECYCLE_STATE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/products/%s/lifecycleState/%s";
+ final String CHANGE_COMPONENT_LIFECYCLE_STATE = SDC_HTTP_METHOD + "://%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 DECLARE_PROPERTIES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/create/inputs";
+ final String CREATE_PROPERTY = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties";
+ final String DECLARE_PROPERTIES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/create/inputs";
+ final String UPDATE_INPUT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/update/inputs";
- final String UPDATE_RESOURCE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/metadata";
+ final String UPDATE_RESOURCE_METADATA = SDC_HTTP_METHOD + "://%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 DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/artifacts/%s";
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/resources/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/sdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/artifacts";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts";
- 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";
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/resources/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
+
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+
+ final String GET_ASSET_LIST = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s";
+ final String GET_FILTERED_ASSET_LIST = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s?%s";
+ final String GET_TOSCA_MODEL = SDC_HTTP_METHOD + "://%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";
-
+ final String GET_ASSET_METADATA = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/%s/%s/metadata";
+ final String POST_AUTHORIZATION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/consumers";
+ final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
+
+ final String POST_EXTERNAL_API_CREATE_RESOURCE = SDC_HTTP_METHOD + "://%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 POST_EXTERNAL_API_CHANGE_LIFE_CYCLE_OF_ASSET = SDC_HTTP_METHOD + "://%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 ADD_ARTIFACT_TO_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts";
+ final String UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts/%s";
+ final String ADD_ARTIFACT_TO_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts";
+ final String UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE = SDC_HTTP_METHOD + "://%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_DELETE_ARTIFACT_OF_COMPONENT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/artifacts";
+ final String UPDATE_ARTIFACT_OF_COMPONENT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/artifacts/%s";
+ final String UPLOAD_HEAT_ENV_ARTIFACT = SDC_HTTP_METHOD + "://%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_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/";
+ final String UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE = SDC_HTTP_METHOD + "://%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";
+ final String UPLOAD_ARTIFACT_BY_INTERFACE_TO_COMPONENT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/";
+ final String UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_COMPONENT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/%s";
// *****************************************************************************************************
// "/sdc2/v1/services/<serviceName>/<0.1>/artifacts/aaa.hh"
@@ -242,148 +246,150 @@ public interface Urls {
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 DOWNLOAD_SERVICE_ARTIFACT_FULL_URL = SDC_HTTP_METHOD + "://%s:%s%s";
+ final String DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL = SDC_HTTP_METHOD + "://%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 UI_DOWNLOAD_RESOURCE_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts/%s";
+ final String UI_DOWNLOAD_SERVICE_ARTIFACT = SDC_HTTP_METHOD + "://%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 UPDATE_PROPERTY = SDC_HTTP_METHOD + "://%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 DELETE_PROPERTY = SDC_HTTP_METHOD + "://%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 GET_PROPERTY = SDC_HTTP_METHOD + "://%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 VALIDATE_RESOURCE_NAME = SDC_HTTP_METHOD + "://%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 CREATE_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services";
+ final String DELETE_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s";
+ final String GET_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s";
+ final String GET_SERVICE_BY_NAME_AND_VERSION = SDC_HTTP_METHOD + "://%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 GET_SERVICES_REQUIRMENTS_CAPABILITIES = SDC_HTTP_METHOD + "://%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";
+ final String CREATE_COMPONENT_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance";
+ final String DELETE_COMPONENT_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s";
+ final String UPDATE_COMPONENT_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s";
+ final String GET_COMPONENT_INSTANCES = SDC_HTTP_METHOD + "://%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 UPDATE_MULTIPLE_COMPONENT_INSTANCE = SDC_HTTP_METHOD + "://%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 CHANGE__RESOURCE_INSTANCE_VERSION = SDC_HTTP_METHOD + "://%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 CREATE_AND_ASSOCIATE_RESOURCE_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/createAndAssociate";
+ final String ASSOCIATE__RESOURCE_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/associate";
+ final String DISSOCIATE__RESOURCE_INSTANCE = SDC_HTTP_METHOD + "://%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 DISTRIBUTION_SERVICE_MONITOR = "http://%s:%s/sdc2/rest/v1/catalog/services/distribution/%s";
+ final String DISTRIBUTION_INIT = SDC_HTTP_METHOD + "://%s:%s/init";
+ final String DISTRIBUTION_INIT_RESET = SDC_HTTP_METHOD + "://%s:%s/initReset";
+ final String APPROVE_DISTRIBUTION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution-state/approve";
+ final String REJECT_DISTRIBUTION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution-state/reject";
+ final String DISTRIBUTION_DOWNLOAD_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/download";
+ final String ACTIVATE_DISTRIBUTION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution/%s/activate";
+ final String DISTRIBUTION_SERVICE_LIST = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution";
+ final String DISTRIBUTION_SERVICE_MONITOR = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/distribution/%s";
- 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";
+ final String DEPLOY_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution/%s/markDeployed";
+ final String UPDATE_SERVICE_METADATA = SDC_HTTP_METHOD + "://%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";
+ final String UPDATE_PROPERTY_TO_RESOURCE_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/property";
+ final String DELETE_PROPERTY_FROM_RESOURCE_INSTANCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/property/%s";
+ final String UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS = SDC_HTTP_METHOD + "://%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";
+ final String ADD_RESOURCE_INSTANCE_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts";
+ final String UPDATE_RESOURCE_INSTANCE_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s";
+ final String DELETE_RESOURCE_INSTANCE_ARTIFACT = SDC_HTTP_METHOD + "://%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";
+ public static final String UPDATE_ATTRIBUTE_ON_RESOURCE_INSTANCE = SDC_HTTP_METHOD + "://%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";
+ final String DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT = SDC_HTTP_METHOD + "://%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 UPDATE_DELETE_SERVICE_API_ARTIFACT = SDC_HTTP_METHOD + "://%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 CREATE_ADDITIONAL_INFORMATION_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo";
+ final String UPDATE_ADDITIONAL_INFORMATION_RESOURCE = SDC_HTTP_METHOD + "://%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 GET_ADDITIONAL_INFORMATION_RESOURCE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo/%s";
+ final String GET_ALL_ADDITIONAL_INFORMATION_RESOURCE = SDC_HTTP_METHOD + "://%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 CREATE_ADDITIONAL_INFORMATION_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo";
+ final String UPDATE_ADDITIONAL_INFORMATION_SERVICE = SDC_HTTP_METHOD + "://%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_ADDITIONAL_INFORMATION_SERVICE = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo/%s";
+ final String GET_ALL_ADDITIONAL_INFORMATION_SERVICE = SDC_HTTP_METHOD + "://%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";
+ final String GET_COMPONENT_AUDIT_RECORDS = SDC_HTTP_METHOD + "://%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";
+ final String CREATE_CONSUMER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/consumers";
+ final String GET_CONSUMER = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/consumers/%s";
+ final String DELETE_CONSUMER = SDC_HTTP_METHOD + "://%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";
+ final String CREATE_CATEGORY = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/category/%s";
+ final String GET_ALL_CATEGORIES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/categories/%s";
+ final String GET_ALL_CATEGORIES_FE = SDC_HTTP_METHOD + "://%s:%s/sdc1/feProxy/rest/v1/categories/%s";
+ final String DELETE_CATEGORY = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/category/%s/%s";
+ final String CREATE_SUB_CATEGORY = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory";
+ final String DELETE_SUB_CATEGORY = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s";
+ final String CREATE_GROUPING = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s/grouping";
+ final String DELETE_GROUPING = SDC_HTTP_METHOD + "://%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";
+ final String CREATE_PRODUCT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/products";
+ final String DELETE_PRODUCT = SDC_HTTP_METHOD + "://%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";
+ final String GET_PRODUCT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/products/%s";
+ final String UPDATE_PRODUCT = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/products/%s/metadata";
+ final String GET_PRODUCT_BY_NAME_AND_VERSION = SDC_HTTP_METHOD + "://%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";
-
+ final String GET_GROUP_BY_ID = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/groups/%s";
+ //module property
+ final String RESOURCE_GROUP_PROPERTY = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/resources/%s/groups/%s/properties";
// modules
- final String GET_MODULE_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/groups/%s";
-
+ final String GET_MODULE_BY_ID = SDC_HTTP_METHOD + "://%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
+ final String ADD_INPUTS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/create/inputs"; //{componentType}/{componentId}/create/inputs
+ final String DELETE_INPUT_BY_ID = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/delete/%s/input"; //{componentType}/{componentId}/delete/{inputId}/input
+ final String GET_COMPONENT_INPUTS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/services/%s/inputs"; //services/{componentId}/inputs
+ final String GET_COMPONENT_INSTANCE_INPUTS = SDC_HTTP_METHOD + "://%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 = SDC_HTTP_METHOD + "://%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";
-
+ final String ONBOARD_VERSION = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/docs/build-info.json";
+ final String OS_VERSION = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/version";
+
// amdocs APIs
- final String GET_VENDOR_SOFTWARE_PRODUCT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/packages/%s";
- final String UPLOAD_SNMP_POLL_ARTIFACT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/uploads/types/SNMP_POLL";
- final String UPLOAD_SNMP_TRAP_ARTIFACT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/uploads/types/SNMP_TRAP";
- final String UPLOAD_VES_EVENTS_ARTIFACT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/uploads/types/VES_EVENTS";
- final String UPLOAD_AMDOCS_ARTIFACT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/uploads/types/%s";
- final String DELETE_AMDOCS_ARTIFACT_BY_TYPE = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/%s";
- final String GET_VSP_COMPONENTS = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components";
- final String CREATE_VENDOR_LISENCE_MODELS = "http://%s:%s/onboarding-api/v1.0/vendor-license-models";
- final String CREATE_VENDOR_LISENCE_AGREEMENT = "http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-agreements";
- final String CREATE_VENDOR_LISENCE_FEATURE_GROUPS = "http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/feature-groups";
- final String CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL = "http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/entitlement-pools";
- final String CREATE_VENDOR_LISENCE_KEY_GROUPS = "http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-key-groups";
- final String CREATE_VENDOR_SOFTWARE_PRODUCT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products";
- final String VALIDATE_UPLOAD = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate/process";
- final String UPLOAD_HEAT_PACKAGE = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/orchestration-template-candidate";
- final String ACTION_ON_COMPONENT = "http://%s:%s/onboarding-api/v1.0/%s/%s/versions/%s/actions";
- final String UPDATE_VSP = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s";
- final String GET_VSP_COMPONENT_BY_VERSION = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s";
- final String GET_VLM_COMPONENT_BY_VERSION = "http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/%s";
+ final String GET_VENDOR_SOFTWARE_PRODUCT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/packages/%s";
+ final String UPLOAD_SNMP_POLL_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/components/%s/uploads/types/SNMP_POLL";
+ final String UPLOAD_SNMP_TRAP_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/components/%s/uploads/types/SNMP_TRAP";
+ final String UPLOAD_VES_EVENTS_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/components/%s/uploads/types/VES_EVENTS";
+ final String UPLOAD_AMDOCS_ARTIFACT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/components/%s/uploads/types/%s";
+ final String DELETE_AMDOCS_ARTIFACT_BY_TYPE = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/components/%s/monitors/%s";
+ final String GET_VSP_COMPONENTS = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/components";
+ final String CREATE_VENDOR_LISENCE_MODELS = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-license-models";
+ final String CREATE_VENDOR_LISENCE_AGREEMENT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/%s/license-agreements";
+ final String CREATE_VENDOR_LISENCE_FEATURE_GROUPS = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/%s/feature-groups";
+ final String CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/%s/entitlement-pools";
+ final String CREATE_VENDOR_LISENCE_KEY_GROUPS = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/%s/license-key-groups";
+ final String CREATE_METHOD = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/%s/%s/versions/%s/";
+ final String CREATE_VENDOR_SOFTWARE_PRODUCT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products";
+ final String VALIDATE_UPLOAD = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/orchestration-template-candidate/process";
+ final String UPLOAD_HEAT_PACKAGE = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s/orchestration-template-candidate";
+ final String ACTION_ON_COMPONENT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/%s/%s/versions/%s/actions";
+ final String UPDATE_VSP = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s";
+ final String GET_VSP_COMPONENT_BY_VERSION = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s";
+ final String GET_VLM_COMPONENT_BY_VERSION = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/%s";
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
index 7bb4602433..590297e130 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
@@ -92,7 +92,17 @@ public class Config {
private String windowsDownloadDirectory;
private boolean captureTraffic;
private boolean useBrowserMobProxy;
-
+ private String sdcHttpMethod;
+ private String localDataCenter;
+
+ public String getLocalDataCenter() {
+ return localDataCenter;
+ }
+
+ public void setLocalDataCenter(String localDataCenter) {
+ this.localDataCenter = localDataCenter;
+ }
+
private static Config configIt = null;
private static Yaml yaml = new Yaml();
@@ -150,6 +160,8 @@ public class Config {
if (configFile == null) {
if (System.getProperty("os.name").contains("Windows")) {
configFile = WINDOWS_CONFIG_FILE;
+ } else if (System.getProperty("os.name").contains("Mac")) {
+ configFile = WINDOWS_CONFIG_FILE;
} else {
throw new RuntimeException("Please Add Jvm Argument config.resource");
}
@@ -246,6 +258,14 @@ public class Config {
this.systemUnderDebug = systemUnderDebug;
}
+ public String getSdcHttpMethod() {
+ return sdcHttpMethod;
+ }
+
+ public void setSdcHttpMethod(String sdcHttpMethod) {
+ this.sdcHttpMethod = sdcHttpMethod;
+ }
+
public boolean getRerun() {
return rerun;
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java
index 8a9171e5bd..58a11b012f 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java
@@ -1,14 +1,15 @@
package org.openecomp.sdc.ci.tests.dataProviders;
-import static org.testng.Assert.assertFalse;
+import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
+import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
+import org.testng.annotations.DataProvider;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
-import org.testng.annotations.DataProvider;
+import static org.testng.Assert.assertFalse;
public class OnbordingDataProviders {
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
index 03bedd6746..5ebb2608b7 100644
--- 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
@@ -28,6 +28,8 @@ import java.util.Map;
public class GroupHeatMetaDefinition {
private int group = 0;
+ private String groupName;
+
// private List<String> artifactList = new ArrayList<String>();
private List<HeatMetaFirstLevelDefinition> artifactList = new ArrayList<HeatMetaFirstLevelDefinition>();
@Override
@@ -75,7 +77,15 @@ public class GroupHeatMetaDefinition {
this.group = group;
}
-// public List<String> getArtifactList() {
+ public String getGroupName() {
+ return groupName;
+ }
+
+ public void setGroupName(String groupName) {
+ this.groupName = groupName;
+ }
+
+ // public List<String> getArtifactList() {
// return artifactList;
// }
//
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
index 0089eec5a7..e7899eeeb4 100644
--- 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
@@ -36,7 +36,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.openecomp.sdc.be.model.User;
@@ -45,6 +45,8 @@ import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.yaml.snakeyaml.Yaml;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
public class ImportReqDetails extends ResourceReqDetails {
private String payloadName;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyObject.java
new file mode 100644
index 0000000000..9fea62bba5
--- /dev/null
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyObject.java
@@ -0,0 +1,90 @@
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class PropertyObject {
+
+ private String defaultValue;
+ private String name;
+ private String parentUniqueId;
+ private boolean password;
+ private boolean required;
+ private List<Schema> Schema;
+ private String type;
+ private String uniqueId;
+ private boolean definition;
+ private Object value = null;
+
+
+ public PropertyObject() {
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public void setValue(Object value) {
+ this.value = value;
+ }
+
+ public PropertyObject(String defaultValue, String name, String parentUniqueId, String uniqueId) {
+ this.defaultValue = defaultValue;
+ this.name = name;
+ this.parentUniqueId = parentUniqueId;
+ this.uniqueId = uniqueId;
+ this.password = false;
+ this.required = false;
+ this.type = "String";
+ this.definition = false;
+ this.Schema = new ArrayList<Schema>();
+ }
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getParentUniqueId() {
+ return parentUniqueId;
+ }
+
+ public void setParentUniqueId(String parentUniqueId) {
+ this.parentUniqueId = parentUniqueId;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+}
+
+class Schema {
+
+ private List<Property> property;
+}
+
+class Property {}
+
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
index 5a80fd14ca..e3517a8ab4 100644
--- 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
@@ -29,7 +29,11 @@ public class ResourceReqDetails extends ComponentReqDetails {
List<String> derivedFrom;
String vendorName;
String vendorRelease;
+ String componentType = "RESOURCE";
+ public String getComponentType() {
+ return componentType;
+ }
// Unsettable/unupdatable fields
Boolean isAbstract;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java
index 8b40210c0d..a6aba7f13c 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java
@@ -16,8 +16,8 @@ public class VendorSoftwareProductObject extends VendorSoftwareProductObjectReqD
this.version = version;
}
- public VendorSoftwareProductObject(String name, String description, String category, String subCategory, String vendorId, String vendorName, LicensingVersion licensingVersion, LicensingData licensingData, String onboardingMethod, String networkPackageName, String onboardingOrigin, String vspId, String componentId, String attContact, String version) {
- super(name, description, category, subCategory, vendorId, vendorName, licensingVersion, licensingData, onboardingMethod, networkPackageName, onboardingOrigin);
+ public VendorSoftwareProductObject(String name, String description, String category, String subCategory, String vendorId, String vendorName, String licensingVersion, LicensingData licensingData, String onboardingMethod, String networkPackageName, String onboardingOrigin, String icon, String vspId, String componentId, String attContact, String version) {
+ super(name, description, category, subCategory, vendorId, vendorName, licensingVersion, licensingData, onboardingMethod, networkPackageName, onboardingOrigin, icon);
this.vspId = vspId;
this.componentId = componentId;
this.attContact = attContact;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObjectReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObjectReqDetails.java
index 10093c2a93..459bfaab2f 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObjectReqDetails.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObjectReqDetails.java
@@ -8,11 +8,14 @@ public class VendorSoftwareProductObjectReqDetails {
private String subCategory;
private String vendorId;
private String vendorName;
- private LicensingVersion licensingVersion;
+// private LicensingVersion licensingVersion;
+ private String licensingVersion;
private LicensingData licensingData;
private String onboardingMethod;
private String networkPackageName;
private String onboardingOrigin;
+ private String icon;
+
public String getIcon() {
return icon;
@@ -22,12 +25,10 @@ public class VendorSoftwareProductObjectReqDetails {
this.icon = icon;
}
- private String icon;
-
public VendorSoftwareProductObjectReqDetails() {
}
- public VendorSoftwareProductObjectReqDetails(String name, String description, String category, String subCategory, String vendorId, String vendorName, LicensingVersion licensingVersion, LicensingData licensingData, String onboardingMethod, String networkPackageName, String onboardingOrigin) {
+ public VendorSoftwareProductObjectReqDetails(String name, String description, String category, String subCategory, String vendorId, String vendorName, String licensingVersion, LicensingData licensingData, String onboardingMethod, String networkPackageName, String onboardingOrigin, String icon) {
this.name = name;
this.description = description;
this.category = category;
@@ -39,6 +40,15 @@ public class VendorSoftwareProductObjectReqDetails {
this.onboardingMethod = onboardingMethod;
this.networkPackageName = networkPackageName;
this.onboardingOrigin = onboardingOrigin;
+ this.icon = icon;
+ }
+
+ public String getLicensingVersion() {
+ return licensingVersion;
+ }
+
+ public void setLicensingVersion(String licensingVersion) {
+ this.licensingVersion = licensingVersion;
}
public String getName() {
@@ -89,13 +99,13 @@ public class VendorSoftwareProductObjectReqDetails {
this.vendorName = vendorName;
}
- public LicensingVersion getLicensingVersion() {
- return licensingVersion;
- }
-
- public void setLicensingVersion(LicensingVersion licensingVersion) {
- this.licensingVersion = licensingVersion;
- }
+// public LicensingVersion getLicensingVersion() {
+// return licensingVersion;
+// }
+//
+// public void setLicensingVersion(LicensingVersion licensingVersion) {
+// this.licensingVersion = licensingVersion;
+// }
public LicensingData getLicensingData() {
return licensingData;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/GroupPropertyEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/GroupPropertyEnum.java
new file mode 100644
index 0000000000..4651995655
--- /dev/null
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/GroupPropertyEnum.java
@@ -0,0 +1,46 @@
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public enum GroupPropertyEnum {
+
+ IS_BASE("isBase"),
+ MIN_VF_MODULE_INSTANCES("min_vf_module_instances"),
+ MAX_VF_MODULE_INSTANCES("max_vf_module_instances"),
+ VF_MODULE_LABEL("vf_module_label"),
+ VFC_LIST("vfc_list"),
+ VF_MODULE_TYPE("vf_module_type"),
+ VF_MODULE_DESCRIPTION("vf_module_description"),
+ INITIAL_COUNT("initial_count"),
+ VOLUME_GROUP("volume_group"),
+ AVAILABILITY_ZONE_COUNT("availability_zone_count");
+
+ private String propertyName;
+
+ GroupPropertyEnum(String propertyName) {
+ this.propertyName = propertyName;
+ }
+
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ public static List<String> getGroupPropertyNamesWithoutIsbase(){
+ List<String> groupPropertyNames = new ArrayList<>();
+
+ for(GroupPropertyEnum groupProperty : GroupPropertyEnum.values()) {
+ if (!groupProperty.getPropertyName().equals(GroupPropertyEnum.IS_BASE)){
+ groupPropertyNames.add(groupProperty.getPropertyName());
+ }
+ }
+ return groupPropertyNames;
+ }
+
+ public static List<String> getGroupPropertyNames(){
+ List<String> groupPropertyNames = GroupPropertyEnum.getGroupPropertyNamesWithoutIsbase();
+ groupPropertyNames.add(GroupPropertyEnum.IS_BASE.getPropertyName());
+ return groupPropertyNames;
+ }
+
+}
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
index 1ba6c5c7f1..a0b13b7539 100644
--- 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
@@ -20,6 +20,11 @@
package org.openecomp.sdc.ci.tests.datatypes.enums;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+
import java.util.Random;
public enum ResourceCategoryEnum {
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
index 20a4b12a92..aa70c376bb 100644
--- 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
@@ -26,7 +26,7 @@ public enum UserRoleEnum {
// 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");
ADMIN("jh0003", "Jimmy", "Hendrix"), DESIGNER("m08740", "Zero", "ASDCMech"), DESIGNER2("me0009", "Melissa","Etheridge"), DESIGNER3("cs0008", "Carlos", "Santana"),TESTER("jm0007", "Johnny", "Depp"), ADMIN4("km2000", "Kot", "May"),
- GOVERNOR("gv0001","David", "Shadmi"), OPS("op0001", "Aretha", "Franklin"), PRODUCT_STRATEGIST1("ps0001", "Eden","Rozin"), PRODUCT_STRATEGIST2("ps0002", "Ella", "Kvetny"), PRODUCT_STRATEGIST3("ps0003", "Geva", "Alon"),
+ GOVERNOR("gv0001","David", "Shadmi"), OPS("af0006", "Aretha", "Franklin"), 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;
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
index a8ca77d055..2435b10dd5 100644
--- 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
@@ -20,24 +20,6 @@
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;
@@ -45,23 +27,29 @@ 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.utils.rest.BaseRestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import sun.net.www.protocol.https.DefaultHostnameVerifier;
-import com.google.gson.Gson;
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
public class HttpRequest {
static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
-
- public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
+
+// -----------------------------Http------------------------------------------------------------------------
+ public RestResponse httpSendGetInternal(String url, Map<String, String> headers) throws IOException {
RestResponse restResponse = new RestResponse();
url = url.replaceAll("\\s", "%20");
@@ -69,15 +57,7 @@ public class HttpRequest {
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
- // add request header
- if (headers != null) {
- for (Entry<String, String> header : headers.entrySet()) {
- String key = header.getKey();
- String value = header.getValue();
- con.setRequestProperty(key, value);
- }
-
- }
+ addHttpRequestHEaders(headers, con);
int responseCode = con.getResponseCode();
logger.debug("Send GET http request, url: {}",url);
@@ -85,293 +65,246 @@ public class HttpRequest {
StringBuffer response = new StringBuffer();
String result;
-
try {
result = IOUtils.toString(con.getInputStream());
response.append(result);
-
- } catch (Exception e) {
+ } catch (Exception e) {
+ logger.debug("Fail with exception", e);
}
-
try {
-
result = IOUtils.toString(con.getErrorStream());
response.append(result);
-
} catch (Exception e) {
+// logger.debug("Fail with exception", e);
}
logger.debug("Response body: {}" ,response);
// print result
-
- restResponse.setErrorCode(responseCode);
-
- if (response != null) {
- restResponse.setResponse(response.toString());
- }
-
- restResponse.setErrorCode(responseCode);
- Map<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
+ setHttpResponseToObject(restResponse, con, responseCode, response);
con.disconnect();
return restResponse;
}
- public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
+ public RestResponse httpSendByMethodInternal(String url, String method, String body, Map<String, String> 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<String, String> header : headers.entrySet()) {
- String key = header.getKey();
- String value = header.getValue();
- con.setRequestProperty(key, value);
- }
-
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+// add request method
+ con.setRequestMethod(method);
+// add request headers
+ addHttpRequestHEaders(headers, con);
+ 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();
}
int responseCode = con.getResponseCode();
- logger.debug("Send GET http request, url: {}",url);
+ 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) {
- logger.debug("response body is null");
- }
-
+ StringBuffer response = generateHttpResponse(con, false);
String result;
-
try {
-
result = IOUtils.toString(con.getErrorStream());
response.append(result);
-
- } catch (Exception e2) {
- // result = null;
+ } catch (Exception e) {
+// logger.debug("Fail with exception", e);
}
logger.debug("Response body: {}",response);
+// print result
+ setHttpResponseToObject(restResponse, con, responseCode, response);
+ con.disconnect();
- // print result
+ return restResponse;
+ }
- restResponse.setErrorCode(responseCode);
+ public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
+ if (url.matches("^(https)://.*$")){
+ return httpsSendDelete(url, headers);
+ }
+ return httpSendDeleteInternal(url, headers);
+ }
- if (response != null) {
- restResponse.setResponse(response.toString());
+ public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
+ if (url.matches("^(https)://.*$")){
+ return httpsSendGet(url, headers);
}
+ return httpSendGetInternal(url, headers);
+ }
- restResponse.setErrorCode(responseCode);
- // restResponse.setResponse(result);
- Map<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
+ public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) throws IOException {
+ if (url.matches("^(https)://.*$")){
+ return httpsSendByMethod(url, method, body, headers);
+ }
+ return httpSendByMethodInternal(url, method, body, headers);
+ }
- con.disconnect();
+ public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
+ if (url.matches("^(https)://.*$")){
+ return httpsSendByMethod(url, "POST", body, headers);
+ }
+ return httpSendByMethod(url, "POST", body, headers);
+ }
- return restResponse;
+ public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
+ if (url.matches("^(https)://.*$")){
+ return httpsSendByMethod(url, "PUT", body, headers);
+ }
+ return httpSendByMethod(url, "PUT", body, headers);
}
- public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers)
- throws IOException {
+
+ public RestResponse httpSendDeleteInternal(String url, Map<String, String> 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<String, String> 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();
+ addHttpRequestHEaders(headers, con);
+ con.setDoOutput(true);
+ con.setRequestMethod("DELETE");
int responseCode = con.getResponseCode();
- logger.debug("Send {} http request, url: {}",method,url);
+ 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) {
- // response = null;
- logger.debug("response body is null");
- }
-
+ StringBuffer response = generateHttpResponse(con, false);
String result;
try {
-
result = IOUtils.toString(con.getErrorStream());
response.append(result);
-
- } catch (Exception e2) {
- result = null;
+ } catch (Exception e) {
+// logger.debug("Fail with exception", e);
}
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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
+// print result
+ setHttpResponseToObject(restResponse, con, responseCode, response);
con.disconnect();
- return restResponse;
+ return restResponse;
}
- public RestResponse sendHttpPost(String url, String body, Map<String, String> headers) throws IOException {
-
- RestResponse restResponse = new RestResponse();
- URL obj = new URL(url);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+ public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers) throws IOException {
+ CloseableHttpResponse response = null;
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ RestResponse restResponse = new RestResponse();
+ for (Entry<String, String> entry : headers.entrySet()) {
+ httpPost.addHeader(entry.getKey(), entry.getValue());
+ }
- // add request method
- con.setRequestMethod("POST");
+ 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 {
- // add request headers
- if (headers != null) {
- for (Entry<String, String> header : headers.entrySet()) {
- String key = header.getKey();
- String value = header.getValue();
- con.setRequestProperty(key, value);
+ } finally {
+ instream.close();
+ }
}
- }
- // Send post request
- if (body != null) {
- con.setDoOutput(true);
- DataOutputStream wr = new DataOutputStream(con.getOutputStream());
- wr.writeBytes(body);
- wr.flush();
- wr.close();
- }
+ restResponse.setErrorCode(response.getStatusLine().getStatusCode());
+ restResponse.setResponse(responseBody);
- // con.connect();
+ return restResponse;
- int responseCode = con.getResponseCode();
- logger.debug("Send POST http request, url: {}",url);
- logger.debug("Response Code: {}",responseCode);
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
- StringBuffer response = new StringBuffer();
+ }
+ }
+
+ private static void closeHttpClient(CloseableHttpClient client) {
try {
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
+ if (client != null) {
+ client.close();
}
- in.close();
- } catch (Exception e) {
- logger.debug("response body is null");
+ } catch (IOException e) {
+ logger.debug("failed to close client or response: ", e);
}
+ }
- String result;
-
+ private static void closeResponse(CloseableHttpResponse response) {
try {
-
- result = IOUtils.toString(con.getErrorStream());
- response.append(result);
-
- } catch (Exception e2) {
- result = null;
+ if (response != null) {
+ response.close();
+ }
+ } catch (IOException e) {
+ logger.debug("failed to close client or response: ", e);
}
- logger.debug("Response body: {}",response);
+ }
- // print result
- restResponse.setErrorCode(responseCode);
+ // -----------------------------Https------------------------------------------------------------------------
+ public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
- if (response != null) {
- restResponse.setResponse(response.toString());
+ RestResponse restResponse = new RestResponse();
+ url = url.replaceAll("\\s", "%20");
+ URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
+ HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
+// optional default is GET
+ con.setRequestMethod("GET");
+ HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
+ con.setHostnameVerifier(hostnameVerifier);
+ addHttpsRequestHeaders(headers, con);
+ Boolean multiPart = false;
+ if(headers.get(HttpHeaderEnum.ACCEPT.getValue()) != null) {
+ if (headers.get(HttpHeaderEnum.ACCEPT.getValue()).equals(BaseRestUtils.acceptMultipartHeader)) {
+ multiPart = true;
+ }
}
+ int responseCode = con.getResponseCode();
+ logger.debug("Send GET http request, url: {}",url);
+ logger.debug("Response Code: {}",responseCode);
- Map<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
+ StringBuffer response = generateHttpsResponse(con, multiPart);
+ String result;
+ try {
+ if(con.getErrorStream()!=null) {
+ result = IOUtils.toString(con.getErrorStream());
+ response.append(result);
+ }
+ } catch (Exception e) {
+// logger.debug("Fail with exception", e);
+ }
+ logger.debug("Response body: {}",response);
+// print result
+ setHttpsResponseToObject(restResponse, con, responseCode, response);
con.disconnect();
- return restResponse;
-
- }
- public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
- return httpSendPost(url, body, headers, "POST");
+ return restResponse;
}
- public RestResponse httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
- return httpSendPost(url, body, headers, "PUT");
- }
- public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType)
- throws IOException {
+ public RestResponse httpsSendPost(String url, String body, Map<String, String> headers) 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<String, String> header : headers.entrySet()) {
- String key = header.getKey();
- String value = header.getValue();
- con.setRequestProperty(key, value);
- }
- }
-
- // Send post request
+ URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
+ HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
+ HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
+ con.setHostnameVerifier(hostnameVerifier);
+// add request method
+ con.setRequestMethod("POST");
+// add request headers
+ addHttpRequestHEaders(headers, con);
+// Send post request
if (body != null) {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
@@ -379,310 +312,108 @@ public class HttpRequest {
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();
+ StringBuffer response = generateHttpsResponse(con, false);
+ String result;
try {
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
+ if(con.getErrorStream()!=null) {
+ result = IOUtils.toString(con.getErrorStream());
+ response.append(result);
}
- 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("Fail with exception", e);
}
logger.debug("Response body: {}",response);
-
- // print result
-
- restResponse.setErrorCode(responseCode);
-
- if (response != null) {
- restResponse.setResponse(response.toString());
- }
-
- Map<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
+// print result
+ setHttpResponseToObject(restResponse, con, responseCode, response);
con.disconnect();
- return restResponse;
-
- }
-
- public RestResponse httpSendDeleteWithBody2(String url, String body, Map<String, String> 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<String, String> 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<String, String> headers)
- throws IOException {
+ public RestResponse httpsSendByMethod(String url, String method, String body, Map<String, String> 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<String, String> header : headers.entrySet()) {
- String key = header.getKey();
- String value = header.getValue();
- con.setRequestProperty(key, value);
- }
+ URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
+ HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
+ HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
+ con.setHostnameVerifier(hostnameVerifier);
+// add request method
+ con.setRequestMethod(method);
+// add request headers
+ addHttpRequestHEaders(headers, con);
+ 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();
}
- // 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("Send {} http request, url: {}",method,url);
logger.debug("Response Code: {}",responseCode);
- StringBuffer response = new StringBuffer();
+ StringBuffer response = generateHttpResponse(con, false);
+ String result;
try {
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
+ if(con.getErrorStream()!=null) {
+ result = IOUtils.toString(con.getErrorStream());
+ response.append(result);
}
- in.close();
} catch (Exception e) {
- logger.debug("response body is null");
+// logger.debug("Fail with exception", e);
}
-
- 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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
+ logger.debug("Response body: {}",response);
+// print result
+ setHttpResponseToObject(restResponse, con, responseCode, response);
con.disconnect();
- return restResponse;
+ return restResponse;
}
- public RestResponse httpSendPostWithOutBody(String url, Map<String, String> headers) throws IOException {
- RestResponse restResponse = new RestResponse();
- URL obj = new URL(url);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
-
- // add request method
- con.setRequestMethod("POST");
+ public RestResponse httpsSendDelete(String url, Map<String, String> headers) throws IOException {
- // add request headers
- if (headers != null) {
- for (Entry<String, String> header : headers.entrySet()) {
- String key = header.getKey();
- String value = header.getValue();
- con.setRequestProperty(key, value);
- }
- }
-
- // con.connect();
+ RestResponse restResponse = new RestResponse();
+ URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());
+ HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
+ HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
+ con.setHostnameVerifier(hostnameVerifier);
+// add request headers
+ addHttpRequestHEaders(headers, con);
+ con.setDoOutput(true);
+ con.setRequestMethod("DELETE");
int responseCode = con.getResponseCode();
- logger.debug("Send POST http request, url: {}",url);
+ logger.debug("Send DELETE http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
- StringBuffer response = new StringBuffer();
-
+ StringBuffer response = generateHttpsResponse(con, false);
+ String result;
try {
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
+ if(con.getErrorStream()!=null) {
+ result = IOUtils.toString(con.getErrorStream());
+ response.append(result);
}
- 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("Fail with exception", e);
}
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<String, List<String>> headerFields = con.getHeaderFields();
- restResponse.setHeaderFields(headerFields);
- String responseMessage = con.getResponseMessage();
- restResponse.setResponseMessage(responseMessage);
-
+// print result
+ setHttpResponseToObject(restResponse, con, responseCode, response);
con.disconnect();
- return restResponse;
-
- }
-
- public RestResponse httpSendPostMultipart(String url, Map<String, String> 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<String, String> 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
+ // ---------------------------------------
+ private void addHttpsRequestHeaders(Map<String, String> headers, HttpsURLConnection con) {
+ // add request header
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
@@ -691,40 +422,24 @@ public class HttpRequest {
}
}
+ }
- // 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);
+ private void addHttpRequestHEaders(Map<String, String> headers, HttpURLConnection con) {
+ // add request header
+ if (headers != null) {
+ for (Entry<String, String> header : headers.entrySet()) {
+ String key = header.getKey();
+ String value = header.getValue();
+ con.setRequestProperty(key, value);
}
- in.close();
- } catch (Exception e) {
- response = null;
}
- logger.debug("Response body: {}",response);
-
- // print result
+ }
+ private void setHttpResponseToObject(RestResponse restResponse, HttpURLConnection con, int responseCode, StringBuffer response) throws IOException {
restResponse.setErrorCode(responseCode);
- if (response == null) {
- restResponse.setResponse(null);
- } else {
+
+ if (response != null) {
restResponse.setResponse(response.toString());
}
@@ -732,135 +447,67 @@ public class HttpRequest {
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
-
- con.disconnect();
- return restResponse;
-
}
- public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
-
- RestResponse restResponse = new RestResponse();
- URL obj = new URL(url);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
-
- if (headers != null) {
- for (Entry<String, String> 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);
-
+ private StringBuffer generateHttpResponse(HttpURLConnection con, Boolean isMultiPart) {
StringBuffer response = new StringBuffer();
-
+ StringWriter writer = new StringWriter();
try {
- BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
+ if(isMultiPart) {
+ IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
+ response = writer.getBuffer();
+ }else {
+
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
+ }
+ in.close();
}
- 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);
+ return response;
+ }
+ private void setHttpsResponseToObject(RestResponse restResponse, HttpsURLConnection con, int responseCode, StringBuffer response) throws IOException {
if (response != null) {
restResponse.setResponse(response.toString());
}
- restResponse.setErrorCode(con.getResponseCode());
+ restResponse.setErrorCode(responseCode);
+ // restResponse.setResponse(result);
Map<String, List<String>> 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<String, String> headers)
- throws IOException, ClientProtocolException {
- CloseableHttpResponse response = null;
- CloseableHttpClient client = HttpClients.createDefault();
+ private StringBuffer generateHttpsResponse(HttpsURLConnection con, Boolean isMultiPart) {
+ StringBuffer response = new StringBuffer();
+ StringWriter writer = new StringWriter();
try {
- HttpPost httpPost = new HttpPost(url);
- RestResponse restResponse = new RestResponse();
- for (Entry<String, String> 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();
+ if(isMultiPart) {
+ IOUtils.copy((con.getInputStream()), writer, Charset.forName("UTF-8"));
+ response = writer.getBuffer();
+ }else {
+
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
}
+ in.close();
}
-
- restResponse.setErrorCode(response.getStatusLine().getStatusCode());
- restResponse.setResponse(responseBody);
-
- return restResponse;
-
- } finally {
- closeResponse(response);
- closeHttpClient(client);
-
+ } catch (Exception e) {
+ logger.debug("response body is null");
}
- }
- private static void closeHttpClient(CloseableHttpClient client) {
- try {
- if (client != null) {
- client.close();
- }
- } catch (IOException e) {
- logger.debug("failed to close client or response: ", e);
- }
+ return response;
}
- 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 {
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
index 49b556fc28..66e450b077 100644
--- 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
@@ -37,7 +37,7 @@ 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 com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@@ -77,6 +77,7 @@ import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import fj.data.Either;
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
index 65c0bba6a0..fb620c9b82 100644
--- 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
@@ -39,7 +39,7 @@ 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 com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
@@ -91,6 +91,7 @@ import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@@ -316,7 +317,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
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);
+// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
}
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
index 846b5d24d3..0417d565e3 100644
--- 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
@@ -93,7 +93,8 @@ public class GetComponentAuditApiTest extends ComponentBaseTest {
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);
+// RestResponse sendHttpPost = new HttpRequest().sendHttpPost(url, fileContentUTF8.left().value(), null);
+ RestResponse sendHttpPost = new HttpRequest().httpSendPost(url, fileContentUTF8.left().value(), null);
AssertJUnit.assertTrue(sendHttpPost.getErrorCode() == HttpStatus.SC_OK);
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java
index 3e72fae6fc..8d62dae8bf 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java
@@ -21,6 +21,9 @@
package org.openecomp.sdc.ci.tests.sanity;
+
+
+
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -51,6 +54,10 @@ import com.clearspring.analytics.util.Pair;
import fj.data.Either;
+
+
+
+
public class Onboard extends ComponentBaseTest {
@@ -86,7 +93,7 @@ public class Onboard extends ComponentBaseTest {
System.out.println("print - >" + makeDistributionValue);
runOnboardToDistributionFlow(filePath, vnfFile);
}
-
+
@Test
public void passTest() {
System.out.println("print - >" + "test Passed");
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupPropertyDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupPropertyDefinition.java
new file mode 100644
index 0000000000..53409024df
--- /dev/null
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupPropertyDefinition.java
@@ -0,0 +1,112 @@
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+import org.yaml.snakeyaml.TypeDescription;
+
+public class ToscaGroupPropertyDefinition {
+
+ public String min_vf_module_instances;
+ public String max_vf_module_instances;
+ public String vf_module_label;
+ public String vfc_list;
+ public String vf_module_type;
+ public String vf_module_description;
+ public String initial_count;
+ public String volume_group;
+ public String availability_zone_count;
+
+ public ToscaGroupPropertyDefinition() {
+ }
+
+ public String getMin_vf_module_instances() {
+ return min_vf_module_instances;
+ }
+
+ public void setMin_vf_module_instances(String min_vf_module_instances) {
+ this.min_vf_module_instances = min_vf_module_instances;
+ }
+
+ public String getMax_vf_module_instances() {
+ return max_vf_module_instances;
+ }
+
+ public void setMax_vf_module_instances(String max_vf_module_instances) {
+ this.max_vf_module_instances = max_vf_module_instances;
+ }
+
+ public String getVf_module_label() {
+ return vf_module_label;
+ }
+
+ public void setVf_module_label(String vf_module_label) {
+ this.vf_module_label = vf_module_label;
+ }
+
+ public String getVfc_list() {
+ return vfc_list;
+ }
+
+ public void setVfc_list(String vfc_list) {
+ this.vfc_list = vfc_list;
+ }
+
+ public String getVf_module_type() {
+ return vf_module_type;
+ }
+
+ public void setVf_module_type(String vf_module_type) {
+ this.vf_module_type = vf_module_type;
+ }
+
+ public String getVf_module_description() {
+ return vf_module_description;
+ }
+
+ public void setVf_module_description(String vf_module_description) {
+ this.vf_module_description = vf_module_description;
+ }
+
+ public String getInitial_count() {
+ return initial_count;
+ }
+
+ public void setInitial_count(String initial_count) {
+ this.initial_count = initial_count;
+ }
+
+ public String getVolume_group() {
+ return volume_group;
+ }
+
+ public void setVolume_group(String volume_group) {
+ this.volume_group = volume_group;
+ }
+
+ public String getAvailability_zone_count() {
+ return availability_zone_count;
+ }
+
+ public void setAvailability_zone_count(String availability_zone_count) {
+ this.availability_zone_count = availability_zone_count;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaGroupPropertyDefinition{" +
+ ", min_vf_module_instances='" + min_vf_module_instances + '\'' +
+ ", max_vf_module_instances='" + max_vf_module_instances + '\'' +
+ ", vf_module_label='" + vf_module_label + '\'' +
+ ", vfc_list='" + vfc_list + '\'' +
+ ", vf_module_type='" + vf_module_type + '\'' +
+ ", vf_module_description='" + vf_module_description + '\'' +
+ ", initial_count='" + initial_count + '\'' +
+ ", volume_group='" + volume_group + '\'' +
+ ", availability_zone_count='" + availability_zone_count + '\'' +
+ '}';
+ }
+
+ //gets Type description for Yaml snake
+ public static TypeDescription getTypeDescription(){
+ TypeDescription typeDescription = new TypeDescription(ToscaGroupPropertyDefinition.class);
+ return typeDescription;
+ }
+}
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
index e3051515cd..fd30691963 100644
--- 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
@@ -26,15 +26,17 @@ import java.util.Map;
import org.yaml.snakeyaml.TypeDescription;
// spec page 102
+
public class ToscaGroupsTopologyTemplateDefinition {
private String type; // required
private String description;
- private Map<String, Object> properties;
+ // private Map<String, String> properties;
+ private ToscaGroupPropertyDefinition properties;
private Map<String, String> targets; // required
private Map<String, Object> interfaces;
private List<String> members;
-// private Map<String, String> metadata;
+ // private Map<String, String> metadata;
private ToscaServiceGroupsMetadataDefinition metadata;
public ToscaGroupsTopologyTemplateDefinition() {
@@ -65,11 +67,19 @@ public class ToscaGroupsTopologyTemplateDefinition {
this.description = description;
}
- public Map<String, Object> getProperties() {
+// public Map<String, String> getProperties() {
+// return properties;
+// }
+//
+// public void setProperties(Map<String, String> properties) {
+// this.properties = properties;
+// }
+
+ public ToscaGroupPropertyDefinition getProperties() {
return properties;
}
- public void setProperties(Map<String, Object> properties) {
+ public void setProperties(ToscaGroupPropertyDefinition properties) {
this.properties = properties;
}
@@ -113,14 +123,15 @@ public class ToscaGroupsTopologyTemplateDefinition {
//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 typeDescription = new TypeDescription(ToscaGroupsTopologyTemplateDefinition.class);
+// typeDescription.putMapPropertyType("properties", String.class, Object.class);
+// typeDescription.putListPropertyType("properties", ToscaGroupPropertyDefinition.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;
+ 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/ToscaServiceGroupsMetadataDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java
index 4072504296..da8c99a59f 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java
@@ -22,11 +22,11 @@ package org.openecomp.sdc.ci.tests.tosca.datatypes;
public class ToscaServiceGroupsMetadataDefinition {
- private String vfModuleModelName;
- private String vfModuleModelInvariantUUID;
- private String vfModuleModelCustomizationUUID;
- private String vfModuleModelUUID;
- private String vfModuleModelVersion;
+ public String vfModuleModelName;
+ public String vfModuleModelInvariantUUID;
+ public String vfModuleModelCustomizationUUID;
+ public String vfModuleModelUUID;
+ public String vfModuleModelVersion;
public ToscaServiceGroupsMetadataDefinition() {
super();
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
index 97944368e2..03f83b4b15 100644
--- 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
@@ -24,8 +24,13 @@ import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.yaml.snakeyaml.TypeDescription;
+import com.clearspring.analytics.util.Pair;
+
+import io.netty.util.collection.IntObjectMap.Entry;
+
// spec page 104
public class ToscaTopologyTemplateDefinition {
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java
index cd6687be0e..157377f47f 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java
@@ -64,7 +64,7 @@ public class CsarParserUtils {
Object parse = parser.parse(csarPayload);
JSONObject jsonObject = (JSONObject) parse;
JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get(ToscaParameterConstants.IMPORT_STRUCTURE);
- List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
+ List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<>();
listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
return listHeatMetaDefenition;
}
@@ -82,7 +82,7 @@ public class CsarParserUtils {
log.debug("{}", jsonObjectImportStructure.get(type));
JSONArray array = (JSONArray) jsonObjectImportStructure.get(type);
heatMetaDefenition.setTypeName((String) type);
- List<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<GroupHeatMetaDefinition>();
+ List<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<>();
heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroupFromJsonArray(array, groupHeatMetaDefinitions, true, false));
listHeatMetaDefenition.add(heatMetaDefenition);
}
@@ -108,6 +108,16 @@ public class CsarParserUtils {
}
groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1);
JSONObject jsonObject = (JSONObject) array.get(i);
+ if (openNewGroup) {
+ String groupName;
+ int lastIndexOfDot = jsonObject.get("fileName").toString().lastIndexOf(".");
+ if(lastIndexOfDot == -1){
+ groupName = jsonObject.get("fileName").toString();
+ }else {
+ groupName = jsonObject.get("fileName").toString().substring(0, lastIndexOfDot);
+ }
+ groupHeatMetaDefinition.setGroupName(groupName);
+ }
fetchArtifactByGroupFromJsonObject(listGroupHeatMetaDefinition, groupHeatMetaDefinition, jsonObject, isNested);
}
}
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
index 35c25b7157..835ef6ebb3 100644
--- 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
@@ -40,6 +40,7 @@ import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.DistributionMonitorObject;
import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
+import org.openecomp.sdc.ci.tests.datatypes.enums.DistributionNotificationStatusEnum;
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;
@@ -51,6 +52,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import com.clearspring.analytics.util.Pair;
import com.google.gson.Gson;
+import fj.data.Either;
public class DistributionUtils extends BaseRestUtils{
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
index 0c193ad13c..f345aad60c 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
@@ -43,7 +43,7 @@ import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinitio
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.http.client.api.HttpResponse;
import org.openecomp.sdc.common.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -193,8 +193,8 @@ public class ToscaParserUtils {
public static String getCsarPayload(String csarName, String yamlFileLocation) throws Exception {
- RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ HttpResponse<byte []> csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertTrue("Return response code different from 200", csar.getStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
byte[] data = csar.getResponse();
return getDataFromZipFileByBytes(yamlFileLocation, data);
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
index 3515191433..05dcc7e663 100644
--- 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
@@ -34,6 +34,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
@@ -228,6 +229,15 @@ public final class Utils {
return config;
}
+ public static Config getConfigHandleException() {
+ Config config = null;
+ try{
+ config = Config.instance();
+ }catch (Exception e){
+ System.out.println("Configuration file not found. " + e);
+ }
+ return config;
+ }
// public void uploadNormativeTypes() throws IOException{
// Config config = getConfig();
// String[] normativeTypes = {"root", "compute", "blockStorage",
@@ -686,4 +696,12 @@ public final class Utils {
long epoch = date.getTime();
return epoch;
}
+
+ public static Long getActionDuration(Runnable func) throws Exception{
+ long startTime = System.nanoTime();
+ func.run();
+ long estimateTime = System.nanoTime();
+ long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime);
+ return duration;
+ }
}
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
index bd1066a662..aa68392adc 100644
--- 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
@@ -21,10 +21,10 @@
package org.openecomp.sdc.ci.tests.utils.cassandra;
import java.io.FileNotFoundException;
+import com.datastax.driver.core.policies.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-
import org.javatuples.Pair;
import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
import org.openecomp.sdc.ci.tests.utils.Utils;
@@ -38,188 +38,212 @@ import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.TableMetadata;
+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
+import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
+import com.datastax.driver.core.policies.DefaultRetryPolicy;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.querybuilder.Select.Where;
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<TableMetadata> 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<Row> fetchFromTable(String keyspace, String tableName,
- List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
-
- List<Pair<String, String>> fieldsConverted = new ArrayList<>();
+ private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
+
+ protected static Cluster cluster = null;
+ protected static Session session;
+
+ public static void initConnection(String keyspace) throws FileNotFoundException {
+ List<String> cassandraHosts = new ArrayList<>();
+ try {
+ cassandraHosts.add(Utils.getConfig().getCassandraHost());
+ long reconnectTimeout = 30000;
+
+ logger.debug("creating cluster to hosts:{} with reconnect timeout:{}", cassandraHosts, reconnectTimeout);
+ Cluster.Builder clusterBuilder = Cluster.builder()
+ .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
+ .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
+
+ cassandraHosts.forEach(host -> clusterBuilder.addContactPoint(host));
+ enableAuthentication(clusterBuilder);
+ enableSsl(clusterBuilder);
+ setLocalDc(clusterBuilder);
+
+ cluster = clusterBuilder.build();
+ session = cluster.connect(keyspace);
+ } catch (Exception e) {
+ logger.info("** CassandraClient isn't connected to {}", cassandraHosts);
+ }
+ }
+
+ private static void enableAuthentication(Cluster.Builder clusterBuilder) throws FileNotFoundException {
+ boolean authenticate = Utils.getConfig().getCassandraAuthenticate();
+ if (authenticate) {
+ String username = Utils.getConfig().getCassandraUsername();
+ String password = Utils.getConfig().getCassandraPassword();
+ if (username == null || password == null) {
+ logger.error("authentication is enabled but username or password were not supplied.");
+ } else {
+ clusterBuilder.withCredentials(username, password);
+ }
+
+ }
+ }
+
+ private static void enableSsl(Cluster.Builder clusterBuilder) throws FileNotFoundException {
+ boolean ssl = Utils.getConfig().getCassandraSsl();
+ if (ssl) {
+ String truststorePath = Utils.getConfig().getCassandraTruststorePath();
+ String truststorePassword = Utils.getConfig().getCassandraTruststorePassword();
+ if (truststorePath == null || truststorePassword == null) {
+ logger.error("ssl is enabled but truststorePath or truststorePassword were not supplied.");
+ } else {
+ System.setProperty("javax.net.ssl.trustStore", truststorePath);
+ System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
+ clusterBuilder.withSSL();
+ }
+ }
+ }
+
+
+ private static void setLocalDc(Cluster.Builder clusterBuilder) throws FileNotFoundException {
+ String localDataCenter = Utils.getConfig().getLocalDataCenter();
+ if (localDataCenter != null) {
+ logger.info("localDatacenter was provided, setting Cassndra clint to use datacenter: {} as local.", localDataCenter);
+ LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
+ clusterBuilder.withLoadBalancingPolicy(tokenAwarePolicy);
+ } else {
+ logger.info("localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization");
+ }
+ }
+
+ public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
+
+ if (session == null || session.isClosed()) {
+ initConnection(keyspace);
+ }
+
+ try (Cluster cluster = CassandraUtils.cluster){
+
+ 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");
+ }
+ }
+ }
+
+ 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<TableMetadata> 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<Row> fetchFromTable(String keyspace, String tableName, List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
+
+ List<Pair<String, String>> fieldsConverted = new ArrayList<>();
// fields.forEach(pair -> {
// Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
// fieldsConverted.add(newPair);
// });
-
- fields.forEach(pair ->{
- Pair<String, String> newPair;
- if(pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL ){
- newPair = new Pair<String, String>("RESOURE_URL", pair.getValue1());
-
- }else{
- newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
- }
- fieldsConverted.add(newPair);
-
- });
-
- return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
- }
-
- public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> 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<Entry<AuditingFieldsKeysEnum, String>> entrySet =
- // fields.entrySet();
- // fields.
- boolean multiple = (fields.size() > 1) ? true : false;
- Where where = null;
- int size = 0;
-
- for (Pair<String, String> 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<Row> 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<AuditingFieldsKeysEnum, String> 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 );
- // }
+
+ fields.forEach(pair -> {
+ Pair<String, String> newPair;
+ if (pair.getValue0() == AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL) {
+ newPair = new Pair<String, String>("RESOURE_URL", pair.getValue1());
+
+ } else {
+ newPair = new Pair<String, String>(pair.getValue0().getDisplayName(), pair.getValue1());
+ }
+ fieldsConverted.add(newPair);
+
+ });
+
+ return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
+ }
+
+ public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> 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<Entry<AuditingFieldsKeysEnum, String>> entrySet =
+ // fields.entrySet();
+ // fields.
+ boolean multiple = (fields.size() > 1) ? true : false;
+ Where where = null;
+ int size = 0;
+
+ for (Pair<String, String> 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<Row> rows = session.execute(select).all();
+ for (Row row : rows) {
+ logger.debug("{}", row);
+ }
+ return rows;
+ }
+ } finally {
+ // if (cluster != null) {
+ // cluster.close();
+ // }
+ }
+ return null;
+ }
+
+
+
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
index 56c350f471..e81c63fa53 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
@@ -38,18 +38,22 @@ import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONException;
import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+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.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.GroupDefinition;
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.be.model.GroupDefinition;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.ExtentTestActions;
import org.openecomp.sdc.ci.tests.api.Urls;
@@ -76,6 +80,7 @@ import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.CsarToscaTester;
import org.openecomp.sdc.ci.tests.utils.DistributionUtils;
import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
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;
@@ -118,7 +123,7 @@ public final class AtomicOperationUtils {
public static Either<Resource, RestResponse> importResource(String filePath, String fileName) {
try {
User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource("ciTmpVFC");
+ ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource(ElementFactory.getResourcePrefix());
importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null);
return buildResourceFromResponse(importResourceResponse);
@@ -127,6 +132,26 @@ public final class AtomicOperationUtils {
}
}
+ public static Either<Resource, RestResponse> importResource(ImportReqDetails importReqDetails, String filePath, String fileName, User userRole, Boolean validateState) {
+ try {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, userRole, null);
+
+ if (validateState) {
+ assertTrue("Import resource failed with error: " + importResourceResponse.getResponse(),importResourceResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (importResourceResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ return Either.left(resourceResponseObject);
+ }
+ return Either.right(importResourceResponse);
+ } catch (Exception e) {
+ throw new AtomicOperationException(e);
+ }
+ }
+
+
public static Either<Resource, RestResponse> createResourceByType(ResourceTypeEnum resourceType, UserRoleEnum userRole, Boolean validateState) {
try {
User defaultUser = ElementFactory.getDefaultUser(userRole);
@@ -134,7 +159,7 @@ public final class AtomicOperationUtils {
RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
if (validateState) {
- assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
}
if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
@@ -153,7 +178,7 @@ public final class AtomicOperationUtils {
RestResponse resourceResp = ResourceRestUtils.createResource(resourceDetails, defaultUser);
if (validateState) {
- assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ assertTrue("Create resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
}
if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
@@ -192,7 +217,7 @@ public final class AtomicOperationUtils {
RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
if (validateState) {
- assertTrue("actual result: " + resourceResp.getResponseMessage(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ assertTrue("Create resource failed with error: " + resourceResp.getResponse(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
}
if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
@@ -210,7 +235,7 @@ public final class AtomicOperationUtils {
RestResponse resourceResp = ResourceRestUtils.updateResource(resourceReqDetails, defaultUser, resourceReqDetails.getUniqueId());
if (validateState) {
- assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS);
+ assertTrue("Update resource failed with error: " + resourceResp.getResponse(),resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS);
}
if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS) {
@@ -231,7 +256,7 @@ public final class AtomicOperationUtils {
RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
if (validateState) {
- assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
+ assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
}
if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
@@ -247,7 +272,7 @@ public final class AtomicOperationUtils {
RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
if (validateState) {
- assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
+ assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
}
if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
@@ -262,7 +287,7 @@ public final class AtomicOperationUtils {
RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
if (validateState) {
- assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
+ assertTrue("Create service failed with error: " + createServiceResp.getResponse(),createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
}
if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
@@ -329,10 +354,8 @@ public final class AtomicOperationUtils {
component = getComponentObject(component, userRole);
return Pair.of(component, null);
}
- // List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
- // ArrayList<LifeCycleStatesEnum>(EnumSet.allOf(LifeCycleStatesEnum.class));
- ArrayList<String> lifeCycleStatesEnumList = new ArrayList<String>();
+ ArrayList<String> lifeCycleStatesEnumList = new ArrayList<>();
if (curentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) {
lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
@@ -395,16 +418,14 @@ public final class AtomicOperationUtils {
}
if (validateState) {
- assertTrue(approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
- assertTrue(distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
+ assertTrue("Distribution approve failed with error: " + approveDistribution.getResponse(),approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
+ assertTrue("Distribute service failed with error: " + distributionService.getResponse(),distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
return distributionService;
}
return distributionService;
-
}
-
-
+
public static void toscaValidation(Component component, String vnfFile) throws Exception {
ISdcCsarHelper fdntCsarHelper;
@@ -476,6 +497,34 @@ public final class AtomicOperationUtils {
}
}
+ public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState, String positionX, String positionY) {
+ try {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent);
+ componentInstanceDetails.setPosX(positionX);
+ componentInstanceDetails.setPosY(positionY);
+ 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());
@@ -619,7 +668,7 @@ public final class AtomicOperationUtils {
public static Either<ComponentInstanceProperty, RestResponse> addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
User defaultUser = ElementFactory.getDefaultUser(userRole);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
+ Map<String, PropertyReqDetails> propertyToSend = new HashMap<>();
propertyToSend.put(propDetails.getName(), propDetails);
Gson gson = new Gson();
RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
@@ -641,7 +690,7 @@ public final class AtomicOperationUtils {
public static Either<ComponentInstanceProperty, RestResponse> updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception {
User defaultUser = ElementFactory.getDefaultUser(userRole);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
+ Map<String, PropertyReqDetails> propertyToSend = new HashMap<>();
propertyToSend.put(propDetails.getName(), propDetails);
Gson gson = new Gson();
RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser);
@@ -668,7 +717,7 @@ public final class AtomicOperationUtils {
User defaultUser = ElementFactory.getDefaultUser(userRole);
PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType);
- Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
+ Map<String, PropertyReqDetails> propertyToSend = new HashMap<>();
propertyToSend.put(propDetails.getName(), propDetails);
Gson gson = new Gson();
RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
@@ -687,6 +736,23 @@ public final class AtomicOperationUtils {
return Either.right(addPropertyResponse);
}
+ public static Either<GroupDefinition, RestResponse> updateGroupPropertyOnResource(List<PropertyDataDefinition> propertyObject, Resource resource, String groupId, User user, Boolean validateState) throws Exception {
+
+ Gson gson = new Gson();
+ RestResponse updateGroupPropertyResponse = PropertyRestUtils.updateGroupProperty(resource, groupId, gson.toJson(propertyObject), user);
+
+ if (validateState) {
+ assertTrue("update group property to resource failed: " + updateGroupPropertyResponse.getResponseMessage(), updateGroupPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ if (updateGroupPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
+ GroupDefinition responseGroupDefinition = ResponseParser.convertPropertyResponseToObject(updateGroupPropertyResponse.getResponse());
+ return Either.left(responseGroupDefinition);
+ }
+ return Either.right(updateGroupPropertyResponse);
+ }
+
+
public static RestResponse createDefaultConsumer(Boolean validateState) {
try {
ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails();
@@ -725,7 +791,7 @@ public final class AtomicOperationUtils {
}
private static final long serialVersionUID = 1L;
- };
+ }
/**
* Import resource from CSAR
@@ -801,11 +867,11 @@ public final class AtomicOperationUtils {
url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), component.getToscaArtifacts().get(artifactType).getUniqueId());
}
String userId = component.getLastUpdaterUserId();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), BaseRestUtils.cacheControlHeader);
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
if (userId != null) {
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
}
@@ -818,7 +884,7 @@ public final class AtomicOperationUtils {
}
- public static RestResponse getDistributionStatusByDistributionId(String distributionId ,Boolean validateState) {
+ public static RestResponse getDistributionStatusByDistributionId(String distributionId, Boolean validateState) {
try {
User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
@@ -834,12 +900,11 @@ public final class AtomicOperationUtils {
}
}
- public static Either <RestResponse, Map<String, List<DistributionMonitorObject>>> getSortedDistributionStatusMap(Service service ,Boolean validateState) {
+ public static Either <RestResponse, Map<String, List<DistributionMonitorObject>>> getSortedDistributionStatusMap(Service service, Boolean validateState) {
try {
ServiceDistributionStatus serviceDistributionObject = DistributionUtils.getLatestServiceDistributionObject(service);
RestResponse response = getDistributionStatusByDistributionId(serviceDistributionObject.getDistributionID(), true);
-
if(validateState) {
assertTrue(response.getErrorCode() == ResourceRestUtils.STATUS_CODE_SUCCESS);
}
@@ -863,36 +928,39 @@ public final class AtomicOperationUtils {
* @throws Exception
*/
public static Boolean distributeAndValidateService(Service service, int pollingCount, int pollingInterval) throws Exception {
-
+ int firstPollingInterval = 30000; //this value define first be polling topic time, should change if DC configuration changed
Boolean statusFlag = true;
AtomicOperationUtils.distributeService(service, true);
- TimeUnit.MILLISECONDS.sleep(pollingInterval);
+ TimeUnit.MILLISECONDS.sleep(firstPollingInterval);
int timeOut = pollingCount * pollingInterval;
+ com.clearspring.analytics.util.Pair<Boolean,Map<String,List<String>>> verifyDistributionStatus = null;
+
while (timeOut > 0) {
Map<String,List<DistributionMonitorObject>> sortedDistributionStatusMap = AtomicOperationUtils.getSortedDistributionStatusMap(service, true).right().value();
- com.clearspring.analytics.util.Pair<Boolean,Map<String,List<String>>> verifyDistributionStatus = DistributionUtils.verifyDistributionStatus(sortedDistributionStatusMap);
+ verifyDistributionStatus = DistributionUtils.verifyDistributionStatus(sortedDistributionStatusMap);
if(verifyDistributionStatus.left.equals(false)){
- if((verifyDistributionStatus.right != null && ! verifyDistributionStatus.right.isEmpty()) && timeOut == 0){
- for(Entry<String, List<String>> entry : verifyDistributionStatus.right.entrySet()){
- if(ComponentBaseTest.getExtendTest() != null){
- ComponentBaseTest.getExtendTest().log(Status.INFO, "Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue());
- statusFlag = false;
- }else{
- System.out.println("Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue());
- }
- }
- }
TimeUnit.MILLISECONDS.sleep(pollingInterval);
timeOut-=pollingInterval;
}else {
timeOut = 0;
}
}
+
+ if((verifyDistributionStatus.right != null && ! verifyDistributionStatus.right.isEmpty())){
+ for(Entry<String, List<String>> entry : verifyDistributionStatus.right.entrySet()){
+ if(ComponentBaseTest.getExtendTest() != null){
+ ComponentBaseTest.getExtendTest().log(Status.INFO, "Consumer: " + entry.getKey() + " failed on following: "+ entry.getValue());
+ }else{
+ System.out.println("Consumer: [" + entry.getKey() + "] failed on following: "+ entry.getValue());
+ }
+ }
+ statusFlag = false;
+ }
return statusFlag;
}
public static Boolean distributeAndValidateService(Service service) throws Exception {
- return distributeAndValidateService(service, 6, 10000);
+ return distributeAndValidateService(service, 10, 10000);
}
}
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
index 8224f08018..d1701241fe 100644
--- 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
@@ -20,49 +20,18 @@
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.CapabilityRequirementRelationship;
-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.RelationshipInfo;
-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.*;
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.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.*;
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;
@@ -72,6 +41,12 @@ import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
public class ElementFactory {
private static final String CI_SERVICE = "ciService";
@@ -131,6 +106,10 @@ public class ElementFactory {
}
// New
+ public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName, ResourceCategoryEnum resourceCategory, String vendorName, String vendorModelNumber) {
+ return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, resourceCategory, "jh0003", ResourceType.toString(), vendorName, vendorModelNumber);
+ }
+
public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName) {
return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003", ResourceType.toString());
}
@@ -154,10 +133,10 @@ public class ElementFactory {
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<String> resourceTags = new ArrayList<String>();
+ ArrayList<String> resourceTags = new ArrayList<>();
resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = new ArrayList<String>();
+ ArrayList<String> derivedFrom = new ArrayList<>();
derivedFrom.add(derived.normativeName);
String vendorName = "ATT Tosca";
String vendorRelease = "1.0.0.wd03";
@@ -177,10 +156,10 @@ public class ElementFactory {
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<String> resourceTags = new ArrayList<String>();
+ ArrayList<String> resourceTags = new ArrayList<>();
resourceTags.add(resourceName);
- ArrayList<String> derivedFrom = new ArrayList<String>();
+ ArrayList<String> derivedFrom = new ArrayList<>();
derivedFrom.add(derived.getToscaResourceName());
String vendorName = "ATT Tosca";
String vendorRelease = "1.0.0.wd03";
@@ -200,7 +179,7 @@ public class ElementFactory {
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<String> resourceTags = new ArrayList<String>();
+ ArrayList<String> resourceTags = new ArrayList<>();
resourceTags.add(resourceName);
ArrayList<String> derivedFrom = null;
if (derived != null) {
@@ -216,6 +195,25 @@ public class ElementFactory {
return resourceDetails;
}
+ public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType, String vendorName, String vendorModelNumber) {
+ resourceName = (resourceName + resourceType + generateUUIDforSufix());
+
+ String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
+ ArrayList<String> resourceTags = new ArrayList<>();
+ resourceTags.add(resourceName);
+ ArrayList<String> derivedFrom = null;
+ if (derived != null) {
+ derivedFrom = new ArrayList<>();
+ derivedFrom.add(derived.normativeName);
+ }
+ 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());
+ resourceDetails.setResourceVendorModelNumber(vendorModelNumber);
+ return resourceDetails;
+ }
+
public static ResourceReqDetails getRandomCategoryResource() {
ResourceReqDetails resourceDetails = getDefaultResource(ResourceCategoryEnum.getRandomElement());
return resourceDetails;
@@ -224,7 +222,7 @@ public class ElementFactory {
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<String> resourceTags = new ArrayList<String>();
+ ArrayList<String> resourceTags = new ArrayList<>();
resourceTags.add(resourceName);
String vendorName = "ATT Tosca";
String vendorRelease = "1.0.0.wd03";
@@ -239,11 +237,11 @@ public class ElementFactory {
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<String> resourceTags = new ArrayList<String>();
+ ArrayList<String> resourceTags = new ArrayList<>();
resourceTags.add(resourceName);
ArrayList<String> derivedFrom = null;
if (derived != null) {
- derivedFrom = new ArrayList<String>();
+ derivedFrom = new ArrayList<>();
derivedFrom.add(derived.normativeName);
}
String vendorName = "ATT Tosca";
@@ -310,7 +308,7 @@ public class ElementFactory {
public static ServiceReqDetails getDefaultService(String serviceName, ServiceCategoriesEnum category, String contactId) {
serviceName = (serviceName + generateUUIDforSufix());
- ArrayList<String> tags = new ArrayList<String>();
+ ArrayList<String> tags = new ArrayList<>();
tags.add("serviceTag");
tags.add("serviceTag1");
tags.add(serviceName);
@@ -965,12 +963,12 @@ public class ElementFactory {
ProductReqDetails product = new ProductReqDetails(productName);
productName = (productName + generateUUIDforSufix());
product.setName(productName);
- ArrayList<String> tags = new ArrayList<String>();
+ ArrayList<String> tags = new ArrayList<>();
tags.add(productName);
product.setTags(tags);
product.setProjectCode("12345");
product.setIcon("myIcon");
- ArrayList<String> contacts = new ArrayList<String>();
+ ArrayList<String> 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());
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java
index 9759653af2..7af18dd3b7 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.ci.tests.utils.general;
+import com.aventstack.extentreports.Status;
import static org.testng.AssertJUnit.assertTrue;
import java.io.BufferedOutputStream;
@@ -51,6 +52,15 @@ import org.openecomp.sdc.common.util.GeneralUtility;
import org.yaml.snakeyaml.Yaml;
import com.aventstack.extentreports.Status;
+import java.io.*;
+import java.nio.file.Paths;
+import java.util.*;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+
+import static org.testng.AssertJUnit.assertTrue;
public class FileHandling {
@@ -94,7 +104,6 @@ public class FileHandling {
return dataTypesMap;
}
// -------------------------------------------------------------------------------------------------
-
/**
* @param folder, folder name under "Files" folder
@@ -154,7 +163,7 @@ public class FileHandling {
public static String getVnfRepositoryPath() {
return getFilePath("VNFs");
}
-
+
public static String getPortMirroringRepositoryPath() {
return getFilePath("PortMirroring");
}
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
index 28964e2f7e..f0ca9dd517 100644
--- 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
@@ -104,8 +104,7 @@ public class FileUtils {
return loadPayloadFile(newList, pattern, isBase64);
}
- public static String loadPayloadFile(List<String> listFileName, String pattern, Boolean isBase64)
- throws IOException {
+ public static String loadPayloadFile(List<String> listFileName, String pattern, Boolean isBase64) throws IOException {
String fileName;
String payload = null;
fileName = FileUtils.getFilePathFromListByPattern(listFileName, pattern);
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java
index 76e4c51b3f..8637a9ba7a 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java
@@ -30,15 +30,17 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+import com.google.gson.Gson;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
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.ci.tests.api.ExtentTestActions;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
@@ -53,7 +55,6 @@ 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.BaseRestUtils;
-import com.aventstack.extentreports.Status;
import com.clearspring.analytics.util.Pair;
import com.google.gson.Gson;
@@ -61,28 +62,28 @@ import fj.data.Either;
public class OnboardingUtillViaApis {
- protected static Map<String, String> prepareHeadersMap(String userId) {
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
- return headersMap;
- }
-
+// protected static Map<String, String> prepareHeadersMap(String userId) {
+// Map<String, String> headersMap = new HashMap<String, String>();
+// 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 Pair<String, VendorSoftwareProductObject> createVspViaApis(ResourceReqDetails resourceReqDetails, String filepath, String vnfFile, User user) throws Exception {
VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
- ExtentTestActions.log(Status.INFO, String.format("Create Vendor License"));
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(user);
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers);
- Map<String, String> map = createVendorSoftwareProduct.right;
- vendorSoftwareProductObject.setAttContact(map.get("attContact"));
- vendorSoftwareProductObject.setCategory(map.get("category"));
- vendorSoftwareProductObject.setComponentId(map.get("componentId"));
- vendorSoftwareProductObject.setDescription(map.get("description"));
- vendorSoftwareProductObject.setSubCategory(map.get("subCategory"));
- vendorSoftwareProductObject.setVendorName(map.get("vendorName"));
- vendorSoftwareProductObject.setVspId(map.get("vspId"));
+
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(user);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers);
+ VendorSoftwareProductObject map = createVendorSoftwareProduct.right;
+ vendorSoftwareProductObject.setAttContact(map.getAttContact());
+ vendorSoftwareProductObject.setCategory(map.getCategory());
+ vendorSoftwareProductObject.setComponentId(map.getComponentId());
+ vendorSoftwareProductObject.setDescription(map.getDescription());
+ vendorSoftwareProductObject.setSubCategory(map.getSubCategory());
+ vendorSoftwareProductObject.setVendorName(map.getVendorName());
+ vendorSoftwareProductObject.setVspId(map.getVspId());
Pair<String, VendorSoftwareProductObject> pair = new Pair<String, VendorSoftwareProductObject>(createVendorSoftwareProduct.left, vendorSoftwareProductObject);
return pair;
}
@@ -109,18 +110,18 @@ public class OnboardingUtillViaApis {
return resource;
}*/
-
- public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails, UserRoleEnum user) throws Exception {
- Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, user, true).left().value();
-
- return resource;
- }
-
public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails) throws Exception {
Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
-
return resource;
+
}
+
+ public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails, UserRoleEnum userRole) throws Exception {
+ Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, userRole, true).left().value();
+ return resource;
+
+ }
+
public static void downloadToscaCsarToDirectory(Component component, File file) {
try {
Either<String, RestResponse> componentToscaArtifactPayload = AtomicOperationUtils.getComponenetArtifactPayload(component, "assettoscacsar");
@@ -236,7 +237,7 @@ public class OnboardingUtillViaApis {
Config config = Utils.getConfig();
String url = String.format(Urls.GET_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), vspId);
String userId = user.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), "123456");
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "*/*");
headersMap.put("Accept-Encoding", "gzip, deflate, br");
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java
index dc38d40064..c1950dfd08 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java
@@ -20,268 +20,98 @@
package org.openecomp.sdc.ci.tests.utils.general;
-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.Calendar;
import java.util.HashMap;
-import java.util.Iterator;
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.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.AmdocsLicenseMembers;
-import org.openecomp.sdc.ci.tests.datatypes.LicensingData;
-import org.openecomp.sdc.ci.tests.datatypes.LicensingVersion;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject;
-import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObjectReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.CvfcTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
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.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
-import com.google.gson.Gson;
+import java.util.*;
public class OnboardingUtils {
/**
* excluded VNF file list
*/
- protected static List<String> exludeVnfList =
-// new ArrayList<String>();
-
- Arrays.asList(
-
-// new VNFs
- "Vhss-epc-rdm3-lab-vf-0921-v2.0-MOBILITY-10-20.zip", "Apndns-1710-vf-v3.0-10-20.zip",
- "HeatCandidate_2017-09-22_01-48_55Name_2016-182-asbg-nsbg-tsbg-v1.0-(VOIP).zip", "HeatCandidate_2017-09-22_01-47_55Name_2016-182-asbg-nsbg-tsbg-v7.0-(VOIP).zip",
- "Efmc-dbe-nin-v24.0-VOIP-10-20.zip", "VF_LMSP_v5-062317-V3.0-(Mobility).zip", "base_bwks_nfm_volume-236262502.zip",
-
-// newest failed VNFs
- "HeatCandidate_2017-09-20_15-07_66Name_2016-20-visbc1vf-v4.0-(VOIP).zip",
- "HeatCandidate_2017-09-20_15-06_66Name_2016-20-visbc1vf-v6.0-(VOIP).zip", "1-Vf-zrdm5bpxtc02-092017-(MOBILITY)_v3.0.zip",
- "1-2017-491-4vshaken-HTTP-CM-vf-(VOIP)_v2.0.zip"
-
- );
+ public static List<String> exludeVnfList =
+// new ArrayList<>();
+ Arrays.asList(
+// DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES:
+ "2017-376_vMOG_11_1.zip",
+ "HeatCandidate_2017-09-20_15-06_66Name_2016-20-visbc1vf-v6.0-(VOIP).zip",
+ "1 Apndns-1710-vf v3.0.zip",
+ "1 AVPN_vRE_BV_volume-V2.zip",
+ "1-Vf-zrdm5bpxtc02-092017-(MOBILITY)_v3.0.zip",
+ "1-Mobility_vprobe_fe_11_2_1_vf_(MOBILITY)_v1.0.zip",
+// ORCHESTRATION_NOT_FOUND:
+ "1-2017-491-4vshaken-HTTP-CM-vf-(VOIP)_v2.0.zip",
+// did not succeed to create package of new VSP expected:<200> but was:<500>:
+ "1-Riverbed-WANx1710VFv_v2.0.zip",
+ "1-LMSP_v5-062317_v3.0.zip",
+ "1-VF-Cisco-vCSR-1710_v2.0.zip",
+ "1-mDNS-preload_1710-0914_v3.0.zip",
+ "1-Firewall_170_Pala_Aloto_VF_v2.0.zip",
+ "2-mDNS-preload-1710-0914_v3.1VF.zip",
+ "1-2016-233_xsp_bfsa_nin2-vf-V1.0-VOIP-10-20.zip",
+// did not succeed to submit new VSP expected:<200> but was:<417>
+ "1-VF_vEPDG_v4.0.zip",
+ "1-VF-2017-491_9vShaken-F5-LB_v1.0.zip",
+ "2-2016-73_Mow-AVPN-vpe-BV-L_v1.0.zip",
+ "VF-2017389vTSBCDPA2-v4.0.zip",
+ "1-vEPDG_V1.0(3).zip",
+ "1-vHSS-EPC-RDM3-Lab-VF-0830_V3.0.zip",
+ "2-2016-73_Mow-AVPN-vPE-BV-L_VF_V2.0_1027.zip",
+ "1-ADIOD_base_vPE_BV_v9.0.zip",
+ "Vhss-epc-rdm3-lab-vf-0921-v2.0-MOBILITY-10-20.zip",
+ "1-Vhss-epc-rdm3-lab-vf-0921_VF00816v2.0-MOBILITY-10-20.zip",
+ "1-VF-vUSP-CCF-DB-0620_v1.0base_vDB.zip",
+ "1-Vusp_vhss-ims_cm-repo1_V1.zip",
+ "1-base_vepdg_volume_v4.0.zip",
+ "1-Vocg_1710-2017-509(2)_v1.0.zip",
+ "1-2016-20-vISBC3VF_v3.0.zip",
+ "Apndns-1710-vf-v3.0-10-20.zip",
+ "1-VF-EFMC_DBE_Nin_v27.0.zip",
+ "2-APNDNS_1710-VF_v4.0.zip",
+ "1-Mow_adig_vpe_bv-V3.0.zip",
+ "1-VF-2017-488_ADOID_vPE_v9.0.zip",
+ "1-MOBT_Nimbus_3_Sprint-1.zip",
+ "1-VF-2017-491_9vShaken-CM_v1.0.zip",
+ "1-VF_zrdm5bpxtc02_092017_v2.0.zip",
+// Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain \u0027topology_template
+ "1-VF-Checkpoint_vFW-1710_v1.0.zip"
+ );
/**
* additional files to exludeVnfList files for tosca parser tests
*/
protected static List<String> exludeVnfListForToscaParser = //new ArrayList<String>();
- Arrays.asList("1-Vvig-062017-(MOBILITY)_v5.1.zip",
- "HeatCandidate_2017-09-22_01-43_57Name_2017389vtsbc4vf-v1.0-(VOIP).zip",
- "1-Mvm-sbc-1710-092017-(MOBILITY)_v7.0.zip",
- "1-2017-492-5vshaken-SIP-AS-vf-(VOIP)_v2.0.zip",
- "HeatCandidate_2017-09-20_13-37_70Name_2017-491-4vshaken-HTTP-CM-vf-v1.0-(VOIP)_10202017.zip", "1-201712-488-adiod-vpe-(Layer-0-3)_v2.0.zip",
- "2017-502.zip",
- "1-2017-505-urlb-vhepe-(Layer-0-3)_v2.0.zip",
- "2017-376_vMOG_11_1.zip",
- "HeatCandidate_2017-09-22_00-55_62Name_2017-491-6vshaken-http-cm-vf-v1.0-(VOIP).zip", "HeatCandidate_2017-09-22_01-30_60Name_Vdbe-vsp-15.1x49-d50.3-v3.0-(VOIP).zip",
- "HeatCandidate_2017-09-22_01-35_59Name_2017-418-afx-v1.0.zip",
- "1-2017-488-adiod-vpe-(Layer-0-3)_v-5.0.zip",
- "HeatCandidate_2017-09-22_01-42_57Name_2017389vtsbc4vf-v10.0-(VOIP).zip",
- "HeatCandidate_2017-09-20_13-47_68Name_2017-492-5vshaken-SIP-AS-vf-v1.0-(VOIP)_10202017.zip", "1-2016-20-visbc3vf-(VOIP)_v2.1.zip",
- "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip", "1-2017389vtsbc4vf-(VOIP)_v11.0.zip",
- "HeatCandidate_2017-09-22_01-32_60Name_Vdbe-vsp-15.1x49-d50.3-v1.0-(VOIP).zip", "1-2017-418-afx-v1.1.zip");
+ Arrays.asList(
+ "1-Vvig-062017-(MOBILITY)_v5.1.zip",
+ "1-Mvm-sbc-1710-092017-(MOBILITY)_v7.0.zip",
+ "1-2017-492-5vshaken-SIP-AS-vf-(VOIP)_v2.0.zip",
+ "1-201712-488-adiod-vpe-(Layer-0-3)_v2.0.zip",
+ "2017-502.zip",
+ "1-2017-505-urlb-vhepe-(Layer-0-3)_v2.0.zip",
+ "2017-376_vMOG_11_1.zip",
+ "HeatCandidate_2017-09-22_01-30_60Name_Vdbe-vsp-15.1x49-d50.3-v3.0-(VOIP).zip",
+ "HeatCandidate_2017-09-22_01-42_57Name_2017389vtsbc4vf-v10.0-(VOIP).zip",
+ "HeatCandidate_2017-09-20_13-47_68Name_2017-492-5vshaken-SIP-AS-vf-v1.0-(VOIP)_10202017.zip",
+ "1-2016-20-visbc3vf-(VOIP)_v2.1.zip",
+ "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip",
+ "1-2017389vtsbc4vf-(VOIP)_v11.0.zip"
+ );
- public OnboardingUtils() {
- }
-
- public static Pair<String, Map<String, String>> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts)
- throws Exception {
-
- Pair<String, Map<String, String>> pair = createVSP(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers);
- String vspid = pair.right.get("vspId");
- if(cvfcArtifacts != null && ! cvfcArtifacts.isEmpty()){
- OnboardingUtils.addCvfcArtifacts(cvfcArtifacts, vspid, user, null);
-
- }
- prepareVspForUse(user, vspid, "0.1");
- return pair;
- }
-
- public static Pair<String, Map<String, String>> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers)
- throws Exception {
-
- Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>();
- return createVendorSoftwareProduct(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers, cvfcArtifacts);
- }
-
-// duplicate function
- public static void prepareVspForUse(User user, String vspid, String vspVersion) throws Exception {
-
- RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspid, user, vspVersion);
- assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspid, user, vspVersion);
- assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
-
- RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspid, user, vspVersion);
- assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
-
-// ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product");
- }
-
- public static VendorSoftwareProductObject createAndFillVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filePath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts)
- throws Exception {
-
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, heatFileName, filePath, user, amdocsLicenseMembers, cvfcArtifacts);
- VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(heatFileName, createVendorSoftwareProduct);
- return vendorSoftwareProductObject;
-
- }
-
- public static void updateVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user, String vlmVersion) throws Exception {
-
- RestResponse checkoutVendorLicense = checkoutVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion);
- assertEquals("did not succeed to checkout vendor license", 200, checkoutVendorLicense.getErrorCode().intValue());
-
- RestResponse checkinVendorLicense = checkinVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion);
- assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
-
- RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion);
- assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
-
- if(ComponentBaseTest.getExtendTest() != null){
- ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor license");
- }
- }
-
- public static Pair<String, Map<String, String>> createVSP(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception {
- String vspName = handleFilename(heatFileName);
-
- if(ComponentBaseTest.getExtendTest() != null){
- ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product");
- }
-
- Pair<RestResponse, Map<String, String>> createNewVspPair = createNewVendorSoftwareProduct(resourceReqDetails, vspName, amdocsLicenseMembers, 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<String, String> vspMeta = createNewVspPair.right;
- Map<String, String> vspObject = new HashMap<String, String>();
- Iterator<String> 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", amdocsLicenseMembers.getVendorLicenseName());
- vspObject.put("attContact", user.getUserId());
-
- RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vspid, user, "0.1");
- assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
-
- RestResponse validateUpload = validateUpload(vspid, user, "0.1");
- assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
-
- Pair<String, Map<String, String>> pair = new Pair<String, Map<String, String>>(vspName, vspObject);
-
- return pair;
- }
-
- public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user, String vspVersion) throws Exception{
- RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-// ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL");
- deleteArtifactByType(componentId, vspId, user, CvfcTypeEnum.SNMP_POLL);
-// ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP");
- deleteArtifactByType(componentId, vspId, user, CvfcTypeEnum.SNMP_TRAP);
- addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId);
- prepareVspForUse(user, vspId, vspVersion);
- }
-
- private static RestResponse deleteArtifactByType(String componentId, String vspId, User user, CvfcTypeEnum snmpType) throws Exception
- {
- Config config = Utils.getConfig();
- String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue());
- String userId = user.getUserId();
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendDelete(url, headersMap);
- return response;
- }
-
-// duplicated method
- public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user, String vspVersion)
- throws Exception, Throwable {
- String vspName = OnboardingUtils.handleFilename(HeatFileName);
- ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product");
-
- RestResponse checkout = OnboardingUtils.checkoutVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-
- RestResponse uploadHeatPackage = OnboardingUtils.uploadHeatPackage(filepath, HeatFileName, vspId, user, vspVersion);
- assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
-
- RestResponse validateUpload = OnboardingUtils.validateUpload(vspId, user, vspVersion);
- assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue());
-
- RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
-
- RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to update package of VSP ", 200, createPackage.getErrorCode().intValue());
-
- ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor software product");
-
- return vspName;
- }
-
- public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, String toVspVersion, User user)
- throws Exception, Throwable {
-
- RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
- assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-
- RestResponse checkin = checkinVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
- assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
- assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
-
- vendorSoftwareProductObject.setVersion(toVspVersion);
- }
-
public static String handleFilename(String heatFileName) {
- final String namePrefix = "ciVFOnboarded-";
+ final String namePrefix = String.format("%sVF%s", ElementFactory.getResourcePrefix(), "Onboarded-");
final String nameSuffix = "-" + getShortUUID();
String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf("."));
@@ -299,498 +129,22 @@ public class OnboardingUtils {
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 addCvfcArtifacts(Map<CvfcTypeEnum, String> componentVfcArtifacts, String vspid, User user, String vspComponentId) throws Exception{
- vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId;
- if (vspComponentId != null){
- for(Map.Entry<CvfcTypeEnum, String> entry : componentVfcArtifacts.entrySet()){
-// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type " + entry.getKey().getValue() + " with the file " + entry.getValue());
- RestResponse uploadSnmpPollArtifact = uploadCvfcArtifact(entry.getValue(), entry.getKey().getValue(), vspid, user, vspComponentId);
- assertEquals("Did not succeed to add " + entry.getKey().getValue(), BaseRestUtils.STATUS_CODE_SUCCESS, uploadSnmpPollArtifact.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);
- }
-
- public static RestResponse uploadCvfcArtifact(String filepath, String cvfcType, String vspid, User user, String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException {
- Config config = Utils.getConfig();
- String snmpPollUrl = String.format(Urls.UPLOAD_AMDOCS_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId, cvfcType);
- return uploadFile(filepath, null, snmpPollUrl, user);
- }
-
-
- 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(Urls.UPLOAD_SNMP_POLL_ARTIFACT, 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(Urls.UPLOAD_SNMP_POLL_ARTIFACT, 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<String, String> 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<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response);
- JSONArray results = (JSONArray)responseMap.get("results");
- for (Object res : results){
- Map<String, Object> compMap= (Map<String, Object>) 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(Urls.GET_VSP_COMPONENTS, config.getCatalogBeHost(),config.getCatalogBePort(), vspid);
- String userId = user.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendGet(url, headersMap);
- return response;
- }
-
- private static RestResponse getVLMComponentByVersion(String vlmId, String vlmVersion, User user) throws Exception{
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_VLM_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vlmId,vlmVersion);
- String userId = user.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendGet(url, headersMap);
- return response;
- }
-
- public static boolean validateVspExist(String vspId, String vspVersion, User user) throws Exception {
- RestResponse restResponse = getVSPComponentByVersion(vspId, vspVersion, user);
- assertEquals(String.format("Vsp version not updated, reponse message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
- return (restResponse.getErrorCode()==200);
- }
-
- public static boolean validateVlmExist(String vlmId, String vlmVersion, User user) throws Exception {
- RestResponse restResponse = getVLMComponentByVersion(vlmId, vlmVersion, user);
- assertEquals(String.format("VLM version not updated, reponse code message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
- return (restResponse.getErrorCode()==200);
- }
-
-
- private static RestResponse getVSPComponentByVersion(String vspId, String vspVersion, User user) throws Exception{
- Config config = Utils.getConfig();
- String url = String.format(Urls.GET_VSP_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vspId,vspVersion);
- String userId = user.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
-
- HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendGet(url, headersMap);
- return response;
- }
-
-// Duplicate method
- public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception {
-
- AmdocsLicenseMembers amdocsLicenseMembers;
-// ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license");
- String vendorLicenseName = "ciLicense" + OnboardingUtils.getShortUUID();
- RestResponse vendorLicenseResponse = OnboardingUtils.createVendorLicenseModels_1(vendorLicenseName, user);
- assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue());
- String 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());
- String 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());
- String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value");
-
- RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user, "0.1");
- assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
-
- RestResponse submitVendorLicense = OnboardingUtils.submitVendorLicense(vendorId, user, "0.1");
- assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
-
-// ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license");
-
- amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId);
- amdocsLicenseMembers.setVersion("1.0"); // Once object created and submitted, his initial version is 1.0
-
- return amdocsLicenseMembers;
- }
public static String getShortUUID() {
return UUID.randomUUID().toString().split("-")[0];
}
- private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user, String componentVersion)
- throws Exception {
+ private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception {
Config config = Utils.getConfig();
String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion);
String userId = user.getUserId();
-
- JSONObject jObject = new JSONObject();
- jObject.put("action", action);
-
- Map<String, String> 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, String vlmVersion) throws Exception {
- return actionOnComponent(vspid, "Checkin", "vendor-license-models", user, vlmVersion);
- }
-
- public static RestResponse checkoutVendorLicense(String vspid, User user, String vlmVersion) throws Exception {
- return actionOnComponent(vspid, "Checkout", "vendor-license-models", user, vlmVersion);
- }
-
- public static RestResponse submitVendorLicense(String vspid, User user, String vlmVersion) throws Exception {
- return actionOnComponent(vspid, "Submit", "vendor-license-models", user, vlmVersion);
- }
-
- public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_VENDOR_LISENCE_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<String, String> 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(Urls.CREATE_VENDOR_LISENCE_AGREEMENT, 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<String, String> 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(Urls.CREATE_VENDOR_LISENCE_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("manufacturerReferenceNumber", "5");
- jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
- jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
-
- Map<String, String> 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(Urls.CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL, 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"+ getShortUUID());
- 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<String, String> 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(Urls.CREATE_VENDOR_LISENCE_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" + getShortUUID());
- jObjectBody.put("description", "new vendor license key group");
- jObjectBody.put("operationalScope", jOperationalScope);
- jObjectBody.put("type", "Universal");
-
Map<String, String> headersMap = prepareHeadersMap(userId);
HttpRequest http = new HttpRequest();
- RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
- return response;
- }
-
- public static Pair<RestResponse, Map<String, String>> createNewVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String vspName, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
- Map<String, String> vspMetadta = new HashMap<String, String>();
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.CREATE_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
- String userId = user.getUserId();
- VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
- LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()));
- LicensingVersion licensingVersion = new LicensingVersion("1.0", "1.0");
- ResourceCategoryEnum resourceCategoryEnum = ResourceCategoryEnum.findEnumNameByValues(resourceReqDetails.getCategories().get(0).getName(), resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName());
-
- vendorSoftwareProductObject.setLicensingVersion(licensingVersion);
-
- vendorSoftwareProductObject.setName(vspName);
- vendorSoftwareProductObject.setDescription(resourceReqDetails.getDescription());
- vendorSoftwareProductObject.setCategory(resourceCategoryEnum.getCategoryUniqeId());
- vendorSoftwareProductObject.setSubCategory(resourceCategoryEnum.getSubCategoryUniqeId());
- vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
- vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName());
- vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId());
- vendorSoftwareProductObject.setIcon("icon");
- vendorSoftwareProductObject.setLicensingData(licensingData);
-
- vspMetadta.put("description", resourceReqDetails.getDescription());
- vspMetadta.put("category", resourceCategoryEnum.getCategory());
- vspMetadta.put("subCategory", resourceCategoryEnum.getSubCategory());
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRequest http = new HttpRequest();
- Gson gson = new Gson();
- String body = gson.toJson(vendorSoftwareProductObject);
-
- RestResponse response = http.httpSendPost(url, body, headersMap);
- return new Pair<RestResponse, Map<String, String>>(response, vspMetadta);
- }
-
- public static RestResponse validateUpload(String vspid, User user, String vspVersion) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vspid,vspVersion);
-
- String userId = user.getUserId();
-
- Map<String, String> 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, String vspVersion) throws Exception {
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPLOAD_HEAT_PACKAGE, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, vspVersion);
- 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<String, String> 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<String> 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();
- try {
- StringWriter writer = new StringWriter();
- IOUtils.copy(instream, writer);
- responseBody = writer.toString();
- } 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();
-// }
-
- private static File getTestZipFile(String filepath, String filename) throws IOException {
- Config config = Utils.getConfig();
- String sourceDir = config.getImportResourceTestsConfigDir();
- java.nio.file.Path filePath;
- if(filename == null){
- filePath = FileSystems.getDefault().getPath(filepath);
- }else{
- filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename);
- }
- return filePath.toFile();
- }
-
- public static RestResponse checkinVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
- return actionOnComponent(vspid, "Checkin", "vendor-software-products", user, vspVersion);
- }
-
- public static RestResponse checkoutVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
- return actionOnComponent(vspid, "Checkout", "vendor-software-products", user, vspVersion);
- }
-
- public static RestResponse submitVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
- return actionOnComponent(vspid, "Submit", "vendor-software-products", user, vspVersion);
- }
-
- public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
- return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user, vspVersion);
- }
-
protected static Map<String, String> prepareHeadersMap(String userId) {
Map<String, String> headersMap = new HashMap<String, String>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
@@ -799,193 +153,7 @@ public class OnboardingUtils {
return headersMap;
}
- public static VendorSoftwareProductObject updateVSPWithNewVLMParameters(VendorSoftwareProductObject vendorSoftwareProductObject,
- AmdocsLicenseMembers amdocsLicenseMembers, User user, String vspCurrentVersion, String vspNextVersion) throws Exception {
-
- LicensingVersion licensingVersion = new LicensingVersion(amdocsLicenseMembers.getLicenseVersionId(),amdocsLicenseMembers.getLicenseVersionId());
- LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()));
- vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId());
- vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName());
- vendorSoftwareProductObject.setLicensingVersion(licensingVersion);
- vendorSoftwareProductObject.setLicensingData(licensingData);
-
- VendorSoftwareProductObjectReqDetails vendorSoftwareProductObjectReqDetails = new VendorSoftwareProductObjectReqDetails(
- vendorSoftwareProductObject.getName(),
- vendorSoftwareProductObject.getDescription(),
- vendorSoftwareProductObject.getCategory(),
- vendorSoftwareProductObject.getSubCategory(),
- vendorSoftwareProductObject.getVendorId(),
- vendorSoftwareProductObject.getVendorName(),
- licensingVersion,
- licensingData,
- vendorSoftwareProductObject.getOnboardingMethod(),
- vendorSoftwareProductObject.getNetworkPackageName(),
- vendorSoftwareProductObject.getOnboardingOrigin());
-
- Gson gson = new Gson();
- String json = gson.toJson(vendorSoftwareProductObjectReqDetails);
-
- RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, "1.0");
- assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-
- Config config = Utils.getConfig();
- String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vspCurrentVersion);
- String userId = user.getUserId();
-
- Map<String, String> headersMap = prepareHeadersMap(userId);
- HttpRequest http = new HttpRequest();
-
- RestResponse response = http.httpSendPut(url, json, headersMap);
-
- RestResponse checkin = checkinVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vspCurrentVersion);
- assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vspCurrentVersion);
- assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
-
- vendorSoftwareProductObject.setVersion(vspNextVersion);
-
- return vendorSoftwareProductObject;
- }
-
-// private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{
-// String vspName = vsp.left;
-// Map<String, String> vspMetadata = vsp.right;
-// boolean vspFound = HomePage.searchForVSP(vspName);
-//
-// if (vspFound){
-//
-// List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable();
-//// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
-//// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
-//// 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<String, Map<String, String>> vsp) throws Exception{
-// ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left);
-// importUpdateVSP(vsp, true);
-// }
-//
-// public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{
-// ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left);
-// importUpdateVSP(vsp, false);
-// }
-//
-// public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> 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<String, String> 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<String, Map<String, String>> 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));
-//
-// AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user);
-// Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers);
-// String vspName = createVendorSoftwareProduct.left;
-//
-// DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId"));
-// File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
-//
-// 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<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath());
-//
-// LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment"));
-// ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts);
-//
-// List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")).
-// map(e -> e.getFileName()).
-// collect(Collectors.toList());
-//
-// validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR);
-//
-// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile);
-// return createVendorSoftwareProduct;
-// }
-//
-// public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts,
-// List<String> heatEnvFilesFromCSAR) {
-// String artifactVersion;
-// String artifactName;
-//
-// for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) {
-// artifactVersion = "1";
-//
-// if(deploymentArtifact.getType().equals("HEAT_ENV")) {
-// continue;
-// } else if(deploymentArtifact.getFileName().contains(".")) {
-// artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
-// } else {
-// artifactName = deploymentArtifact.getFileName().trim();
-// }
-//
-// if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){
-// artifactVersion = "2";
-// }
-// ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
-// }
-// }
-
-
/**
* @return
* The method returns VNF names list from Files directory under sdc-vnfs repository
@@ -993,11 +161,30 @@ public class OnboardingUtils {
public static List<String> getVnfNamesFileList() {
String filepath = FileHandling.getVnfRepositoryPath();
List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ //Please remove the hardcoded configuration ONAP Tal G!!!!!!
fileNamesFromFolder.removeAll(exludeVnfList);
+ //List<String> halfResourceListByDay = divideListByDayOfMonth(fileNamesFromFolder);
+ //System.out.println(halfResourceListByDay.toString());
return fileNamesFromFolder;
}
/**
+ * @param vnfNamesFileList
+ * @return divide List according to day of month, if day of month is even as get first half part of the List, else - second
+ */
+ public static List<String> divideListByDayOfMonth(List<String> vnfNamesFileList){
+
+ Calendar cal = Calendar.getInstance();
+ int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH)+1;
+ int filesCount = vnfNamesFileList.size();
+ if(dayOfMonth%2 == 0){
+ return vnfNamesFileList.subList(0,filesCount/2);
+ }else{
+ return vnfNamesFileList.subList(filesCount/2, filesCount);
+ }
+ }
+
+ /**
* @return
* The method returns VNF names list from Files directory under sdc-vnfs repository excluding zip files that known as failed in tosca parser
*/
@@ -1007,41 +194,6 @@ public class OnboardingUtils {
return fileNamesFromFolder;
}
- public static VendorSoftwareProductObject fillVendorSoftwareProductObjectWithMetaData(String vnfFile, Pair<String, Map<String, String>> createVendorSoftwareProduct) {
- VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
- Map<String, String> map = createVendorSoftwareProduct.right;
- vendorSoftwareProductObject.setAttContact(map.get("attContact"));
- vendorSoftwareProductObject.setCategory(map.get("category"));
- vendorSoftwareProductObject.setComponentId(map.get("componentId"));
- vendorSoftwareProductObject.setDescription(map.get("description"));
- vendorSoftwareProductObject.setSubCategory(map.get("subCategory"));
- vendorSoftwareProductObject.setVendorName(map.get("vendorName"));
- vendorSoftwareProductObject.setVspId(map.get("vspId"));
- vendorSoftwareProductObject.setName(createVendorSoftwareProduct.left);
- String[] arrFileNameAndExtension = vnfFile.split("\\.");
- vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
- vendorSoftwareProductObject.setNetworkPackageName(arrFileNameAndExtension[0]);
- vendorSoftwareProductObject.setOnboardingOrigin(arrFileNameAndExtension[1]);
-
- return vendorSoftwareProductObject;
- }
-
- public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, String toVspVersion, User user, String filepath, String heatFileName)
- throws Exception, Throwable {
-
- RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
- assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-
- RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vendorSoftwareProductObject.getVspId(), user, "1.1");
- assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
-
- RestResponse validateUpload = validateUpload(vendorSoftwareProductObject.getVspId(), user, "1.1");
- assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
-
- prepareVspForUse(user,vendorSoftwareProductObject.getVspId(),toVspVersion);
-
- vendorSoftwareProductObject.setVersion(toVspVersion);
- }
public static Object[][] filterObjectArrWithExcludedVnfs(Object[][] objectArr)
{
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java
index 366962ef0a..71038920ae 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java
@@ -20,6 +20,56 @@
package org.openecomp.sdc.ci.tests.utils.general;
+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 java.util.stream.Collectors;
+
+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.AmdocsLicenseMembers;
+
+import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition;
+
+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.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+
+import org.testng.Assert;
+
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+
enum SnmpTypeEnum{
SNMP_POLL ("snmp"),
SNMP_TRAP ("snmp-trap");
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java
new file mode 100644
index 0000000000..ec368df621
--- /dev/null
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorLicenseModelRestUtils.java
@@ -0,0 +1,285 @@
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import com.aventstack.extentreports.Status;
+import org.json.JSONObject;
+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.AmdocsLicenseMembers;
+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 java.util.Arrays;
+import java.util.Map;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+public class VendorLicenseModelRestUtils {
+
+ public static void updateVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user, Boolean isVlmUpdated) throws Exception {
+
+// create major method
+ RestResponse creationMethodVendorLicense = creationMethodVendorLicense(amdocsLicenseMembers, user);
+ assertEquals("did not succeed to create method for vendor license", 200, creationMethodVendorLicense.getErrorCode().intValue());
+ amdocsLicenseMembers.setVersion(ResponseParser.getValueFromJsonResponse(creationMethodVendorLicense.getResponse(), "id"));
+
+ if(isVlmUpdated) {
+// TODO update vlm do nothing
+// commit
+ RestResponse commitVendorLicense = commitVendorLicense(amdocsLicenseMembers, user);
+ assertEquals("did not succeed to commit vendor license", 200, commitVendorLicense.getErrorCode().intValue());
+ }
+
+// submit
+ RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers, user);
+ assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
+
+ if(ComponentBaseTest.getExtendTest() != null){
+ ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor license");
+ }
+ }
+
+ private static RestResponse getVLMComponentByVersion(String vlmId, String vlmVersion, User user) throws Exception{
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_VLM_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vlmId,vlmVersion);
+ String userId = user.getUserId();
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendGet(url, headersMap);
+ return response;
+ }
+
+ public static boolean validateVlmExist(String vlmId, String vlmVersion, User user) throws Exception {
+ RestResponse restResponse = getVLMComponentByVersion(vlmId, vlmVersion, user);
+ assertEquals(String.format("VLM version not updated, reponse code message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
+ return (restResponse.getErrorCode()==200);
+ }
+
+ public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception {
+
+ AmdocsLicenseMembers amdocsLicenseMembers;
+// ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license");
+ String vendorLicenseName = "ciLicense" + OnboardingUtils.getShortUUID();
+ RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user);
+ assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue());
+ String vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "itemId");
+ String versionId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "version:id");
+
+ RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, versionId, 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, versionId, 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, versionId, keyGroupId, entitlementPoolId, user);
+ assertEquals("did not succeed to create vendor license feature groups", 200, vendorLicenseFeatureGroups.getErrorCode().intValue());
+ String featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value");
+
+ RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, versionId, featureGroupId, user);
+ assertEquals("did not succeed to create vendor license agreement", 200, vendorLicenseAgreement.getErrorCode().intValue());
+ String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value");
+
+// RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user, versionId);
+// assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
+
+ amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId);
+ amdocsLicenseMembers.setVersion(versionId); // Once object created and submitted, his initial version is 1.0
+
+ RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers, user);
+ assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
+
+// ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license");
+
+ return amdocsLicenseMembers;
+ }
+
+ private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion);
+ String userId = user.getUserId();
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPut(url, body, headersMap);
+ return response;
+ }
+
+ private static RestResponse createMethodVendorLicense(String vendorId, String body, String onboardComponent, User user, String componentVersion) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_METHOD, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vendorId, componentVersion);
+ String userId = user.getUserId();
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, body, headersMap);
+ return response;
+ }
+
+ public static RestResponse submitVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
+ return actionOnComponent(amdocsLicenseMembers.getVendorId(), "{\"action\":\"Submit\"}", "vendor-license-models", user, amdocsLicenseMembers.getVersion());
+ }
+
+ /**
+ * @param amdocsLicenseMembers
+ * @param user
+ * @return
+ * checkOut exist VLM method
+ * @throws Exception
+ */
+ public static RestResponse creationMethodVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
+ String messageBody = "{\"description\":\"2.0\",\"creationMethod\":\"major\"}";
+ return createMethodVendorLicense(amdocsLicenseMembers.getVendorId(), messageBody, "items", user, amdocsLicenseMembers.getVersion());
+ }
+
+ public static RestResponse commitVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
+ String messageBody = "{\"action\":\"Commit\",\"commitRequest\":{\"message\":\"commit\"}}";
+ return actionOnComponent(amdocsLicenseMembers.getVendorId(), messageBody, "items", user, amdocsLicenseMembers.getVersion());
+ }
+
+ public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_VENDOR_LISENCE_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<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
+ return response;
+
+ }
+
+ public static RestResponse createVendorLicenseAgreement_5(String vspid, String versionId, String featureGroupId, User user)
+ throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_VENDOR_LISENCE_AGREEMENT, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId);
+ 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<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
+ return response;
+ }
+
+ public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String versionId, String licenseKeyGroupId,
+ String entitlementPoolId, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_VENDOR_LISENCE_FEATURE_GROUPS, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId);
+ 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("manufacturerReferenceNumber", "5");
+ jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
+ jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap);
+ return response;
+
+ }
+
+ public static RestResponse createVendorEntitlementPool_3(String vspid, String versionId, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId);
+ 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"+ OnboardingUtils.getShortUUID());
+ 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<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
+ return response;
+ }
+
+ public static RestResponse createVendorKeyGroups_2(String vspid, String versionId, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_VENDOR_LISENCE_KEY_GROUPS, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, versionId);
+ 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" + OnboardingUtils.getShortUUID());
+ jObjectBody.put("description", "new vendor license key group");
+ jObjectBody.put("operationalScope", jOperationalScope);
+ jObjectBody.put("type", "Universal");
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
+ return response;
+ }
+
+ public static RestResponse validateUpload(String vspid, User user, String vspVersion) throws Exception {
+ String body = null;
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vspid,vspVersion);
+ String userId = user.getUserId();
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPut(url, body, headersMap);
+
+ return response;
+ }
+
+}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java
new file mode 100644
index 0000000000..c3b0a28f03
--- /dev/null
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/VendorSoftwareProductRestUtils.java
@@ -0,0 +1,697 @@
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+import com.google.gson.Gson;
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+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.simple.JSONArray;
+import org.json.simple.JSONValue;
+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.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.CvfcTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+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.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+
+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 static org.testng.AssertJUnit.assertEquals;
+
+public class VendorSoftwareProductRestUtils {
+
+ public static Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts)
+ throws Exception {
+
+ Pair<String, VendorSoftwareProductObject> pair = createVSP(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers);
+ if(cvfcArtifacts != null && ! cvfcArtifacts.isEmpty()){
+ addCvfcArtifacts(cvfcArtifacts, user, pair.right);
+ }
+ prepareVspForUse(user, pair.right, true);
+ return pair;
+ }
+
+ public static Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers)
+ throws Exception {
+
+ Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>();
+ return createVendorSoftwareProduct(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers, cvfcArtifacts);
+ }
+
+ /**
+ * @param user user
+ * @param vendorSoftwareProductObject vendorSoftwareProductObject
+ * @param isVspUpdated - in case isVspUpdated = false the commit API should not be issued
+ * the method do commit, submit and create package
+ * @throws Exception
+ */
+ public static void prepareVspForUse(User user, VendorSoftwareProductObject vendorSoftwareProductObject, Boolean isVspUpdated) throws Exception {
+
+ if(isVspUpdated) {
+ RestResponse commit = commitVendorSoftwareProduct(vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to commit new VSP", 200, commit.getErrorCode().intValue());
+ }
+ RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getComponentId());
+ assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
+
+ RestResponse createPackage = createPackageOfVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getComponentId());
+ assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
+
+ }
+
+ public static VendorSoftwareProductObject createAndFillVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filePath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts)
+ throws Exception {
+
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = createVendorSoftwareProduct(resourceReqDetails, heatFileName, filePath, user, amdocsLicenseMembers, cvfcArtifacts);
+ VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(heatFileName, createVendorSoftwareProduct);
+ return vendorSoftwareProductObject;
+
+ }
+
+
+ public static Pair<String, VendorSoftwareProductObject> createVSP(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception {
+ String vspName = handleFilename(heatFileName);
+
+ if(ComponentBaseTest.getExtendTest() != null){
+ ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product");
+ }
+
+ Pair<RestResponse, VendorSoftwareProductObject> createNewVspPair = createNewVendorSoftwareProduct(resourceReqDetails, vspName, amdocsLicenseMembers, user);
+ assertEquals("did not succeed to create new VSP", 200,createNewVspPair.left.getErrorCode().intValue());
+
+ RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, createNewVspPair.right, user);
+ assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
+
+ RestResponse validateUpload = validateUpload(createNewVspPair.right, user);
+ assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
+
+ Pair<String, VendorSoftwareProductObject> pair = new Pair<>(vspName, createNewVspPair.right);
+ return pair;
+ }
+
+ public static void updateVspWithVfcArtifacts(String filepath, String updatedSnmpPoll, String updatedSnmpTrap, String componentInstanceId, User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception{
+ RestResponse checkout = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
+// ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL");
+ deleteArtifactByType(componentInstanceId, vendorSoftwareProductObject, user, CvfcTypeEnum.SNMP_POLL);
+// ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP");
+ deleteArtifactByType(componentInstanceId, vendorSoftwareProductObject, user, CvfcTypeEnum.SNMP_TRAP);
+ addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vendorSoftwareProductObject, user, componentInstanceId);
+ prepareVspForUse(user, vendorSoftwareProductObject, true);
+ }
+
+ private static RestResponse deleteArtifactByType(String componentInstanceId, VendorSoftwareProductObject vendorSoftwareProductObject, User user, CvfcTypeEnum snmpType) throws Exception
+ {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId, snmpType.getValue());
+ String userId = user.getUserId();
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendDelete(url, headersMap);
+ return response;
+ }
+
+ public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user, Boolean isVspUpdated) throws Throwable {
+
+ RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to createMethod for new VSP", 200, createMethod.getErrorCode().intValue());
+ prepareVspForUse(user,vendorSoftwareProductObject, isVspUpdated);
+
+ }
+
+ public static String handleFilename(String heatFileName) {
+ final String namePrefix = String.format("%sVF%s", ElementFactory.getResourcePrefix(), "Onboarded-");
+ final String nameSuffix = "-" + OnboardingUtils.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, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String componentInstanceId) throws Exception{
+ componentInstanceId = (componentInstanceId == null) ? getVspComponentId(vendorSoftwareProductObject, user) : componentInstanceId;
+ if (componentInstanceId != null){
+ if (snmpPoll != null){
+// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll);
+ RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vendorSoftwareProductObject, user, componentInstanceId);
+ 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, vendorSoftwareProductObject, user, componentInstanceId);
+ assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue());
+ }
+ }
+
+ return componentInstanceId;
+ }
+
+ public static String addCvfcArtifacts(Map<CvfcTypeEnum, String> componentVfcArtifacts, User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception{
+ String componentInstanceId = getVspComponentId(vendorSoftwareProductObject, user);
+ if (componentInstanceId != null){
+ for(Map.Entry<CvfcTypeEnum, String> entry : componentVfcArtifacts.entrySet()){
+// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type " + entry.getKey().getValue() + " with the file " + entry.getValue());
+ RestResponse uploadSnmpPollArtifact = uploadCvfcArtifact(entry.getValue(), entry.getKey().getValue(), user, vendorSoftwareProductObject, componentInstanceId);
+ assertEquals("Did not succeed to add " + entry.getKey().getValue(), BaseRestUtils.STATUS_CODE_SUCCESS, uploadSnmpPollArtifact.getErrorCode().intValue());
+ }
+ }
+ return componentInstanceId;
+ }
+
+ public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{
+ return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vendorSoftwareProductObject, user, null);
+ }
+
+ public static RestResponse uploadCvfcArtifact(String filepath, String cvfcType, User user, VendorSoftwareProductObject vendorSoftwareProductObject, String componentInstanceId) throws IOException {
+ Config config = Utils.getConfig();
+ String snmpPollUrl = String.format(Urls.UPLOAD_AMDOCS_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId, cvfcType);
+ return uploadFile(filepath, null, snmpPollUrl, user);
+ }
+
+
+ private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String componentInstanceId) throws IOException {
+ Config config = Utils.getConfig();
+ String snmpPollUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), componentInstanceId);
+ return uploadFile(filepath, zipArtifact, snmpPollUrl, user);
+ }
+
+ private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, VendorSoftwareProductObject vendorSoftwareProductObject, User user, String vspComponentId) throws IOException {
+ Config config = Utils.getConfig();
+ String snmpTrapUrl = String.format(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId(), 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(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue());
+ String userId = user.getUserId();
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendDelete(url, headersMap);
+ return response;
+ }
+
+
+ /**
+ * @param vendorSoftwareProductObject VendorSoftwareProductObject
+ * @param user user object
+ * @return return first found component instance Id from list
+ * @throws Exception Exception
+ */
+ private static String getVspComponentId(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
+ RestResponse componentList = getVSPComponents(vendorSoftwareProductObject, user);
+ String response = componentList.getResponse();
+ Map<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response);
+ JSONArray results = (JSONArray)responseMap.get("results");
+ for (Object res : results){
+ Map<String, Object> componentMap = (Map<String, Object>) JSONValue.parse(res.toString());
+ String componentInstanceId = componentMap.get("id").toString();
+ return componentInstanceId;
+ }
+ return null;
+ }
+
+ private static RestResponse getVSPComponents(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_VSP_COMPONENTS, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(user.getUserId());
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendGet(url, headersMap);
+ return response;
+ }
+
+
+
+ public static boolean validateVspExist(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
+ RestResponse restResponse = getVSPComponentByVersion(vendorSoftwareProductObject, user);
+ assertEquals(String.format("Vsp version not updated, reponse message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
+ return (restResponse.getErrorCode()==200);
+ }
+
+
+ private static RestResponse getVSPComponentByVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception{
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_VSP_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+ String userId = user.getUserId();
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendGet(url, headersMap);
+ return response;
+ }
+
+ private static RestResponse actionOnComponent(String vspid, String body, String onboardComponent, User user, String componentVersion) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion);
+ String userId = user.getUserId();
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPut(url, body, headersMap);
+ return response;
+ }
+
+ public static Pair<RestResponse, VendorSoftwareProductObject> createNewVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String vspName, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
+ String userId = user.getUserId();
+ VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
+ LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()));
+ ResourceCategoryEnum resourceCategoryEnum = ResourceCategoryEnum.findEnumNameByValues(resourceReqDetails.getCategories().get(0).getName(), resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName());
+
+ vendorSoftwareProductObject.setName(vspName);
+ vendorSoftwareProductObject.setDescription(resourceReqDetails.getDescription());
+ vendorSoftwareProductObject.setCategory(resourceCategoryEnum.getCategoryUniqeId());
+ vendorSoftwareProductObject.setSubCategory(resourceCategoryEnum.getSubCategoryUniqeId());
+ vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
+ vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName());
+ vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId());
+ vendorSoftwareProductObject.setIcon("icon");
+ vendorSoftwareProductObject.setLicensingData(licensingData);
+ vendorSoftwareProductObject.setLicensingVersion(amdocsLicenseMembers.getVersion());
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ Gson gson = new Gson();
+ String body = gson.toJson(vendorSoftwareProductObject);
+
+ RestResponse response = http.httpSendPost(url, body, headersMap);
+
+ vendorSoftwareProductObject.setVspId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "itemId"));
+ vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:id"));
+// vendorSoftwareProductObject.setVersion(ResponseParser.getValueFromJsonResponse(response.getResponse(), "version:name"));
+ vendorSoftwareProductObject.setAttContact(user.getUserId());
+
+ return new Pair<>(response, vendorSoftwareProductObject);
+ }
+
+ public static RestResponse validateUpload(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+ String userId = user.getUserId();
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPut(url, null, headersMap);
+
+ return response;
+ }
+
+ public static RestResponse uploadHeatPackage(String filepath, String filename, VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPLOAD_HEAT_PACKAGE, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+ return uploadFile(filepath, filename, url, user);
+ }
+
+ private static RestResponse uploadFile(String filepath, String filename, String url, User user) throws IOException{
+ CloseableHttpResponse response = null;
+
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+ mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename)));
+
+ Map<String, String> headersMap = OnboardingUtils.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<String> 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();
+ try {
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(instream, writer);
+ responseBody = writer.toString();
+ } 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;
+ if(filename == null){
+ filePath = FileSystems.getDefault().getPath(filepath);
+ }else{
+ filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename);
+ }
+ return filePath.toFile();
+ }
+
+ public static RestResponse checkinVendorSoftwareProduct(User user, VendorSoftwareProductObject vendorSoftwareProductObject) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+
+ String userId = user.getUserId();
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+// unset vspId, componentId, attContact, onboardingMethod
+ String vspId = vendorSoftwareProductObject.getVspId();
+ String componentId = vendorSoftwareProductObject.getComponentId();
+ String attContact = vendorSoftwareProductObject.getAttContact();
+ String onboardingMethod = vendorSoftwareProductObject.getOnboardingMethod();
+ vendorSoftwareProductObject.setVspId(null);
+ vendorSoftwareProductObject.setComponentId(null);
+ vendorSoftwareProductObject.setAttContact(null);
+ vendorSoftwareProductObject.setOnboardingMethod(null);
+ Gson gson = new Gson();
+ String body = gson.toJson(vendorSoftwareProductObject);
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPut(url, body, headersMap);
+// set back vspId, componentId, attContact, onboardingMethod
+ vendorSoftwareProductObject.setVspId(vspId);
+ vendorSoftwareProductObject.setComponentId(componentId);
+ vendorSoftwareProductObject.setAttContact(attContact);
+ vendorSoftwareProductObject.setOnboardingMethod(onboardingMethod);
+
+ return response;
+ }
+
+ public static RestResponse commitVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
+ String messageBody = "{\"action\":\"Commit\",\"commitRequest\":{\"message\":\"commit\"}}";
+ return actionOnComponent(vendorSoftwareProductObject.getVspId(), messageBody, "items", user, vendorSoftwareProductObject.getComponentId());
+ }
+
+ public static RestResponse submitVendorSoftwareProduct(String vspid, User user, String componentId) throws Exception {
+ return actionOnComponent(vspid, "{\"action\":\"Submit\"}", "vendor-software-products", user, componentId);
+ }
+
+ public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user, String componentId) throws Exception {
+ return actionOnComponent(vspid, "{\"action\":\"Create_Package\"}", "vendor-software-products", user, componentId);
+ }
+
+ public static RestResponse creationMethodVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception {
+ String messageBody = "{\"description\":\"2.0\",\"creationMethod\":\"major\"}";
+ return createMethodVendorSoftwareProduct(vendorSoftwareProductObject, messageBody, "items", user);
+ }
+
+ private static RestResponse createMethodVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, String body, String onboardComponent, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_METHOD, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+ String userId = user.getUserId();
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, body, headersMap);
+ if(response.getErrorCode().intValue() == 200) {
+ vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "id"));
+ }
+ return response;
+ }
+
+ public static VendorSoftwareProductObject updateVSPWithNewVLMParameters(VendorSoftwareProductObject vendorSoftwareProductObject, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
+
+ RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to checkout new VSP", 200, createMethod.getErrorCode().intValue());
+// vendorSoftwareProductObject.setComponentId(ResponseParser.getValueFromJsonResponse(createMethod.getResponse(), "id"));
+
+ String licensingVersion = amdocsLicenseMembers.getVersion();
+ LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()));
+ vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId());
+ vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName());
+ vendorSoftwareProductObject.setLicensingVersion(licensingVersion);
+ vendorSoftwareProductObject.setLicensingData(licensingData);
+
+ VendorSoftwareProductObjectReqDetails vendorSoftwareProductObjectReqDetails = new VendorSoftwareProductObjectReqDetails(
+ vendorSoftwareProductObject.getName(), vendorSoftwareProductObject.getDescription(), vendorSoftwareProductObject.getCategory(),
+ vendorSoftwareProductObject.getSubCategory(), vendorSoftwareProductObject.getVendorId(), vendorSoftwareProductObject.getVendorName(),
+ vendorSoftwareProductObject.getLicensingVersion(), vendorSoftwareProductObject.getLicensingData(),
+ null, null, null, vendorSoftwareProductObject.getIcon() );
+
+ Gson gson = new Gson();
+ String body = gson.toJson(vendorSoftwareProductObjectReqDetails);
+ RestResponse updateResponse = updateVendorSoftwareProduct(vendorSoftwareProductObject, body, user);
+ assertEquals("did not succeed to update VSP", 200, updateResponse.getErrorCode().intValue());
+
+ prepareVspForUse(user, vendorSoftwareProductObject, true);
+
+ return vendorSoftwareProductObject;
+ }
+
+ public static RestResponse updateVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, String body, User user) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vendorSoftwareProductObject.getComponentId());
+ String userId = user.getUserId();
+
+ Map<String, String> headersMap = OnboardingUtils.prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+
+ RestResponse response = http.httpSendPut(url, body, headersMap);
+ return response;
+ }
+
+// private static void importUpdateVSP(Pair<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{
+// String vspName = vsp.left;
+// Map<String, String> vspMetadata = vsp.right;
+// boolean vspFound = HomePage.searchForVSP(vspName);
+//
+// if (vspFound){
+//
+// List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable();
+//// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
+//// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
+//// 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<String, Map<String, String>> vsp) throws Exception{
+// ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left);
+// importUpdateVSP(vsp, true);
+// }
+//
+// public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{
+// ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left);
+// importUpdateVSP(vsp, false);
+// }
+//
+// public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> 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<String, String> 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<String, Map<String, String>> 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));
+//
+// AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user);
+// Pair<String, Map<String, String>> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers);
+// String vspName = createVendorSoftwareProduct.left;
+//
+// DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId"));
+// File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
+//
+// 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<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath());
+//
+// LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment"));
+// ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts);
+//
+// List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")).
+// map(e -> e.getFileName()).
+// collect(Collectors.toList());
+//
+// validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR);
+//
+// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile);
+// return createVendorSoftwareProduct;
+// }
+//
+// public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts,
+// List<String> heatEnvFilesFromCSAR) {
+// String artifactVersion;
+// String artifactName;
+//
+// for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) {
+// artifactVersion = "1";
+//
+// if(deploymentArtifact.getType().equals("HEAT_ENV")) {
+// continue;
+// } else if(deploymentArtifact.getFileName().contains(".")) {
+// artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
+// } else {
+// artifactName = deploymentArtifact.getFileName().trim();
+// }
+//
+// if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){
+// artifactVersion = "2";
+// }
+// ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
+// }
+// }
+
+
+ public static VendorSoftwareProductObject fillVendorSoftwareProductObjectWithMetaData(String vnfFile, Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct) {
+ VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
+ VendorSoftwareProductObject map = createVendorSoftwareProduct.right;
+ vendorSoftwareProductObject.setAttContact(map.getAttContact());
+ vendorSoftwareProductObject.setCategory(map.getCategory());
+ vendorSoftwareProductObject.setComponentId(map.getComponentId());
+ vendorSoftwareProductObject.setDescription(map.getDescription());
+ vendorSoftwareProductObject.setSubCategory(map.getSubCategory());
+ vendorSoftwareProductObject.setVendorName(map.getVendorName());
+ vendorSoftwareProductObject.setVspId(map.getVspId());
+ vendorSoftwareProductObject.setName(createVendorSoftwareProduct.left);
+ String[] arrFileNameAndExtension = vnfFile.split("\\.");
+ vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
+ vendorSoftwareProductObject.setNetworkPackageName(arrFileNameAndExtension[0]);
+ vendorSoftwareProductObject.setOnboardingOrigin(arrFileNameAndExtension[1]);
+
+ return vendorSoftwareProductObject;
+ }
+
+ public static void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, User user, String filepath, String heatFileName) throws Throwable {
+
+ RestResponse createMethod = creationMethodVendorSoftwareProduct(vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to createMethod for new VSP", 200, createMethod.getErrorCode().intValue());
+
+ RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
+
+ RestResponse validateUpload = validateUpload(vendorSoftwareProductObject, user);
+ assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
+
+ prepareVspForUse(user,vendorSoftwareProductObject, true);
+ }
+
+
+}
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
index a7ab544725..448442e112 100644
--- 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
@@ -50,15 +50,12 @@ 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());
@@ -68,7 +65,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
String resourceInstanceName = resourceInstance.getNormalizedName();
@@ -88,7 +85,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
System.out.println(component.getComponentType());
@@ -110,7 +107,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
String resourceInstanceName = resourceInstance.getNormalizedName();
@@ -130,7 +127,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
System.out.println(component.getComponentType());
@@ -150,7 +147,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
String resourceInstanceName = resourceInstance.getNormalizedName();
@@ -170,7 +167,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
System.out.println(component.getComponentType());
@@ -190,7 +187,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
String resourceInstanceName = resourceInstance.getNormalizedName();
@@ -210,7 +207,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
// 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 resourceType;
String resourceUUID = component.getUUID();
System.out.println(component.getComponentType());
@@ -232,7 +229,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
//
public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException {
Config config = Utils.getConfig();
- String url = null;
+ String url;
if (resourceType.toUpperCase().equals("SERVICE")) {
url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID);
@@ -241,11 +238,12 @@ public class ArtifactRestUtils extends BaseRestUtils {
url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID);
}
- Map<String, String> headersMap = new HashMap<String,String>();
+ Map<String, String> 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");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(),acceptMultipartHeader);
HttpRequest http = new HttpRequest();
@@ -265,7 +263,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentNormalizedName, String artifactUUID,User sdncModifierDetails, String resourceType) throws IOException {
Config config = Utils.getConfig();
- String url = null;
+ String url;
if (resourceType.toLowerCase().equals("service")) {
url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID);
@@ -274,11 +272,12 @@ public class ArtifactRestUtils extends BaseRestUtils {
url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentNormalizedName, artifactUUID);
}
- Map<String, String> headersMap = new HashMap<String,String>();
+ Map<String, String> 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");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(),acceptMultipartHeader);
HttpRequest http = new HttpRequest();
@@ -443,7 +442,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
public static Map<String, String> getHeadersMap(User sdncModifierDetails) {
- Map<String, String> headersMap = new HashMap<String,String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader);
@@ -602,9 +601,9 @@ public class ArtifactRestUtils extends BaseRestUtils {
public static RestResponse uploadDeploymentArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> additionalHeaders = null;
+ Map<String, String> additionalHeaders;
String checksum = ResponseParser.calculateMD5Header(artifactDetails);
- additionalHeaders = new HashMap<String, String>();
+ additionalHeaders = new HashMap<>();
additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
ComponentTypeEnum componentType = component.getComponentType();
@@ -614,26 +613,26 @@ public class ArtifactRestUtils extends BaseRestUtils {
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;
- }
+ {
+ 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;
+ }
}
@@ -654,9 +653,9 @@ public class ArtifactRestUtils extends BaseRestUtils {
public static RestResponse uploadArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException {
Config config = Utils.getConfig();
List<String> placeHolderlst = Utils.getListOfResPlaceHoldersDepArtTypes();
- Map<String, String> additionalHeaders = null;
- String checksum = null;
- String url= null;
+ Map<String, String> additionalHeaders;
+ String checksum;
+ String url;
//
//
// if (artifactDetails.getArtifactGroupType() != null
@@ -676,7 +675,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
//
// else {
checksum = ResponseParser.calculateMD5Header(artifactDetails);
- additionalHeaders = new HashMap<String, String>();
+ 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()),
@@ -700,13 +699,13 @@ public class ArtifactRestUtils extends BaseRestUtils {
//*************** PRIVATE **************
private static RestResponse deleteInformationalArtifact(User sdncModifierDetails, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
+ Map<String, String> additionalHeaders;
- additionalHeaders = new HashMap<String, String>();
+ additionalHeaders = new HashMap<>();
additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
return sendDelete(url, sdncModifierDetails.getUserId(), additionalHeaders);
@@ -729,12 +728,12 @@ public class ArtifactRestUtils extends BaseRestUtils {
private static RestResponse uploadInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
Map<String, String> additionalHeaders = null;
if (checksum != null && !checksum.isEmpty()) {
- additionalHeaders = new HashMap<String, String>();
+ 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");
+ additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
Gson gson = new Gson();
// System.out.println("ArtifactDetails: "+ jsonBody);
@@ -749,10 +748,10 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
private static RestResponse addArtifactToInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
- additionalHeaders = new HashMap<String, String>();
+ Map<String, String> additionalHeaders;
+ additionalHeaders = new HashMap<>();
if (checksum != null && !checksum.isEmpty()) {
- additionalHeaders = new HashMap<String, String>();
+ additionalHeaders = new HashMap<>();
additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
}
additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
@@ -769,8 +768,8 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
private static RestResponse updateDeploymentArtifact(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
- additionalHeaders = new HashMap<String, String>();
+ Map<String, String> additionalHeaders;
+ additionalHeaders = new HashMap<>();
additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
@@ -782,9 +781,9 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
private static RestResponse updateDeploymentArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String url) throws IOException {
- Map<String, String> additionalHeaders = null;
+ Map<String, String> additionalHeaders;
- additionalHeaders = new HashMap<String, String>();
+ 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");
@@ -805,7 +804,7 @@ public class ArtifactRestUtils extends BaseRestUtils {
private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders,boolean addEcompHeader) throws IOException
{
if(addEcompHeader){
- addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), ecomp);
+ addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
}
return downloadArtifact(url, user, addionalHeaders, acceptOctetStream);
}
@@ -906,29 +905,5 @@ public class ArtifactRestUtils extends BaseRestUtils {
}
-
- 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
index 4ade9eb16c..13cfb8fb63 100644
--- 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
@@ -31,7 +31,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.UUID;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
@@ -39,7 +38,7 @@ 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 com.fasterxml.jackson.databind.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;
@@ -78,8 +77,6 @@ public class AssetRestUtils extends BaseRestUtils {
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";
@@ -93,7 +90,7 @@ public class AssetRestUtils extends BaseRestUtils {
assetType.getValue(), uuid);
HttpGet httpGet = new HttpGet(url);
- httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
logger.debug("Send GET request to get Tosca model: {}", url);
@@ -101,18 +98,27 @@ public class AssetRestUtils extends BaseRestUtils {
return httpclient.execute(httpGet);
}
+ public static File getToscaModelCsarFile(AssetTypeEnum assetType, String uuid) throws IOException {
+ return getToscaModelCsarFile(assetType, uuid, "");
+ }
+
public static File getToscaModelCsarFile(AssetTypeEnum assetType, String uuid, String fileName) throws IOException {
+ File myFile;
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);
-
- String csarDir = FileHandling.getCreateDirByName("outputCsar");
- File myFile = new File(csarDir+ File.separator + "tmpCSAR_" + fileName + ".csar");
+
+ if(fileName.isEmpty()) {
+ myFile = new File("tmpCSAR");
+ } else {
+ String csarDir = FileHandling.getCreateDirByName("outputCsar");
+ myFile = new File(csarDir+ File.separator + "tmpCSAR_" + fileName + ".csar");
+ }
- httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
logger.debug("Send GET request to get Tosca model: {}", url);
@@ -127,19 +133,17 @@ public class AssetRestUtils extends BaseRestUtils {
}
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<String, String> headersMap = new HashMap<String,String>();
+ Map<String, String> 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");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
HttpRequest http = new HttpRequest();
@@ -158,16 +162,16 @@ public class AssetRestUtils extends BaseRestUtils {
public static RestResponse getComponentListByAssetType(boolean isBasicAuthentication, AssetTypeEnum assetType,
String... filterArrayString) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
if (isBasicAuthentication) {
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
}
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
HttpRequest http = new HttpRequest();
- String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(),
+ String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(),
assetType.getValue());
if (filterArrayString != null && filterArrayString.length > 0) {
url = buildUrlWithFilter(url, filterArrayString);
@@ -180,11 +184,11 @@ public class AssetRestUtils extends BaseRestUtils {
public static RestResponse getFilteredComponentList(AssetTypeEnum assetType, String query) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
HttpRequest http = new HttpRequest();
@@ -217,13 +221,13 @@ public class AssetRestUtils extends BaseRestUtils {
AssetTypeEnum assetType, String uuid) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
if (isBasicAuthentication) {
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
}
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
HttpRequest http = new HttpRequest();
String url = String.format(Urls.GET_ASSET_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
@@ -628,8 +632,5 @@ public class AssetRestUtils extends BaseRestUtils {
}
return null;
}
- private static String getShortUUID() {
- return UUID.randomUUID().toString().split("-")[0];
- }
}
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
index 2e27907fb5..65ab6c920a 100644
--- 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
@@ -61,11 +61,19 @@ public class AutomationUtils extends BaseRestUtils {
- public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData, String suiteName)
- throws FileNotFoundException, IOException {
+ public static void createVersionsInfoFile(String filepath, String onboardVersion, String osVersion, String envData, String suiteName) throws IOException {
+ File myFoo = new File(filepath);
+ FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
+ String versions = ("onboardVersion=\""+ 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, String suiteName, String reportStartTime) throws 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");
+ String versions = ("onboardVersion=\""+ onboardVersion+ "\"\n" + "osVersion=\"" + osVersion + "\"\n" + "env=\""+ envData + "\"\n" + "suiteName=\""+ suiteName+ "\"\n" + "reportStartTime=\""+ reportStartTime+ "\"\n");
byte[] myBytes = versions.getBytes();
fooStream.write(myBytes);
fooStream.close();
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
index 4ea404784a..4ec0353abd 100644
--- 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
@@ -45,10 +45,13 @@ public class BaseRestUtils extends BaseValidationUtils {
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 acceptMultipartHeader = "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 xEcompInstanceId = "a1bd39f6-d55e-45b2-9207-156216af5cb5";
+ public static final String cacheControlHeader = "no-cache";
public static final String RESOURCE_COMPONENT_TYPE = "resources";
public static final String PRODUCT_COMPONENT_TYPE = "products";
@@ -86,7 +89,7 @@ public class BaseRestUtils extends BaseValidationUtils {
}
protected static Map<String, String> prepareHeadersMap(String userId, String accept) {
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
if (contentTypeHeaderData != null) {
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
}
@@ -257,7 +260,7 @@ public class BaseRestUtils extends BaseValidationUtils {
String userCredentials = userName + ":" + password;
encodeBase64 = Base64.encodeBase64(userCredentials.getBytes());
String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64);
- Map<String, String> authorizationHeader = new HashMap<String, String>();
+ Map<String, String> 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
index 449b6beca5..b09ba10df1 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
@@ -67,7 +67,7 @@ public class CatalogRestUtils extends BaseRestUtils {
String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
BaseRestUtils.RESOURCE_COMPONENT_TYPE);
- Map<String, String> additionalHeaders = new HashMap<String, String>();
+ Map<String, String> additionalHeaders = new HashMap<>();
additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders);
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
index 1b550e4fff..64b576e3e2 100644
--- 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
@@ -43,7 +43,7 @@ import org.openecomp.sdc.ci.tests.utils.Utils;
import com.google.gson.Gson;
public class ComponentInstanceRestUtils extends BaseRestUtils {
- public static String acceptHeaderDate = "application/json";
+// public static String acceptHeaderDate = "application/json";
static Config config = Config.instance();
public static Gson gson = new Gson();
@@ -87,7 +87,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
@@ -207,7 +207,7 @@ public class ComponentInstanceRestUtils extends BaseRestUtils {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
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
index 0aadfdbaeb..5e35327305 100644
--- 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
@@ -20,12 +20,9 @@
package org.openecomp.sdc.ci.tests.utils.rest;
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.util.Map;
-
-import org.codehaus.jackson.map.DeserializationConfig;
-import org.codehaus.jackson.map.ObjectMapper;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.Urls;
@@ -34,7 +31,9 @@ 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 java.util.Map;
+
+import static org.testng.AssertJUnit.assertEquals;
public class ConsumerRestUtils extends BaseRestUtils {
@@ -123,9 +122,8 @@ public class ConsumerRestUtils extends BaseRestUtils {
String bodyToParse = restResponse.getResponse();
ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ConsumerDataDefinition component = mapper.readValue(bodyToParse, ConsumerDataDefinition.class);
return component;
} catch (Exception e) {
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
index 458aa4a91c..9fdab02bb1 100644
--- 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
@@ -44,8 +44,6 @@ 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";
@@ -58,9 +56,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse pushUser(EcompUser ecompUser) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
@@ -84,9 +82,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse editUser(String loginId, EcompUser ecompUser) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
@@ -110,9 +108,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse getUser(String loginId) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
@@ -130,9 +128,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse getAllUsers() throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
@@ -150,9 +148,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse getAllAvailableRoles() throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
@@ -174,9 +172,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse pushUserRoles(String loginId, List<EcompRole> roles) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
@@ -204,9 +202,9 @@ public class EcompUserRestUtils extends BaseRestUtils {
public static RestResponse getUserRoles(String loginId) throws IOException {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
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
index d79c8e002c..f55cdbd035 100644
--- 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
@@ -36,7 +36,6 @@ 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();
@@ -44,7 +43,7 @@ public class GroupRestUtils extends BaseRestUtils {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
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
index 0be438470d..40dc060993 100644
--- 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
@@ -48,7 +48,6 @@ 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;
@@ -61,7 +60,7 @@ 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.openecomp.sdc.common.http.client.api.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -351,7 +350,7 @@ public class ImportRestUtils extends BaseRestUtils {
}
}
- public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
+ public static HttpResponse<byte []> getCsar(String csarUid, User sdncModifierDetails) throws Exception {
Config config = Utils.getConfig();
String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
@@ -367,17 +366,11 @@ public class ImportRestUtils extends BaseRestUtils {
// System.out.println(url);
// System.out.println(userBodyJson);
- HttpRestClient httpRestClient = new HttpRestClient();
-
for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
}
- RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
- // RestResponse getCsar = http.httpSendGet(url, headersMap);
-
- return doGetAsByteArray;
-
+ return org.openecomp.sdc.common.http.client.api.HttpRequest.getAsByteArray(url, downloadCsarHeaders);
}
private static File getGroupTypeZipFile(String elementName) throws IOException {
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
index 39afff9022..9c0b7a89e0 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
@@ -111,10 +111,10 @@ public class LifecycleRestUtils extends BaseRestUtils {
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<String, String> additionalHeaders = new HashMap<String, String>();
+ Map<String, String> additionalHeaders = new HashMap<>();
additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
String jsonBody = "{\"userRemarks\": \"" + comment + "\"}";
@@ -361,7 +361,7 @@ public class LifecycleRestUtils extends BaseRestUtils {
}
private static Map<String, String> prepareHeadersMap(User sdncModifierDetails) {
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
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
index 33704a5128..d507c2cb23 100644
--- 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
@@ -20,32 +20,28 @@
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.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.Gson;
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.ComponentInstanceInput;
-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.be.model.*;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
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.HttpRequest;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyObject;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.testng.AssertJUnit.*;
import com.google.gson.Gson;
@@ -69,6 +65,14 @@ public class PropertyRestUtils extends BaseRestUtils {
return sendPut(url, body, user.getUserId(), acceptHeaderData);
}
+ public static RestResponse updateGroupProperty(Component component, String groupId, String body, User user)
+ throws Exception {
+ Config config = Config.instance();
+
+ String url = String.format(Urls.RESOURCE_GROUP_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), groupId);
+ 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,
@@ -337,4 +341,24 @@ public class PropertyRestUtils extends BaseRestUtils {
}
return declareProportiesResponse;
}
+
+ public static RestResponse updateInput(Component componentObject, PropertyObject componentInput, User sdncModifierDetails)
+ throws Exception {
+ Config config = Config.instance();
+ String url = String.format(Urls.UPDATE_INPUT, config.getCatalogBeHost(), config.getCatalogBePort(), componentObject.getUniqueId());
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(componentInput);
+ String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson);
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse declareProportiesResponse = http.httpSendPost(url, userBodyJson, headersMap);
+ if (declareProportiesResponse.getErrorCode() == STATUS_CODE_GET_SUCCESS) {
+
+ }
+ return declareProportiesResponse;
+ }
}
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
index 2f33273319..5f8eeca911 100644
--- 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
@@ -113,15 +113,12 @@ public class ResourceRestUtils extends BaseRestUtils {
Gson gson = new Gson();
String resourceImportBodyJson = gson.toJson(importReqDetails);
HttpRequest http = new HttpRequest();
- // System.out.println(url);
- // System.out.println(resourceImportBodyJson);
Map<String, String> headersMap = prepareHeadersMap(userId);
if (additionalHeaders != null) {
headersMap.putAll(additionalHeaders);
} else {
- headersMap.put(HttpHeaderEnum.Content_MD5.getValue(),
- ArtifactRestUtils.calculateMD5(resourceImportBodyJson));
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), ArtifactRestUtils.calculateMD5(resourceImportBodyJson));
}
RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap);
@@ -272,7 +269,7 @@ public class ResourceRestUtils extends BaseRestUtils {
Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
@@ -285,7 +282,7 @@ public class ResourceRestUtils extends BaseRestUtils {
Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
@@ -298,7 +295,7 @@ public class ResourceRestUtils extends BaseRestUtils {
Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
- headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
return sendGet(url, sdncModifierDetails.getUserId(), headersMap);
@@ -359,9 +356,9 @@ public class ResourceRestUtils extends BaseRestUtils {
HttpRequest http = new HttpRequest();
String url = String.format(Urls.GET_PROPERTY_SCOPES_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
return http.httpSendGet(url, headersMap);
@@ -374,10 +371,10 @@ public class ResourceRestUtils extends BaseRestUtils {
HttpRequest http = new HttpRequest();
String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), acceptJsonHeader);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
return http.httpSendGet(url, headersMap);
@@ -390,9 +387,9 @@ public class ResourceRestUtils extends BaseRestUtils {
HttpRequest http = new HttpRequest();
String url = String.format(Urls.GET_CONFIGURATION, config.getCatalogBeHost(), config.getCatalogBePort());
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), acceptJsonHeader);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
return http.httpSendGet(url, headersMap);
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
index d9b8ec3d4b..76d2ededfc 100644
--- 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
@@ -50,7 +50,7 @@ public class ResourceRestUtilsExternalAPI extends BaseRestUtils {
String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(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.X_ECOMP_INSTANCE_ID.getValue(), BaseRestUtils.xEcompInstanceId);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
HttpRequest http = new HttpRequest();
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
index 6f83ec9d52..d78a6c9026 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
@@ -20,22 +20,16 @@
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 com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+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 org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
-import org.codehaus.jackson.Version;
-import org.codehaus.jackson.map.DeserializationConfig;
-import org.codehaus.jackson.map.JsonDeserializer;
-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;
@@ -44,12 +38,13 @@ 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.GroupDefinition;
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.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
@@ -57,11 +52,16 @@ 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.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
+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.List;
+import java.util.Map;
public class ResponseParser {
@@ -104,16 +104,25 @@ public class ResponseParser {
public static String getValueFromJsonResponse(String response, String fieldName) {
try {
- JSONObject jsonResp = (JSONObject) JSONValue.parse(response);
- Object fieldValue = jsonResp.get(fieldName);
- return fieldValue.toString();
+// JSONObject jsonResp = (JSONObject) JSONValue.parse(response);
+ String[] split = fieldName.split(":");
+ String fieldValue = response;
+ for(int i=0; i<split.length; i++) {
+ fieldValue = parser(fieldValue, split[i]);
+ }
+ return fieldValue;
} catch (Exception e) {
return null;
}
}
+ private static String parser(String response, String field){
+ JSONObject fieldValue = (JSONObject) JSONValue.parse(response);
+ return fieldValue.get(field).toString();
+ }
+
public static String getUniqueIdFromResponse(RestResponse response) {
return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
}
@@ -152,7 +161,7 @@ public class ResponseParser {
JsonObject jObject = jElement.getAsJsonObject();
JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType);
Gson gson = new Gson();
- Map<String, Object> map = new HashMap<String, Object>();
+ Map<String, Object> map = new HashMap<>();
ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
@@ -169,19 +178,19 @@ public class ResponseParser {
}
- public static Resource convertResourceResponseToJavaObject(String response) {
-
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> deserializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, deserializer);
+ private static ObjectMapper newObjectMapper() {
+ SimpleModule module = new SimpleModule("customDeserializationModule");
+ module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
+ return new ObjectMapper()
+ .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+ .registerModule(module);
+ }
- mapper.registerModule(module);
+ public static Resource convertResourceResponseToJavaObject(String response) {
+ ObjectMapper mapper = newObjectMapper();
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);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
resource = mapper.readValue(response, Resource.class);
logger.debug(resource.toString());
@@ -199,15 +208,9 @@ public class ResponseParser {
public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule", new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
+ ObjectMapper mapper = newObjectMapper();
ComponentInstanceProperty propertyDefinition = null;
try {
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
logger.debug(propertyDefinition.toString());
} catch (IOException e) {
@@ -216,6 +219,19 @@ public class ResponseParser {
return propertyDefinition;
}
+ public static GroupDefinition convertPropertyResponseToObject(String response) {
+
+ ObjectMapper mapper = newObjectMapper();
+ GroupDefinition groupDefinition = null;
+ try {
+ groupDefinition = mapper.readValue(response, GroupDefinition.class);
+ logger.debug(groupDefinition.toString());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return groupDefinition;
+ }
+
public static String toJson(Object object) {
Gson gson = new Gson();
return gson.toJson(object);
@@ -225,7 +241,7 @@ public class ResponseParser {
ObjectMapper mapper = new ObjectMapper();
ArtifactDefinition artifactDefinition = null;
try {
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
artifactDefinition = mapper.readValue(response, ArtifactDefinition.class);
logger.debug(artifactDefinition.toString());
} catch (IOException e) {
@@ -257,18 +273,10 @@ public class ResponseParser {
public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
// Generic convert
- ObjectMapper mapper = new ObjectMapper();
+ ObjectMapper mapper = newObjectMapper();
T object = null;
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
- mapper.registerModule(module);
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
object = mapper.readValue(json, clazz);
- // System.out.println("Class: "+clazz.getSimpleName()+", json:
- // "+json);
} catch (IOException e) {
e.printStackTrace();
}
@@ -286,25 +294,11 @@ public class ResponseParser {
return artifactReqDetails;
}
- public static <T> void addDeserializer(SimpleModule module, Class<T> clazz,
- final JsonDeserializer<T> 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<PropertyConstraint> deserializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, deserializer);
-
- mapper.registerModule(module);
+ ObjectMapper mapper = newObjectMapper();
Service service = null;
try {
-// TODO Andrey L. uncomment line below in case to ignore on unknown properties, not recommended, added by Matvey
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
service = mapper.readValue(response, Service.class);
logger.debug(service.toString());
} catch (IOException e) {
@@ -316,18 +310,9 @@ public class ResponseParser {
public static Product convertProductResponseToJavaObject(String response) {
- ObjectMapper mapper = new ObjectMapper();
-
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
-
+ ObjectMapper mapper = newObjectMapper();
Product product = null;
try {
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
product = mapper.readValue(response, Product.class);
logger.debug(product.toString());
} catch (IOException e) {
@@ -339,16 +324,9 @@ public class ResponseParser {
public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
- ObjectMapper mapper = new ObjectMapper();
- final SimpleModule module = new SimpleModule("customerSerializationModule",
- new Version(1, 0, 0, "static version"));
- JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
- addDeserializer(module, PropertyConstraint.class, desrializer);
-
- mapper.registerModule(module);
+ ObjectMapper mapper = newObjectMapper();
ComponentInstance componentInstance = null;
try {
- mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
componentInstance = mapper.readValue(response, ComponentInstance.class);
logger.debug(componentInstance.toString());
} catch (IOException e) {
@@ -360,7 +338,7 @@ public class ResponseParser {
}
public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
- List<String> artifactTypesArrayFromApi = new ArrayList<String>();
+ List<String> artifactTypesArrayFromApi = new ArrayList<>();
org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
JSONArray jArr = responseObject.getJSONArray("artifactTypes");
@@ -392,7 +370,7 @@ public class ResponseParser {
}
public static List<Map<String, Object>> getAuditFromMessage(Map<String, Object> auditingMessage) {
- List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> auditList = new ArrayList<>();
auditList.add(auditingMessage);
return auditList;
}
@@ -425,8 +403,8 @@ public class ResponseParser {
}
public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException {
- JSONArray listFromJson = getListFromJson(res, "derivedList");
- List<String> lst = new ArrayList<String>();
+ JSONArray listFromJson = getListFromJson(res, "derivedFrom");
+ List<String> lst = new ArrayList<>();
for (int i = 0; i < listFromJson.length(); i++) {
lst.add(listFromJson.getString(i));
}
@@ -440,7 +418,7 @@ public class ResponseParser {
}
public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> list = new ArrayList<>();
JSONArray listFromJson = getListFromJson(res, field);
for (int i = 0; i < listFromJson.length(); i++) {
Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
@@ -472,7 +450,7 @@ public class ResponseParser {
// Map<String, ArrayList<Component>> map = new HashMap<String,
// ArrayList<Component>>();
- Map<String, List<Component>> map = new HashMap<String, List<Component>>();
+ Map<String, List<Component>> map = new HashMap<>();
JsonElement jElement = new JsonParser().parse(response);
JsonObject jObject = jElement.getAsJsonObject();
@@ -531,7 +509,7 @@ public class ResponseParser {
public static Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject(String response) throws ParseException {
- Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<Long, ServiceDistributionStatus>();
+ Map<Long, ServiceDistributionStatus> serviceDistributionStatusMap = new HashMap<>();
ServiceDistributionStatus serviceDistributionStatusObject = null;
JsonElement jElement = new JsonParser().parse(response);
@@ -551,7 +529,7 @@ public class ResponseParser {
public static Map<String, String> getPropertiesNameType(RestResponse restResponse)
throws JSONException {
- Map<String, String> propertiesMap = new HashMap<String, String>();
+ Map<String, String> 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());
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
index 9ba4a906c6..1d8aef6f04 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
@@ -45,9 +45,6 @@ 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();
@@ -68,8 +65,7 @@ public class ServiceRestUtils extends BaseRestUtils {
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);
+ String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
RestResponse sendDelete = sendDelete(url, userId);
return sendDelete;
@@ -79,8 +75,7 @@ public class ServiceRestUtils extends BaseRestUtils {
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);
+ String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
RestResponse sendDelete = sendDelete(url, userId);
deleteMarkedServices(userId);
return sendDelete;
@@ -177,12 +172,12 @@ public class ServiceRestUtils extends BaseRestUtils {
}
public static Map<String, String> prepareHeadersMap(User sdncModifierDetails, boolean isCached) {
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
if (isCached)
- headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), cacheControl);
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), BaseRestUtils.cacheControlHeader);
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
return headersMap;
}
@@ -202,7 +197,7 @@ public class ServiceRestUtils extends BaseRestUtils {
String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
serviceId);
String userBodyJson = gson.toJson(comment);
- return sendPost(url, userBodyJson, userId, acceptHeaderData);
+ return sendPost(url, userBodyJson, userId, BaseRestUtils.acceptHeaderData);
}
@@ -268,9 +263,9 @@ public class ServiceRestUtils extends BaseRestUtils {
String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
- Map<String, String> headersMap = new HashMap<String, String>();
- headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
- headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), BaseRestUtils.contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), BaseRestUtils.acceptHeaderData);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap);
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
index 881e9469dd..5031391fe4 100644
--- 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
@@ -171,7 +171,7 @@ public class UserRestUtils extends BaseRestUtils {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
@@ -189,7 +189,7 @@ public class UserRestUtils extends BaseRestUtils {
Config config = Utils.getConfig();
- Map<String, String> headersMap = new HashMap<String, String>();
+ Map<String, String> headersMap = new HashMap<>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
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
index a07300671f..61d340094d 100644
--- 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
@@ -20,17 +20,9 @@
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 com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
@@ -44,8 +36,14 @@ 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.JsonElement;
-import com.google.gson.JsonParser;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+import static org.testng.AssertJUnit.assertTrue;
public class ArtifactValidationUtils {
@@ -109,16 +107,14 @@ public class ArtifactValidationUtils {
counter);
}
- public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse)
- throws JsonParseException, JsonProcessingException, Exception {
+ public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse) throws 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;
+ return mapper.readValue(jsourceElement.toString(), ESArtifactData.class);
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
index 4cf712f2fc..5f5afb2126 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
@@ -48,7 +48,6 @@ 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;
@@ -66,7 +65,6 @@ 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;
@@ -129,41 +127,18 @@ public class AuditValidationUtils {
public static void validateAuditDownloadExternalAPI(ExpectedResourceAuditJavaObject resourceAuditJavaObject,
String action, String body, boolean checkAllFields) throws Exception {
- Map<String, Object> actualAuditRecords = new HashMap<String, Object>();
- // Andrey's comment
- // actualAuditRecords = parseAuditResourceByAction(action, body);
- actualAuditRecords = parseAuditResourceByAction(action, null);
-
- // List<Map<String, Object>> actualAuditRecords = new
- // ArrayList<Map<String, Object>>();
- // actualAuditRecords = parseAuditResourceByActionToList(action, body);
+ Map<String, Object> actualAuditRecords = parseAuditResourceByAction(action, null);
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());
+ 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());
}
- public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action,
- String body, boolean checkAllFields) throws Exception {
- Map<String, Object> actualAuditRecords = new HashMap<String, Object>();
- // Andrey's comment
- // actualAuditRecords = parseAuditResourceByAction(action, body);
- actualAuditRecords = parseAuditResourceByAction(action, null);
+ public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action, String body, boolean checkAllFields) throws Exception {
+ Map<String, Object> actualAuditRecords = parseAuditResourceByAction(action, null);
if ((resourceAuditJavaObject.getModifierName() != null) && (resourceAuditJavaObject.getModifierUid() != null)) {
resourceAuditJavaObject.setModifierUid(getModifierString(resourceAuditJavaObject.getModifierName(),
@@ -171,77 +146,45 @@ public class AuditValidationUtils {
}
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);
+ 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(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
+ 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<AuditingFieldsKeysEnum, String> body) throws Exception {
+ public static void validateExternalAudit(ExpectedExternalAudit externalAuditObject, String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> actualAuditRecord = new HashMap<String, Object>();
- actualAuditRecord = parseAuditResourceByAction(action, body);
+ Map<String, Object> actualAuditRecord = parseAuditResourceByAction(action, body);
validateField(actualAuditRecord, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
- validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
- externalAuditObject.getCONSUMER_ID());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(), externalAuditObject.getCONSUMER_ID());
// TODO
- validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
- externalAuditObject.getRESOURCE_URL());
+ 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());
+ 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());
+ 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());
+// 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());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(), externalAuditObject.getARTIFACT_DATA());
}
@@ -288,26 +231,19 @@ public class AuditValidationUtils {
}
// //Benny
- public static void validateEcompConsumerAudit(ExpectedEcomConsumerAudit ecompConsumerAuditJavaObject, String action)
- throws Exception {
+ public static void validateEcompConsumerAudit(ExpectedEcomConsumerAudit ecompConsumerAuditJavaObject, String action) throws Exception {
String fixedAction = BaseRestUtils.encodeUrlForDownload(action);
- Map<String, Object> map2 = new HashMap<String, Object>();
- 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());
+ Map<String, Object> 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 {
+ public static void ecompConsumerAuditSuccess(String action, ConsumerDataDefinition consumerDataDefinition, User user, int status) throws Exception {
ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
expectedEcomConsumerAuditJavaObject.setAction(action);
expectedEcomConsumerAuditJavaObject.setEcomUser(
@@ -384,34 +320,24 @@ public class AuditValidationUtils {
public static void validateAuditGetListOfUsersByRoles(ExpectedGetUserListAudit GetListOfUsersAuditJavaObject,
String action) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> 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());
+ 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 {
+ public static void validateAuditImport(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> map2 = parseAuditResourceByAction(action, null);
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+ 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.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());
@@ -420,28 +346,20 @@ public class AuditValidationUtils {
}
- public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
+ public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> map2 = parseAuditResourceByAction(action, null);
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+ 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.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.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());
@@ -450,46 +368,34 @@ public class AuditValidationUtils {
}
// Benny
- public static void validateAudit_Distribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject,
- String action) throws Exception {
+ public static void validateAudit_Distribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception {
List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
Map<String, Object> 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.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.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 {
+ public void validateAuditNotification(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> map2 = parseAuditResourceByAction(action, null);
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+ 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.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());
@@ -498,39 +404,31 @@ public class AuditValidationUtils {
}
- public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action)
- throws Exception {
+ public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> 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());
+ 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<AuditingFieldsKeysEnum, String> body)
throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, body);
+ Map<String, Object> 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());
+ 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<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, body);
+ Map<String, Object> map2 = parseAuditResourceByAction(action, body);
validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(), expectedExternalAudit.getResourceName());
@@ -549,8 +447,7 @@ public class AuditValidationUtils {
}
public static void validateAuditExternalChangeAssetLifeCycle(ExpectedResourceAuditJavaObject expectedExternalAudit, String action, Map<AuditingFieldsKeysEnum, String> body) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, body);
+ Map<String, Object> map2 = parseAuditResourceByAction(action, body);
validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedExternalAudit.getDesc());
@@ -566,28 +463,20 @@ public class AuditValidationUtils {
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<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> map2 = parseAuditResourceByAction(action, null);
- resourceAuditJavaObject.setModifierUid(
- getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+ 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.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());
@@ -598,25 +487,19 @@ public class AuditValidationUtils {
public static void validateAuditProduct(ExpectedProductAudit productExpectedAudit, String action,
AuditJsonKeysEnum... additionalFields) throws Exception {
- Map<String, Object> map2 = new HashMap<String, Object>();
- map2 = parseAuditResourceByAction(action, null);
+ Map<String, Object> 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.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());
+ validateField(map2, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(), productExpectedAudit.getSERVICE_INSTANCE_ID());
if (additionalFields != null) {
List<AuditJsonKeysEnum> fieldsList = Arrays.asList(additionalFields);
if (fieldsList.contains(AuditJsonKeysEnum.COMMENT)) {
@@ -837,76 +720,6 @@ public class AuditValidationUtils {
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<AuditingFieldsKeysEnum, String> myFields= new
- // HashMap<AuditingFieldsKeysEnum, String>();
- //// myFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION , pattern);
- //
- // List<Pair<AuditingFieldsKeysEnum, String>> myFields = new
- // ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
- // Pair<AuditingFieldsKeysEnum, String> myPair = new
- // Pair<AuditingFieldsKeysEnum, String>(AuditingFieldsKeysEnum.AUDIT_ACTION
- // , pattern);
- // myFields.add(0, myPair);
- //
- //
- // List<Row> 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<String> metaDataList = new
- // ArrayList<String>(Arrays.asList(metaData.split(", ")));
- //
- //
- //
- // Map<String, String> resultsMap = new HashMap<String, String>();
- //
- //
- // 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<String> dataArray = new
- // ArrayList<String>(Arrays.asList(dataString.split(", ")));
- ////
- ////
- //// Map<String, String> resultsMap = new HashMap<String, String>();
- //// for (int i=0 ; i<metaDataList.size() ; i++) {
- //// resultsMap.put(metaDataList.get(i), dataArray.get(i));
- //// }
- ////
- //// return restResponse.getResponse();
- // return resultsMap;
- // }
-
public static void categoryAuditSuccess(String action, CategoryDefinition categoryDefinition, User user, int status,
String resourceType) throws Exception {
categoryAuditSuccessInternal(action, categoryDefinition, null, null, user, status, resourceType);
@@ -955,8 +768,7 @@ public class AuditValidationUtils {
expectedCatrgoryAuditJavaObject.setAction(action);
expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName());
- String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
- : Constants.EMPTY_STRING);
+ String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() : Constants.EMPTY_STRING);
expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
@@ -989,8 +801,7 @@ public class AuditValidationUtils {
///////////////////////////
///// BENNNNNNNNY
public enum UserAuditJsonKeysEnum {
- ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER(
- "USER_AFTER"), USER_BEFORE("USER_BEFORE");
+ ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER("USER_AFTER"), USER_BEFORE("USER_BEFORE");
private String auditJsonKeyName;
private UserAuditJsonKeysEnum(String auditJsonKeyName) {
@@ -1002,20 +813,15 @@ public class AuditValidationUtils {
}
}
- public static void validateAddUserAudit(ExpectedUserCRUDAudit expectedAddUserAuditJavaObject, String action)
- throws Exception {
+ public static void validateAddUserAudit(ExpectedUserCRUDAudit expectedAddUserAuditJavaObject, String action) throws Exception {
List<Map<String, Object>> actionToList = getAuditListByAction(expectedAddUserAuditJavaObject.getAction(), 1);
Map<String, Object> 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.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());
}
@@ -1029,8 +835,7 @@ public class AuditValidationUtils {
expectedCatrgoryAuditJavaObject.setAction(action);
expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName());
- String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
- : Constants.EMPTY_STRING);
+ String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName() : Constants.EMPTY_STRING);
expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
@@ -1049,14 +854,10 @@ public class AuditValidationUtils {
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());
+ 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());
}
@@ -1066,20 +867,13 @@ public class AuditValidationUtils {
List<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
Map<String, Object> 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());
+ 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)
@@ -1122,60 +916,6 @@ public class AuditValidationUtils {
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<String>()));
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedComponentNotFoundAuditObject(String Action,
- String resourceUid, ComponentType resourceType, String artifactUid, User user,
- ArrayList<String> 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)
@@ -1205,144 +945,27 @@ public class AuditValidationUtils {
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<String>());
-
- 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<String>());
-
- expectedAudit.setDesc(desc);
- return expectedAudit;
- }
-
- public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(String Action, String resourceName,
- ComponentType resourceType, String artifactUid, User user, String currVersion, String currState,
- ArrayList<String> 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<String> 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<String, String> actionMap = new HashMap<String, String>();
+ Map<String, String> actionMap = new HashMap<>();
actionMap.put("ACTION", action);
JSONObject actionJsonObject = new JSONObject(actionMap);
- Map<String, String> uuidMap = new HashMap<String, String>();
+ Map<String, String> uuidMap = new HashMap<>();
uuidMap.put("SERVICE_INSTANCE_ID", uuid);
JSONObject uuidJsonObject = new JSONObject(uuidMap);
- List<JSONObject> filters = new ArrayList<JSONObject>(Arrays.asList(actionJsonObject, uuidJsonObject));
+ List<JSONObject> filters = new ArrayList<>(Arrays.asList(actionJsonObject, uuidJsonObject));
JSONObject body = buildElasticQueryBody(filters);
return body;
}
- public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
- throws Exception {
+ public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action) throws Exception {
List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
Map<String, Object> 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.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());
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
index 2d50ebffcc..91effad4c4 100644
--- 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
@@ -20,12 +20,9 @@
package org.openecomp.sdc.externalApis;
-import static java.util.Arrays.asList;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.aventstack.extentreports.Status;
+import com.google.gson.Gson;
+import fj.data.Either;
import org.json.simple.parser.JSONParser;
import org.junit.Rule;
import org.junit.rules.TestName;
@@ -33,41 +30,16 @@ 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.be.model.*;
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.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.*;
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.rest.*;
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;
@@ -75,11 +47,6 @@ 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());
@@ -153,12 +120,12 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> 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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
restResponse = LifecycleRestUtils.checkOutResource(parsedCreatedResponse.getUuid(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_CREATED, "Fail to check out.");
@@ -166,7 +133,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// 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());
@@ -174,7 +141,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrVersion("0.2");
expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString());
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@@ -193,12 +160,12 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> 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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
restResponse = LifecycleRestUtils.checkOutService(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_CREATED, "Fail to check out.");
@@ -206,7 +173,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// 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());
@@ -214,7 +181,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrVersion("0.2");
expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString());
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -274,7 +241,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
}
Assert.assertEquals(restResponse.getErrorCode(), (Integer)STATUS_CODE_NOT_FOUND, "Asset found.");
- // auditing verification
+ /* // auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, String.format("/sdc/v1/catalog/%s/%s/lifecycleState/%s", assetTypeEnum.getValue().toLowerCase(), assetUUID, lifeCycleStatesEnum.getState()));
@@ -283,7 +250,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
List<String> variables = asList(assetUUID);
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -304,14 +271,12 @@ public class AssetLifeCycle extends ComponentBaseTest {
// US849997 - Story [BE]: External API for asset lifecycle - checkout
@Test(dataProvider="invalidUserCheckinForCheckedOutService")
public void invalidUserCheckinForCheckedOutService(User defaultUser) throws Exception {
- Component resourceDetails = null;
- Either<Service, RestResponse> createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
- resourceDetails = createdComponent.left().value();
-
+ Component resourceDetails = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -321,7 +286,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckinForCheckedInService")
@@ -348,7 +313,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
RestResponse restResponse = LifecycleRestUtils.checkInService(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -359,7 +324,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckoutForCheckedOutService")
@@ -378,14 +343,12 @@ public class AssetLifeCycle extends ComponentBaseTest {
// US849997 - Story [BE]: External API for asset lifecycle - checkout
@Test(dataProvider="invalidUserCheckoutForCheckedOutService")
public void invalidUserCheckoutForCheckedOutService(User defaultUser) throws Exception {
- Component resourceDetails = null;
- Either<Service, RestResponse> createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
- resourceDetails = createdComponent.left().value();
-
+
+ Component resourceDetails = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
RestResponse restResponse = LifecycleRestUtils.checkOutService(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation.");
- // auditing verification
+ /* // auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -395,7 +358,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckoutForCheckedInService")
@@ -414,15 +377,13 @@ public class AssetLifeCycle extends ComponentBaseTest {
// US849997 - Story [BE]: External API for asset lifecycle - checkout
@Test(dataProvider="invalidUserCheckoutForCheckedInService")
public void invalidUserCheckoutForCheckedInService(User defaultUser) throws Exception {
- Component resourceDetails = null;
- Either<Service, RestResponse> createdComponent = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
- resourceDetails = createdComponent.left().value();
+ Component resourceDetails = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).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
+ /* // auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -433,7 +394,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckinForCheckedOutResource")
@@ -452,14 +413,12 @@ public class AssetLifeCycle extends ComponentBaseTest {
// US849997 - Story [BE]: External API for asset lifecycle - checkout
@Test(dataProvider="invalidUserCheckinForCheckedOutResource")
public void invalidUserCheckinForCheckedOutResource(User defaultUser) throws Exception {
- Component resourceDetails = null;
- Either<Resource, RestResponse> createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
- resourceDetails = createdComponent.left().value();
-
+
+ Component resourceDetails = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true).left().value();
RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -469,7 +428,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckinForCheckedInResource")
@@ -496,7 +455,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
RestResponse restResponse = LifecycleRestUtils.checkInResource(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -507,7 +466,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckoutForCheckedOutResource")
@@ -526,14 +485,12 @@ public class AssetLifeCycle extends ComponentBaseTest {
// US849997 - Story [BE]: External API for asset lifecycle - checkout
@Test(dataProvider="invalidUserCheckoutForCheckedOutResource")
public void invalidUserCheckoutForCheckedOutResource(User defaultUser) throws Exception {
- Component resourceDetails = null;
- Either<Resource, RestResponse> createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
- resourceDetails = createdComponent.left().value();
-
+
+ Component resourceDetails = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true).left().value();
RestResponse restResponse = LifecycleRestUtils.checkOutResource(resourceDetails.getUUID(), defaultUser);
Assert.assertEquals(restResponse.getErrorCode(), (Integer)RESTRICTED_OPERATION, "Expected for restricted operation.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -543,7 +500,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@DataProvider(name="invalidUserCheckoutForCheckedInResource")
@@ -562,15 +519,14 @@ public class AssetLifeCycle extends ComponentBaseTest {
// US849997 - Story [BE]: External API for asset lifecycle - checkout
@Test(dataProvider="invalidUserCheckoutForCheckedInResource")
public void invalidUserCheckoutForCheckedInResource(User defaultUser) throws Exception {
- Component resourceDetails = null;
- Either<Resource, RestResponse> createdComponent = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
- resourceDetails = createdComponent.left().value();
+
+ Component resourceDetails = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true).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
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -581,7 +537,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList("");
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -653,7 +609,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
Assert.assertEquals(restResponse.getErrorCode(), (Integer)errorCode, "Expected that response code will be equal.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -680,7 +636,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
}
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@@ -756,7 +712,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
Assert.assertEquals(restResponse.getErrorCode(), (Integer)errorCode, "Expected that response code will be equal.");
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -783,7 +739,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
}
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@@ -803,7 +759,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
// Certification request
restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- // Auditing verification
+ /*// Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -811,19 +767,19 @@ public class AssetLifeCycle extends ComponentBaseTest {
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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
// Start testing
restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER));
- // Auditing verification
+ /* // 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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
// US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing
@@ -836,7 +792,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
// Certification request
restResponse = LifecycleRestUtils.certificationRequestService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- // Auditing verification
+ /*// Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -844,19 +800,19 @@ public class AssetLifeCycle extends ComponentBaseTest {
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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
// Start testing
restResponse = LifecycleRestUtils.startTestingService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER));
- // Auditing verification
+ /* // 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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
// US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing
@@ -869,7 +825,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
// Certification request
restResponse = LifecycleRestUtils.certificationRequestResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- // Auditing verification
+ /*// Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -883,7 +839,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
List<String> variables = asList(LifeCycleStatesEnum.CERTIFICATIONREQUEST.getState());
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
// US824692 - Story [BE]: External API for asset lifecycle - submit for test / start testing
@@ -896,7 +852,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
// Certification request
restResponse = LifecycleRestUtils.startTestingResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER));
- // Auditing verification
+ /*// Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -910,7 +866,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
List<String> variables = asList(LifeCycleStatesEnum.STARTCERTIFICATION.getState());
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@@ -938,7 +894,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
// Certify
restResponse = LifecycleRestUtils.certifyResource(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER));
- // Auditing verification
+ /*// Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -947,7 +903,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.toString());
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString());
expectedResourceAuditJavaObject.setCurrVersion("1.0");
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@@ -967,7 +923,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
// Certify
restResponse = LifecycleRestUtils.certifyService(resourceDetails.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER));
- // Auditing verification
+ /*// Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -976,7 +932,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.toString());
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString());
expectedResourceAuditJavaObject.setCurrVersion("1.0");
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
}
@@ -1017,7 +973,9 @@ public class AssetLifeCycle extends ComponentBaseTest {
ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "OTHER", true, false);
RestResponse uploadArtifactRestResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(initComponentVersion, defaultUser, artifactReqDetails);
BaseRestUtils.checkSuccess(uploadArtifactRestResponse);
- ArtifactDefinition responseArtifact = ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse());
+
+ ArtifactDefinition responseArtifact = ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactRestResponse.getResponse());
+// ArtifactDefinition responseArtifact = ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse());
initComponentVersion = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, parsedCreatedResponse.getName(), parsedCreatedResponse.getVersion());
// 5. Update artifact via external API.
@@ -1033,13 +991,13 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /* // Auditing verification
AuditingActionEnum action = AuditingActionEnum.CHANGE_LIFECYCLE_BY_API;
Map <AuditingFieldsKeysEnum, String> 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);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
// 7. Then checkout the VFCMT via external API.
RestResponse checkOutRestResponse = LifecycleRestUtils.checkOutResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
@@ -1049,7 +1007,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// 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()));
@@ -1057,7 +1015,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString());
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
expectedResourceAuditJavaObject.setCurrVersion("0.2");
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ 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())));
@@ -1078,7 +1036,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// 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()));
@@ -1087,8 +1045,8 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.toString());
expectedResourceAuditJavaObject.setCurrVersion("0.2");
expectedResourceAuditJavaObject.setPrevVersion("0.2");
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
-
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
+
// 11. Certify via external API.
RestResponse certifyRestResponse = LifecycleRestUtils.certifyResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
BaseRestUtils.checkCreateResponse(certifyRestResponse);
@@ -1097,7 +1055,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// 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()));
@@ -1106,7 +1064,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString());
expectedResourceAuditJavaObject.setCurrVersion("1.0");
expectedResourceAuditJavaObject.setPrevVersion("0.2");
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);*/
// 12. Check out via external API.
checkOutRestResponse = LifecycleRestUtils.checkOutResource(initComponentVersion.getUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
@@ -1116,7 +1074,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
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
+ /*// 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()));
@@ -1125,7 +1083,7 @@ public class AssetLifeCycle extends ComponentBaseTest {
expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
expectedResourceAuditJavaObject.setCurrVersion("1.1");
expectedResourceAuditJavaObject.setPrevVersion("1.0");
- AuditValidationUtils.validateAuditExternalChangeAssetLifeCycle(expectedResourceAuditJavaObject, action.getName(), body);
+ 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
index 26d1c18907..318316e5ad 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java
@@ -20,75 +20,27 @@
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 com.aventstack.extentreports.Status;
+import fj.data.Either;
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.be.model.*;
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.enums.*;
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.validation.AuditValidationUtils;
-import org.openecomp.sdc.ci.tests.utils.validation.DistributionValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
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.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -97,12 +49,11 @@ 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 java.io.IOException;
+import java.util.List;
+import java.util.Map;
-import fj.data.Either;
+import static java.util.Arrays.asList;
public class CRUDExternalAPI extends ComponentBaseTest {
@@ -111,11 +62,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
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;
@@ -132,7 +78,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnVfcVlCpViaExternalAPI" , parallel=true)
public static Object[][] dataProviderUploadArtifactOnVfcVlCpViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
@@ -317,7 +262,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
- @DataProvider(name="uploadArtifactOnServiceViaExternalAPIIncludingDistribution", parallel=true)
+/* @DataProvider(name="uploadArtifactOnServiceViaExternalAPIIncludingDistribution", parallel=true)
public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPIIncludingDistribution() {
return new Object[][] {
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
@@ -339,7 +284,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> 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
@@ -366,7 +311,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
numberOfArtifact = component.getDeploymentArtifacts().size();
}
- ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
+ ArtifactDefinition responseArtifact = ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
// Get list of deployment artifact + download them via external API
Map<String, ArtifactDefinition> deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifacts will be increase by one.");
@@ -401,7 +346,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
- // Check auditing for upload operation
+ /*// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
@@ -413,7 +358,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);*/
return restResponse;
}
@@ -455,7 +400,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
- // Check auditing for upload operation
+ /*// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
@@ -465,7 +410,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);*/
return restResponse;
}
@@ -538,7 +483,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
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.");
}
@@ -645,8 +589,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
-
-
+
+
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
@@ -655,7 +599,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
-
+
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
@@ -664,8 +608,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
-
-
+
+
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
@@ -674,7 +618,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
-
+
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
@@ -683,7 +627,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
-
+
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
@@ -692,7 +636,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
-
+
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
@@ -701,7 +645,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
-
+
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
@@ -710,7 +654,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
-
+
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
@@ -1018,7 +962,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
- ArtifactDefinition artifactDefinition = getArtifactDataFromJson(restResponse.getResponse());
+ ArtifactDefinition artifactDefinition = ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_EXIST.name());
List<String> variables = asList(artifactDefinition.getArtifactDisplayName());
@@ -1043,7 +987,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Integer responseCode = restResponse.getErrorCode();
Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
- // Check auditing for upload operation
+ /*// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
@@ -1076,7 +1020,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);*/
return restResponse;
@@ -1103,7 +1047,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
// List<String> variables = asList("artifact name", "255");
- ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
+ /*ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
@@ -1125,7 +1069,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
} else {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);*/
return restResponse;
@@ -1520,7 +1464,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
- @DataProvider(name="updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI", parallel=true)
+ @DataProvider(name="updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI() {
return new Object[][] {
{ResourceTypeEnum.VFC},
@@ -1528,14 +1472,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{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 {
-
- if(true){
- throw new SkipException("Open bug 321612");
- }
getExtendTest().log(Status.INFO, String.format("resourceTypeEnum: %s", resourceTypeEnum));
Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, resourceTypeEnum);
@@ -1546,7 +1486,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value();
component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion());
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.OK.name());
Map<String, ArtifactDefinition> deploymentArtifacts;
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE);
String artifactUUID = null;
@@ -1704,7 +1644,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
- @DataProvider(name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
+ @DataProvider(name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() {
return new Object[][] {
{ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
@@ -1757,7 +1697,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@Test(dataProvider="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
public void updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset(ComponentTypeEnum componentTypeEnum, UserRoleEnum userRoleEnum, LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
if(true){
- throw new SkipException("Open bug 321612");
+ throw new SkipException("Open bug 321612");
}
getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, userRoleEnum: %s, lifeCycleStatesEnum: %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType));
Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null);
@@ -1843,7 +1783,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null);
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name());
List<String> variables = asList(component.getName(), component.getComponentType().toString().toLowerCase(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getFirstName(),
- ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getLastName(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId());
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getLastName(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId());
updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, LifeCycleStatesEnum.STARTCERTIFICATION, artifactType, errorInfo, variables, UserRoleEnum.DESIGNER);
}
@@ -2166,15 +2106,18 @@ public class CRUDExternalAPI extends ComponentBaseTest {
String artifactName = artifactReqDetails.getArtifactLabel();
String artifactUUID = deploymentArtifacts.get(artifactName).getArtifactUUID();
String artifactVersionBeforeUpdate = deploymentArtifacts.get(artifactName).getArtifactVersion();
- int numberOfArtifact = deploymentArtifacts.size();
-
+ int numberOfArtifact = deploymentArtifacts.size();
+
+ ArtifactReqDetails updateArtifactReqDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.SNMP_POLL.name(), ArtifactTypeEnum.SNMP_POLL.name(), true, true);
+ updateArtifactReqDetails.setPayload("dGVzdA==");
+
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
+ component.getComponentInstances().get(0), updateArtifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- null, artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
+ null, updateArtifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
}
if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
@@ -2190,9 +2133,15 @@ public class CRUDExternalAPI extends ComponentBaseTest {
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.");
+ if (errorInfo.getCode().equals(200)) {
+ Assert.assertNotEquals(String.valueOf((Integer.parseInt(artifactVersionBeforeUpdate))), deploymentArtifacts.get(artifactName).getArtifactVersion(), "Artifact version should be changed.");
+ Assert.assertNotEquals(artifactUUID, deploymentArtifacts.get(artifactName).getArtifactUUID(), "Artifact UUID should be changed.");
+ }else{
+ Assert.assertEquals(String.valueOf((Integer.parseInt(artifactVersionBeforeUpdate))), deploymentArtifacts.get(artifactName).getArtifactVersion(), "Artifact version should not be changed.");
+ Assert.assertEquals(artifactUUID, deploymentArtifacts.get(artifactName).getArtifactUUID(), "Artifact UUID should not be changed.");
+ }
+
return component;
}
@@ -2212,7 +2161,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
- //TODO
+ /* //TODO
// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
@@ -2255,7 +2204,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);*/
return restResponse;
}
@@ -2349,7 +2298,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
restResponse = updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID, 200);
}
- ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
+ ArtifactDefinition responseArtifact = ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
component = getNewerVersionOfComponent(component, chosenLifeCycleState);
// Get list of deployment artifact + download them via external API
@@ -2379,7 +2328,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
- // Check auditing for upload operation
+ /* // Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API;
@@ -2392,7 +2341,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);*/
return restResponse;
}
@@ -2407,7 +2356,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
- // Check auditing for upload operation
+ /* // Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API;
@@ -2418,7 +2367,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);*/
return restResponse;
}
@@ -2973,10 +2922,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Verify that it cannot delete VFC/VL/CP artifact on VFCi/VLi/CPi - Failure flow
@Test(dataProvider="deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI")
public void deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI(ResourceTypeEnum resourceTypeEnum) throws Exception {
- if(true){
- throw new SkipException("Open bug 321550");
- }
-
+
getExtendTest().log(Status.INFO, String.format("resourceTypeEnum: %s", resourceTypeEnum));
Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, resourceTypeEnum);
@@ -2987,7 +2933,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value();
component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion());
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.OK.name());
Map<String, ArtifactDefinition> deploymentArtifacts;
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE);
String artifactUUID = null;
@@ -3017,7 +2963,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Integer responseCode = restResponse.getErrorCode();
Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
- // Check auditing for upload operation
+ /*// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
@@ -3062,7 +3008,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// 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);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);*/
return restResponse;
@@ -3139,7 +3085,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
- // Check auditing for upload operation
+ /*// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
@@ -3152,7 +3098,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);*/
component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
return restResponse;
}
@@ -3167,7 +3113,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
- // Check auditing for upload operation
+ /*// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
@@ -3178,7 +3124,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
- AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);*/
component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
return restResponse;
}
@@ -3259,159 +3205,5 @@ public class CRUDExternalAPI extends ComponentBaseTest {
return resourceDetails;
}
-
-
-
-
- protected String createUploadArtifactBodyJson() {
- Map<String, Object> jsonBody = new HashMap<String, Object>();
- 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.calculateMD5Base64EncodedByString(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<String, Object> json = new HashMap<String, Object>();
- 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
index 07cb7d9e02..9e82a818a1 100644
--- 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
@@ -20,28 +20,10 @@
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 com.aventstack.extentreports.Status;
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.Resource;
@@ -50,12 +32,10 @@ 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;
@@ -64,35 +44,35 @@ import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;
-import com.aventstack.extentreports.Status;
-
-
-
-
-
-
-
+import java.io.File;
+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.*;
+import java.util.stream.Collectors;
+import static org.testng.AssertJUnit.assertTrue;
+import static org.testng.AssertJUnit.assertTrue;
public class DeploymentValiditaion extends ComponentBaseTest{
-
-
-
@Rule
public static TestName name = new TestName();
-
+// These tests should run in executable jar only on deployed environment
public DeploymentValiditaion() {
super(name, DeploymentValiditaion.class.getName());
}
-
+
protected final static String categoryFilterKey = "category";
protected final static String subCategoryFilterKey = "subCategory";
protected String attVersionStr ;
-
-
+ protected String pathPrefix;
+
+
public static List<File> listf(String directoryName) {
File directory = new File(directoryName);
- List<File> resultList = new ArrayList<File>();
+ List<File> resultList = new ArrayList<>();
// get all the files from a directory
File[] fList = directory.listFiles();
@@ -106,40 +86,35 @@ public class DeploymentValiditaion extends ComponentBaseTest{
}
//System.out.println(fList);
return resultList;
- }
+ }
@BeforeTest
public void beforeTest() throws Exception{
RestResponse attVersion = CatalogRestUtils.getOsVersion();
attVersionStr = ResponseParser.getVersionFromResponse(attVersion);
+ pathPrefix = File.separator+"opt"+File.separator+"app"+File.separator+"asdc_kits"+File.separator+"catalog-be-"+attVersionStr+File.separator+"import"+File.separator+"tosca"+File.separator;
}
-
-
- @Test
+
+ /*@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<File> yamlList1 = getYamlFilesList(path);
+
+
+ String path = pathPrefix+"normative-types";
+ String path2 = pathPrefix+"heat-types";
+
+ List<File> yamlList1 = getYamlFilesList(path);
List<String> nodeNamesFromYamlList1 = getNodeNamesFromYamlList(yamlList1);
- List<File> yamlList2 = getYamlFilesList(path2);
+ List<File> yamlList2 = getYamlFilesList(path2);
List<String> nodeNamesFromYamlList2 = getNodeNamesFromYamlList(yamlList2);
-
-
- List<String> expectedList = new ArrayList<String>();
+
+
+ List<String> 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<String, String> resourceAssetList = AssetRestUtils.getResourceAssetMap(assetResponse);
@@ -149,7 +124,7 @@ public class DeploymentValiditaion extends ComponentBaseTest{
resourceToscaNamesList.forEach(System.out::println);
getExtendTest().log(Status.INFO, "list of normatives from APIs:");
getExtendTest().log(Status.INFO, resourceToscaNamesList.toString());
-
+
boolean good = true;
List<String> missingNormatives = new ArrayList<>();
@@ -157,23 +132,21 @@ public class DeploymentValiditaion extends ComponentBaseTest{
if (!resourceToscaNamesList.contains(expectedList.get(i))) {
good = false;
missingNormatives.add(expectedList.get(i));
-
-
}
}
-
+
System.out.println("<<<<<<<<<MISSING NORMATIVES>>>>>>");
missingNormatives.forEach(System.out::println);
getExtendTest().log(Status.INFO, "MISSING NORMATIVES:");
getExtendTest().log(Status.INFO, missingNormatives.toString());
-
+
assertTrue("missing normatives ", good);
-
- }
+
+ }*/
public List<String> getNodeNamesFromYamlList(List<File> yamlList) throws IOException {
- List<String> nodeNameList = new ArrayList<String>();
+ List<String> nodeNameList = new ArrayList<>();
for (File file : yamlList) {
String content = new String(Files.readAllBytes(Paths.get(file.getPath())), StandardCharsets.UTF_8);
@@ -190,7 +163,7 @@ public class DeploymentValiditaion extends ComponentBaseTest{
public List<File> getYamlFilesList(String path) throws IOException {
- List<File> yamlList = new ArrayList<File>();
+ List<File> yamlList = new ArrayList<>();
File dir = new File(path);
String[] extensions = new String[] { "yml" };
System.out.println("Getting all .yml files in " + dir.getCanonicalPath()
@@ -202,22 +175,13 @@ public class DeploymentValiditaion extends ComponentBaseTest{
}
return yamlList;
}
-
-
-
-
-
@Test (enabled=false)
public void testYaml() throws IOException{
-
+
System.out.println("");
-
- File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
-
-
- //read file
+ File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
Map<String, byte[]> readZip = null;
Path path = Paths.get("C:\\Users\\ys9693\\Documents\\csar\\attributesWithProporties\\attributesWithProporties.csar");
@@ -229,117 +193,89 @@ public class DeploymentValiditaion extends ComponentBaseTest{
byte[] artifactsBs = readZip.get("Definitions/VF_RI2_G6.yaml");
String str = new String(artifactsBs, StandardCharsets.UTF_8);
-
-
-
Yaml yaml = new Yaml();
Map<String, Object> load = (Map<String, Object>) yaml.load(str);
Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
-
+
Set<String> 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 path = pathPrefix+"data-types"+File.separator+"dataTypes.yml";
String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
-
-
+
Yaml yaml = new Yaml();
Map<String, Object> load = (Map<String, Object>) yaml.load(content);
- List<String> listOfDataTypes = new ArrayList<String>();
+ List<String> 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 path = pathPrefix+"categories"+File.separator+"categoryTypes.yml";
String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
-
- List<String> serviceCategories = new ArrayList<String>();
- List<String> resourceCategories = new ArrayList<String>();
-
+
+ List<String> serviceCategories = new ArrayList<>();
+ List<String> resourceCategories = new ArrayList<>();
+
Yaml yaml = new Yaml();
Map<String, Object> load = (Map<String, Object>) yaml.load(content);
Map<String, Map> services = (Map<String, Map>) load.get("services");
Map<String, Map> resources = (Map<String, Map>) load.get("resources");
-
- Map<String, List<String>> resourcesListFromFile = new HashMap<String, List<String>>() ;
-
+
+ Map<String, List<String>> resourcesListFromFile = new HashMap<>() ;
+
//retrieve subcategories
for ( String resourceCategoryName : resources.keySet()) {
Map<String, Map> subcategory = (Map) resources.get(resourceCategoryName).get("subcategories");
-
+
resourceCategories = new ArrayList<String>();
- for (String subcategoryName : subcategory.keySet()) {
+ 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);
- }
-
+ 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
+
+ //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<String, List<CategoryDefinition>> categoriesMap = getCategories();
List<CategoryDefinition> resourceSubCategories = categoriesMap.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
List<SubCategoryDefinition> subcategories;
@@ -347,80 +283,69 @@ public class DeploymentValiditaion extends ComponentBaseTest{
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<String, List<String>> 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()));
-
-
-
-
+
+ assertTrue("missing categories ", resourceMapFromUrl.keySet().containsAll(resourcesListFromFile.keySet()));
}
-
-
+
+
public Map<String, List<CategoryDefinition>> getCategories() throws Exception {
-
+
User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
-
+
Map<String,List<CategoryDefinition>> map = new HashMap<String,List<CategoryDefinition>>();
-
-
+
+
RestResponse allResourceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.RESOURCE_PARAM_NAME);
RestResponse allServiceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.SERVICE_PARAM_NAME);
List<CategoryDefinition> parsedResourceCategories = ResponseParser.parseCategories(allResourceCategories);
List<CategoryDefinition> parsedServiceCategories = ResponseParser.parseCategories(allServiceCategories);
-
+
map.put(ComponentTypeEnum.RESOURCE_PARAM_NAME, parsedResourceCategories);
map.put(ComponentTypeEnum.SERVICE_PARAM_NAME, parsedServiceCategories);
-
+
return map;
}
-
- @Test (enabled=false)
+
+/* @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<Map> values = (Collection<Map>) map.values();
for (Map map2 : values) {
Collection values2 = map2.values();
for (Object object : values2) {
-
-
+
+
}
}
-
- {
-
- }
+
List<Object> 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
index fdef535f95..9db9e8a4d8 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
@@ -20,21 +20,14 @@
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 com.google.gson.Gson;
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 com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
@@ -45,35 +38,26 @@ 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.*;
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.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.ci.tests.utils.rest.*;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.testng.annotations.Test;
-import com.google.gson.Gson;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.testng.AssertJUnit.assertEquals;
public class GetAssetServlet extends ComponentBaseTest {
@@ -102,78 +86,52 @@ public class GetAssetServlet extends ComponentBaseTest {
// CassandraUtils.truncateAllKeyspaces();
List<String> expectedAssetNamesList = new ArrayList<>();
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(resourceDetails.getName());
- 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);
+ resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
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);
+ expectedAssetNamesList.add(resourceDetails.getName());
+
+ resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(resourceDetails.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);
+ resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(resourceDetails.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);
+ resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(resourceDetails.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);
+ resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft();
- expectedAssetNamesList.add(resource.getName());
+ expectedAssetNamesList.add(resourceDetails.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);
+ resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(resourceDetails.getName());
System.out.println("7 VF resources were created");
@@ -186,11 +144,11 @@ public class GetAssetServlet extends ComponentBaseTest {
AssetRestUtils.checkComponentTypeInObjectList(resourceAssetList, ComponentTypeEnum.RESOURCE);
- // Validate audit message
+ /* // Validate audit message
ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_ASSET_LIST);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), body);*/
}
@@ -202,76 +160,59 @@ public class GetAssetServlet extends ComponentBaseTest {
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);
+ Service service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(serviceDetails.getName());
+
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(serviceDetails.getName());
- serviceDetails.setName("ciService3");
- createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- BaseRestUtils.checkCreateResponse(createService);
- service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(serviceDetails.getName());
- serviceDetails.setName("ciService4");
- createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- BaseRestUtils.checkCreateResponse(createService);
- service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(serviceDetails.getName());
- serviceDetails.setName("ciService5");
- createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- BaseRestUtils.checkCreateResponse(createService);
- service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(serviceDetails.getName());
- serviceDetails.setName("ciService6");
- createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- BaseRestUtils.checkCreateResponse(createService);
- service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(serviceDetails.getName());
- serviceDetails.setName("ciService7");
- createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- BaseRestUtils.checkCreateResponse(createService);
- service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
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());
+ expectedAssetNamesList.add(serviceDetails.getName());
System.out.println("7 Services were created");
@@ -282,24 +223,20 @@ public class GetAssetServlet extends ComponentBaseTest {
List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList);
Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
- // Validate audit message
+ /*// Validate audit message
ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_ASSET_LIST);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), body);*/
}
- @Test
+ @Test(enabled = false)
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);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, sdncUserDetails);
+ Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
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();
@@ -320,6 +257,7 @@ public class GetAssetServlet extends ComponentBaseTest {
.append(artifactUiDownloadData.getArtifactName()).append("\"").toString());
}
+
private HttpGet createGetRequest(String url) {
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java
index 7ab35b758e..fbbd394731 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java
@@ -20,41 +20,33 @@
package org.openecomp.sdc.externalApis;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-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.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.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.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.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.validation.AuditValidationUtils;
-import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+
+import static org.testng.AssertJUnit.assertTrue;
+
public class GetCSARofVF extends ComponentBaseTest {
// protected User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
@@ -86,16 +78,14 @@ public class GetCSARofVF extends ComponentBaseTest {
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(), "");
+ File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID());
// validate tosca structure
validateCsarContent(resource, toscaModelCsarFile);
- // Validate audit message
- validateAudit(resource);
-
-
-
+ /* // Validate audit message
+ validateAudit(resource);*/
+
}
@@ -108,16 +98,14 @@ public class GetCSARofVF extends ComponentBaseTest {
AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID());
- File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID(), "");
+ File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID());
// validate tosca structure
validateCsarContent(resource, toscaModelCsarFile);
- // Validate audit message
- validateAudit(resource);
-
-
-
+ /*// Validate audit message
+ validateAudit(resource);*/
+
}
@Test
@@ -128,15 +116,14 @@ public class GetCSARofVF extends ComponentBaseTest {
AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID());
- File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID(), "");
+ File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.RESOURCES, resource.getUUID());
// validate tosca structure
validateCsarContent(resource, toscaModelCsarFile);
- // Validate audit message
- validateAudit(resource);
-
-
+ /*// Validate audit message
+ validateAudit(resource);*/
+
}
@@ -146,15 +133,13 @@ public class GetCSARofVF extends ComponentBaseTest {
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(), "");
+ File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID());
// validate tosca structure
validateCsarContent(service, toscaModelCsarFile);
- validateAudit(service);
-
-
-
+ /*validateAudit(service);*/
+
}
@Test
@@ -165,14 +150,13 @@ public class GetCSARofVF extends ComponentBaseTest {
AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID());
- File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID(), "");
+ File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID());
// validate tosca structure
validateCsarContent(service, toscaModelCsarFile);
- validateAudit(service);
-
-
+ /*validateAudit(service);*/
+
}
@Test
@@ -183,12 +167,12 @@ public class GetCSARofVF extends ComponentBaseTest {
AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
// HttpResponse componentToscaModel = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID());
- File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID(), "");
+ File toscaModelCsarFile = AssetRestUtils.getToscaModelCsarFile(AssetTypeEnum.SERVICES, service.getUUID());
// validate tosca structure
validateCsarContent(service, toscaModelCsarFile);
- validateAudit(service);
+ /*validateAudit(service);*/
}
@@ -230,7 +214,7 @@ public class GetCSARofVF extends ComponentBaseTest {
assertTrue("missing files in csar template definitions folder", expectedDefinitionFolderFileList.size() == 0);
}
- public void validateAudit(Component resource) throws Exception {
+ /*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"));
@@ -245,6 +229,6 @@ public class GetCSARofVF extends ComponentBaseTest {
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
index 70d8ef50f4..57a0f26a90 100644
--- 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
@@ -20,15 +20,6 @@
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;
@@ -37,40 +28,27 @@ 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.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.*;
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.rest.*;
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.Test;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
public class GetFilteredAssetServlet extends ComponentBaseTest {
private static Logger log = LoggerFactory.getLogger(GetAssetServlet.class.getName());
@@ -115,12 +93,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateSuccessAudit(filter, AssetTypeEnum.RESOURCES);*/
}
@@ -145,12 +119,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateSuccessAudit(filter, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -169,12 +139,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateSuccessAudit(filter, AssetTypeEnum.RESOURCES);*/
}
// Failure
@@ -192,14 +158,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.RESOURCES)*/;
}
@Test // (enabled = false)
@@ -216,14 +176,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -240,14 +194,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -264,14 +212,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.RESOURCES);*/
}
// ---------------------------------------------------------------------------------------------------------
@@ -292,12 +234,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateSuccessAudit(filter, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -321,12 +259,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateSuccessAudit(filter, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -350,12 +284,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateSuccessAudit(filter, AssetTypeEnum.SERVICES);*/
}
// Failure
@@ -373,14 +303,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -396,14 +320,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -420,14 +338,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -444,14 +356,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -468,14 +374,8 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
List<String> 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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ /*// Validate audit message
+ validateFailureAudit(filter, errorInfo, variables, AssetTypeEnum.SERVICES);*/
}
@@ -486,226 +386,206 @@ public class GetFilteredAssetServlet extends ComponentBaseTest {
RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.RESOURCES, query);
BaseRestUtils.checkErrorResponse(assetResponse, ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, "resource", "category", "Application L3+");
- // Validate audit message
+ /*// Validate audit message
ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getFilteredAssetListAuditCategoryNotFound(AssetTypeEnum.RESOURCES, "?" + query, "Application L3+");
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);*/
}
- @Test
- public void getFilteredResourceAssetSuccess() throws Exception {
-
- List<String> 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<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
- List<String> getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList);
- Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+ @Test
+ public void getFilteredResourceAssetSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_APP_SERVER);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_BORDER);
+ resourceDetails.setResourceType(ResourceTypeEnum.VFC.name());
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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.setResourceType(ResourceTypeEnum.VF.name());
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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.setResourceType(ResourceTypeEnum.VF.name());
+ resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
+ List<String> 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 <AuditingFieldsKeysEnum, String> 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<String> 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<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
- Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
-
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultFilteredAssetListAudit(AssetTypeEnum.SERVICES, "?" + query);
- Map <AuditingFieldsKeysEnum, String> 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<String> 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<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
- List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
- Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
-
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultFilteredAssetListAudit(AssetTypeEnum.SERVICES, "?" + query);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
-
- }
-
+ /*// Validate audit message
+ validateFilteredAudit(query, AssetTypeEnum.RESOURCES);*/
+
+ }
+
+ @Test
+ public void getFilteredServiceAssetInformationalSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true);
+ artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType());
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ Service service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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 = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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 = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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 = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ /*// Validate audit message
+ validateFilteredAudit(query, AssetTypeEnum.SERVICES);*/
+
+ }
+
+ @Test
+ public void getFilteredServiceAssetDeploymentSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true);
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ Service service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ serviceDetails = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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 = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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 = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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 = ElementFactory.getDefaultService();
+ service = AtomicOperationUtils.createCustomService(serviceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ 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<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ /*// Validate audit message
+ validateFilteredAudit(query, AssetTypeEnum.SERVICES);*/
+ }
+
+ /*private void validateSuccessAudit(String[] filter, AssetTypeEnum assetType) throws Exception {
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ Map<AuditingFieldsKeysEnum, String> body = new HashMap<>();
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ }
+
+ private void validateFilteredAudit(String query, AssetTypeEnum assetType) throws Exception {
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultFilteredAssetListAudit(assetType, "?" + query);
+ Map<AuditingFieldsKeysEnum, String> body = new HashMap<>();
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ }
+
+ private void validateFailureAudit(String[] filter, ErrorInfo errorInfo, List<String> variables, AssetTypeEnum assetType) throws Exception {
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(assetType, 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<AuditingFieldsKeysEnum, String> 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
index a55a458168..c036c7fb41 100644
--- 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
@@ -21,24 +21,21 @@
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.Component;
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;
@@ -47,9 +44,7 @@ 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.Test;
public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
@@ -80,11 +75,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /* // Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -103,12 +95,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory
- .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -137,11 +125,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /* // Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -170,11 +155,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /* // Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -203,11 +185,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -236,11 +215,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /* // Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
@Test // (enabled = false)
@@ -265,13 +241,11 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(resourceVF, AssetTypeEnum.RESOURCES);*/
}
+
// Import CSAR
// Service
@@ -286,11 +260,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(service, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -309,11 +280,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(service, AssetTypeEnum.SERVICES);*/
}
@@ -345,11 +313,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(service, AssetTypeEnum.SERVICES);*/
}
@@ -385,11 +350,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(service, AssetTypeEnum.SERVICES);*/
}
@@ -424,11 +386,8 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
- // Validate audit message
- ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
- Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
- AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ /*// Validate audit message
+ validateAudit(service, AssetTypeEnum.SERVICES);*/
}
@Test // (enabled = false)
@@ -443,4 +402,11 @@ public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables, assetResponse.getResponse());
}
+ /*private void validateAudit(Component component, AssetTypeEnum assetType) throws Exception {
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetMetadataAudit(assetType, component);
+ Map<AuditingFieldsKeysEnum, String> body = new HashMap<>();
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedAssetListAudit.getRESOURCE_URL());
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_METADATA.getName(), body);
+ }*/
+
}
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
index ca7c5aefb9..8b174e550d 100644
--- 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
@@ -20,13 +20,10 @@
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 com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
import org.json.simple.parser.JSONParser;
import org.junit.Rule;
import org.junit.rules.TestName;
@@ -36,34 +33,29 @@ 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;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
@@ -101,15 +93,19 @@ public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
List<String> variables = Arrays.asList("resourceTypeinvalid", "[resourceType, subCategory, category]");
ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, restResponse.getResponse());
+ /*validateFailureAudit(variables);*/
+ }
+
+ /*private void validateFailureAudit(List<String> variables) throws Exception {
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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
+ Map<AuditingFieldsKeysEnum, String> 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[][] {
@@ -129,13 +125,13 @@ public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
List<String> 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);
+ /*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 <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
- AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);*/
}
// Searching for resource filter incorrect resource type using external API
@@ -160,10 +156,10 @@ public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
}
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString());
+ /*ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString());
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
- AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);*/
}
}
@@ -182,10 +178,10 @@ public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
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());
+ /*ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + resourceTypeEnum.toString());
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
- AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);
+ AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), body);*/
}
}
@@ -209,8 +205,8 @@ public class SearchFilterCategoryExternalAPI extends ComponentBaseTest {
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.VFCMT.toString());
- AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ /*ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalAuditObject(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST, "?" + SearchCriteriaEnum.RESOURCE_TYPE.getValue() + "=" + ResourceTypeEnum.VFCMT.toString());
+ AuditValidationUtils.validateAuditExternalSearchAPI(expectedExternalAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);*/
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java
index cd96af225f..4cd5c1c0d5 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java
@@ -20,21 +20,16 @@
package org.openecomp.sdc.externalApis;
-import static java.util.Arrays.asList;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
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;
@@ -45,25 +40,22 @@ 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.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.openecomp.sdc.common.util.ValidationUtils;
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 java.util.List;
+
+import static java.util.Arrays.asList;
+import static org.testng.Assert.assertTrue;
public class VFCMTExternalAPI extends ComponentBaseTest {
@@ -110,12 +102,12 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser);
ResourceAssetStructure parsedCreatedResponse = gson.fromJson(restResponse.getResponse(), ResourceAssetStructure.class);
- // auditing verification
+ /* // auditing verification
AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parsedCreatedResponse.getName());
- ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(parsedCreatedResponse.getName());
- AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);
+ 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());
@@ -158,28 +150,28 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
RestResponse firstTryToCreate = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser);
ResourceAssetStructure parsedCreatedResponse = gson.fromJson(firstTryToCreate.getResponse(), ResourceAssetStructure.class);
- // auditing verification
+ /*// auditing verification
AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parsedCreatedResponse.getName());
ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(parsedCreatedResponse.getName());
- AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);
+ 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");
+ /*body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "409");
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name());
List<String> variables = asList(ComponentTypeEnum.RESOURCE.getValue(), defaultResource.getName());
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
expectedResourceAuditJavaObject.setStatus("409");
- AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);*/
}
- @DataProvider(name="createVfcmtVariousFailureFlows", parallel=true)
+ @DataProvider(name="createVfcmtVariousFailureFlows", parallel=true)
public static Object[][] dataProviderCreateVfcmtVariousFailureFlows() {
return new Object[][] {
{"name_missing"},
@@ -217,11 +209,11 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
ErrorInfo errorInfo = null;
- List<String> variables = null;
+ /*List<String> variables = null;
AuditingActionEnum action = AuditingActionEnum.CREATE_RESOURCE_BY_API;
ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultCreateResourceExternalAPI(defaultResource.getName());
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, defaultResource.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, defaultResource.getName());*/
switch (flow) {
case "name_missing":
@@ -229,149 +221,149 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
List<String> resourceTags = defaultResource.getTags();
resourceTags.add("");
defaultResource.setTags(resourceTags);
- expectedResourceAuditJavaObject.setResourceName("");
errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_COMPONENT_NAME.name());
+ /*expectedResourceAuditJavaObject.setResourceName("");
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
+ 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());
+ /*expectedResourceAuditJavaObject.setResourceName("asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1");
variables = asList(ComponentTypeEnum.RESOURCE.getValue(), "1024");
-
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1");
+ 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());
+ /*expectedResourceAuditJavaObject.setResourceName("!@#$%^&*(");
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "!@#$%^&*(");
+ 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());
+ /*expectedResourceAuditJavaObject.setDesc("");
+ 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");
+ /*expectedResourceAuditJavaObject.setDesc("asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1asdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjklasdfghjk1");
+ 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());
+ /*expectedResourceAuditJavaObject.setDesc("t");
+ 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.INVALID_CONTENT.name());
- variables = asList(ComponentTypeEnum.RESOURCE.getValue());
+ /*expectedResourceAuditJavaObject.setResourceType("");
+ 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_RESOURCE_TYPE.name());
- variables = asList(ComponentTypeEnum.RESOURCE.getValue());
+ /*expectedResourceAuditJavaObject.setResourceType(ComponentTypeEnum.RESOURCE.getValue());
+ 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());
+ /*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());
+ /*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());
+ /*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());
+ /*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());
+ /*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(ValidationUtils.VENDOR_NAME_MAX_LENGTH.toString());
+ /*variables = asList(ValidationUtils.VENDOR_NAME_MAX_LENGTH.toString());*/
break;
case "vendor_name_with_invalid_char":
defaultResource.setVendorName("!@#$*()&*^%$#@");
errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_VENDOR_NAME.name());
- variables = asList(ComponentTypeEnum.RESOURCE.getValue());
+ /*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());
+ /*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");
+ /*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());
+ /*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");
+ /*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");
+ /*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());
+ /*variables = asList(ComponentTypeEnum.RESOURCE.getValue());*/
break;
case "icon_missing":
defaultResource.setIcon("");
errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_ICON.name());
- variables = asList(ComponentTypeEnum.RESOURCE.getValue());
+ /*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());
+ /*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());
+ /*variables = asList(ComponentTypeEnum.RESOURCE.getValue());*/
break;
}
// create vfcmt
RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser);
+ assertTrue(errorInfo.getCode().equals(restResponse.getErrorCode()), "Expected response code on [" + flow + "] is: " + errorInfo.getCode() + ", actual is: " + restResponse.getErrorCode());
- expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ /*expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
- AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);
+ AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);*/
}
diff --git a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml
index 904b3d1327..5ee9d0590e 100644
--- a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml
+++ b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml
@@ -42,6 +42,8 @@ cassandraAuditKeySpace: sdcaudit
cassandraArtifactKeySpace: sdcartifact
url: http://localhost:8181/sdc1/proxy-designer1#/dashboard
+sdcHttpMethod: https
+localDataCenter: DC-Automate01
stopOnClassFailure: false
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
index 1b6f0258d6..e695db26b2 100644
--- a/test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh
+++ b/test-apis-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh
@@ -46,12 +46,12 @@ function addUser ()
firstName=`echo $user|awk '{print $3}'`
lastName=`echo $user|awk '{print $4}'`
email=`echo $user|awk '{print $5}'`
- curl --noproxy '*' -i -X post -d '{ "userId" : "'${userId}'", "role" : "'${role}'", "firstName" : "'${firstName}'", "lastName" : "'${lastName}'", "email" : "'${email}'" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" http://${IP}:8080/sdc2/rest/v1/user
+ curl --noproxy '*' -i -X post -d '{ "userId" : "'${userId}'", "role" : "'${role}'", "firstName" : "'${firstName}'", "lastName" : "'${lastName}'", "email" : "'${email}'" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" https://${IP}:8443/sdc2/rest/v1/user
else
echo "Host" $IP "Is Unreachable"
fi
done
-curl --noproxy '*' -i -X post -d '{"consumerName": "ci","consumerSalt": "2a1f887d607d4515d4066fe0f5452a50","consumerPassword": "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"}' -H "Content-Type: application/json" -H "USER_ID: jh0003" -H "Authorization:Basic Y2k6MTIzNDU2" http://${IP}:8080/sdc2/rest/v1/consumers
+curl --noproxy '*' -i -X post -d '{"consumerName": "ci","consumerSalt": "2a1f887d607d4515d4066fe0f5452a50","consumerPassword": "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"}' -H "Content-Type: application/json" -H "USER_ID: jh0003" -H "Authorization:Basic Y2k6MTIzNDU2" https://${IP}:8443/sdc2/rest/v1/consumers
}
diff --git a/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh b/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh
index 4c23a7973e..d2b142a20c 100644
--- a/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh
+++ b/test-apis-ci/src/main/resources/ci/scripts/sendMail.sh
@@ -6,9 +6,9 @@ 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"
-
+RECIPIENTS1="dl-sdcqa@att.com,ml636r@att.com,bl5783@att.com,ak314p@att.com,el489u@att.com,hk096q@att.com,bs5719@att.com"
+#RECIPIENTS2="dl-asdcqa@intl.att.com"
+RECIPIENTS2="md9897@att.com,ms656r@att.com,al714h@att.com,ak991p@att.com,ya107f@att.com,bv095y@att.com,st198j@att.com,th0695@att.com,vk195d@att.com,gg980r@att.com,il0695@att.com,el489u@att.com"
source ExtentReport/versions.info
if [ -z "$REPORT_NAME" ]
then
diff --git a/test-apis-ci/src/main/resources/ci/scripts/startTest.sh b/test-apis-ci/src/main/resources/ci/scripts/startTest.sh
index 764e046653..88c9521ac4 100644
--- a/test-apis-ci/src/main/resources/ci/scripts/startTest.sh
+++ b/test-apis-ci/src/main/resources/ci/scripts/startTest.sh
@@ -91,7 +91,7 @@ ADD_USERS_SCRIPT="addUsersFromList_new.sh"
USER_LIST="conf/userList.txt"
chmod +x ${ADD_USERS_SCRIPT}
echo "add users..."
-`./${ADD_USERS_SCRIPT} -ip ${BE_IP} -f ${USER_LIST}`
+./${ADD_USERS_SCRIPT} -ip ${BE_IP} -f ${USER_LIST}
@@ -137,7 +137,7 @@ fi
COPY_REPORT_SCRIPT="copyToStorage.sh"
chmod +x ${COPY_REPORT_SCRIPT}
echo "copy report to storage..."
-sh ./${COPY_REPORT_SCRIPT} ${REPORT_NAME} ${VERSION} ${MYENV}
+( ./${COPY_REPORT_SCRIPT} ${REPORT_NAME} ${VERSION} ${MYENV} )
MAILING_SCRIPT_NAME="sendMail.sh"
diff --git a/test-apis-ci/src/main/resources/ci/testSuites/ExternalApiSanity.xml b/test-apis-ci/src/main/resources/ci/testSuites/ExternalApiSanity.xml
new file mode 100644
index 0000000000..02594526cb
--- /dev/null
+++ b/test-apis-ci/src/main/resources/ci/testSuites/ExternalApiSanity.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
+<suite name="CRUDArtifacts" configfailurepolicy="continue" verbose="2" parallel="methods" thread-count="2" data-provider-thread-count="2">
+
+ <test name="Test">
+ <classes>
+ <class name="org.openecomp.sdc.externalApis.CRUDExternalAPI">
+ <methods>
+ <include name="uploadArtifactOnVfcVlCpViaExternalAPI" invocation-numbers="0" />
+ <include name="uploadArtifactOnVFViaExternalAPI" invocation-numbers="0" />
+ <include name="uploadArtifactOnServiceViaExternalAPI" invocation-numbers="0" />
+ <include name="uploadArtifactOnRIViaExternalAPI" invocation-numbers="0" />
+ <include name="uploadArtifactOnVfcVlCpRIViaExternalAPI" invocation-numbers="0" />
+ <include name="updateArtifactForServiceViaExternalAPI" invocation-numbers="0" />
+ <include name="updateArtifactForVFViaExternalAPI" invocation-numbers="0" />
+ <include name="updateArtifactForVfcVlCpViaExternalAPI" invocation-numbers="0" />
+ <include name="updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI" invocation-numbers="0" />
+ <include name="updateArtifactOnRIViaExternalAPI" invocation-numbers="0" />
+ <include name="updateArtifactOnVfcVlCpRIViaExternalAPI" invocation-numbers="0" />
+ <include name="deleteArtifactForServiceViaExternalAPI" invocation-numbers="0" />
+ <include name="deleteArtifactForVFViaExternalAPI" invocation-numbers="0" />
+ <include name="deleteArtifactOnRIViaExternalAPI" invocation-numbers="0" />
+ <include name="deleteArtifactOnVfcVlCpRIViaExternalAPI" invocation-numbers="0" />
+ <include name="deleteArtifactOnAssetWhichNotExist" />
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.ci.tests.execute.artifacts.DownloadComponentArt">
+ <methods>
+ <include name="downloadArtifactOfComponentInstanceFromServiceViaExternalAPI"/>
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.externalApis.GetFilteredAssetServlet">
+ <methods>
+ <include name="getResourceAssetBySpecifiedCategory"/>
+ <include name="getServiceAssetBySpecifiedCategory"/>
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.externalApis.SearchFilterCategoryExternalAPI">
+ <methods>
+ <include name="normativeResourceCategory" invocation-numbers="0"/>
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.externalApis.GetCSARofVF">
+ <methods>
+ <include name="getServiceToscaModelCheckInState"/>
+ <include name="getRsourceToscaModelCertifyState"/>
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.externalApis.GetFilteredAssetServlet">
+ <methods>
+ <include name="getResourceAssetBySpecifiedCategory"/>
+ <include name="getServiceAssetBySpecifiedCategory"/>
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.externalApis.GetSpecificAssetMetadataServlet">
+ <methods>
+ <include name="getResourceAssetMetadataSuccess"/>
+ <include name="getServiceAssetMetadataWithResourceInstancesSuccess"/>
+ </methods>
+ </class>
+ <class name="org.openecomp.sdc.externalApis.AssetLifeCycle">
+ <methods>
+ <include name="theFlow"/>
+ </methods>
+ </class>
+ </classes>
+ </test> <!-- Test -->
+</suite> <!-- Suite --> \ 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
index d32839bdb7..6440dc147b 100644
--- a/test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml
+++ b/test-apis-ci/src/main/resources/ci/testSuites/externalAPIs.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="externalApis" configfailurepolicy="continue" verbose="2" parallel="methods" thread-count="1" data-provider-thread-count="1">
+<suite name="externalApis" configfailurepolicy="continue" verbose="2" parallel="methods" thread-count="1" data-provider-thread-count="10">
<test name="ExternalApis">
<classes>
diff --git a/test-apis-ci/src/main/resources/ci/testSuites/onap.xml b/test-apis-ci/src/main/resources/ci/testSuites/onap.xml
index 4aad3681c9..707500a54c 100644
--- a/test-apis-ci/src/main/resources/ci/testSuites/onap.xml
+++ b/test-apis-ci/src/main/resources/ci/testSuites/onap.xml
@@ -7,17 +7,6 @@
<classes>
<class name="org.openecomp.sdc.ci.tests.sanity.Onboard"/>
-
-<!-- <class name="org.openecomp.sdc.ci.tests.execute.product.ChangeServiceInstanceVersionTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductCheckinTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductCheckoutTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductComponentInstanceCRUDTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductCreateWithValidationsTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductCrudTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductGetFollowedTest"/>
- <class name="org.openecomp.sdc.ci.tests.execute.product.ProductUndoCheckoutTest"/> -->
-
-
</classes>
</test>
</suite> \ No newline at end of file
diff --git a/test-apis-ci/src/test/java/org/openecomp/sdc/conf/TestAPIConfDependentTest.java b/test-apis-ci/src/test/java/org/openecomp/sdc/conf/TestAPIConfDependentTest.java
new file mode 100644
index 0000000000..99b6888211
--- /dev/null
+++ b/test-apis-ci/src/test/java/org/openecomp/sdc/conf/TestAPIConfDependentTest.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.conf;
+
+import org.junit.BeforeClass;
+import org.openecomp.sdc.common.test.BaseConfDependent;
+
+public class TestAPIConfDependentTest extends BaseConfDependent{
+ @BeforeClass
+ public static void setupBeforeClass() {
+ componentName = "test-apis-ci";
+ confPath = "src/test/resources/config";
+ setUp();
+ }
+}
diff --git a/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationCucumberCI.java b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationCucumberCI.java
new file mode 100644
index 0000000000..d9183fc5c4
--- /dev/null
+++ b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/runners/RunTenantIsolationCucumberCI.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.cucumber.runners;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.conf.TestAPIConfDependentTest;
+
+import cucumber.api.CucumberOptions;
+import cucumber.api.junit.Cucumber;
+
+@RunWith(Cucumber.class)
+@CucumberOptions(features = "classpath:cucumber/tenantIsolation.feature", glue = "org.openecomp.sdc.cucumber.steps")
+
+public class RunTenantIsolationCucumberCI extends TestAPIConfDependentTest {
+
+ @BeforeClass
+ public static void beforeClass() {
+ }
+
+ @AfterClass
+ public static void afterClassJUnit() {
+ }
+
+ @org.testng.annotations.BeforeClass
+ public static void beforeClassTestNg() {
+ }
+
+ @org.testng.annotations.AfterClass
+ public static void afterClassTestNG() {
+ }
+} \ No newline at end of file
diff --git a/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/spring/ImportTableConfig.java b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/spring/ImportTableConfig.java
new file mode 100644
index 0000000000..f0c7610513
--- /dev/null
+++ b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/spring/ImportTableConfig.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.cucumber.spring;
+
+import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ImportTableConfig {
+ @Bean(name = "cassandra-client")
+ public CassandraClient cassandraClient() {
+ return new CassandraClient();
+ }
+
+ @Bean(name = "operational-environment-dao")
+ public OperationalEnvironmentDao operationalEnvironmentDao() {
+ return new OperationalEnvironmentDao();
+ }
+}
diff --git a/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/PrecannedTestExpectationCallback.java b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/PrecannedTestExpectationCallback.java
new file mode 100644
index 0000000000..56802ec7d4
--- /dev/null
+++ b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/PrecannedTestExpectationCallback.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.cucumber.steps;
+
+import static org.mockserver.model.HttpResponse.response;
+
+import org.apache.http.entity.ContentType;
+import org.mockserver.mock.action.ExpectationCallback;
+import org.mockserver.model.Header;
+import org.mockserver.model.HttpRequest;
+import org.mockserver.model.HttpResponse;
+
+import com.google.common.net.HttpHeaders;
+
+public class PrecannedTestExpectationCallback implements ExpectationCallback {
+ private static volatile int countRequests;
+
+ static HttpResponse httpResponse = response()
+ .withStatusCode(200)
+ .withHeaders(new Header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));
+
+ @Override
+ public HttpResponse handle(HttpRequest httpRequest) {
+ countRequests++;
+
+ System.out.println(
+ String.format("MSO Server Simulator Recieved %s Final Distribution Complete Rest Reports From ASDC",
+ countRequests));
+
+ return httpResponse;
+ }
+
+} \ No newline at end of file
diff --git a/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/StepsTenantIsolationCI.java b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/StepsTenantIsolationCI.java
new file mode 100644
index 0000000000..490b3e0c84
--- /dev/null
+++ b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/steps/StepsTenantIsolationCI.java
@@ -0,0 +1,597 @@
+package org.openecomp.sdc.cucumber.steps;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.mockserver.model.HttpCallback.callback;
+import static org.mockserver.model.HttpRequest.request;
+import static org.mockserver.model.HttpResponse.response;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.retryMethodOnResult;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.apache.commons.collections.CollectionUtils;
+//import org.openecomp.sdc.dmaap.DmaapPublisher;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpStatus;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.mockserver.integration.ClientAndServer;
+import org.mockserver.model.Header;
+import org.mockserver.model.HttpRequest;
+import org.openecomp.sdc.api.IDistributionClient;
+import org.openecomp.sdc.api.consumer.IConfiguration;
+import org.openecomp.sdc.api.consumer.IFinalDistrStatusMessage;
+import org.openecomp.sdc.api.consumer.INotificationCallback;
+import org.openecomp.sdc.api.notification.IArtifactInfo;
+import org.openecomp.sdc.api.notification.INotificationData;
+import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
+import org.openecomp.sdc.api.results.IDistributionClientResult;
+import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
+import org.openecomp.sdc.be.dao.cassandra.OperationalEnvironmentDao;
+import org.openecomp.sdc.be.datatypes.enums.EnvironmentStatusEnum;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.common.datastructure.FunctionalInterfaces;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.cucumber.spring.ImportTableConfig;
+import org.openecomp.sdc.http.HttpAsdcClient;
+import org.openecomp.sdc.http.HttpAsdcResponse;
+import org.openecomp.sdc.http.IHttpAsdcClient;
+import org.openecomp.sdc.impl.DistributionClientFactory;
+import org.openecomp.sdc.utils.ArtifactTypeEnum;
+import org.openecomp.sdc.utils.DistributionActionResultEnum;
+import org.openecomp.sdc.utils.DistributionStatusEnum;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+import com.google.common.base.Strings;
+import com.google.common.net.HttpHeaders;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+
+import cucumber.api.java.After;
+import cucumber.api.java.Before;
+import cucumber.api.java.en.Given;
+import cucumber.api.java.en.Then;
+import cucumber.api.java.en.When;
+import fj.data.Either;
+
+public class StepsTenantIsolationCI {
+
+ private Map<String, OperationalEnvironmentEntry> recordMap = new HashMap<>();
+ private OperationalEnvironmentDao operationalEnvironmentDao;
+ private ClientAndServer aaiMockServer;
+ private ClientAndServer msoMockServer;
+ private List<IDistributionClient> distributionClients = new ArrayList<>();
+
+ private List<String> wdFinalStatusSent = new ArrayList<>();
+
+ private HttpRequest msoHttpRequest;
+ private List<String> uuidServicesList;
+ private boolean cleanFlag = true;
+ private int maxStepWaitTimeMs;
+
+ private List<String> envIds = new ArrayList<>();
+ private List<OperationalEnvironmentEntry> envList = new ArrayList<>();
+ private String asdcAddress;
+ private volatile int numberOfFinalDistributionsSentByASDC;
+ private int numOfArtifactsToDownload;
+ private volatile int totalNumOfArtifactsToDownload;
+ private List<String> envNames = new ArrayList<>(Arrays.asList("Apple", "Orange", "Grape", "Pear", "Watermelon", "Bannana", "Cherry", "Coconut", "Fig", "Mango", "Peach", "Pineapple", "Plum", "Strawberries", "Apricot"));
+
+ private static final String AAI_RESPONSE_BODY_FMT = "{\"operational-environment-id\":\"UUID of Operational Environment\","
+ + "\"operational-environment-name\":\"Op Env Name\"," + "\"operational-environment-type\":\"ECOMP\","
+ + "\"operational-environment-status\":\"Activate\"," + "\"tenant-context\":\"%s\","
+ + "\"workload-context\":\"%s\"," + "\"resource-version\":\"1505228226913\"," + "\"relationship-list\":{}}";
+
+ private static final String AAI_PATH_REGEX = "/aai/v12/cloud-infrastructure/operational-environments/.*";
+
+ private static final String MSO_PATH_REGEX = "/onap/mso/infra/modelDistributions/v1/distributions/.*";
+
+ @Before
+ public void beforeScenario() {
+ Collections.shuffle(envNames);
+ aaiMockServer = ClientAndServer.startClientAndServer(1111);
+ msoMockServer = ClientAndServer.startClientAndServer(1112);
+
+ this.operationalEnvironmentDao = createDaoObj();
+ }
+
+ @After
+ public void afterScenario() {
+ System.out.println("Cleaning Up After Scenario...");
+ aaiMockServer.stop();
+ msoMockServer.stop();
+ if (cleanFlag) {
+ envIds.stream().forEach(operationalEnvironmentDao::delete);
+ }
+ distributionClients.stream().forEach(IDistributionClient::stop);
+ System.out.println("Cleaning Up After Scenario Done");
+ }
+
+ // ############################# Given - Start #############################
+
+ @Given("^clean db after test is (.*)$")
+ public void clean_db_after_test_is(boolean cleanFlag) {
+ this.cleanFlag = cleanFlag;
+ }
+
+ @Given("^AAI returns (.*) and aai_body contains (.*) and (.*)$")
+ public void aai_returns(int retCode, String tenant, String workload) throws Throwable {
+ String aaiResponseBody = String.format(AAI_RESPONSE_BODY_FMT, tenant, workload);
+
+ setAaiMockServer(aaiResponseBody);
+
+ System.out.println(aaiMockServer.getClass());
+ }
+
+ @Given("^MSO-WD Simulators Started with topic name (.*)$")
+ public void notification_listner_simulators_started(String topicName) throws Throwable {
+ envList.forEach(env -> {
+ final IDistributionClient distClientSim = simulateDistributionClientWD(topicName, env);
+ distributionClients.add(distClientSim);
+ });
+
+ }
+
+ @Given("^MSO Final Distribution Simulator is UP$")
+ public void mso_Final_Distribution_Simulator_is_UP() throws Throwable {
+ msoHttpRequest = request().withPath(MSO_PATH_REGEX);
+ msoMockServer.when(msoHttpRequest).callback(
+ callback().withCallbackClass("org.openecomp.sdc.cucumber.steps.PrecannedTestExpectationCallback"));
+ }
+
+ @Given("^ASDC Address is (.*)$")
+ public void asdc_Address_is(String asdcAddress) throws Throwable {
+ this.asdcAddress = asdcAddress;
+
+ }
+
+ @Given("^ASDC Contains the following services (.*)$")
+ public void asdc_Contains_the_following_services(String listOfServicesUUID) throws Throwable {
+ uuidServicesList = Arrays.asList(listOfServicesUUID.split(",")).stream().map(String::trim)
+ .collect(Collectors.toList());
+
+ int maxMinWait = uuidServicesList.size() * envIds.size();
+ this.maxStepWaitTimeMs = 60000 * maxMinWait;
+ System.out.println(String.format("Set Max Step Wait Time To: %s Minutes", maxMinWait));
+ }
+
+ @Given("^The number of complete environments is (.*)$")
+ public void the_number_of_complete_environments_is(int envNum) throws Throwable {
+
+ int counter = 1;
+ while( envNum > envNames.size()){
+ envNames.add(String.valueOf(counter));
+ counter++;
+ }
+
+
+ for (int i = 0; i < envNum; i++) {
+ OperationalEnvironmentEntry preSaveEntry = new OperationalEnvironmentEntry();
+
+ preSaveEntry.setStatus(EnvironmentStatusEnum.COMPLETED);
+ preSaveEntry.setLastModified(new Date(System.currentTimeMillis()));
+
+ Set<String> uebAdresses = new HashSet<>();
+ uebAdresses.add("uebsb92sfdc.it.att.com");
+ preSaveEntry.setDmaapUebAddress(uebAdresses);
+ preSaveEntry.setIsProduction(false);
+ preSaveEntry.setUebApikey("sSJc5qiBnKy2qrlc");
+ preSaveEntry.setUebSecretKey("4ZRPzNJfEUK0sSNBvccd2m7X");
+ preSaveEntry.setTenant("TEST");
+ preSaveEntry.setEcompWorkloadContext("ECOMP_E2E-IST");
+
+ // String envId = UUID.randomUUID().toString();
+ String envId = envNames.get(i);
+ preSaveEntry.setEnvironmentId(envId);
+ envIds.add(envId);
+ envList.add(preSaveEntry);
+ operationalEnvironmentDao.save(preSaveEntry);
+ }
+ }
+
+ @Given("^The number of artifacts each Simulator downloads from a service is (.*)$")
+ public void number_of_artifacts_each_simulator_downloads(int numOfArtifactsToDownload) throws Throwable {
+ this.numOfArtifactsToDownload = numOfArtifactsToDownload;
+ }
+
+ // ############################# Given - End #############################
+
+ // ############################# When - Start #############################
+ @When("^Distribution Requests are Sent By MSO$")
+ public void distribution_Requests_are_Sent_By_MSO() throws Throwable {
+ envList.stream().forEach(this::distributeServiceInEnv);
+
+ }
+
+ @When("^The Number Of Operational Envrinoments that created is (.*) and Records are added with data (.*)$")
+ public void operational_envrinoments_records_are_added_with_data(int numOfRecords, String recordData)
+ throws Throwable {
+ for (int i = 0; i < numOfRecords; i++) {
+ OperationalEnvironmentEntry preSaveEntry = new OperationalEnvironmentEntry();
+ JsonElement root = new JsonParser().parse(recordData);
+
+ String originalStatus = root.getAsJsonObject().get("status").getAsString();
+ int delta = root.getAsJsonObject().get("last_modified_delta").getAsInt();
+ preSaveEntry.setStatus(EnvironmentStatusEnum.getByName(originalStatus));
+ long last_modified = System.currentTimeMillis() + delta * 1000;
+ preSaveEntry.setLastModified(new Date(last_modified));
+ String envId = UUID.randomUUID().toString();
+ preSaveEntry.setEnvironmentId(envId);
+ envIds.add(envId);
+ // envrionmentIds.add(envId);
+ operationalEnvironmentDao.save(preSaveEntry);
+
+ }
+
+ }
+
+ // ############################# When - End #############################
+
+ // ############################# Then - Start #############################
+ @Then("^Operational Environment record contains tenant field (.*$)")
+ public void operational_environment_record_contains_tenant(boolean tenantExist) throws Throwable {
+ envIds.forEach(envId -> {
+ validateStringFieldPresent(tenantExist, OperationalEnvironmentEntry::getTenant, envId,
+ "Tenant is not as expected");
+ });
+ }
+
+ @Then("^Operational Environment record contains workload field (.*$)")
+ public void operational_environment_record_contains_workload(boolean workloadExist) throws Throwable {
+ envIds.forEach(envId -> {
+ validateStringFieldPresent(workloadExist, OperationalEnvironmentEntry::getEcompWorkloadContext, envId,
+ "Workload is not as expected");
+ });
+ }
+
+ @Then("^Operational Environment record contains UEB Address field (.*$)")
+ public void operational_environment_record_contains_ueb_address(boolean uebAddresExist) throws Throwable {
+ envIds.forEach(envId -> {
+ validateStringFieldPresent(uebAddresExist, this::convertUebAddressToList, envId,
+ "UEB Address is not as expected");
+ });
+ }
+
+ @Then("^The Number Of Environment is (.*) with status (.*)$")
+ public void the_Number_Of_Environment_Created_is(int numberOfEnvsCreated, String status) throws Throwable {
+ // Write code here that turns the phrase above into concrete actions
+
+ retryMethodOnResult(() -> getCurrentEnvironmets(status), envList -> envList.size() == numberOfEnvsCreated,
+ 40000, 500);
+
+ List<OperationalEnvironmentEntry> environmentsFound = getCurrentEnvironmets(status);
+
+ assertThat(environmentsFound.size(), is(numberOfEnvsCreated));
+
+ environmentsFound.forEach(env -> recordMap.put(env.getEnvironmentId(), env));
+ envList.addAll(environmentsFound);
+ }
+
+ @Then("^MSO Final Distribution Recieved Correct Number Of Request$")
+ public void mso_final_distribution_recieved_request() throws Throwable {
+ int expectedNumberOfRequestsSentByASDC = calculateExcpectedNumberOfDistributionRequets();
+ Function<Integer, Boolean> resultVerifier = actualStatusList -> actualStatusList >= expectedNumberOfRequestsSentByASDC;
+ retryMethodOnResult(() -> numberOfFinalDistributionsSentByASDC(expectedNumberOfRequestsSentByASDC),
+ resultVerifier, maxStepWaitTimeMs, 500);
+ int actualNumberOfRequestsSentByASDC = numberOfFinalDistributionsSentByASDC(expectedNumberOfRequestsSentByASDC);
+ assertThat(actualNumberOfRequestsSentByASDC, is(expectedNumberOfRequestsSentByASDC));
+ }
+
+ @Then("^All MSO-WD Simulators Sent The Distribution Complete Notifications$")
+ public void all_mso_wd_simulators_sent_the_distribution_complete_notifications() {
+ // Wait Watch Dogs To Send Final Distribution
+ int excpectedNumberOfDistributionCompleteNotifications = calculateExcpectedNumberOfDistributionRequets();
+ final Function<List<String>, Boolean> resultVerifier = actualStatusList -> actualStatusList
+ .size() == excpectedNumberOfDistributionCompleteNotifications;
+ retryMethodOnResult(() -> wdFinalStatusSent, resultVerifier, maxStepWaitTimeMs, 500);
+ assertThat(wdFinalStatusSent.size(), is(excpectedNumberOfDistributionCompleteNotifications));
+ }
+ @Then("^All Artifacts were downloaded by Simulators$")
+ public void all_artifacts_downloaded() {
+ // Wait Watch Dogs To Send Final Distribution
+ int excpectedNumberOfArtifactsToDownload = numOfArtifactsToDownload * envIds.size() * uuidServicesList.size();
+ assertThat(totalNumOfArtifactsToDownload, is(excpectedNumberOfArtifactsToDownload));
+ }
+ // ############################# Then - End #############################
+
+ private List<OperationalEnvironmentEntry> getCurrentEnvironmets(String status) {
+ Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherStatus = operationalEnvironmentDao
+ .getByEnvironmentsStatus(EnvironmentStatusEnum.getByName(status));
+ assertThat(eitherStatus.isLeft(), is(true));
+
+ List<OperationalEnvironmentEntry> environmentsRetrieved = eitherStatus.left().value();
+
+ List<OperationalEnvironmentEntry> environmentsFound = environmentsRetrieved.stream()
+ .filter(env -> envIds.contains(env.getEnvironmentId())).collect(Collectors.toList());
+ return environmentsFound;
+ }
+
+ private int numberOfFinalDistributionsSentByASDC(int expectedNumberOfRequestsSentByASDC) {
+ final int newVal = msoMockServer.retrieveRecordedRequests(msoHttpRequest).length;
+ if (newVal != numberOfFinalDistributionsSentByASDC) {
+ System.out.println(String.format(
+ "MSO Server Simulator Recieved %s/%s Final Distribution Complete Rest Reports From ASDC", newVal,
+ expectedNumberOfRequestsSentByASDC));
+ numberOfFinalDistributionsSentByASDC = newVal;
+ }
+
+ return newVal;
+ }
+
+ private int calculateExcpectedNumberOfDistributionRequets() {
+ int numberOfDistributionRequests = envList.size() * uuidServicesList.size();
+ return numberOfDistributionRequests;
+ }
+
+ private static OperationalEnvironmentDao createDaoObj() {
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ImportTableConfig.class);
+ final OperationalEnvironmentDao openvDao = (OperationalEnvironmentDao) context
+ .getBean("operational-environment-dao");
+ return openvDao;
+ }
+
+ private OperationalEnvironmentEntry getRecord(String environmentId) {
+ Either<OperationalEnvironmentEntry, CassandraOperationStatus> result = operationalEnvironmentDao
+ .get(environmentId);
+ return result.isLeft() ? result.left().value() : null;
+ }
+
+ private void validateStringFieldPresent(boolean fieldExist,
+ Function<OperationalEnvironmentEntry, String> getFieldFunc, String envId, String msg) {
+ OperationalEnvironmentEntry record = recordMap.computeIfAbsent(envId, this::getRecord);
+
+ assertNotNull(record, "Expected DB record was not found");
+
+ String actualValue = getFieldFunc.apply(record);
+
+ assertEquals(fieldExist, !Strings.isNullOrEmpty(actualValue), msg);
+ }
+
+ private void setAaiMockServer(String aaiResponseBody) {
+ HttpRequest httpRequest = request().withMethod("GET").withPath(AAI_PATH_REGEX)
+ .withHeaders(new Header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));
+
+ aaiMockServer.when(httpRequest)
+ .respond(response()
+ .withHeaders(new Header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()))
+ .withBody(aaiResponseBody));
+ }
+
+ private IDistributionClient simulateDistributionClientWD(String topicName, OperationalEnvironmentEntry opEnv) {
+
+ IDistributionClient client = DistributionClientFactory.createDistributionClient();
+ final IConfiguration buildDistributionClientConfiguration = buildDistributionClientConfiguration(topicName,
+ opEnv);
+ IDistributionClientResult initResult = client.init(buildDistributionClientConfiguration,
+ new INotificationCallback() {
+
+ @Override
+ public void activateCallback(INotificationData data) {
+ buildWdSimulatorCallback(opEnv, client, buildDistributionClientConfiguration, data);
+
+ }
+
+ });
+ assertThat(initResult.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
+ IDistributionClientResult startResult = client.start();
+ assertThat(startResult.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
+ System.out.println(String.format("WD Simulator On Environment:\"%s\" Started Successfully",
+ buildDistributionClientConfiguration.getConsumerID()));
+ return client;
+ }
+
+ private IFinalDistrStatusMessage buildFinalDistribution() {
+ return new IFinalDistrStatusMessage() {
+
+ @Override
+ public long getTimestamp() {
+ return System.currentTimeMillis();
+ }
+
+ @Override
+ public DistributionStatusEnum getStatus() {
+ return DistributionStatusEnum.DISTRIBUTION_COMPLETE_OK;
+ }
+
+ @Override
+ public String getDistributionID() {
+ return "FakeDistributionId";
+ }
+ };
+ }
+
+ private IConfiguration buildDistributionClientConfiguration(String topicName, OperationalEnvironmentEntry opEnv) {
+ return new IConfiguration() {
+
+ public String getUser() {
+ return "ci";
+ }
+
+ public int getPollingTimeout() {
+ return 20;
+ }
+
+ public int getPollingInterval() {
+ return 20;
+ }
+
+ public String getPassword() {
+ return "123456";
+ }
+
+ public String getEnvironmentName() {
+ return topicName;
+ }
+
+ public String getConsumerID() {
+ return opEnv.getEnvironmentId();
+ }
+
+ public String getConsumerGroup() {
+ return String.format("BenchMarkDistributionClientConsumerGroup%s", opEnv.getEnvironmentId());
+ }
+
+ public String getAsdcAddress() {
+ return String.format("%s:8443", asdcAddress);
+ }
+
+ @Override
+ public String getKeyStorePath() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getKeyStorePassword() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean activateServerTLSAuth() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public List<String> getRelevantArtifactTypes() {
+ return Arrays.asList(ArtifactTypeEnum.values()).stream()
+ .map(artifactTypeEnum -> artifactTypeEnum.name()).collect(Collectors.toList());
+ }
+
+ @Override
+ public boolean isFilterInEmptyResources() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public Boolean isUseHttpsWithDmaap() {
+ return null;
+ }
+
+ @Override
+ public List<String> getMsgBusAddress() {
+ return opEnv.getDmaapUebAddress().stream().map(this::extractHost).collect(Collectors.toList());
+ }
+
+ private String extractHost(String url) {
+ return url.split(":")[0];
+ }
+ };
+ }
+
+ private void distributeServiceInEnv(OperationalEnvironmentEntry env) {
+ uuidServicesList.stream().forEach(serviceUUID -> distributeSingleService(env, serviceUUID));
+ }
+
+ private void distributeSingleService(OperationalEnvironmentEntry env, String serviceUUID) {
+ IHttpAsdcClient client = new HttpAsdcClient(buildDistributionClientConfiguration(StringUtils.EMPTY, env));
+ String pattern = "/sdc/v1/catalog/services/%s/distribution/%s/activate";
+ String requestUrl = String.format(pattern, serviceUUID, env.getEnvironmentId());
+ String requestBody = String.format("{\"workloadContext\":\"%s\"}", env.getEnvironmentId());
+ StringEntity body = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
+ Map<String, String> headersMap = new HashMap<>();
+ headersMap.put("USER_ID", "cs0008");
+ headersMap.put("X-ECOMP-InstanceID", "test");
+ headersMap.put("Content-Type", "application/json");
+
+ HttpAsdcResponse postRequest = FunctionalInterfaces.retryMethodOnResult(
+ () -> distributeMethod(client, requestUrl, serviceUUID, body, headersMap, env.getEnvironmentId()),
+ resp -> resp.getStatus() == HttpStatus.SC_ACCEPTED);
+ assertThat(postRequest.getStatus(), is(HttpStatus.SC_ACCEPTED));
+
+ }
+
+ private HttpAsdcResponse distributeMethod(IHttpAsdcClient client, String requestUrl, String serviceUUID,
+ StringEntity body, Map<String, String> headersMap, String envId) {
+
+ final HttpAsdcResponse postRequest = client.postRequest(requestUrl, body, headersMap);
+ final String message = String.format(
+ "MSO Client Simulator Distributes Service:%s On Environment:\"%s\" - Recieved Response: %s", serviceUUID, envId,
+ postRequest.getStatus());
+ if (postRequest.getStatus() != HttpStatus.SC_ACCEPTED) {
+ System.err.println(message);
+ } else {
+ System.out.println(message);
+ }
+
+ return postRequest;
+ }
+
+ private String convertUebAddressToList(OperationalEnvironmentEntry op) {
+ Set<String> dmaapUebAddress = op.getDmaapUebAddress();
+ Wrapper<String> resultWrapper = new Wrapper<>(StringUtils.EMPTY);
+ if (!CollectionUtils.isEmpty(dmaapUebAddress)) {
+ dmaapUebAddress.stream()
+ .forEach(uebAddress -> resultWrapper.setInnerElement(resultWrapper.getInnerElement() + uebAddress));
+ }
+
+ return resultWrapper.getInnerElement();
+ }
+
+ private void buildWdSimulatorCallback(OperationalEnvironmentEntry opEnv, IDistributionClient client,
+ final IConfiguration buildDistributionClientConfiguration, INotificationData data) {
+ if (StringUtils.equals(data.getWorkloadContext(), opEnv.getEnvironmentId())) {
+
+ final String expectedArtifactType = org.openecomp.sdc.common.api.ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.name();
+ Optional<IArtifactInfo> optional = data.getServiceArtifacts().stream().filter( artifact -> {
+ return StringUtils.equals(artifact.getArtifactType(), expectedArtifactType);
+ }).findAny();
+
+ for (int i = 0; i < numOfArtifactsToDownload; i++) {
+ optional.ifPresent( artifactInfo -> simulateDownload(client , artifactInfo, data) );
+ optional.orElseThrow( () -> handleArtifactNotFound(expectedArtifactType, data));
+
+ }
+ if( numOfArtifactsToDownload > 0 ){
+ System.out.println(String.format(
+ "ASDC Consumer Simulator On Environment:\"%s\" Downloaded %s Artifacts From ASDC Service with UUID:%s Total Artifacts Downloaded from ASDC is: %s",
+ data.getWorkloadContext(), numOfArtifactsToDownload,
+ data.getServiceUUID(), totalNumOfArtifactsToDownload));
+ }
+
+ IDistributionClientResult finalDistrStatus = client.sendFinalDistrStatus(buildFinalDistribution());
+ assertThat(finalDistrStatus.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
+ wdFinalStatusSent.add(data.getWorkloadContext());
+
+ System.out.println(String.format(
+ "WD Simulator On Environment:\"%s\" Recieved Notification From ASDC On WorkLoad: %s And Service UUID:%s And Sends Distribution Complete Notification",
+ buildDistributionClientConfiguration.getConsumerID(), data.getWorkloadContext(),
+ data.getServiceUUID()));
+ }
+ }
+
+ private IllegalStateException handleArtifactNotFound(String expectedArtifactType, INotificationData data ){
+ final String stringMessage = String.format("Did Not Find Artifact of type: %s to download from service with UUID:%s", expectedArtifactType, data.getServiceUUID());
+ System.err.println(stringMessage);
+ return new IllegalStateException(stringMessage);
+
+ }
+
+ private void simulateDownload(IDistributionClient client, IArtifactInfo info, INotificationData data){
+ IDistributionClientDownloadResult downloadResult = client.download(info);
+ if( downloadResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS ){
+ System.err.println(String.format("Client Simulator %s Failed to download artifact from service : %s", client.getConfiguration().getConsumerID(), data.getServiceUUID()));
+ assertThat(downloadResult.getDistributionActionResult(), is(DistributionActionResultEnum.SUCCESS));
+ }
+ else{
+ totalNumOfArtifactsToDownload++;
+
+ }
+ }
+}
diff --git a/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/utils/RunnerSession.java b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/utils/RunnerSession.java
new file mode 100644
index 0000000000..c93b3d2f0c
--- /dev/null
+++ b/test-apis-ci/src/test/java/org/openecomp/sdc/cucumber/utils/RunnerSession.java
@@ -0,0 +1,61 @@
+package org.openecomp.sdc.cucumber.utils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Store Data here that is relevant for the whole runner and not just a single scenario.
+ * @author ms172g
+ *
+ */
+public class RunnerSession {
+ private static final RunnerSession instance = new RunnerSession();
+ private Map<String, String> stringElements;
+ private Map<String, Integer> intElements;
+ private Map<String, Object> elements;
+ private RunnerSession(){
+ stringElements = new HashMap<>();
+ intElements = new HashMap<>();
+ elements = new HashMap<>();
+ }
+ public static RunnerSession getSession(){
+ return instance;
+ }
+
+ public void putInSession(String key, String value){
+ stringElements.put(key, value);
+ }
+
+ public String getString(String key){
+ return stringElements.get(key);
+
+ }
+
+ public void putInSession(String key, Integer value){
+ intElements.put(key, value);
+ }
+
+
+ public Integer getInt(String key){
+ return intElements.get(key);
+ }
+
+ public void putInSession(String key, Object value) {
+ elements.put(key, value);
+
+ }
+
+ public Object get(String key){
+ return elements.get(key);
+ }
+
+ public void clean(){
+ intElements.clear();
+ stringElements.clear();
+ }
+
+
+
+
+
+}
diff --git a/test-apis-ci/src/test/resources/CI/tests/tenantIsolationCI/aai_error.properties b/test-apis-ci/src/test/resources/CI/tests/tenantIsolationCI/aai_error.properties
new file mode 100644
index 0000000000..b4ae9e332b
--- /dev/null
+++ b/test-apis-ci/src/test/resources/CI/tests/tenantIsolationCI/aai_error.properties
@@ -0,0 +1,10 @@
+400=Bad Request
+401=Unauthorized
+403=Forbidden
+404=Not Found
+405=Method Not Allowed
+409=The request could not be completed due to a conflict with the current state of the target resource
+410=You are using a version of the API that has been retired
+412=Precondition failed
+415=Unsupported Media Type
+500=Internal Server Error \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/catalogMgmtTest.properties b/test-apis-ci/src/test/resources/catalogMgmtTest.properties
new file mode 100644
index 0000000000..7a26a0c905
--- /dev/null
+++ b/test-apis-ci/src/test/resources/catalogMgmtTest.properties
@@ -0,0 +1,34 @@
+TransportType=DME2
+Latitude =32.109333
+Longitude =34.855499
+Version =1.0
+ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+Environment =TEST
+Partner=BOT_R
+routeOffer=MR1
+SubContextPath =/
+Protocol =http
+MethodType =POST
+username = m09875@sdc.att.com
+password =Aa123456
+contenttype = application/json
+Authorization = Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2
+authKey=
+authDate=
+#Dmaap Server Url port 3904-HTTP 3905-https
+host=olsd004.wnsnet.attws.com:3904
+###topic=com.att.ccd.CCD-CatalogManagement-go539p or com.att.sdc.SDCforTestDev | com.att.sdc.23911-SDCforTestDev-v001
+topic=com.att.sdc.23911-SDCforTestDev-v001
+partition=1
+maxBatchSize=100
+maxAgeMs=250
+AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler
+AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler
+AFT_DME2_REQ_TRACE_ON=true
+AFT_ENVIRONMENT=AFTUAT
+AFT_DME2_EP_CONN_TIMEOUT=15000
+AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000
+AFT_DME2_EP_READ_TIMEOUT_MS=50000
+sessionstickinessrequired=NO
+DME2preferredRouterFilePath=src/test/resources/preferredRouter.txt
+MessageSentThreadOccurance=50 \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/catalogMgmtTest.yaml b/test-apis-ci/src/test/resources/catalogMgmtTest.yaml
new file mode 100644
index 0000000000..ee419f4f50
--- /dev/null
+++ b/test-apis-ci/src/test/resources/catalogMgmtTest.yaml
@@ -0,0 +1,6 @@
+publisherPropertiesFilePath: "catalogMgmtTest.properties"
+topicMessages:
+ - "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"product\"],\"republish\":\"No\",\"Authorization\": \"Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"logo\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"availabilitymatrix\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"product\",\"availabilitymatrix\"],\"republish\":\"No\"}" \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/config/configuration1.yaml b/test-apis-ci/src/test/resources/config/configuration1.yaml
new file mode 100644
index 0000000000..12ab2c777f
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/configuration1.yaml
@@ -0,0 +1,17 @@
+version: 1.0
+released: 2012-11-30
+
+# Connection parameters
+connection:
+ url: jdbc:mysql://localhost:3306/db
+ poolSize: 5
+
+# Protocols
+protocols:
+ - http
+ - https
+
+# Users
+users:
+ tom: passwd
+ bob: passwd \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/config/elasticsearch.yml b/test-apis-ci/src/test/resources/config/elasticsearch.yml
new file mode 100644
index 0000000000..a6a2c1b950
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/elasticsearch.yml
@@ -0,0 +1,387 @@
+
+cluster.name: elasticsearch_1_5_2
+
+discovery.zen.ping.multicast.enabled: false
+discovery.zen.ping.unicast.enabled: true
+discovery.zen.ping.unicast.hosts: elasticsearch_host
+
+
+
+##################### Elasticsearch Configuration Example #####################
+
+# This file contains an overview of various configuration settings,
+# targeted at operations staff. Application developers should
+# consult the guide at <http://elasticsearch.org/guide>.
+#
+# The installation procedure is covered at
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup.html>.
+#
+# Elasticsearch comes with reasonable defaults for most settings,
+# so you can try it out without bothering with configuration.
+#
+# Most of the time, these defaults are just fine for running a production
+# cluster. If you're fine-tuning your cluster, or wondering about the
+# effect of certain configuration option, please _do ask_ on the
+# mailing list or IRC channel [http://elasticsearch.org/community].
+
+# Any element in the configuration can be replaced with environment variables
+# by placing them in ${...} notation. For example:
+#
+# node.rack: ${RACK_ENV_VAR}
+
+# For information on supported formats and syntax for the config file, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup-configuration.html>
+
+
+################################### Cluster ###################################
+
+# Cluster name identifies your cluster for auto-discovery. If you're running
+# multiple clusters on the same network, make sure you're using unique names.
+#
+# cluster.name: elasticsearch
+
+
+#################################### Node #####################################
+
+# Node names are generated dynamically on startup, so you're relieved
+# from configuring them manually. You can tie this node to a specific name:
+#
+# node.name: "Franz Kafka"
+
+# Every node can be configured to allow or deny being eligible as the master,
+# and to allow or deny to store the data.
+#
+# Allow this node to be eligible as a master node (enabled by default):
+#
+# node.master: true
+#
+# Allow this node to store data (enabled by default):
+#
+# node.data: true
+
+# You can exploit these settings to design advanced cluster topologies.
+#
+# 1. You want this node to never become a master node, only to hold data.
+# This will be the "workhorse" of your cluster.
+#
+# node.master: false
+# node.data: true
+#
+# 2. You want this node to only serve as a master: to not store any data and
+# to have free resources. This will be the "coordinator" of your cluster.
+#
+# node.master: true
+# node.data: false
+#
+# 3. You want this node to be neither master nor data node, but
+# to act as a "search load balancer" (fetching data from nodes,
+# aggregating results, etc.)
+#
+# node.master: false
+# node.data: false
+
+# Use the Cluster Health API [http://localhost:9200/_cluster/health], the
+# Node Info API [http://localhost:9200/_nodes] or GUI tools
+# such as <http://www.elasticsearch.org/overview/marvel/>,
+# <http://github.com/karmi/elasticsearch-paramedic>,
+# <http://github.com/lukas-vlcek/bigdesk> and
+# <http://mobz.github.com/elasticsearch-head> to inspect the cluster state.
+
+# A node can have generic attributes associated with it, which can later be used
+# for customized shard allocation filtering, or allocation awareness. An attribute
+# is a simple key value pair, similar to node.key: value, here is an example:
+#
+# node.rack: rack314
+
+# By default, multiple nodes are allowed to start from the same installation location
+# to disable it, set the following:
+# node.max_local_storage_nodes: 1
+
+
+#################################### Index ####################################
+
+# You can set a number of options (such as shard/replica options, mapping
+# or analyzer definitions, translog settings, ...) for indices globally,
+# in this file.
+#
+# Note, that it makes more sense to configure index settings specifically for
+# a certain index, either when creating it or by using the index templates API.
+#
+# See <http://elasticsearch.org/guide/en/elasticsearch/reference/current/index-modules.html> and
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
+# for more information.
+
+# Set the number of shards (splits) of an index (5 by default):
+#
+# index.number_of_shards: 5
+
+# Set the number of replicas (additional copies) of an index (1 by default):
+#
+# index.number_of_replicas: 1
+
+# Note, that for development on a local machine, with small indices, it usually
+# makes sense to "disable" the distributed features:
+#
+index.number_of_shards: 1
+index.number_of_replicas: 0
+
+# These settings directly affect the performance of index and search operations
+# in your cluster. Assuming you have enough machines to hold shards and
+# replicas, the rule of thumb is:
+#
+# 1. Having more *shards* enhances the _indexing_ performance and allows to
+# _distribute_ a big index across machines.
+# 2. Having more *replicas* enhances the _search_ performance and improves the
+# cluster _availability_.
+#
+# The "number_of_shards" is a one-time setting for an index.
+#
+# The "number_of_replicas" can be increased or decreased anytime,
+# by using the Index Update Settings API.
+#
+# Elasticsearch takes care about load balancing, relocating, gathering the
+# results from nodes, etc. Experiment with different settings to fine-tune
+# your setup.
+
+# Use the Index Status API (<http://localhost:9200/A/_status>) to inspect
+# the index status.
+
+
+#################################### Paths ####################################
+
+# Path to directory containing configuration (this file and logging.yml):
+#
+path.conf: /src/test/resources
+
+# Path to directory where to store index data allocated for this node.
+#
+path.data: target/esdata
+#
+# Can optionally include more than one location, causing data to be striped across
+# the locations (a la RAID 0) on a file level, favouring locations with most free
+# space on creation. For example:
+#
+# path.data: /path/to/data1,/path/to/data2
+
+# Path to temporary files:
+#
+path.work: /target/eswork
+
+# Path to log files:
+#
+path.logs: /target/eslogs
+
+# Path to where plugins are installed:
+#
+# path.plugins: /path/to/plugins
+
+
+#################################### Plugin ###################################
+
+# If a plugin listed here is not installed for current node, the node will not start.
+#
+# plugin.mandatory: mapper-attachments,lang-groovy
+
+
+################################### Memory ####################################
+
+# Elasticsearch performs poorly when JVM starts swapping: you should ensure that
+# it _never_ swaps.
+#
+# Set this property to true to lock the memory:
+#
+# bootstrap.mlockall: true
+
+# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set
+# to the same value, and that the machine has enough memory to allocate
+# for Elasticsearch, leaving enough memory for the operating system itself.
+#
+# You should also make sure that the Elasticsearch process is allowed to lock
+# the memory, eg. by using `ulimit -l unlimited`.
+
+
+############################## Network And HTTP ###############################
+
+# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens
+# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node
+# communication. (the range means that if the port is busy, it will automatically
+# try the next port).
+
+# Set the bind address specifically (IPv4 or IPv6):
+#
+# network.bind_host: 192.168.0.1
+
+# Set the address other nodes will use to communicate with this node. If not
+# set, it is automatically derived. It must point to an actual IP address.
+#
+# network.publish_host: 192.168.0.1
+
+# Set both 'bind_host' and 'publish_host':
+#
+# network.host: 192.168.0.1
+
+# Set a custom port for the node to node communication (9300 by default):
+#
+# transport.tcp.port: 9300
+
+# Enable compression for all communication between nodes (disabled by default):
+#
+# transport.tcp.compress: true
+
+# Set a custom port to listen for HTTP traffic:
+#
+# http.port: 9200
+
+# Set a custom allowed content length:
+#
+# http.max_content_length: 100mb
+
+# Disable HTTP completely:
+#
+# http.enabled: false
+
+
+################################### Gateway ###################################
+
+# The gateway allows for persisting the cluster state between full cluster
+# restarts. Every change to the state (such as adding an index) will be stored
+# in the gateway, and when the cluster starts up for the first time,
+# it will read its state from the gateway.
+
+# There are several types of gateway implementations. For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-gateway.html>.
+
+# The default gateway type is the "local" gateway (recommended):
+#
+# gateway.type: local
+
+# Settings below control how and when to start the initial recovery process on
+# a full cluster restart (to reuse as much local data as possible when using shared
+# gateway).
+
+# Allow recovery process after N nodes in a cluster are up:
+#
+gateway.recover_after_nodes: 1
+
+# Set the timeout to initiate the recovery process, once the N nodes
+# from previous setting are up (accepts time value):
+#
+# gateway.recover_after_time: 5m
+
+# Set how many nodes are expected in this cluster. Once these N nodes
+# are up (and recover_after_nodes is met), begin recovery process immediately
+# (without waiting for recover_after_time to expire):
+#
+gateway.expected_nodes: 1
+
+
+############################# Recovery Throttling #############################
+
+# These settings allow to control the process of shards allocation between
+# nodes during initial recovery, replica allocation, rebalancing,
+# or when adding and removing nodes.
+
+# Set the number of concurrent recoveries happening on a node:
+#
+# 1. During the initial recovery
+#
+# cluster.routing.allocation.node_initial_primaries_recoveries: 4
+#
+# 2. During adding/removing nodes, rebalancing, etc
+#
+# cluster.routing.allocation.node_concurrent_recoveries: 2
+
+# Set to throttle throughput when recovering (eg. 100mb, by default 20mb):
+#
+# indices.recovery.max_bytes_per_sec: 20mb
+
+# Set to limit the number of open concurrent streams when
+# recovering a shard from a peer:
+#
+# indices.recovery.concurrent_streams: 5
+
+
+################################## Discovery ##################################
+
+# Discovery infrastructure ensures nodes can be found within a cluster
+# and master node is elected. Multicast discovery is the default.
+
+# Set to ensure a node sees N other master eligible nodes to be considered
+# operational within the cluster. Its recommended to set it to a higher value
+# than 1 when running more than 2 nodes in the cluster.
+#
+# discovery.zen.minimum_master_nodes: 1
+
+# Set the time to wait for ping responses from other nodes when discovering.
+# Set this option to a higher value on a slow or congested network
+# to minimize discovery failures:
+#
+# discovery.zen.ping.timeout: 3s
+
+# For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-zen.html>
+
+# Unicast discovery allows to explicitly control which nodes will be used
+# to discover the cluster. It can be used when multicast is not present,
+# or to restrict the cluster communication-wise.
+#
+# 1. Disable multicast discovery (enabled by default):
+#
+# discovery.zen.ping.multicast.enabled: false
+#
+# 2. Configure an initial list of master nodes in the cluster
+# to perform discovery when new nodes (master or data) are started:
+#
+# discovery.zen.ping.unicast.hosts: ["host1", "host2:port"]
+
+# EC2 discovery allows to use AWS EC2 API in order to perform discovery.
+#
+# You have to install the cloud-aws plugin for enabling the EC2 discovery.
+#
+# For more information, see
+# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-ec2.html>
+#
+# See <http://elasticsearch.org/tutorials/elasticsearch-on-ec2/>
+# for a step-by-step tutorial.
+
+# GCE discovery allows to use Google Compute Engine API in order to perform discovery.
+#
+# You have to install the cloud-gce plugin for enabling the GCE discovery.
+#
+# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-gce>.
+
+# Azure discovery allows to use Azure API in order to perform discovery.
+#
+# You have to install the cloud-azure plugin for enabling the Azure discovery.
+#
+# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-azure>.
+
+################################## Slow Log ##################################
+
+# Shard level query and fetch threshold logging.
+
+#index.search.slowlog.threshold.query.warn: 10s
+#index.search.slowlog.threshold.query.info: 5s
+#index.search.slowlog.threshold.query.debug: 2s
+#index.search.slowlog.threshold.query.trace: 500ms
+
+#index.search.slowlog.threshold.fetch.warn: 1s
+#index.search.slowlog.threshold.fetch.info: 800ms
+#index.search.slowlog.threshold.fetch.debug: 500ms
+#index.search.slowlog.threshold.fetch.trace: 200ms
+
+#index.indexing.slowlog.threshold.index.warn: 10s
+#index.indexing.slowlog.threshold.index.info: 5s
+#index.indexing.slowlog.threshold.index.debug: 2s
+#index.indexing.slowlog.threshold.index.trace: 500ms
+
+################################## GC Logging ################################
+
+#monitor.jvm.gc.young.warn: 1000ms
+#monitor.jvm.gc.young.info: 700ms
+#monitor.jvm.gc.young.debug: 400ms
+
+#monitor.jvm.gc.old.warn: 10s
+#monitor.jvm.gc.old.info: 5s
+#monitor.jvm.gc.old.debug: 2s
+
diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/DME2preferredRouter.txt b/test-apis-ci/src/test/resources/config/test-apis-ci/DME2preferredRouter.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/test-apis-ci/DME2preferredRouter.txt
diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml
new file mode 100644
index 0000000000..f138ba15e5
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/test-apis-ci/configuration.yaml
@@ -0,0 +1,677 @@
+identificationHeaderFields:
+ - HTTP_IV_USER
+ - HTTP_CSP_FIRSTNAME
+ - HTTP_CSP_LASTNAME
+ - HTTP_IV_REMOTE_ADDRESS
+ - HTTP_CSP_WSTYPE
+
+# catalog backend hostname
+beFqdn: localhost
+# sdccatalog.att.com
+
+# catalog backend http port
+beHttpPort: 8080
+
+# catalog backend http context
+beContext: /sdc/rest/config/get
+
+# catalog backend protocol
+beProtocol: http
+
+# catalog backend ssl port
+beSslPort: 8443
+
+version: 1.1.0
+released: 2012-11-30
+toscaConformanceLevel: 5.0
+minToscaConformanceLevel: 3.0
+
+titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
+titanInMemoryGraph: false
+titanLockTimeout: 1800
+
+# The interval to try and reconnect to titan DB when it is down during ASDC startup:
+titanReconnectIntervalInSeconds: 3
+
+# The read timeout towards Titan DB when health check is invoked:
+titanHealthCheckReadTimeout: 1
+
+# The interval to try and reconnect to Elasticsearch when it is down during ASDC startup:
+esReconnectIntervalInSeconds: 3
+uebHealthCheckReconnectIntervalInSeconds: 15
+uebHealthCheckReadTimeout: 4
+
+# Protocols
+protocols:
+ - http
+ - https
+
+# Default imports
+defaultImports:
+ - nodes:
+ file: nodes.yml
+ - datatypes:
+ file: data.yml
+ - capabilities:
+ file: capabilities.yml
+ - relationships:
+ file: relationships.yml
+ - groups:
+ file: groups.yml
+ - policies:
+ file: policies.yml
+
+# Users
+users:
+ tom: passwd
+ bob: passwd
+
+neo4j:
+ host: neo4jhost
+ port: 7474
+ user: neo4j
+ password: "12345"
+
+cassandraConfig:
+ cassandraHosts: ['localhost']
+ localDataCenter: datacenter1
+ reconnectTimeout : 30000
+ authenticate: false
+ username: koko
+ password: bobo
+ ssl: false
+ truststorePath : /path/path
+ truststorePassword : 123123
+ keySpaces:
+ - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+
+#Application-specific settings of ES
+elasticSearch:
+ # Mapping of index prefix to time-based frame. For example, if below is configured:
+ #
+ # - indexPrefix: auditingevents
+ # creationPeriod: minute
+ #
+ # then ES object of type which is mapped to "auditingevents-*" template, and created on 2015-12-23 13:24:54, will enter "auditingevents-2015-12-23-13-24" index.
+ # Another object created on 2015-12-23 13:25:54, will enter "auditingevents-2015-12-23-13-25" index.
+ # If creationPeriod: month, both of the above will enter "auditingevents-2015-12" index.
+ #
+ # PLEASE NOTE: the timestamps are created in UTC/GMT timezone! This is needed so that timestamps will be correctly presented in Kibana.
+ #
+ # Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour).
+ #
+ # If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month.
+
+ indicesTimeFrequency:
+ - indexPrefix: auditingevents
+ creationPeriod: month
+ - indexPrefix: monitoring_events
+ creationPeriod: month
+
+artifactTypes:
+ - CHEF
+ - PUPPET
+ - SHELL
+ - YANG
+ - YANG_XML
+ - HEAT
+ - BPEL
+ - DG_XML
+ - MURANO_PKG
+ - WORKFLOW
+ - NETWORK_CALL_FLOW
+ - TOSCA_TEMPLATE
+ - TOSCA_CSAR
+ - AAI_SERVICE_MODEL
+ - AAI_VF_MODEL
+ - AAI_VF_MODULE_MODEL
+ - AAI_VF_INSTANCE_MODEL
+ - OTHER
+ - SNMP_POLL
+ - SNMP_TRAP
+ - GUIDE
+
+licenseTypes:
+ - User
+ - Installation
+ - CPU
+
+#Deployment artifacts placeHolder
+resourceTypes: &allResourceTypes
+ - VFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - CVFC
+
+# validForResourceTypes usage
+# validForResourceTypes:
+# - VF
+# - VL
+deploymentResourceArtifacts:
+# heat:
+# displayName: "Base HEAT Template"
+# type: HEAT
+# validForResourceTypes: *allResourceTypes
+# heatVol:
+# displayName: "Volume HEAT Template"
+# type: HEAT_VOL
+# validForResourceTypes: *allResourceTypes
+# heatNet:
+# displayName: "Network HEAT Template"
+# type: HEAT_NET
+# validForResourceTypes: *allResourceTypes
+
+deploymentResourceInstanceArtifacts:
+ heatEnv:
+ displayName: "HEAT ENV"
+ type: HEAT_ENV
+ description: "Auto-generated HEAT Environment deployment artifact"
+ fileExtension: "env"
+ VfHeatEnv:
+ displayName: "VF HEAT ENV"
+ type: HEAT_ENV
+ description: "VF Auto-generated HEAT Environment deployment artifact"
+ fileExtension: "env"
+
+#tosca artifacts placeholders
+toscaArtifacts:
+ assetToscaTemplate:
+ artifactName: -template.yml
+ displayName: Tosca Template
+ type: TOSCA_TEMPLATE
+ description: TOSCA representation of the asset
+ assetToscaCsar:
+ artifactName: -csar.csar
+ displayName: Tosca Model
+ type: TOSCA_CSAR
+ description: TOSCA definition package of the asset
+
+
+#Informational artifacts placeHolder
+excludeResourceCategory:
+ - Generic
+excludeResourceType:
+ - PNF
+informationalResourceArtifacts:
+ features:
+ displayName: Features
+ type: OTHER
+ capacity:
+ displayName: Capacity
+ type: OTHER
+ vendorTestResult:
+ displayName: Vendor Test Result
+ type: OTHER
+ testScripts:
+ displayName: Test Scripts
+ type: OTHER
+ CloudQuestionnaire:
+ displayName: Cloud Questionnaire (completed)
+ type: OTHER
+ HEATTemplateFromVendor:
+ displayName: HEAT Template from Vendor
+ type: HEAT
+ resourceSecurityTemplate:
+ displayName: Resource Security Template
+ type: OTHER
+
+excludeServiceCategory:
+
+informationalServiceArtifacts:
+ serviceArtifactPlan:
+ displayName: Service Artifact Plan
+ type: OTHER
+ summaryOfImpactsToECOMPElements:
+ displayName: Summary of impacts to ECOMP elements,OSSs, BSSs
+ type: OTHER
+ controlLoopFunctions:
+ displayName: Control Loop Functions
+ type: OTHER
+ dimensioningInfo:
+ displayName: Dimensioning Info
+ type: OTHER
+ affinityRules:
+ displayName: Affinity Rules
+ type: OTHER
+ operationalPolicies:
+ displayName: Operational Policies
+ type: OTHER
+ serviceSpecificPolicies:
+ displayName: Service-specific Policies
+ type: OTHER
+ engineeringRules:
+ displayName: Engineering Rules (ERD)
+ type: OTHER
+ distributionInstructions:
+ displayName: Distribution Instructions
+ type: OTHER
+ certificationTestResults:
+ displayName: TD Certification Test Results
+ type: OTHER
+ deploymentVotingRecord:
+ displayName: Deployment Voting Record
+ type: OTHER
+ serviceQuestionnaire:
+ displayName: Service Questionnaire
+ type: OTHER
+ serviceSecurityTemplate:
+ displayName: Service Security Template
+ type: OTHER
+
+serviceApiArtifacts:
+ configuration:
+ displayName: Configuration
+ type: OTHER
+ instantiation:
+ displayName: Instantiation
+ type: OTHER
+ monitoring:
+ displayName: Monitoring
+ type: OTHER
+ reporting:
+ displayName: Reporting
+ type: OTHER
+ logging:
+ displayName: Logging
+ type: OTHER
+ testing:
+ displayName: Testing
+ type: OTHER
+
+additionalInformationMaxNumberOfKeys: 50
+
+systemMonitoring:
+ enabled: false
+ isProxy: false
+ probeIntervalInSeconds: 15
+
+defaultHeatArtifactTimeoutMinutes: 60
+
+serviceDeploymentArtifacts:
+ YANG_XML:
+ acceptedTypes:
+ - xml
+ VNF_CATALOG:
+ acceptedTypes:
+ - xml
+ MODEL_INVENTORY_PROFILE:
+ acceptedTypes:
+ - xml
+ MODEL_QUERY_SPEC:
+ acceptedTypes:
+ - xml
+ UCPE_LAYER_2_CONFIGURATION:
+ acceptedTypes:
+ - xml
+
+#AAI Artifacts
+ AAI_SERVICE_MODEL:
+ acceptedTypes:
+ - xml
+ AAI_VF_MODULE_MODEL:
+ acceptedTypes:
+ - xml
+ AAI_VF_INSTANCE_MODEL:
+ acceptedTypes:
+ - xml
+ OTHER:
+ acceptedTypes:
+
+resourceDeploymentArtifacts:
+ HEAT:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ HEAT_VOL:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ HEAT_NET:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ HEAT_NESTED:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ HEAT_ARTIFACT:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ YANG_XML:
+ acceptedTypes:
+ - xml
+ validForResourceTypes: *allResourceTypes
+ VNF_CATALOG:
+ acceptedTypes:
+ - xml
+ validForResourceTypes: *allResourceTypes
+ VF_LICENSE:
+ acceptedTypes:
+ - xml
+ validForResourceTypes: *allResourceTypes
+ VENDOR_LICENSE:
+ acceptedTypes:
+ - xml
+ validForResourceTypes: *allResourceTypes
+ MODEL_INVENTORY_PROFILE:
+ acceptedTypes:
+ - xml
+ validForResourceTypes: *allResourceTypes
+ MODEL_QUERY_SPEC:
+ acceptedTypes:
+ - xml
+ validForResourceTypes: *allResourceTypes
+ LIFECYCLE_OPERATIONS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes:
+ - VF
+ - VFC
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ validForResourceTypes: *allResourceTypes
+ APPC_CONFIG:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ DCAE_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_JSON:
+ acceptedTypes:
+ - json
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_POLICY:
+ acceptedTypes:
+ - emf
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_DOC:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_EVENT:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ AAI_VF_MODEL:
+ acceptedTypes:
+ - xml
+ validForResourceTypes:
+ - VF
+ AAI_VF_MODULE_MODEL:
+ acceptedTypes:
+ - xml
+ validForResourceTypes:
+ - VF
+ OTHER:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+
+resourceInstanceDeploymentArtifacts:
+ HEAT_ENV:
+ acceptedTypes:
+ - env
+ VF_MODULES_METADATA:
+ acceptedTypes:
+ - json
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ DCAE_INVENTORY_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ DCAE_INVENTORY_JSON:
+ acceptedTypes:
+ - json
+ DCAE_INVENTORY_POLICY:
+ acceptedTypes:
+ - emf
+ DCAE_INVENTORY_DOC:
+ acceptedTypes:
+ DCAE_INVENTORY_BLUEPRINT:
+ acceptedTypes:
+ DCAE_INVENTORY_EVENT:
+ acceptedTypes:
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+
+resourceInformationalArtifacts:
+ CHEF:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ PUPPET:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SHELL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ YANG:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ YANG_XML:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ HEAT:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ BPEL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ DG_XML:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ MURANO_PKG:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ OTHER:
+ acceptedTypes:
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
+ SNMP_POLL:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ SNMP_TRAP:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
+ GUIDE:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFC
+ - CVFC
+
+resourceInformationalDeployedArtifacts:
+
+requirementsToFulfillBeforeCert:
+
+capabilitiesToConsumeBeforeCert:
+
+unLoggedUrls:
+ - /sdc2/rest/healthCheck
+
+cleanComponentsConfiguration:
+ cleanIntervalInMinutes: 1440
+ componentsToClean:
+ - Resource
+ - Service
+
+artifactsIndex: resources
+
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
+
+onboarding:
+ protocol: http
+ host: localhost
+ port: 8080
+ downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
+
+dcae:
+ protocol: http
+ host: 127.0.0.1
+ port: 8080
+ healthCheckUri: "/dcae/healthCheck"
+
+switchoverDetector:
+ gBeFqdn: AIO-BE.ecomp.idns.cip.com
+ gFeFqdn: AIO-FE.ecomp.idns.cip.com
+ beVip: 0.0.0.0
+ feVip: 0.0.0.0
+ beResolveAttempts: 3
+ feResolveAttempts: 3
+ enabled: false
+ interval: 60
+ changePriorityUser: ecompasdc
+ changePriorityPassword: ecompasdc123
+ publishNetworkUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/update_network?user=root"
+ publishNetworkBody: '{"note":"publish network"}'
+ groups:
+ beSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.com?user=root",
+ changePriorityBody: '{"name":"AIO-BE.ecomp.idns.com","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.com","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'}
+ feSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com?user=root",
+ changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.com","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com"}'}
+
+applicationL1Cache:
+ datatypes:
+ enabled: true
+ firstRunDelay: 10
+ pollIntervalInSec: 60
+
+applicationL2Cache:
+ enabled: true
+ catalogL1Cache:
+ enabled: true
+ resourcesSizeInCache: 300
+ servicesSizeInCache: 200
+ productsSizeInCache: 100
+ queue:
+ syncIntervalInSecondes: 43200
+ waitOnShutDownInMinutes: 10
+ numberOfCacheWorkers: 4
+
+toscaValidators:
+ stringMaxLength: 2500
+
+disableAudit: false
+
+vfModuleProperties:
+ min_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ max_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule:
+ initial_count:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ vf_module_type:
+ forBaseModule: Base
+ forNonBaseModule: Expansion
+
+genericAssetNodeTypes:
+ VFC: org.openecomp.resource.abstract.nodes.VFC
+ CVFC: org.openecomp.resource.abstract.nodes.VFC
+ VF : org.openecomp.resource.abstract.nodes.VF
+ PNF: org.openecomp.resource.abstract.nodes.PNF
+ Service: org.openecomp.resource.abstract.nodes.service
+
+workloadContext: Production
+environmentContext:
+ defaultValue: General_Revenue-Bearing
+ validValues:
+ - Critical_Revenue-Bearing
+ - Vital_Revenue-Bearing
+ - Essential_Revenue-Bearing
+ - Important_Revenue-Bearing
+ - Needed_Revenue-Bearing
+ - Useful_Revenue-Bearing
+ - General_Revenue-Bearing
+ - Critical_Non-Revenue
+ - Vital_Non-Revenue
+ - Essential_Non-Revenue
+ - Important_Non-Revenue
+ - Needed_Non-Revenue
+ - Useful_Non-Revenue
+ - General_Non-Revenue
+
+dmaapConsumerConfiguration:
+ hosts: olsd004.wnsnet.attws.com:3905
+ consumerGroup: asdc
+ consumerId: mama
+ timeoutMs: 15000
+ limit: 1
+ pollingInterval: 2
+ topic: com.att.sdc.23911-SDCforTestDev-v001
+ latitude: 32.109333
+ longitude: 34.855499
+ version: 1.0
+ serviceName: dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+ environment: TEST
+ partner: BOT_R
+ routeOffer: MR1
+ protocol: https
+ contenttype: application/json
+ dme2TraceOn: true
+ aftEnvironment: AFTUAT
+ aftDme2ConnectionTimeoutMs: 15000
+ aftDme2RoundtripTimeoutMs: 240000
+ aftDme2ReadTimeoutMs: 50000
+ dme2preferredRouterFilePath: DME2preferredRouter.txt
+ timeLimitForNotificationHandleMs: 0
+ credential:
+ username: m09875@sdc.att.com
+ password: hmXYcznAljMSisdy8zgcag==
+
+dmeConfiguration:
+ dme2Search: DME2SEARCH
+ dme2Resolve: DME2RESOLVE
diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/distribution-engine-configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/distribution-engine-configuration.yaml
new file mode 100644
index 0000000000..00ae8f59c0
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/test-apis-ci/distribution-engine-configuration.yaml
@@ -0,0 +1,77 @@
+uebServers:
+ - uebsb91kcdc.it.att.com
+ - uebsb92kcdc.it.att.com
+# - uebsb93kcdc.it.att.com
+
+uebPublicKey: 8F3MDAtMSBwwpSMy
+
+uebSecretKey: gzFmsTxSCtO5RQfAccM6PqqX
+
+distributionNotifTopicName: ASDC-DISTR-NOTIF-TOPIC
+distributionStatusTopicName: ASDC-DISTR-STATUS-TOPIC
+
+initRetryIntervalSec: 5
+initMaxIntervalSec: 60
+
+distribNotifServiceArtifactTypes:
+ info:
+ - MURANO-PKG
+
+distribNotifResourceArtifactTypes:
+ lifecycle:
+ - HEAT
+ - DG-XML
+
+environments:
+ - PROD
+
+distributionStatusTopic:
+ pollingIntervalSec: 60
+ fetchTimeSec: 15
+ consumerGroup: asdc
+ consumerId: asdc-id
+
+distributionNotificationTopic:
+ minThreadPoolSize: 0
+ maxThreadPoolSize: 10
+ maxWaitingAfterSendingSeconds: 5
+
+createTopic:
+ partitionCount: 1
+ replicationCount: 1
+
+startDistributionEngine: true
+
+
+aaiConfig:
+ serverRootUrl: https://127.0.0.1/aai/v1
+ resourceNamespaces:
+ operationalEnvironments: /aai/cloud-infrastructure/operational-environments
+
+ httpRequestConfig:
+ readTimeoutMs: 5000
+ connectTimeoutMs: 1000
+ maxReadConnectionRetry: 3
+ userName: abcd
+ password: hmXYcznAljMSisdy8zgcag==
+ clientSslAuthentication: false
+ keyStore: opt/app/catalog-be/cert/.keystore
+ keyStorePassword: hmXYcznAljMSisdy8zgcag==
+
+ httpRequestHeaders:
+ XFromAppId: asdc
+
+opEnvRecoveryIntervalSec: 180
+allowedTimeBeforeStaleSec: 300
+
+msoConfig:
+ serverRootUrl: https://127.0.0.1/onap/so/infra/modelDistributions/v1
+ resourceNamespaces:
+ distributions: /distributions
+
+ httpClientConfig:
+ readTimeout: 2000
+ connectTimeout: 500
+ numOfRetries: 3
+ userName: asdc
+ password: OTLEp5lfVhYdyw5EAtTUBQ== \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/ecomp-error-configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/ecomp-error-configuration.yaml
new file mode 100644
index 0000000000..9d7cd74a2b
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/test-apis-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/asdc-tests/src/test/resources/CI/error-configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/error-configuration.yaml
index 33207def3b..5494c2fce3 100644
--- a/asdc-tests/src/test/resources/CI/error-configuration.yaml
+++ b/test-apis-ci/src/test/resources/config/test-apis-ci/error-configuration.yaml
@@ -8,101 +8,112 @@ errors:
code: 201,
message: "OK"
}
+ ACCEPTED: {
+ code: 202,
+ message: "Accepted"
+ }
NO_CONTENT: {
code: 204,
message: "No Content"
}
-#--------POL4050-----------------------------
+#--------POL4050-----------------------------
NOT_ALLOWED: {
code: 405,
message: "Error: Method not allowed.",
messageId: "POL4050"
}
-#--------POL5000-----------------------------
+#--------POL5000-----------------------------
GENERAL_ERROR: {
code: 500,
message: "Error: Internal Server Error. Please try again later.",
messageId: "POL5000"
}
-#---------POL5001------------------------------
+#---------POL5001------------------------------
MISSING_X_ECOMP_INSTANCE_ID: {
code: 400 ,
message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.",
messageId: "POL5001"
}
-#---------POL5002------------------------------
+#---------POL5002------------------------------
AUTH_REQUIRED: {
code: 401 ,
message: "Error: Authentication is required to use the API.",
messageId: "POL5002"
}
-#---------POL5003------------------------------
+#---------POL5003------------------------------
AUTH_FAILED: {
code: 403 ,
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
-#---------SVC4000-----------------------------
+#---------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-----------------------------
+#---------SVC4002-----------------------------
MISSING_INFORMATION: {
code: 403,
message: "Error: Missing information.",
messageId: "SVC4002"
}
-#---------SVC4003------------------------------
-# %1 - Users's USER ID
+#---------SVC4003------------------------------
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
messageId: "SVC4003"
}
-#---------SVC4004-----------------------------
-# %1 - Users's email address
+#---------SVC4004-----------------------------
+# %1 - Users's email address
INVALID_EMAIL_ADDRESS: {
code: 400,
message: "Error: Invalid email address '%1'.",
messageId: "SVC4004"
}
-#---------SVC4005------------------------------
+#---------SVC4005------------------------------
# %1 - role
INVALID_ROLE: {
code: 400,
message: "Error: Invalid role '%1'.",
messageId: "SVC4005"
}
-#---------SVC4006------------------------------
-# %1 - Users's USER ID
+#---------SVC4006------------------------------
+# %1 - Users's USER_ID
USER_ALREADY_EXIST: {
code: 409,
message: "Error: User with '%1' ID already exists.",
messageId: "SVC4006"
}
-#---------SVC4007------------------------------
+#---------SVC4007------------------------------
DELETE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator can only be deleted by another administrator.",
messageId: "SVC4007"
}
-#---------SVC4008-----------------------------
-# %1 - Users's USER ID
+#---------SVC4008-----------------------------
+# %1 - Users's userId
INVALID_USER_ID: {
code: 400,
message: "Error: Invalid userId '%1'.",
messageId: "SVC4008"
}
-#---------SVC4049------------------------------
+
+#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
- message: "Error: Invalid Content. Missing %1 Contact Id.",
- messageId: "SVC4049"
- }
-#---------SVC4050-----------------------------
+ message: "Error: Invalid Content. Missing %1 contact.",
+ messageId: "SVC4051"
+ }
+#---------SVC4050-----------------------------
# %1 - Service/Resource/Additional parameter
# %2 - service/resource/label name
COMPONENT_NAME_ALREADY_EXIST: {
@@ -110,90 +121,90 @@ errors:
message: "Error: %1 with name '%2' already exists.",
messageId: "SVC4050"
}
-#---------SVC4051------------------------------
-# %1 - resource/service
+#---------SVC4051------------------------------
+# %1 - resource/service
COMPONENT_MISSING_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Missing %1 category.",
messageId: "SVC4051"
}
-#---------SVC4052------------------------------
+#---------SVC4052------------------------------
COMPONENT_MISSING_TAGS: {
code: 400,
message: "Error: Invalid Content. At least one tag has to be specified.",
messageId: "SVC4052"
}
-#---------SVC4053------------------------------
+#---------SVC4053------------------------------
# %1 - service/resource
COMPONENT_MISSING_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. Missing %1 description.",
messageId: "SVC4053"
}
-#---------SVC4054------------------------------
+#---------SVC4054------------------------------
# %1 - resource/service
COMPONENT_INVALID_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 category.",
messageId: "SVC4054"
}
-#---------SVC4055------------------------------
+#---------SVC4055------------------------------
MISSING_VENDOR_NAME: {
code: 400,
message: "Error: Invalid Content. Missing vendor name.",
messageId: "SVC4055"
}
-#---------SVC4056------------------------------
+#---------SVC4056------------------------------
MISSING_VENDOR_RELEASE: {
code: 400,
message: "Error: Invalid Content. Missing vendor release.",
messageId: "SVC4056"
}
-#---------SVC4057------------------------------
+#---------SVC4057------------------------------
MISSING_DERIVED_FROM_TEMPLATE: {
code: 400,
message: "Error: Invalid Content. Missing derived from template specification.",
messageId: "SVC4057"
}
-#---------SVC4058------------------------------
+#---------SVC4058------------------------------
# %1 - service/resource
COMPONENT_MISSING_ICON: {
code: 400,
message: "Error: Invalid Content. Missing %1 icon.",
messageId: "SVC4058"
}
-#---------SVC4059------------------------------
+#---------SVC4059------------------------------
# %1 - service/resource
COMPONENT_INVALID_ICON: {
code: 400,
message: "Error: Invalid Content. Invalid %1 icon.",
messageId: "SVC4059"
}
-#---------SVC4060------------------------------
+#---------SVC4060------------------------------
PARENT_RESOURCE_NOT_FOUND: {
code: 400,
message: "Error: Invalid Content. Derived from resource template was not found.",
messageId: "SVC4060"
}
-#---------SVC4061------------------------------
+#---------SVC4061------------------------------
MULTIPLE_PARENT_RESOURCE_FOUND: {
code: 400,
message: "Error: Invalid Content. Multiple derived from resource template is not allowed.",
messageId: "SVC4061"
}
-#---------SVC4062------------------------------
+#---------SVC4062------------------------------
# %1 - service/resource
MISSING_COMPONENT_NAME: {
code: 400,
message: "Error: Invalid Content. Missing %1 name.",
messageId: "SVC4062"
}
-#---------SVC4063------------------------------
+#---------SVC4063------------------------------
#%1  -  resource/service name
RESOURCE_NOT_FOUND: {
code: 404,
@@ -201,51 +212,51 @@ errors:
messageId: "SVC4063"
}
-#---------SVC4064------------------------------
-# %1 - Service/Resource
+#---------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
-# %2 - max resource/service name length
+#---------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
+#---------SVC4066------------------------------
+# %1 - max length
COMPONENT_TAGS_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.",
messageId: "SVC4066"
}
#---------SVC4067------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor name exceeds limit of %1 characters.",
messageId: "SVC4067"
}
#---------SVC4068------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_RELEASE_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.",
messageId: "SVC4068"
}
-#---------SVC4069------------------------------
+#---------SVC4069------------------------------
# %1 - Service/Resource/Product
COMPONENT_INVALID_CONTACT: {
code: 400,
message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
-#---------SVC4070------------------------------
+#---------SVC4070------------------------------
# %1 - Service/Resource
INVALID_COMPONENT_NAME: {
code: 400,
@@ -253,27 +264,27 @@ errors:
messageId: "SVC4070"
}
-#---------SVC4071------------------------------
+#---------SVC4071------------------------------
INVALID_VENDOR_NAME: {
code: 400,
message: 'Error: Invalid Content. Vendor name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4071"
}
-#---------SVC4072------------------------------
+#---------SVC4072------------------------------
INVALID_VENDOR_RELEASE: {
code: 400,
message: 'Error: Invalid Content. Vendor release is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4072"
}
-#---------SVC4073------------------------------
+#---------SVC4073------------------------------
# %1 - Service/Resource
-# %2 - max resource/service name
+# %2 - max resource/service name
COMPONENT_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 name exceeds limit of %2 characters.",
messageId: "SVC4073"
}
-#---------SVC4080------------------------------
+#---------SVC4080------------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -284,7 +295,7 @@ errors:
message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).",
messageId: "SVC4080"
}
-#---------SVC4081-----------------------------
+#---------SVC4081-----------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -296,7 +307,7 @@ errors:
messageId: "SVC4081"
}
-#-----------SVC4082---------------------------
+#-----------SVC4082---------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -386,7 +397,7 @@ errors:
}
#-----------SVC4102---------------------------
-# %1 - capability type name
+# %1 - capability type name
CAPABILITY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Capability Type with name '%1' already exists.",
@@ -399,7 +410,7 @@ errors:
messageId: "SVC4114"
}
#-----------SVC4115---------------------------
-# %1 - capability type name
+# %1 - capability type name
MISSING_CAPABILITY_TYPE: {
code: 400,
message: "Error: Invalid Content. Missing Capability Type '%1'.",
@@ -477,7 +488,7 @@ errors:
message: "Error: Artifact '%1' already exists.",
messageId: "SVC4125"
}
-#---------SVC4126------------------------------
+#---------SVC4126------------------------------
# %1 - resource/service/product/...
# %2 - field (tag, vendor name...)
INVALID_FIELD_FORMAT: {
@@ -512,7 +523,7 @@ errors:
#-----------SVC4131---------------------------
# %1-resource/service
# %2-srtifact/artifacts
-# %3-semicolomn separated list of artifact
+# %3-semicolomn separated list of artifact
COMPONENT_MISSING_MANDATORY_ARTIFACTS: {
code: 403,
message: "Error: Missing mandatory informational %1 %2: [%3].",
@@ -539,60 +550,60 @@ errors:
message: "Error: Invalid Content. Missing interface life-cycle type.",
messageId: "SVC4134"
}
-#---------SVC4135------------------------------
+#---------SVC4135------------------------------
SERVICE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service category cannot be changed once the service is certified.",
messageId: "SVC4135"
}
-#---------SVC4136------------------------------
-# %1 - distribution environment name
+#---------SVC4136------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: {
code: 500,
message: "Error: Requested distribution environment '%1' is not available.",
messageId: "SVC4136"
}
-#---------SVC4137------------------------------
-# %1 - distribution environment name
+#---------SVC4137------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_FOUND: {
code: 400,
message: "Error: Requested distribution environment '%1' was not found.",
messageId: "SVC4137"
}
-#---------SVC4138------------------------------
+#---------SVC4138------------------------------
DISTRIBUTION_ENVIRONMENT_INVALID: {
code: 400,
message: "Error: Invalid distribution environment.",
messageId: "SVC4138"
}
-#---------SVC4139------------------------------
+#---------SVC4139------------------------------
# %1 - service name
DISTRIBUTION_ARTIFACT_NOT_FOUND: {
code: 409,
message: "Error: Service '%1' cannot be distributed due to missing deployment artifacts.",
messageId: "SVC4139"
}
-#---------SVC4200------------------------------
+#---------SVC4200------------------------------
# %1 - Service/Resource
-# %2 - max icon name length
+# %2 - max icon name length
COMPONENT_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 icon name exceeds limit of %2 characters.",
messageId: "SVC4200"
}
-#---------SVC4300------------------------------
+#---------SVC4300------------------------------
RESTRICTED_ACCESS: {
code: 403,
message: "Error: Restricted access.",
messageId: "SVC4300"
}
-#---------SVC4301------------------------------
+#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
code: 409,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
-#---------SVC4500------------------------------
+#---------SVC4500------------------------------
MISSING_BODY: {
code: 400 ,
message: "Error: Missing request body.",
@@ -604,7 +615,7 @@ errors:
message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." ,
messageId: "SVC4501"
}
-#---------SVC4502------------------------------
+#---------SVC4502------------------------------
DISTRIBUTION_ENV_DOES_NOT_EXIST: {
code: 400 ,
message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." ,
@@ -618,7 +629,7 @@ errors:
messageId: "SVC4503"
}
-#---------SVC4504------------------------------
+#---------SVC4504------------------------------
# %1 - Service/Resource
# %2 - service/resource version
COMPONENT_VERSION_NOT_FOUND: {
@@ -628,103 +639,103 @@ errors:
}
#-----------SVC4505---------------------------
#%1-artifact name
-
+
ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Artifact '%1' was not found.",
messageId: "SVC4505"
}
-#---------SVC4506------------------------------
+#---------SVC4506------------------------------
MISSING_ENV_NAME: {
code: 400 ,
message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.",
messageId: "SVC4506"
}
-#---------SVC4507------------------------------
+#---------SVC4507------------------------------
COMPONENT_INVALID_TAGS_NO_COMP_NAME: {
code: 400,
message: "Error: Invalid Content. One of the tags should be the component name.",
messageId: "SVC4507"
}
-
-#---------SVC4508------------------------------
+
+#---------SVC4508------------------------------
SERVICE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service name cannot be changed once the service is certified.",
messageId: "SVC4508"
}
-#---------SVC4509------------------------------
+#---------SVC4509------------------------------
SERVICE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the service is certified.",
messageId: "SVC4509"
}
-#---------SVC4510------------------------------
+#---------SVC4510------------------------------
# %1 - icon name max length
SERVICE_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Icon name exceeds limit of %1 characters.",
messageId: "SVC4510"
}
-#---------SVC4511------------------------------
+#---------SVC4511------------------------------
DISTRIBUTION_REQUESTED_NOT_FOUND: {
code: 404,
message: "Error: Requested distribution was not found.",
messageId: "SVC4511"
}
-#---------SVC4512------------------------------
+#---------SVC4512------------------------------
# %1 - Distribution ID
DISTRIBUTION_REQUESTED_FAILED: {
code: 403,
message: "Error: Requested distribution '%1' failed.",
messageId: "SVC4512"
}
-#---------SVC4513------------------------------
+#---------SVC4513------------------------------
RESOURCE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource category cannot be changed once the resource is certified.",
messageId: "SVC4513"
}
-#---------SVC4514------------------------------
+#---------SVC4514------------------------------
RESOURCE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource name cannot be changed once the resource is certified.",
messageId: "SVC4514"
}
-#---------SVC4515------------------------------
+#---------SVC4515------------------------------
RESOURCE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the resource is certified.",
messageId: "SVC4515"
}
-#---------SVC4516------------------------------
+#---------SVC4516------------------------------
RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Vendor name cannot be changed once the resource is certified.",
messageId: "SVC4516"
}
-#---------SVC4517------------------------------
+#---------SVC4517------------------------------
RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Derived from resource template cannot be changed once the resource is certified.",
messageId: "SVC4517"
}
-#---------SVC4518------------------------------
-# %1 - max length
+#---------SVC4518------------------------------
+# %1 - max length
COMPONENT_SINGLE_TAG_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.",
messageId: "SVC4518"
}
-#---------SVC4519------------------------------
+#---------SVC4519------------------------------
INVALID_DEFAULT_VALUE: {
code: 400,
message: "Error: mismatch in data-type occurred for property %1. data type is %2 and default value found is %3.",
messageId: "SVC4519"
}
-#---------SVC4520------------------------------
-# %1 - service or resource
+#---------SVC4520------------------------------
+# %1 - service or resource
ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: {
code: 409,
message: "Error: Maximal number of additional %1 parameters was reached.",
@@ -736,7 +747,7 @@ errors:
message: "Error: Invalid Content. The Additional information label and value cannot be empty.",
messageId: "SVC4521"
}
-#---------SVC4522------------------------------
+#---------SVC4522------------------------------
# %1 - label/value
# %2 - Maximal length of %1
ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: {
@@ -756,32 +767,32 @@ errors:
message: "Error: Requested additional information was not found.",
messageId: "SVC4524"
}
-#---------SVC4525------------------------------
+#---------SVC4525------------------------------
ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: {
code: 400,
message: 'Error: Invalid Content. Additional information contains non-english characters.',
messageId: "SVC4525"
}
-#---------SVC4526------------------------------
+#---------SVC4526------------------------------
RESOURCE_INSTANCE_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' resource instance was not found.",
messageId: "SVC4526"
}
-#---------SVC4527------------------------------
+#---------SVC4527------------------------------
ASDC_VERSION_NOT_FOUND: {
code: 500,
message: 'Error: ASDC version cannot be displayed.',
messageId: "SVC4527"
}
-#---------SVC4528------------------------------
+#---------SVC4528------------------------------
# %1-artifact url/artifact label/artifact description/VNF Service Indicator
MISSING_DATA: {
code: 400,
message: "Error: Invalid content. Missing %1.",
messageId: "SVC4528"
}
-#---------SVC4529------------------------------
+#---------SVC4529------------------------------
# %1-artifact url/artifact label/artifact description/artifact name
# %2 - Maximal length of %1
EXCEEDS_LIMIT: {
@@ -789,51 +800,51 @@ errors:
message: "Error: Invalid Content. %1 exceeds limit of %2 characters.",
messageId: "SVC4529"
}
-#---------SVC4530------------------------------
+#---------SVC4530------------------------------
ARTIFACT_INVALID_TIMEOUT: {
code: 400,
message: "Error: Invalid Content. Artifact Timeout should be set to valid positive non-zero number of minutes.",
messageId: "SVC4530"
}
-#---------SVC4531------------------------------
+#---------SVC4531------------------------------
SERVICE_IS_VNF_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: VNF Indicator cannot be updated for certified service.",
messageId: "SVC4531"
}
- #---------SVC4532------------------------------
+ #---------SVC4532------------------------------
RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE: {
code: 404,
message: "Error: Requested '%1' resource instance was not found on the service '%2.",
messageId: "SVC4532"
}
- #---------SVC4533------------------------------
- # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
+ #---------SVC4533------------------------------
+ # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
WRONG_ARTIFACT_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for %1 artifact type.",
messageId: "SVC4533"
}
-#---------SVC4534------------------------------
-# %1 - "HEAT"/"HEAT_ENV"
+#---------SVC4534------------------------------
+# %1 - "HEAT"/"HEAT_ENV"
INVALID_YAML: {
code: 400,
message: "Error: Uploaded YAML file for %1 artifact is invalid.",
messageId: "SVC4534"
}
-#---------SVC4535------------------------------
-# %1 - "HEAT"
+#---------SVC4535------------------------------
+# %1 - "HEAT"
INVALID_DEPLOYMENT_ARTIFACT_HEAT: {
code: 400,
message: "Error: Invalid %1 artifact.",
messageId: "SVC4535"
}
-#---------SVC4536------------------------------
+#---------SVC4536------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
+# %2 - resource/service name
+# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG
DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: {
code: 400,
@@ -841,80 +852,80 @@ errors:
messageId: "SVC4536"
}
-#---------SVC4537------------------------------
+#---------SVC4537------------------------------
MISSING_HEAT: {
code: 400,
message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.",
messageId: "SVC4537"
}
-#---------SVC4538------------------------------
+#---------SVC4538------------------------------
MISMATCH_HEAT_VS_HEAT_ENV: {
code: 400,
message: "Error: Invalid artifact content. Parameter's set in HEAT_ENV '%1' artifact doesn't match the parameters in HEAT '%2' artifact.",
messageId: "SVC4538"
}
-#---------SVC4539------------------------------
+#---------SVC4539------------------------------
INVALID_RESOURCE_PAYLOAD: {
code: 400,
message: "Error: Invalid resource payload.",
messageId: "SVC4539"
}
-#---------SVC4540------------------------------
+#---------SVC4540------------------------------
INVALID_TOSCA_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for TOSCA template.",
messageId: "SVC4540"
}
-#---------SVC4541------------------------------
+#---------SVC4541------------------------------
INVALID_YAML_FILE: {
code: 400,
message: "Error: Invalid YAML file.",
messageId: "SVC4541"
}
-#---------SVC4542------------------------------
+#---------SVC4542------------------------------
INVALID_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Invalid TOSCA template.",
messageId: "SVC4542"
}
-#---------SVC4543------------------------------
+#---------SVC4543------------------------------
NOT_RESOURCE_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Imported Service TOSCA template.",
messageId: "SVC4543"
}
-#---------SVC4544------------------------------
+#---------SVC4544------------------------------
NOT_SINGLE_RESOURCE: {
code: 400,
message: "Error: Imported TOSCA template should contain one resource definition.",
messageId: "SVC4544"
}
-#---------SVC4545------------------------------
+#---------SVC4545------------------------------
INVALID_RESOURCE_NAMESPACE: {
code: 400,
message: "Error: Invalid resource namespace.",
messageId: "SVC4545"
}
-#---------SVC4546------------------------------
+#---------SVC4546------------------------------
RESOURCE_ALREADY_EXISTS: {
code: 400,
message: "Error: Imported resource already exists in ASDC Catalog.",
messageId: "SVC4546"
}
-#---------SVC4549------------------------------
+#---------SVC4549------------------------------
INVALID_RESOURCE_CHECKSUM: {
code: 400,
message: "Error: Invalid resource checksum.",
messageId: "SVC4549"
}
-#---------SVC4550------------------------------
+#---------SVC4550------------------------------
#%1  -  Consumer salt
INVALID_LENGTH: {
code: 400,
message: "Error: Invalid %1 length.",
messageId: "SVC4550"
}
- #---------SVC4551------------------------------
+ #---------SVC4551------------------------------
#%1  -  ECOMP User name
ECOMP_USER_NOT_FOUND: {
code: 404,
@@ -928,13 +939,13 @@ errors:
messageId: "SVC4552"
}
#---------SVC4553-----------------------------
- #%1  -  Consumer name / Consumer password/ Consumer salt
+ #%1  -  Consumer name / Consumer password/ Consumer salt
INVALID_CONTENT_PARAM: {
code: 400,
message: "Error: %1 is invalid.",
messageId: "SVC4553"
}
- #---------SVC4554------------------------------
+ #---------SVC4554------------------------------
# %1 - "Resource"/"Service"
COMPONENT_ARTIFACT_NOT_FOUND: {
code: 404,
@@ -948,7 +959,7 @@ errors:
message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.",
messageId: "SVC4554"
}
-#---------SVC4555------------------------------
+#---------SVC4555------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_LENGTH: {
@@ -956,7 +967,7 @@ errors:
message: "Error: Invalid %1 %2 name length.",
messageId: "SVC4555"
}
-#---------SVC4556------------------------------
+#---------SVC4556------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_FORMAT: {
@@ -964,7 +975,7 @@ errors:
message: "Error: Invalid %1 %2 name format.",
messageId: "SVC4556"
}
-#---------SVC4557------------------------------
+#---------SVC4557------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category name"
COMPONENT_CATEGORY_ALREADY_EXISTS: {
@@ -995,11 +1006,11 @@ errors:
code: 403,
message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use one of available validated resource versions.",
messageId: "SVC4560"
- }
+ }
#---------SVC4561------------------------------
# %1 - "resource"/"product"
# %2 - "category"
-# %2 - "category name"
+# %3 - "category name"
COMPONENT_CATEGORY_NOT_FOUND: {
code: 404,
message: "Error: Requested %1 %2 '%3' was not found.",
@@ -1008,7 +1019,7 @@ errors:
#---------SVC4562------------------------------
# %1 - "Resource"/"Product"
# %2 - "sub-category name"
-# %2 - "category name"
+# %3 - "category name"
COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY: {
code: 409,
message: "Error: %1 sub-category '%2' already exists under '%3' category.",
@@ -1017,114 +1028,114 @@ errors:
#---------SVC4563------------------------------
# %1 - "Product"
# %2 - "grouping name"
-# %2 - "sub-category 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------------------------------
+#---------SVC4564------------------------------
# %1 - product name
PRODUCT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' product was not found.",
messageId: "SVC4564"
}
-#---------SVC4565------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4565------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
# %3 - parameter name
INVALID_HEAT_PARAMETER_VALUE: {
code: 400,
message: "Error: Invalid %1 artifact. Invalid %2 value set for '%3' parameter.",
messageId: "SVC4565"
}
-#---------SVC4566------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4566------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
INVALID_HEAT_PARAMETER_TYPE: {
code: 400,
message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.",
messageId: "SVC4566"
}
-#---------SVC4567------------------------------
-# %1 - "YANG_XML"
+#---------SVC4567------------------------------
+# %1 - "YANG_XML"
INVALID_XML: {
code: 400,
message: "Error: Uploaded XML file for %1 artifact is invalid.",
messageId: "SVC4567"
}
-#---------SVC4567------------------------------
-# %1 - "User Name and USER_ID"
+#---------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 USER_ID"
+#---------SVC4568------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: Role cannot be changed. User '%1' has %2 projects.",
messageId: "SVC4568"
}
-#---------SVC4570------------------------------
+#---------SVC4570------------------------------
UPDATE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator is not allowed to change his/her role.",
messageId: "SVC4570"
}
-#---------SVC4571------------------------------
+#---------SVC4571------------------------------
SERVICE_CANNOT_CONTAIN_SUBCATEGORY: {
code: 400,
message: "Error: Sub category cannot be defined for service",
messageId: "SVC4571"
}
-#---------SVC4572------------------------------
+#---------SVC4572------------------------------
# %1 - "Resource"/"Service"
COMPONENT_TOO_MUCH_CATEGORIES: {
code: 400,
message: "Error: %1 must have only 1 category",
messageId: "SVC4572"
}
-#---------SVC4574------------------------------
+#---------SVC4574------------------------------
RESOURCE_TOO_MUCH_SUBCATEGORIES: {
code: 400,
message: "Error: Resource must have only 1 sub category",
messageId: "SVC4574"
}
-#---------SVC4575------------------------------
+#---------SVC4575------------------------------
COMPONENT_MISSING_SUBCATEGORY: {
code: 400,
message: "Error: Missing sub category",
messageId: "SVC4575"
}
- #---------SVC4576------------------------------
+ #---------SVC4576------------------------------
# %1 - "component type"
UNSUPPORTED_ERROR: {
code: 400,
message: "Error : Requested component type %1 is unsupported.",
messageId: "SVC4576"
}
- #---------SVC4577------------------------------
+ #---------SVC4577------------------------------
# %1 - "resource type"
RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: {
code: 409,
message: "Error : Resource of type %1 cannot contain resource instances.",
messageId: "SVC4577"
}
-#---------SVC4578------------------------------
+#---------SVC4578------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "artifact name"
+# %2 - resource/service name
+# %3 - "artifact name"
DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS: {
code: 400,
message: "Error: %1 '%2' already has a deployment artifact named '%3'.",
messageId: "SVC4578"
}
-#---------SVC4579------------------------------
+#---------SVC4579------------------------------
# %1 - "Category"/"Sub-Category"/"Group"
# %2 - category/sub-category/grouping name.
INVALID_GROUP_ASSOCIATION: {
@@ -1132,27 +1143,27 @@ errors:
message: "Error: Invalid group association. %1 '%2' was not found.",
messageId: "SVC4579"
}
-#---------SVC4580------------------------------
+#---------SVC4580------------------------------
EMPTY_PRODUCT_CONTACTS_LIST: {
code: 400,
message: "Error: Invalid content. At least one Product Contact has to be specified.",
messageId: "SVC4580"
}
-#---------SVC4581------------------------------
-# %1 - USER_ID
+#---------SVC4581------------------------------
+# %1 - UserId
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
messageId: "SVC4581"
}
-#---------SVC4582------------------------------
+#---------SVC4582------------------------------
# %1 - Product
# %2 - "abbreviated"/"full"
MISSING_ONE_OF_COMPONENT_NAMES: {
code: 400,
message: "Error: Invalid content. Missing %1 %2 name.",
messageId: "SVC4582"
- }
+ }
#---------SVC4583------------------------------
# %1 - "Icon"
# %2 - "resource"/"service"/"product"
@@ -1162,10 +1173,10 @@ errors:
messageId: "SVC4583"
}
#---------SVC4584------------------------------
-# %1 - service/VF name
+# %1 - service/VF name
# %2 - "service" /"VF"
# %3 - resource instance origin type
-# %4 - resource instance name
+# %4 - resource instance name
# %5 - requirement/capability
# %6 - requirement/capability name
# %7 - "fulfilled" (for req)/"consumed (for cap)"
@@ -1174,57 +1185,57 @@ errors:
message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.",
messageId: "SVC4584"
}
-#---------SVC4585------------------------------
+#---------SVC4585------------------------------
INVALID_OCCURRENCES: {
code: 400,
message: "Error: Invalid occurrences format.",
messageId: "SVC4585"
}
-#---------SVC4586------------------------------
-#---------SVC4586------------------------------
+#---------SVC4586------------------------------
+#---------SVC4586------------------------------
INVALID_SERVICE_API_URL: {
code: 400,
message: 'Error: Invalid Service API URL. Please check whether your URL has a valid domain extension and does not contain the following characters - #?&@%+;,=$<>~^`\[]{}|"*!',
messageId: "SVC4586"
}
-#---------SVC4587------------------------------
-# %1 - Data type name
+#---------SVC4587------------------------------
+# %1 - Data type name
DATA_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Data type %1 already exists.',
messageId: "SVC4587"
}
-#---------SVC4588------------------------------
-# %1 - Data type name
+#---------SVC4588------------------------------
+# %1 - Data type name
DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: {
code: 400,
message: 'Error: Invalid Data type %1. Data type must have either a valid derived from declaration or at least one valid property',
messageId: "SVC4588"
}
-#---------SVC4589------------------------------
-# %1 - Data type name
+#---------SVC4589------------------------------
+# %1 - Data type name
DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: {
code: 400,
message: "Error: Invalid Data type %1. 'properties' parameter cannot be empty if provided.",
messageId: "SVC4589"
}
-#---------SVC4590------------------------------
-# %1 - Property type name
+#---------SVC4590------------------------------
+# %1 - Property type name
# %2 - Property name
INVALID_PROPERTY_TYPE: {
code: 400,
message: "Error: Invalid Property type %1 in property %2.",
messageId: "SVC4590"
}
-#---------SVC4591------------------------------
+#---------SVC4591------------------------------
# %1 - Property inner type
-# %2 - Property name
+# %2 - Property name
INVALID_PROPERTY_INNER_TYPE: {
code: 400,
message: "Error: Invalid property inner type %1, in property %2",
messageId: "SVC4591"
}
-#---------SVC4592------------------------------
+#---------SVC4592------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
COMPONENT_INSTANCE_NOT_FOUND: {
@@ -1232,11 +1243,11 @@ errors:
message: "Error: Requested '%1' %2 was not found.",
messageId: "SVC4592"
}
-#---------SVC4593------------------------------
+#---------SVC4593------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
# %3 - "resource/"service"/"product"
-# %4 - container name
+# %4 - container name
COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: {
code: 404,
message: "Error: Requested '%1' %2 was not found on the %3 '%4'.",
@@ -1253,20 +1264,20 @@ errors:
#---------SVC4595------------------------------
#%1 - requirement / capability
#%2 - requirement name
-#%3 - parent containing the requirement
+#%3 - parent containing the requirement
IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED: {
code: 400,
message: "Error: Imported TOSCA template contains %1 '%2' that is already defined by derived template %3.",
messageId: "SVC4595"
}
-#---------SVC4596------------------------------
+#---------SVC4596------------------------------
# %1 - Data type name
DATA_TYPE_DERIVED_IS_MISSING: {
code: 400,
message: "Error: Invalid Content. The ancestor data type %1 cannot be found in the system.",
messageId: "SVC4596"
}
-#---------SVC4597------------------------------
+#---------SVC4597------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: {
@@ -1274,14 +1285,14 @@ errors:
message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.",
messageId: "SVC4597"
}
-#---------SVC4598------------------------------
+#---------SVC4598------------------------------
# %1 - Data type name
DATA_TYPE_DUPLICATE_PROPERTY: {
code: 400,
message: "Error: Invalid Content. The data type %1 contains duplicate property.",
messageId: "SVC4598"
}
-#---------SVC4599------------------------------
+#---------SVC4599------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: {
@@ -1289,14 +1300,14 @@ errors:
message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.",
messageId: "SVC4599"
}
-#---------SVC4600------------------------------
+#---------SVC4600------------------------------
# %1 - Data type name
DATA_TYPE_CANNOT_HAVE_PROPERTIES: {
code: 400,
message: "Error: Invalid Content. The data type %1 cannot have properties since it is of type scalar",
messageId: "SVC4600"
}
-#---------SVC4601------------------------------
+#---------SVC4601------------------------------
NOT_TOPOLOGY_TOSCA_TEMPLATE: {
code: 400,
message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.",
@@ -1311,7 +1322,7 @@ errors:
message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL",
messageId: "SVC4602"
}
-#---------SVC4603------------------------------
+#---------SVC4603------------------------------
# %1 - component type
# %2 - component name
# %3 - state
@@ -1320,21 +1331,21 @@ errors:
message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.",
messageId: "SVC4603"
}
-#---------SVC4604------------------------------
+#---------SVC4604------------------------------
# %1 - csar file name
CSAR_INVALID: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. 'TOSCA-Metadata/Tosca.meta' file must be provided.",
messageId: "SVC4604"
}
-#---------SVC4605------------------------------
+#---------SVC4605------------------------------
# %1 - csar file name
CSAR_INVALID_FORMAT: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. Invalid 'TOSCA-Metadata/Tosca.meta' file format.",
messageId: "SVC4605"
}
-#---------SVC4606------------------------------
+#---------SVC4606------------------------------
# %1 - property name
# %2 - property type
# %3 - property innerType
@@ -1344,14 +1355,14 @@ errors:
message: "Error: Invalid default value of property %1. Data type is %2 with inner type %3 and default value found is %4.",
messageId: "SVC4606"
}
-#---------SVC4607------------------------------
+#---------SVC4607------------------------------
# %1 - csar file name
CSAR_NOT_FOUND: {
code: 400,
message: "Error: TOSCA CSAR '%1' is not found.",
messageId: "SVC4607"
}
-#---------SVC4608------------------------------
+#---------SVC4608------------------------------
# %1 - artifact name
# %2 - component type
# %3 - actual component type
@@ -1361,14 +1372,14 @@ errors:
messageId: "SVC4608"
}
-#---------SVC4609------------------------------
-# %1 - "INVALID_JSON"
+#---------SVC4609------------------------------
+# %1 - "INVALID_JSON"
INVALID_JSON: {
code: 400,
message: "Error: Uploaded JSON file for %1 artifact is invalid.",
messageId: "SVC4609"
}
-#---------SVC4610------------------------------
+#---------SVC4610------------------------------
# %1 - csar file name
# %2 - missing file name
YAML_NOT_FOUND_IN_CSAR: {
@@ -1376,21 +1387,21 @@ errors:
message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.",
messageId: "SVC4610"
}
-#---------SVC4611------------------------------
+#---------SVC4611------------------------------
# %1 - group name
GROUP_MEMBER_EMPTY: {
code: 400,
message: "Error: Invalid Content. Group %1 member list was provided but does not have values",
messageId: "SVC4611"
}
-#---------SVC4612------------------------------
-# %1 - group name
+#---------SVC4612------------------------------
+# %1 - group name
GROUP_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Group type %1 already exists.',
messageId: "SVC4612"
}
-#---------SVC4613------------------------------
+#---------SVC4613------------------------------
# %1 - group name
# %2 - VF name(component name)
# %3 - actual component type [VF]
@@ -1398,15 +1409,15 @@ errors:
code: 409,
message: "Error: Group with name '%1' already exists in %2 %3.",
messageId: "SVC4613"
- }
-#---------SVC4614------------------------------
+ }
+#---------SVC4614------------------------------
# %1 - group type
GROUP_TYPE_IS_INVALID: {
code: 400,
message: "Error: Invalid content. Group type %1 does not exist",
messageId: "SVC4614"
}
-#---------SVC4615------------------------------
+#---------SVC4615------------------------------
# %1 - group name
GROUP_MISSING_GROUP_TYPE: {
code: 400,
@@ -1420,9 +1431,9 @@ errors:
# %4 - component type [VF ]
GROUP_INVALID_COMPONENT_INSTANCE: {
code: 400,
- message: "Error: member %1 listed in group %2 is not part of %3 %4.",
+ message: "Error: Member '%1' listed in group '%2' is not part of '%3' %4.",
messageId: "SVC4616"
- }
+ }
#---------SVC4617------------------------------
# %1 - member name
# %2 - group name
@@ -1432,7 +1443,7 @@ errors:
message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.",
messageId: "SVC4617"
}
-#---------SVC4618------------------------------
+#---------SVC4618------------------------------
# %1 - missing file name
# %2 - csar file name
ARTIFACT_NOT_FOUND_IN_CSAR: {
@@ -1440,7 +1451,7 @@ errors:
message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided",
messageId: "SVC4618"
}
-#---------SVC4619------------------------------
+#---------SVC4619------------------------------
# %1 - artifact name
# %2 - artifact type
# %3 - existing artifact type
@@ -1449,23 +1460,23 @@ errors:
message: "Error: artifact %1 in type %2 already exists in type %3.",
messageId: "SVC4619"
}
-#---------SVC4620------------------------------
+#---------SVC4620------------------------------
FAILED_RETRIVE_ARTIFACTS_TYPES: {
code: 400,
message: "Error: Failed to retrieve list of suported artifact types.",
messageId: "SVC4620"
}
-#---------SVC4621------------------------------
+#---------SVC4621------------------------------
# %1 - artifact name
-# %2 - master
+# %2 - master
ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: {
code: 400,
message: "Error: artifact %1 already exists in master %2 .",
messageId: "SVC4621"
}
-#---------SVC4622------------------------------
+#---------SVC4622------------------------------
# %1 - artifact name
-# %2 - artifact type
+# %2 - artifact type
# %3 - master name
# %4 - master type
ARTIFACT_NOT_VALID_IN_MASTER: {
@@ -1473,9 +1484,9 @@ errors:
message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.",
messageId: "SVC4622"
}
-#---------SVC4623------------------------------
+#---------SVC4623------------------------------
# %1 - artifact name
-# %2 - artifact type
+# %2 - artifact type
# %3 - env name
# %4 - existing env
ARTIFACT_NOT_VALID_ENV: {
@@ -1483,7 +1494,7 @@ errors:
message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4",
messageId: "SVC4623"
}
-#---------SVC4624------------------------------
+#---------SVC4624------------------------------
# %1 - groups names
# %2 - VF name
# %3 - component type [VF ]
@@ -1492,14 +1503,14 @@ errors:
message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.",
messageId: "SVC4624"
}
-#---------SVC4625------------------------------
+#---------SVC4625------------------------------
# %1 - groups name
GROUP_ARTIFACT_ALREADY_ASSOCIATED: {
code: 400,
message: "Error: Invalid Content. Artifact already associated to group '%1'.",
messageId: "SVC4625"
}
-#---------SVC4626------------------------------
+#---------SVC4626------------------------------
# %1 - groups name
GROUP_ARTIFACT_ALREADY_DISSOCIATED: {
code: 400,
@@ -1514,8 +1525,8 @@ errors:
code: 400,
message: "Error: property %1 listed in group %2 is not exist in group type %3.",
messageId: "SVC4627"
- }
-#---------SVC4628------------------------------
+ }
+#---------SVC4628------------------------------
# %1 - csarUUID
# %2 - VF name
VSP_ALREADY_EXISTS: {
@@ -1523,14 +1534,14 @@ errors:
message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.",
messageId: "SVC4628"
}
-#---------SVC4629------------------------------
+#---------SVC4629------------------------------
# %1 - VF name
MISSING_CSAR_UUID: {
code: 400,
message: "Error: The Csar UUID or payload name is missing for VF %1.",
messageId: "SVC4629"
}
-#---------SVC4630------------------------------
+#---------SVC4630------------------------------
# %1 - VF name
# %2 - new csarUUID
# %3 - old csarUUID
@@ -1539,8 +1550,8 @@ errors:
message: "Error: Resource %1 cannot be updated using CsarUUID %2 since the resource is linked to a different VSP with csarUUID %3.",
messageId: "SVC4630"
}
-#---------SVC4631------------------------------
-# %1 - policy name
+#---------SVC4631------------------------------
+# %1 - policy name
POLICY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Policy type %1 already exists.",
@@ -1573,4 +1584,300 @@ errors:
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 - <ServiceName>
+# %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"
+ }
+#---------SVC4661------------------------------
+# %1 - assetType
+# %2 - matching generic node type name
+ TOSCA_SCHEMA_FILES_NOT_FOUND: {
+ code: 400,
+ message: "Error: CSAR packaging failed. TOSCA schema files for SDC-Version: %1 and Conformance-Level %2 were not found",
+ messageId: "SVC4661"
+ }
+#---------SVC4662------------------------------
+# %1 - file name
+# %2 - parser error
+ TOSCA_PARSE_ERROR: {
+ code: 400,
+ message: "Error: Invalid TOSCA template in file %1. %2",
+ messageId: "SVC4662"
+ }
+#---------SVC4663------------------------------
+# %1 - max length
+ RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Resource vendor model number exceeds limit of %1 characters.",
+ messageId: "SVC4663"
+ }
+#---------SVC4664------------------------------
+ INVALID_RESOURCE_VENDOR_MODEL_NUMBER: {
+ code: 400,
+ message: 'Error: Invalid Content. Resource vendor model number is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4664"
+ }
+#---------SVC4665------------------------------
+# %1 - max length
+ SERVICE_TYPE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service type exceeds limit of %1 characters.",
+ messageId: "SVC4665"
+ }
+#---------SVC4666------------------------------
+ INVALID_SERVICE_TYPE: {
+ code: 400,
+ message: 'Error: Invalid Content. Serivce type is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4666"
+ }
+#---------SVC4667------------------------------
+# %1 - max length
+ SERVICE_ROLE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service role exceeds limit of %1 characters.",
+ messageId: "SVC4667"
+ }
+#---------SVC4668------------------------------
+ INVALID_SERVICE_ROLE: {
+ code: 400,
+ message: 'Error: Invalid Content. Service role is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4668"
+ }
+
+#---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ }
+#---------SVC4670------------------------------
+ ARTIFACT_NAME_INVALID: {
+ code: 400,
+ message: "Error: Artifact name is invalid.",
+ messageId: "SVC4670"
+ }
+#---------SVC4671------------------------------
+# %1 - VSP name
+# %2 - VFC name
+ CFVC_LOOP_DETECTED: {
+ code: 400,
+ message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2',
+ messageId: "SVC4671"
+ }
+#---------SVC4672------------------------------
+# %1 - capability uniqueId
+# %2 - instance uniqueId
+# %3 - container uniqueId
+ COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: {
+ code: 404,
+ message: "Error: Requested capability %1 of instance %2 was not found on the container %3.",
+ messageId: "SVC4672"
+ }
+
+
+#---------SVC4673------------------------------
+ INVALID_SERVICE_STATE: {
+ code: 409,
+ message: "Error: Invalid service state. Expected state: %1, actual state: %2",
+ messageId: "SVC4673"
+ }
+
+#---------SVC4674------------------------------
+ INVALID_RESPONSE_FROM_PROXY: {
+ code: 502,
+ message: "Error: The server was acting as a gateway or proxy and received an invalid response from the upstream server",
+ messageId: "SVC4674"
} \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/neo4j-errors-configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/neo4j-errors-configuration.yaml
new file mode 100644
index 0000000000..7a0d6dbfd4
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/test-apis-ci/neo4j-errors-configuration.yaml
@@ -0,0 +1,60 @@
+# Errors
+errors:
+ Neo_ClientError_General_ReadOnly: "This is a read only database, writing or modifying the database is not allowed."
+ Neo_ClientError_LegacyIndex_NoSuchIndex: "The request (directly or indirectly) referred to a index that does not exist."
+ Neo_ClientError_Request_Invalid: "The client provided an invalid Request."
+ Neo_ClientError_Request_InvalidFormat: "The client provided a request that was missing required fields, or had values that are not allowed."
+ Neo_ClientError_Schema_ConstraintAlreadyExists: "Unable to perform operation because it would clash with a pre-existing constraint."
+ Neo_ClientError_Schema_ConstraintVerificationFailure: "Unable to create constraint because data that exists in the database violates it."
+ Neo_ClientError_Schema_ConstraintViolation: "A constraint imposed by the database was violated."
+ Neo_ClientError_Schema_IllegalTokenName: "A token name, such as a label, relationship type or property key, used is not valid. Tokens cannot be empty strings and cannot be null."
+ Neo_ClientError_Schema_IndexAlreadyExists: "Unable to perform operation because it would clash with a pre-existing index."
+ Neo_ClientError_Schema_IndexBelongsToConstraint: "A requested operation can not be performed on the specified index because the index is part of a constraint. If you want to drop the index, for instance, you must drop the constraint."
+ Neo_ClientError_Schema_IndexLimitReached: "The maximum number of index entries supported has been reached, no more entities can be indexed."
+ Neo_ClientError_Schema_LabelLimitReached: "The maximum number of labels supported has been reached, no more labels can be created."
+ Neo_ClientError_Schema_NoSuchConstraint: "The request (directly or indirectly) referred to a constraint that does not exist."
+ Neo_ClientError_Schema_NoSuchIndex: "The request (directly or indirectly) referred to an index that does not exist."
+ Neo_ClientError_Security_AuthenticationFailed: "The client provided an incorrect username and/or password."
+ Neo_ClientError_Security_AuthenticationRateLimit: "The client has provided incorrect authentication details too many times in a row."
+ Neo_ClientError_Security_AuthorizationFailed: "The client does not have privileges to perform the operation requested."
+ Neo_ClientError_Statement_ArithmeticError: "Invalid use of arithmetic, such as dividing by zero."
+ Neo_ClientError_Statement_ConstraintViolation: "A constraint imposed by the statement is violated by the data in the database."
+ Neo_ClientError_Statement_EntityNotFound: "The statement is directly referring to an entity that does not exist."
+ Neo_ClientError_Statement_InvalidArguments: "The statement is attempting to perform operations using invalid arguments"
+ Neo_ClientError_Statement_InvalidSemantics: "The statement is syntactically valid, but expresses something that the database cannot do."
+ Neo_ClientError_Statement_InvalidSyntax: "The statement contains invalid or unsupported syntax."
+ Neo_ClientError_Statement_InvalidType: "The statement is attempting to perform operations on values with types that are not supported by the operation."
+ Neo_ClientError_Statement_NoSuchLabel: "The statement is referring to a label that does not exist."
+ Neo_ClientError_Statement_NoSuchProperty: "The statement is referring to a property that does not exist."
+ Neo_ClientError_Statement_ParameterMissing: "The statement is referring to a parameter that was not provided in the Request."
+ Neo_ClientError_Transaction_ConcurrentRequest: "There were concurrent requests accessing the same transaction, which is not allowed."
+ Neo_ClientError_Transaction_EventHandlerThrewException: "A transaction event handler threw an exception. The transaction will be rolled back."
+ Neo_ClientError_Transaction_HookFailed: "Transaction hook failure."
+ Neo_ClientError_Transaction_InvalidType: "The transaction is of the wrong type to service the Request_ For instance, a transaction that has had schema modifications performed in it cannot be used to subsequently perform data operations, and vice versa."
+ Neo_ClientError_Transaction_MarkedAsFailed: "Transaction was marked as both successful and failed. Failure takes precedence and so this transaction was rolled back although it may have looked like it was going to be committed"
+ Neo_ClientError_Transaction_UnknownId: "The request referred to a transaction that does not exist."
+ Neo_ClientError_Transaction_ValidationFailed: "Transaction changes did not pass validation checks"
+ Neo_DatabaseError_General_CorruptSchemaRule: "A malformed schema rule was encountered. Please contact your support representative."
+ Neo_DatabaseError_General_FailedIndex: "The request (directly or indirectly) referred to an index that is in a failed state. The index needs to be dropped and recreated manually."
+ Neo_DatabaseError_General_UnknownFailure: "An unknown failure occurred."
+ Neo_DatabaseError_Schema_ConstraintCreationFailure: "Creating a requested constraint failed."
+ Neo_DatabaseError_Schema_ConstraintDropFailure: "The database failed to drop a requested constraint."
+ Neo_DatabaseError_Schema_IndexCreationFailure: "Failed to create an index."
+ Neo_DatabaseError_Schema_IndexDropFailure: "The database failed to drop a requested index."
+ Neo_DatabaseError_Schema_NoSuchLabel: "The request accessed a label that did not exist."
+ Neo_DatabaseError_Schema_NoSuchPropertyKey: "The request accessed a property that does not exist."
+ Neo_DatabaseError_Schema_NoSuchRelationshipType: "The request accessed a relationship type that does not exist."
+ Neo_DatabaseError_Schema_NoSuchSchemaRule: "The request referred to a schema rule that does not exist."
+ Neo_DatabaseError_Statement_ExecutionFailure: "The database was unable to execute the Statement."
+ Neo_DatabaseError_Transaction_CouldNotBegin: "The database was unable to start the Transaction."
+ Neo_DatabaseError_Transaction_CouldNotCommit: "The database was unable to commit the Transaction."
+ Neo_DatabaseError_Transaction_CouldNotRollback: "The database was unable to roll back the Transaction."
+ Neo_DatabaseError_Transaction_CouldNotWriteToLog: "The database was unable to write transaction to log."
+ Neo_DatabaseError_Transaction_ReleaseLocksFailed: "The transaction was unable to release one or more of its locks."
+ Neo_TransientError_General_DatabaseUnavailable: "The database is not currently available to serve your request, refer to the database logs for more details. Retrying your request at a later time may succeed."
+ Neo_TransientError_Network_UnknownFailure: "An unknown network failure occurred, a retry may resolve the issue."
+ Neo_TransientError_Schema_ModifiedConcurrently: "The database schema was modified while this transaction was running, the transaction should be retried."
+ Neo_TransientError_Security_ModifiedConcurrently: "The user was modified concurrently to this Request."
+ Neo_TransientError_Statement_ExternalResourceFailure: "The external resource is not available"
+ Neo_TransientError_Transaction_AcquireLockTimeout: "The transaction was unable to acquire a lock, for instance due to a timeout or the transaction thread being interrupted."
+ Neo_TransientError_Transaction_DeadlockDetected: "This transaction, and at least one more transaction, has acquired locks in a way that it will wait indefinitely, and the database has aborted it. Retrying this transaction will most likely be successful." \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/config/test-apis-ci/users-configuration.yaml b/test-apis-ci/src/test/resources/config/test-apis-ci/users-configuration.yaml
new file mode 100644
index 0000000000..a6c23653f0
--- /dev/null
+++ b/test-apis-ci/src/test/resources/config/test-apis-ci/users-configuration.yaml
@@ -0,0 +1,2 @@
+userCredentials:
+ ci: 2a1f887d607d4515d4066fe0f5452a50:0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b \ No newline at end of file
diff --git a/test-apis-ci/src/test/resources/cucumber/tenantIsolation.feature b/test-apis-ci/src/test/resources/cucumber/tenantIsolation.feature
new file mode 100644
index 0000000000..f1a0f6f6e3
--- /dev/null
+++ b/test-apis-ci/src/test/resources/cucumber/tenantIsolation.feature
@@ -0,0 +1,38 @@
+Feature: Tenant Isolation Feature
+
+ #Get individual external AT&T Certificate API
+ Scenario Outline: Create operational Envrionment
+ Given AAI returns <retcode> and aai_body contains <tenant> and <workload>
+ When The Number Of Operational Envrinoments that created is <numberOfEnvs> and Records are added with data <recordData>
+ Then The Number Of Environment is <numberOfEnvs> with status <recordStatus>
+ #Verify Succesfull A&AI Call
+ And Operational Environment record contains tenant field <isTenantExist>
+ And Operational Environment record contains workload field <isWorkloadtExist>
+ #Verify Succesfull DME Call
+ And Operational Environment record contains UEB Address field <isUebAddressExist>
+
+ Examples:
+ | retcode | tenant | workload | recordData | numberOfEnvs | recordStatus | isTenantExist | isWorkloadtExist | isUebAddressExist |
+ | 200 | Test | VNF_Development | {"status": "failed", "last_modified_delta": 0} | 1 | completed | true | true | true |
+
+ Scenario Outline: Distribute To Operational Environment
+ Given ASDC Address is 127.0.0.1
+ And The number of complete environments is <numberOfEnvs>
+ #Start SImulator for each envrionment
+ And The number of artifacts each Simulator downloads from a service is <numberOfArtifactsDownloaded>
+ #5 (3 days) - run jar
+ And MSO-WD Simulators Started with topic name MSHITRIT-D2D
+ And ASDC Contains the following services <ListOfServicesUUID>
+ # (1.5 days)
+ And MSO Final Distribution Simulator is UP
+ #4 (Sends 75 request )(2 days)
+ When Distribution Requests are Sent By MSO
+ Then All MSO-WD Simulators Sent The Distribution Complete Notifications
+ And All Artifacts were downloaded by Simulators
+ #6
+ And MSO Final Distribution Recieved Correct Number Of Request
+
+ Examples:
+ | numberOfEnvs | numberOfArtifactsDownloaded | ListOfServicesUUID |
+ #| 5 | 8 | 74e05aac-48d5-4642-8dc1-dc1ddeb5c0f5,fa86100a-409b-4310-835c-e401896181a5,8dbc41cc-2076-49c0-b95b-cb37b1539367,0c7eb2ac-06c0-41e1-b635-825037942e28,840123d1-b9d6-4036-8e94-471b268026bf,74331473-1eb0-4628-84b8-ab47948f7023, 3277af19-d152-4d94-a4d0-44ad6f226b52, e553c12b-b67b-4d66-a6a9-8676d5e0becf, f648052e-3207-4eb2-9336-29f2fe9df618, 535c6ad3-ad2b-429f-ab9b-b654cf647c86,611c764d-8862-4f09-a8e0-1622f8d97ce9, b5df0774-2445-4daf-b893-61c014652145, 01481626-b58a-49b5-ba1e-74eb8508ed15, 9e17345a-d11d-4219-b4e3-e86cfdb51d07, 5ff40fbc-f4e9-45f1-85de-0a04b8a5d60c |
+ | 2 | 2 | 74e05aac-48d5-4642-8dc1-dc1ddeb5c0f5,fa86100a-409b-4310-835c-e401896181a5 |
diff --git a/test-apis-ci/src/test/resources/preferredRouter.txt b/test-apis-ci/src/test/resources/preferredRouter.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/test-apis-ci/src/test/resources/preferredRouter.txt
diff --git a/ui-ci-dev/.gitignore b/ui-ci-dev/.gitignore
deleted file mode 100644
index 6405eb7c05..0000000000
--- a/ui-ci-dev/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/bin/
-test-output/ \ No newline at end of file
diff --git a/ui-ci-dev/pom.xml b/ui-ci-dev/pom.xml
deleted file mode 100644
index 1d6afa9c01..0000000000
--- a/ui-ci-dev/pom.xml
+++ /dev/null
@@ -1,272 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-main</artifactId>
- <!-- <version>${asdc.version}</version> -->
- <version>1.1.0-SNAPSHOT</version>
- </parent>
- <artifactId>ui-ci-dev</artifactId>
- <description>Selenium tests for the SDnC Application</description>
-
-
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-java</artifactId>
- <version>3.0.1</version>
- </dependency>
-
- <dependency>
- <groupId>org.seleniumhq.selenium</groupId>
- <artifactId>selenium-server</artifactId>
- <version>2.48.2</version>
- <scope>runtime</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>asdc-tests</artifactId>
- <version>${asdc-tests.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>${snakeyaml.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>${gson.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- http client -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpmime</artifactId>
- <version>${httpclient.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>1.3.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>${commons-logging}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- http core -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpcore</artifactId>
- <version>${httpcore.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <!-- TITAN -->
- <dependency>
- <groupId>com.thinkaurelius.titan</groupId>
- <artifactId>titan-core</artifactId>
- <version>${titan.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.thinkaurelius.titan</groupId>
- <artifactId>titan-cassandra</artifactId>
- <version>${titan.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.2</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.3.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.3.1</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.openecomp.sdc</groupId>
- <artifactId>sdc-distribution-client</artifactId>
- <version>1.1.3</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.testng</groupId>
- <artifactId>testng</artifactId>
- <version>${testng.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>xml-apis</groupId>
- <artifactId>xml-apis</artifactId>
- <version>1.4.01</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.googlecode.json-simple</groupId>
- <artifactId>json-simple</artifactId>
- <version>${json-simple.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>com.relevantcodes</groupId>
- <artifactId>extentreports</artifactId>
- <version>1.4</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jci-core</artifactId>
- <version>${commons-jci-core.version}</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.sikuli</groupId>
- <artifactId>sikuli-api</artifactId>
- <version>1.2.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.sikuli</groupId>
- <artifactId>sikuli-core</artifactId>
- <version>1.2.2</version>
- </dependency>
-
-
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>${commons-codec}</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
-
-
-
- <build>
- <plugins>
-
- <!-- ================================================== -->
- <!-- Get the next versions from the properties file. -->
- <!-- ================================================== -->
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>properties-maven-plugin</artifactId>
- <version>1.0-alpha-1</version>
- <inherited>false</inherited>
-
- <executions>
- <execution>
- <id>ui-ci-dev</id>
- <phase>initialize</phase>
- <goals>
- <goal>read-project-properties</goal>
- </goals>
-
- <configuration>
- <files>
- <file>../target/FullReleaseVersion.properties</file>
- </files>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
-
-
- <!-- ============================================= -->
- <!-- Create the JAR file with its dependencies -->
- <!-- ============================================= -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.5.5</version>
- <executions>
- <execution>
- <id>create.jar.with.dependencies</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <configuration>
- <archive>
- <manifest>
- <mainClass>org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest</mainClass>
- </manifest>
- </archive>
- <descriptorRefs>
- <descriptorRef>jar-with-dependencies</descriptorRef>
- </descriptorRefs>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
-
- <!-- =========================== -->
- <!-- HP Fortify scanner -->
- <!-- =========================== -->
- <plugin>
- <groupId>com.fortify.ps.maven.plugin</groupId>
- <artifactId>sca-maven-plugin</artifactId>
- <version>4.30</version>
- <configuration>
- <scanEnabled>false</scanEnabled>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
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
deleted file mode 100644
index b11f8d19ef..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/scripts/CreateVfsFromOnboarding.java
+++ /dev/null
@@ -1,67 +0,0 @@
-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.<br>
- * 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<String> zipFileNames = Arrays.asList(listOfFiles).stream().map(file -> file.getName())
- .filter(fileName -> fileName.endsWith(".zip")).collect(Collectors.toList());
- Map<String, String> 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
deleted file mode 100644
index c23d05ab23..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasElement.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package org.openecomp.sdc.uici.tests.datatypes;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-
-public final class CanvasElement {
- private final String uniqueId;
- private ImmutablePair<Integer, Integer> location;
- private String elementName;
-
- public String getElementName() {
- return elementName;
- }
-
- public CanvasElement(String uniqueId, String elementName, ImmutablePair<Integer, Integer> location) {
- super();
- this.uniqueId = uniqueId;
- this.location = location;
- this.elementName = elementName;
- }
-
- public String getUniqueId() {
- return uniqueId;
- }
-
- public ImmutablePair<Integer, Integer> getLocation() {
- return location;
- }
-
- public void setLocation(ImmutablePair<Integer, Integer> 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
deleted file mode 100644
index 5ef8c7a56a..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CanvasManager.java
+++ /dev/null
@@ -1,206 +0,0 @@
-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<String, CanvasElement> 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<CanvasElement> getCanvasElements() {
- return canvasElements.values().stream().collect(Collectors.toList());
- }
-
- private void addCanvasElement(CanvasElement element) {
- canvasElements.put(element.getUniqueId(), element);
- }
-
- private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair<Integer, Integer> 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<Integer, Integer> 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<Integer, Integer> 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<Integer, Integer> getFreePosition() {
- // TODO ui-ci use better method
- ImmutablePair<Integer, Integer> randomPosition = null;
- boolean freePosition = false;
- int minSpace = 150;
- while (!freePosition) {
- ImmutablePair<Integer, Integer> 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<Integer, Integer> 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<Integer, Integer>(xElement, yElement);
- }
-
- /**
- * Links two elements on canvas.<br>
- * Currently Supports Only elements in the default size.<br>
- * Will not work for container type or smaller elements (cp, vl etc...)<br>
- *
- * @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
deleted file mode 100644
index f0691b89fc..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CleanTypeEnum.java
+++ /dev/null
@@ -1,28 +0,0 @@
-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<CleanTypeEnum> 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
deleted file mode 100644
index 382584a48d..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndImportButtonsEnum.java
+++ /dev/null
@@ -1,7 +0,0 @@
-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
deleted file mode 100644
index 454affe528..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/CreateAndUpdateStepsEnum.java
+++ /dev/null
@@ -1,25 +0,0 @@
-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
deleted file mode 100644
index 2eb838281d..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/DataTestIdEnum.java
+++ /dev/null
@@ -1,477 +0,0 @@
-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
deleted file mode 100644
index 4c45858de0..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/MenuOptionsEnum.java
+++ /dev/null
@@ -1,17 +0,0 @@
-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
deleted file mode 100644
index 0d94529b89..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/datatypes/UserCredentials.java
+++ /dev/null
@@ -1,29 +0,0 @@
-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
deleted file mode 100644
index f9e294cbc7..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/base/SetupCDTest.java
+++ /dev/null
@@ -1,419 +0,0 @@
-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<Edge> edgeList = Lists.newArrayList(getTitanGraph().edges(null));
- List<Vertex> verList = Lists.newArrayList(getTitanGraph().vertices(null));
- setSnapshot(new TitanSnapshot(edgeList, verList));
-
- }
-
- private static class TitanSnapshot {
- List<Edge> edges;
- List<Vertex> vertices;
-
- public List<Edge> getEdges() {
- return edges;
- }
-
- public List<Vertex> getVertices() {
- return vertices;
- }
-
- private TitanSnapshot(List<Edge> edges, List<Vertex> vertices) {
- super();
- this.edges = edges;
- this.vertices = vertices;
- }
- }
-
- private void resetToOriginalSnapshot() {
-
- List<Edge> joinedEdges = new ArrayList<>();
- List<Vertex> 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<Edge> edgesToRemove = removeFromList(current.getEdges(), joinedEdges, e2 -> e2.id());
- List<Vertex> verticesToRemove = removeFromList(current.getVertices(), joinedVertices, e2 -> e2.id());
-
- List<Edge> edgesToAdd = removeFromList(original.getEdges(), joinedEdges, e2 -> e2.id());
- List<Vertex> 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 <Element, ID> List<Element> removeFromList(List<Element> listToRemoveFrom, List<Element> elementsToRemove,
- Function<Element, ID> idGetter) {
- Set<ID> 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 <Element, ID> void addIfIdInList(Element e, List<Element> listToCheck, List<Element> listToAddTo,
- Function<Element, ID> idGetter) {
- Stream<Element> 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<String, String> 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<String, String>) FileHandling.parseYamlFile(credintialsFile));
- System.out.println(credentialsYamlFileMap.toString());
- return (Map<String, String>) credentialsYamlFileMap;
- }
-
- protected UserCredentials getUserCredentialsFromFile(String userRole) throws Exception {
- Map<String, String> credentialsMap = (Map<String, String>) 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.<br>
- * 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
deleted file mode 100644
index c3caa98c54..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/generalTests/GeneralTests.java
+++ /dev/null
@@ -1,26 +0,0 @@
-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
deleted file mode 100644
index e42de862b7..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceBasicTests.java
+++ /dev/null
@@ -1,147 +0,0 @@
-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: <br>
- * 1. Import of VF <br>
- * 2. Certification Of Vf <br>
- * 3. Adding deployment artifact to VF <br>
- * 4. Creation of Service <br>
- * 5. Adding Vf instance to Service <br>
- * 6. Service Certification <br>
- * 7. Approving Service to distribution by Governor <br>
- * 8. Making sure service is ready to distribute by ops <br>
- */
- @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
deleted file mode 100644
index b3e8e023ca..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/service/ServiceInputsTests.java
+++ /dev/null
@@ -1,124 +0,0 @@
-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
deleted file mode 100644
index d3bb8a1375..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfBasicTests.java
+++ /dev/null
@@ -1,333 +0,0 @@
-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<String, Map<String, Object>> artifactsListFromResponse = ArtifactUIUtils
- .getArtifactsListFromResponse(getResourceResponse.getResponse(), "artifacts");
- Map<String, Object> 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
deleted file mode 100644
index 73b09666ae..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfCanvasTests.java
+++ /dev/null
@@ -1,80 +0,0 @@
-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<String, String> 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<String, String> 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
deleted file mode 100644
index 47344b7c68..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfDeploymentTests.java
+++ /dev/null
@@ -1,340 +0,0 @@
-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
deleted file mode 100644
index a81d854630..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vf/VfOnboardingTests.java
+++ /dev/null
@@ -1,63 +0,0 @@
-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<String> zipFileNames = Arrays.asList(listOfFiles).stream().map(file -> file.getName())
- .filter(fileName -> fileName.endsWith(".zip")).collect(Collectors.toList());
- Map<String, String> 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
deleted file mode 100644
index eb4980e3a0..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/execute/vfc/VfcBasicTests.java
+++ /dev/null
@@ -1,270 +0,0 @@
-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<Boolean> supplier = () -> !GeneralUIUtils.isElementPresent("local_storage");
- Function<Boolean, Boolean> 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<Boolean> supplier = () -> GeneralUIUtils.isElementPresent(newPropName);
- Function<Boolean, Boolean> 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<Boolean> supplier = () -> GeneralUIUtils.isElementPresent(newPropName);
- Function<Boolean, Boolean> 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<Boolean> supplier = () -> GeneralUIUtils.isElementPresent(newPropName);
- Function<Boolean, Boolean> 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<WebElement> 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<Boolean> supplier = () -> GeneralUIUtils.isElementPresent(newAttrName);
- Function<Boolean, Boolean> 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<Boolean> supplier = () -> GeneralUIUtils.isElementPresent("float");
- Function<Boolean, Boolean> 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
deleted file mode 100644
index 25cf4749c5..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/run/StartTest.java
+++ /dev/null
@@ -1,252 +0,0 @@
-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<String> suites = new ArrayList<String>();
- 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<Class> getClassesForPackage(String pkgname) {
-
- List<Class> classes = new ArrayList<Class>();
-
- // 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<JarEntry> 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("<tr>");
- results.append("<th>").append("Unit Test").append("</th>");
- results.append("<th>").append("Result").append("</th>");
- results.append("</tr>");
- }
-
- // private void addUnitTestResult(StringBuilder results,
- // Class<? extends AttSdcTest> testClass, Result unitTestResult) {
- //
- // boolean isSuccess = unitTestResult.wasSuccessful();
- //
- // String result = (isSuccess) ? "success" : "fail";
- // String fileName = FileUtils.getFileName(testClass.getName());
- // results.append("<tr>");
- // //
- // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
- // results.append("<td class=\"name\">")
- // .append("<a href=\"" + fileName + timeOfTest + ".html\">"
- // + fileName + "</a>").append("</td>");
- // results.append("<td class=\"" + result + "\">").append(result)
- // .append("</td>");
- // results.append("</tr>");
- // }
-
-}
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
deleted file mode 100644
index 91c9c07da8..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ArtifactUIUtils.java
+++ /dev/null
@@ -1,70 +0,0 @@
-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<String, Map<String, Object>> getArtifactsListFromResponse(String jsonResponse,
- String fieldOfArtifactList) {
- JSONObject object = (JSONObject) JSONValue.parse(jsonResponse);
- Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) object.get(fieldOfArtifactList);
- return map;
- }
-
- /**
- * Creates a deployment artifact on the vf. <br>
- * 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
deleted file mode 100644
index b1549741ed..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/FileHandling.java
+++ /dev/null
@@ -1,30 +0,0 @@
-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
deleted file mode 100644
index 42aab187ea..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/GeneralUIUtils.java
+++ /dev/null
@@ -1,344 +0,0 @@
-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<WebElement> 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<WebElement> 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<WebElement> getWebElementsListWaitForVisible(String dataTestId) {
- WebDriverWait wait = new WebDriverWait(getDriver(), DEFAULT_WAIT_TIME_IN_SECONDS);
- ExpectedCondition<List<WebElement>> 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<WebElement> 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.<br>
- * If 10 seconds has passed and loader didn't finish throws
- * LoaderStuckException.<br>
- */
- public static void waitForLoader() {
- waitForLoader(10);
- }
-
- /**
- * waits until either loader finishes or maxWaitTimeInSeconds has
- * passed.<br>
- * If maxWaitTimeInSeconds has passed and loader didn't finish throws
- * LoaderStuckException.<br>
- *
- * @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.<br>
- * 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<Boolean> elementPresenseChecker = () -> GeneralUIUtils.isElementPresent(dataTestId);
- Function<Boolean, Boolean> 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
deleted file mode 100644
index 28b39e86f3..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/MethodManipulationUtils.java
+++ /dev/null
@@ -1,15 +0,0 @@
-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
deleted file mode 100644
index 3d21539e86..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/OnboardUtility.java
+++ /dev/null
@@ -1,477 +0,0 @@
-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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String> 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<String, String> prepareHeadersMap(String userId) {
- Map<String, String> headersMap = new HashMap<String, String>();
- 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
deleted file mode 100644
index 149912944e..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ResourceUIUtils.java
+++ /dev/null
@@ -1,299 +0,0 @@
-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<String> taglist = new ArrayList<String>();
- ;
- 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<String, String> 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<String, String>(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<Resource> resourceGetter = () -> {
- String resourceString = RestCDUtils.getResource(createResourceInUI).getResponse();
- return ResponseParser.convertResourceResponseToJavaObject(resourceString);
- };
- Function<Resource, Boolean> 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
deleted file mode 100644
index 8b602e305d..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/RestCDUtils.java
+++ /dev/null
@@ -1,167 +0,0 @@
-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<RestResponse> resourceGetter = () -> swallowException(
- () -> ResourceRestUtils.getResourceByNameAndVersion(userId, resourceName, resourceVersion));
- Function<RestResponse, Boolean> 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<RestResponse> serviceFetcher = () -> swallowException(
- () -> ServiceRestUtils.getServiceByNameAndVersion(user, service.getName(), service.getVersion()));
- Function<RestResponse, Boolean> 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<String, String> getAllElementVersionsFromResponse(RestResponse getResource) throws Exception {
- Map<String, String> versionsMap = new HashMap<String, String>();
- 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<String, String> elementVersions, boolean isBeforeTest, Object clazz,
- User user) throws Exception {
- Iterator<String> 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<String, String> 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
deleted file mode 100644
index 0130b710a0..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/utilities/ServiceUIUtils.java
+++ /dev/null
@@ -1,147 +0,0 @@
-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<String> taglist = new ArrayList<String>();
- ;
- 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<Service> serviceGetter = () -> {
- String resourceString = RestCDUtils.getService(createServiceInUI, user).getResponse();
- return ResponseParser.convertServiceResponseToJavaObject(resourceString);
- };
- Function<Service, Boolean> verifier = res -> res.getLifecycleState() == requestedLifeCycleState;
- return FunctionalInterfaces.retryMethodOnResult(serviceGetter, verifier);
-
- }
-
- /**
- * This Method Approves service for distribution<br>
- * 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
deleted file mode 100644
index 0306df0638..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/ServiceVerificator.java
+++ /dev/null
@@ -1,55 +0,0 @@
-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<RestResponse> serviceGetter = () -> FunctionalInterfaces.swallowException(
- () -> ServiceRestUtils.getServiceByNameAndVersion(user, createServiceInUI.getName(), "1.0"));
- Function<RestResponse, Boolean> 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
deleted file mode 100644
index 9e983b44d3..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VerificatorUtil.java
+++ /dev/null
@@ -1,27 +0,0 @@
-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<Boolean> verificator) {
- Function<Boolean, Boolean> 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
deleted file mode 100644
index a1c7ca002b..0000000000
--- a/ui-ci-dev/src/main/java/org/openecomp/sdc/uici/tests/verificator/VfVerificator.java
+++ /dev/null
@@ -1,143 +0,0 @@
-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<Boolean> 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<String, String> prevRIPos, User user) {
- Supplier<Boolean> verificator = () -> {
- ImmutablePair<String, String> 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<Boolean> 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<ArtifactTypeEnum> artifactTypeEnums) {
- String resourceString = RestCDUtils.getResource(vfToVerify).getResponse();
- Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceString);
- List<String> foundArtifacts = new ArrayList<>();
- if (resource.getDeploymentArtifacts() != null) {
- foundArtifacts = resource.getDeploymentArtifacts().values().stream()
- .map(artifact -> artifact.getArtifactType()).collect(Collectors.toList());
- }
- List<String> 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
deleted file mode 100644
index dcb78eefc1..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/attsdc-packages.yaml
+++ /dev/null
@@ -1,2 +0,0 @@
-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
deleted file mode 100644
index 8cd8068d08..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/attsdc.yaml
+++ /dev/null
@@ -1,80 +0,0 @@
-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/log4j.properties b/ui-ci-dev/src/main/resources/ci/conf/log4j.properties
deleted file mode 100644
index 3e159ec8df..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/log4j.properties
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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
deleted file mode 100644
index 94d12cfba0..0000000000
--- a/ui-ci-dev/src/main/resources/ci/conf/titan.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-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
deleted file mode 100644
index cc58bc22c5..0000000000
--- a/ui-ci-dev/src/main/resources/ci/scripts/startTest.sh
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/bin/bash
-
-TOMCAT_DIR=/home/apache-tomcat-7.0.41/webapps/sdc-ci
-
-function usage {
- echo "Usage: $0 <jar file>"
-}
-
-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
deleted file mode 100644
index 9f912e58b8..0000000000
--- a/ui-ci-dev/src/main/resources/ci/testSuites/fullTests.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="uiFullTests" configfailurepolicy="continue" verbose="2">
- <parameter name="clean-type" value="FULL" /> <!--Valid Values are: PARTIAL, FULL, NONE -->
- <test name="Vfc Tests">
- <classes>
- <class name="org.openecomp.sdc.uici.tests.execute.vfc.VfcBasicTests"></class>
- </classes>
- </test>
-
- <test name="VF Tests">
- <classes>
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfBasicTests" />
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfCanvasTests" />
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfOnboardingTests" />
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfDeploymentTests"/>
- </classes>
- </test>
-
- <test name="Service Tests">
- <classes>
- <class name="org.openecomp.sdc.uici.tests.execute.service.ServiceBasicTests"></class>
- <class name="org.openecomp.sdc.uici.tests.execute.service.ServiceInputsTests"></class>
- </classes>
- </test>
-</suite>
diff --git a/ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml b/ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml
deleted file mode 100644
index 99e8765038..0000000000
--- a/ui-ci-dev/src/main/resources/ci/testSuites/sanity.xml
+++ /dev/null
@@ -1,55 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="uiSanity" configfailurepolicy="continue" verbose="2">
- <parameter name="clean-type" value="FULL" /> <!--Valid Values are: PARTIAL, FULL, NONE -->
- <test name="Vfc Tests">
- <classes>
- <class name="org.openecomp.sdc.uici.tests.execute.vfc.VfcBasicTests">
- <methods>
- <include name="testImportVfc" />
- <include name="testUpdateTypeForAttributeOfVfc" />
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="VF Tests">
- <classes>
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfBasicTests">
- <methods>
- <include name="testImportVf" />
- <include name="testUpdateInstanceAttributeValue" />
- <include name="testVfCertification" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfCanvasTests">
- <methods>
- <include name="testCanvasVFSanity" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.uici.tests.execute.vf.VfDeploymentTests">
- <methods>
- <include name="testUpdateModuleNameSanity" />
- <include name="testTabsViewSanity"/>
- </methods>
- </class>
- </classes>
- </test>
-
- <test name="Service Tests">
- <classes>
- <class name="org.openecomp.sdc.uici.tests.execute.service.ServiceBasicTests">
- <methods>
- <include name="testLinkTwoRI" />
- <include name="testBuildServiceForDistribution" />
- </methods>
- </class>
- <class name="org.openecomp.sdc.uici.tests.execute.service.ServiceInputsTests">
- <methods>
- <include name="testInputsSanity" />
- </methods>
- </class>
- </classes>
- </test>
-
-</suite>
diff --git a/ui-ci-dev/src/main/resources/images/gizmorambo.jpg b/ui-ci-dev/src/main/resources/images/gizmorambo.jpg
deleted file mode 100644
index c9a8fe8a64..0000000000
--- a/ui-ci-dev/src/main/resources/images/gizmorambo.jpg
+++ /dev/null
Binary files differ
diff --git a/ui-ci-dev/src/test/Completetheform.js b/ui-ci-dev/src/test/Completetheform.js
deleted file mode 100644
index 7e8b7572cc..0000000000
--- a/ui-ci-dev/src/test/Completetheform.js
+++ /dev/null
@@ -1,3 +0,0 @@
-/**
- * New node file
- */
diff --git a/ui-ci/pom.xml b/ui-ci/pom.xml
index b7cf230b2f..1fc9f7054b 100644
--- a/ui-ci/pom.xml
+++ b/ui-ci/pom.xml
@@ -11,10 +11,10 @@
<artifactId>sdc-main</artifactId>
<version>1.2.0-SNAPSHOT</version>
</parent>
-
+
<properties>
- <sonar.skip>true</sonar.skip>
<jacoco.skip>true</jacoco.skip>
+ <aspectj.version>1.8.10</aspectj.version>
</properties>
<dependencies>
@@ -22,22 +22,22 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
-<!-- <version>21.0</version> -->
+ <!-- <version>21.0</version> -->
<scope>compile</scope>
</dependency>
-
+
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
-<!-- <version>3.4.0</version> -->
+ <!-- <version>3.4.0</version> -->
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.53.1</version>
-<!-- <version>3.4.0</version> -->
+ <!-- <version>3.4.0</version> -->
<scope>runtime</scope>
</dependency>
@@ -69,7 +69,7 @@
<version>${snakeyaml.version}</version>
<scope>compile</scope>
</dependency>
- <dependency>
+ <dependency>
<groupId>org.functionaljava</groupId>
<artifactId>functionaljava</artifactId>
<version>${functionaljava.version}</version>
@@ -87,42 +87,42 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
- <version>${httpclient.version}</version>
+ <version>${httpclient.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
- <version>${commons-logging}</version>
+ <version>${commons-logging}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>${slf4j-api.version}</version>
+ <version>${slf4j-api.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
- <version>${logback.version}</version>
+ <version>${logback.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
+ <version>${logback.version}</version>
<scope>compile</scope>
</dependency>
@@ -143,8 +143,8 @@
</dependency>
<dependency>
- <groupId>org.openecomp.sdc.sdc-titan-cassandra</groupId>
- <artifactId>sdc-titan-cassandra</artifactId>
+ <groupId>com.thinkaurelius.titan</groupId>
+ <artifactId>titan-cassandra</artifactId>
<version>${titan.version}</version>
<scope>compile</scope>
</dependency>
@@ -169,18 +169,18 @@
<version>2.3.1</version>
<scope>compile</scope>
</dependency>
-
+
<dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
<version>${jackson.annotations.version}</version>
- <scope>compile</scope>
- </dependency>
+ <scope>compile</scope>
+ </dependency>
<dependency>
<groupId>org.openecomp.sdc.sdc-distribution-client</groupId>
<artifactId>sdc-distribution-client</artifactId>
- <version>1.1.50-SNAPSHOT</version>
+ <version>1.2.3</version>
<scope>compile</scope>
</dependency>
@@ -194,7 +194,7 @@
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
- <version>${testng.version}</version>
+ <version>6.11</version>
<scope>compile</scope>
</dependency>
@@ -234,38 +234,48 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
- <version>${commons-codec}</version>
+ <version>${commons-codec}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.aventstack</groupId>
+ <artifactId>extentreports</artifactId>
+ <version>3.0.6</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>net.lightbody.bmp</groupId>
+ <!-- To use the legacy, Jetty-based implementation, change the artifactId
+ to browsermob-core -->
+ <artifactId>browsermob-core</artifactId>
+ <version>2.1.4</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.github.markusbernhardt</groupId>
+ <artifactId>proxy-vole</artifactId>
+ <version>1.0.2</version>
+ </dependency>
+
+ <dependency>
+ <groupId>com.paulhammant</groupId>
+ <artifactId>ngwebdriver</artifactId>
+ <version>0.9.7</version>
<scope>compile</scope>
</dependency>
<dependency>
- <groupId>com.aventstack</groupId>
- <artifactId>extentreports</artifactId>
- <version>3.0.6</version>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>net.lightbody.bmp</groupId>
- <!-- To use the legacy, Jetty-based implementation,
- change the artifactId to browsermob-core -->
- <artifactId>browsermob-core</artifactId>
- <version>2.1.4</version>
- </dependency>
-
- <dependency>
- <groupId>com.github.markusbernhardt</groupId>
- <artifactId>proxy-vole</artifactId>
- <version>1.0.2</version>
- </dependency>
-
- <dependency>
- <groupId>com.paulhammant</groupId>
- <artifactId>ngwebdriver</artifactId>
- <version>0.9.7</version>
- <scope>compile</scope>
- </dependency>
-
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ <version>4.1.0</version>
+ </dependency>
+
+
+
+
+
</dependencies>
<build>
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
index 47fd8330c5..f72e531b61 100644
--- 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
@@ -37,10 +37,7 @@ 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.AmdocsLicenseMembers;
-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.*;
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;
@@ -52,14 +49,15 @@ import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils;
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.OnboardingUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.clearspring.analytics.util.Pair;
-
+import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorSoftwareProductRestUtils;
public class AddComponentInstancesArtifactsInCsar extends SetupCDTest {
@@ -84,15 +82,14 @@ public class AddComponentInstancesArtifactsInCsar extends SetupCDTest {
String vnfFile = "FDNT.zip";
String snmpFile = "Fault-alarms-ASDC-vprobes-vLB.zip";
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(getUser());
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> createVSP = OnboardingUtils.createVSP(resourceReqDetails, vnfFile, filePath, getUser(), amdocsLicenseMembers);
+ Pair<String, VendorSoftwareProductObject> createVSP = VendorSoftwareProductRestUtils.createVSP(resourceReqDetails, vnfFile, filePath, getUser(), amdocsLicenseMembers);
String vspName = createVSP.left;
resourceMetaData.setName(vspName);
- Map<String, String> resourceMeta = createVSP.right;
- String vspid = resourceMeta.get("vspId");
- OnboardingUtils.addVFCArtifacts(filePath, snmpFile, null, vspid, getUser());
- OnboardingUtils.prepareVspForUse(getUser(), vspid, "0.1");
+ VendorSoftwareProductObject resourceMeta = createVSP.right;
+ VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpFile, null, resourceMeta, getUser());
+ VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), resourceMeta, true);
HomePage.showVspRepository();
OnboardingUiUtils.importVSP(createVSP);
@@ -355,7 +352,7 @@ public class AddComponentInstancesArtifactsInCsar extends SetupCDTest {
Integer responseCode = uploadArtifactRestResponse.getErrorCode();
Assert.assertEquals(responseCode, (Integer)200, "Response code is not correct.");
- ImmutablePair<ComponentInstance, ArtifactDefinition> pair = ImmutablePair.of(componentInstance, ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse()));
+ ImmutablePair<ComponentInstance, ArtifactDefinition> pair = ImmutablePair.of(componentInstance, ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactRestResponse.getResponse()));
return pair;
}
@@ -381,7 +378,7 @@ public class AddComponentInstancesArtifactsInCsar extends SetupCDTest {
Assert.assertEquals(responseCode, (Integer)200, "Response code is not correct.");
- ImmutablePair<ComponentInstance, ArtifactDefinition> pair = ImmutablePair.of(componentInstance, ArtifactRestUtils.getArtifactDataFromJson(uploadArtifactRestResponse.getResponse()));
+ ImmutablePair<ComponentInstance, ArtifactDefinition> pair = ImmutablePair.of(componentInstance, ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactRestResponse.getResponse()));
return pair;
}
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
index 8fd3c469be..efe2ca1466 100644
--- 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
@@ -44,7 +44,6 @@ 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 {
@@ -56,10 +55,6 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
@Test
public void importVfvArtifactsDeploymentArtifactsMultipleArtifactsMultipleTypes() throws Exception {
- if(true){
- throw new SkipException("Due to the new design the test should be updated accordingly");
- }
-
String filePath = FileHandling.getFilePath(folder);
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
@@ -80,6 +75,8 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
List<ArtifactDefinition> filteredArtifactNames =
//Stream of component Instances
resource.getComponentInstances().stream()
+ //filter out all nulls
+ .filter( e -> e.getDeploymentArtifacts() != null )
//Stream of all the artifacts on all the component instances
.flatMap( e -> e.getDeploymentArtifacts().values().stream())
//filter relevant artifact types
@@ -87,7 +84,6 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
//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())
@@ -109,81 +105,31 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
});
}
-
-
-
- // 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("Due to the new design the test should be updated accordingly");
- }
-
- 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<String, List<String>> artifactsMap = new HashMap<String, List<String>>() {
- {
- 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("Due to the new design the test should be updated accordingly");
- }
-
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")) {
+ if(e.getToscaComponentName().endsWith("heat.cm")) {
Map<String, List<String>> deployArtifactsMap = new HashMap<String, List<String>>() {
{
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<String, List<String>> infoArtifactsMap = new HashMap<String, List<String>>() {
- {
- 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");
-
+ validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.cm");
} else if (e.getToscaComponentName().endsWith("heat.sm")) {
Map<String, List<String>> deployArtifactsMap = new HashMap<String, List<String>>() {
@@ -193,14 +139,6 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
}
};
validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.sm");
-
- Map<String, List<String>> infoArtifactsMap = new HashMap<String, List<String>>() {
- {
- 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");
}
});
@@ -211,18 +149,12 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
@Test
public void importVfcArtifactsDeploymentArtifactsExtraFolderUnderVfcIdentification() throws Exception {
- if(true){
- throw new SkipException("Due to the new design the test should be updated accordingly");
- }
-
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 -> {
@@ -235,14 +167,6 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
}
};
validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ltm");
-
- Map<String, List<String>> infoArtifactsMap = new HashMap<String, List<String>>() {
- {
- 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");
}
});
}
@@ -253,18 +177,12 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
@Test
public void importVfcArtifactsDeploymentArtifactsInvalidArtifactType() throws Exception {
- if(true){
- throw new SkipException("Due to the new design the test should be updated accordingly");
- }
-
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 -> {
@@ -277,44 +195,15 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
}
};
validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ltm");
-
- Map<String, List<String>> infoArtifactsMap = new HashMap<String, List<String>>() {
- {
- 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<String, List<String>> artifactsMap, String endswith){
- if(instacne.getToscaComponentName().endsWith(endswith) ){
- Set<String> types = artifactsMap.keySet();
- Map<String, List<ArtifactDefinition>> 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<String> 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<String, List<String>> artifactsMap, String endswith){
- if(instacne.getToscaComponentName().endsWith(endswith) ){
+ private void validateDeploymentArtifactOnComponetInstance(ComponentInstance instance, Map<String, List<String>> artifactsMap, String endswith){
+ if(instance.getToscaComponentName().endsWith(endswith) ){
Set<String> types = artifactsMap.keySet();
- Map<String, List<ArtifactDefinition>> collect = instacne.getDeploymentArtifacts().values().stream()
+ Map<String, List<ArtifactDefinition>> collect = instance.getDeploymentArtifacts().values().stream()
.filter( a -> types.contains(a.getArtifactType()))
.collect(Collectors.groupingBy( e -> e.getArtifactType()));
@@ -330,11 +219,6 @@ public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest {
}
}
-
-
-
-
-
@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
index e2650fe4b3..9018da6eae 100644
--- 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
@@ -19,11 +19,8 @@
*/
package org.openecomp.sdc.ci.tests.US;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
+import com.clearspring.analytics.util.Pair;
import org.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
@@ -31,14 +28,18 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject;
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.OnboardingUiUtils;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorSoftwareProductRestUtils;
-import com.clearspring.analytics.util.Pair;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
public class LocalGeneralUtilities {
@@ -76,8 +77,8 @@ public static List<String> getValuesFromJsonArray(RestResponse message) throws E
}
public static String simpleOnBoarding(ResourceReqDetails resourceReqDetails, String fileName, String filePath,User user) throws Exception {
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(user);
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, fileName, filePath, user, amdocsLicenseMembers);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(user);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, fileName, filePath, user, amdocsLicenseMembers);
String vspName = createVendorSoftwareProduct.left;
HomePage.showVspRepository();
OnboardingUiUtils.importVSP(createVendorSoftwareProduct);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java
index a7d96dd2c7..7815f69d99 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java
@@ -86,7 +86,7 @@ public class MIBsArtifactsOnResourceInstance extends SetupCDTest {
// 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL.
ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
- List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>();
+ List<ArtifactInfo> 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) {
@@ -101,6 +101,7 @@ public class MIBsArtifactsOnResourceInstance extends SetupCDTest {
// 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);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java
index 6ae9a34a84..2362a1acab 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java
@@ -24,12 +24,8 @@ 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.*;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.StepsEnum;
-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;
@@ -54,7 +50,7 @@ public class Service_Tests_UI extends SetupCDTest{
public void declareVL_CP_InputsInServiceLevel() throws Exception {
String vnfFile = "FDNT.zip";
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> VspName = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> VspName = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
ServiceReqDetails servicemetadata = ElementFactory.getDefaultService(getUser());
ServiceUIUtils.createService(servicemetadata, getUser());
GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
@@ -73,7 +69,7 @@ public class Service_Tests_UI extends SetupCDTest{
public void CreateServiceWithCpInstance() throws Exception {
String vnfFile = "FDNT.zip";
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> VspName = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> VspName = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
ServiceReqDetails servicemetadata = ElementFactory.getDefaultService(getUser());
ServiceUIUtils.createService(servicemetadata, getUser());
GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Testing.java
index 9c727bb100..69f90baee5 100644
--- 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
@@ -22,6 +22,7 @@ package org.openecomp.sdc.ci.tests.US;
import java.io.File;
import java.text.SimpleDateFormat;
+import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@@ -34,6 +35,8 @@ import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils;
import org.testng.Assert;
+import fj.data.Array;
+
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
index 3efb42d569..515649a486 100644
--- 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
@@ -20,50 +20,33 @@
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 com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.ci.tests.dataProviders.OnbordingDataProviders;
-import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
+import org.openecomp.sdc.ci.tests.datatypes.*;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ToscaArtifactsScreenEnum;
-import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
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.pages.*;
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.*;
import org.openecomp.sdc.ci.tests.utilities.FileHandling;
-import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils;
-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.utils.general.OnboardingUtils;
+import org.openecomp.sdc.ci.tests.utils.general.*;
import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator;
import org.openecomp.sdc.ci.tests.verificator.VfModuleVerificator;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
+import java.awt.*;
+import java.io.File;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import static org.testng.AssertJUnit.assertNotNull;
/**
* @author al714h
@@ -87,12 +70,12 @@ public class VfModule extends SetupCDTest {
getExtendTest().log(Status.INFO, String.format("Going to onboard the VNF %s......", vnfFile));
System.out.println(String.format("Going to onboard the VNF %s......", vnfFile));
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, getUser(), amdocsLicenseMembers);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, getUser(), amdocsLicenseMembers);
String vspName = createVendorSoftwareProduct.left;
//
- DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId"));
+ DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.getVspId());
File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(latestFilefromDir);
//
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
index 3b15686733..272e0c16b6 100644
--- 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
@@ -31,6 +31,8 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import ch.qos.logback.classic.util.ContextInitializer;
+import com.google.gson.Gson;
import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.ci.tests.datatypes.HeatAndHeatEnvNamesPair;
@@ -65,14 +67,14 @@ public class ArtifactBusinessLogic {
String artifactsFilePath = filePath + "Artifacts" + File.separator;
List<File> fileListFromArtifactsDirectory = FileHandling.getHeatAndHeatEnvArtifactsFromZip(new File(artifactsFilePath), okFileExtensions);
Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(pathToDirectory.toString());
- LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get(DEPLOYMENT));
+ LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = (LinkedList<HeatMetaFirstLevelDefinition>) 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()));
+ File file = new File(artifactsFilePath + deploymentArtifact.getFileName());
if(fileListFromArtifactsDirectory.contains(file)){
fileList.add(file);
}else{
@@ -184,7 +186,6 @@ public class ArtifactBusinessLogic {
if(parameter.getValue() instanceof java.util.LinkedHashMap){
pairValue = gson.toJson(parameter.getValue());
}
-// pair = Pair.create(envParametersMap.get(key).left, "\"" + pairValue + "\"");
pair = Pair.create(envParametersMap.get(key).left, pairValue );
}else if(envParametersMap.get(key).left.equals("json") && parameter.getValue() == null){
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java
index ad9ce781c8..c201eb8f94 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProvider/OnbordingDataProviders.java
@@ -1,14 +1,15 @@
package org.openecomp.sdc.ci.tests.dataProvider;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
import org.openecomp.sdc.ci.tests.execute.sanity.ToscaValidationTest;
import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
public class OnbordingDataProviders {
protected static String filepath = FileHandling.getVnfRepositoryPath();
@@ -50,10 +51,10 @@ public class OnbordingDataProviders {
}
// -----------------------factories-----------------------------------------
- @Factory(dataProvider = "VNF_List")
- public Object[] OnbordingDataProviders(String filepath, String vnfFile){
- return new Object[] { new ToscaValidationTest(filepath, vnfFile)};
- }
+// @Factory(dataProvider = "VNF_List")
+// public Object[] OnbordingDataProviders(String filepath, String vnfFile){
+// return new Object[] { new ToscaValidationTest(filepath, vnfFile)};
+// }
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
index 818b488d64..e217847815 100644
--- 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
@@ -43,6 +43,12 @@ public final class CanvasElement {
elementType = canvasItem;
}
+ public CanvasElement(String name, ImmutablePair<Integer, Integer> location) {
+ super();
+ this.uniqueId = name;
+ this.location = location;
+ }
+
public String getUniqueId() {
return uniqueId;
}
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
index b4f50020df..910cc54dad 100644
--- 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
@@ -20,14 +20,8 @@
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.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
import org.openecomp.sdc.ci.tests.datatypes.enums.CircleSize;
@@ -40,9 +34,11 @@ import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
+import org.testng.SkipException;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
public final class CanvasManager {
private Map<String, CanvasElement> canvasElements;
@@ -110,7 +106,7 @@ public final class CanvasManager {
actions.clickAndHold();
actions.release();
actions.perform();
- isKeepWaiting = GeneralUIUtils.getWebElementByTestID("selectedCompTitle").getText()
+ isKeepWaiting = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText()
.equals(containerName);
sumOfWaiting += napPeriod;
if (sumOfWaiting > maxWait) {
@@ -131,6 +127,56 @@ public final class CanvasManager {
ExtentTestActions.log(Status.INFO, String.format("Canvas element %s selected", canvasElement.getElementType()));
}
+ public void openLinkPopupReqsCapsConnection(CanvasElement canvasElement)
+ {
+ ExtentTestActions.log(Status.INFO, "Open Link popup");
+ clickOnCanvasLink(canvasElement);
+ int x = canvasElement.getLocation().getLeft() + 30; // view button x delta
+ int y = canvasElement.getLocation().getRight() + 11; // view button y delta
+ clickOnCanvasPosition(x,y);
+ GeneralUIUtils.ultimateWait();
+ }
+ public void closeLinkPopupReqsCapsConnection()
+ {
+ GeneralUIUtils.clickOnElementByTestId("Cancel");
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public void clickSaveOnLinkPopup()
+ {
+ ExtentTestActions.log(Status.INFO, "Click save on link popup");
+ GeneralUIUtils.clickOnElementByTestId("Save");
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public void deleteLinkPopupReqsCapsConnection(CanvasElement canvasElement)
+ {
+ clickOnCanvasLink(canvasElement);
+ int x = canvasElement.getLocation().getLeft() + 30; // delete button x delta
+ int y = canvasElement.getLocation().getRight() + 30; // delete button x delta
+ clickOnCanvasPosition(x,y);
+ }
+
+ public void clickOnCanvasLink(CanvasElement canvasElement) {
+ actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right);
+ actions.click().perform();
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public void clickOnCanvasPosition(int x, int y) {
+
+ try {
+ actions.moveToElement(canvas, x, y);
+ actions.click();
+ actions.perform();
+ GeneralUIUtils.ultimateWait();
+ }
+ catch (Exception e)
+ {
+ System.out.println(e);
+ }
+ }
+
public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception {
moveElementOnCanvas(canvasElement, getFreePosition());
}
@@ -182,6 +228,7 @@ public final class CanvasManager {
private CanvasElement createElementOnCanvasWithoutDuration(String elementDataTestId) throws Exception {
try {
+ CompositionPage.searchForElement(elementDataTestId);
WebElement element = findClickElement(elementDataTestId);
ImmutablePair<Integer, Integer> freePosition = getFreePosition();
actions.moveToElement(element, 20, 20);
@@ -245,12 +292,12 @@ public final class CanvasManager {
}
private void selectReqAndCapAndConnect() throws Exception {
- addFitstReqOrCapAndPressNext();
- addFitstReqOrCapAndPressNext();
+ addFirstReqOrCapAndPressNext();
+ addFirstReqOrCapAndPressNext();
linkMenuClickOnFinishButton();
}
- private void addFitstReqOrCapAndPressNext() throws Exception {
+ private void addFirstReqOrCapAndPressNext() throws Exception {
addFirstReqOrCap();
linkMenuClickOnNextButton();
}
@@ -344,12 +391,35 @@ public final class CanvasManager {
* Validate that instance was selected on right sidebar
*/
public void validateInstanceSelected(CanvasElement canvasElement) {
- long maxWait = 3000;
+ long maxWait = 5000;
+ long sumOfWaiting = 0;
+ long napPeriod = 200;
+ boolean isInstanceSelected;
+ do {
+ isInstanceSelected = CompositionPage.getSelectedInstanceName().toLowerCase().contains(canvasElement.getElementType().toLowerCase());
+
+ if (!isInstanceSelected) {
+ try {
+ TimeUnit.MILLISECONDS.sleep(napPeriod);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ sumOfWaiting += napPeriod;
+ if (sumOfWaiting > maxWait) {
+ throw new SkipException(String.format("Open bug 342260, can't select instance properly, waited for %s seconds", (int) (maxWait/1000)));
+ }
+ } while (!isInstanceSelected);
+ }
+
+ public void validateLinkIsSelected() {
+ long maxWait = 5000;
long sumOfWaiting = 0;
long napPeriod = 200;
boolean isInstanceSelected;
do {
- isInstanceSelected = CompositionPage.getSelectedInstanceName().contains(canvasElement.getElementType());
+ isInstanceSelected = GeneralUIUtils.isWebElementExistByClass("w-sdc-menu-item w-sdc-canvas-menu-item-view");
if (!isInstanceSelected) {
try {
@@ -361,7 +431,7 @@ public final class CanvasManager {
sumOfWaiting += napPeriod;
if (sumOfWaiting > maxWait) {
- Assert.fail(String.format("Can't select instance properly, waited for %s seconds", (int) (maxWait/1000)));
+ Assert.fail(String.format("Can't select link properly, waited for %s seconds", (int) (maxWait/1000)));
}
} while (!isInstanceSelected);
}
@@ -372,18 +442,27 @@ public final class CanvasManager {
GeneralUIUtils.ultimateWait();
}
- private void selectTypeOfReqCap(String reqCapType)
+ private void selectTypeOfReqCap(String dataTestId, String reqCapType)
{
- GeneralUIUtils.getSelectList(reqCapType,DataTestIdEnum.LinkMenuItems.REQ_CAP_SELECT_DATA_TESTS_ID.getValue());
- GeneralUIUtils.ultimateWait();
+ GeneralUIUtils.selectByValueTextContained(dataTestId, reqCapType);
}
public void linkElementsAndSelectCapReqTypeAndCapReqName(CanvasElement firstElement, CircleSize firstElementSize, CanvasElement secondElement, CircleSize secondElementSize, ConnectionWizardPopUpObject connectionWizardPopUpObject) throws Exception {
- drawSimpleLink(firstElement, firstElementSize, secondElement, secondElementSize);
- selectTypeOfReqCap(connectionWizardPopUpObject.getCapabilityTypeSecondItem());
- addFitstReqOrCapAndPressNext();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating link between %s and %s", firstElement.getElementType(), secondElement.getElementType()));
+ drawSimpleLink(firstElement, firstElementSize, secondElement, secondElementSize);
+ selectTypeOfReqCap(DataTestIdEnum.LinkMenuItems.REQ_CAP_SELECT_DATA_TESTS_ID.getValue(),connectionWizardPopUpObject.getCapabilityTypeSecondItem());
+ addFirstReqOrCapAndPressNext();
selectReqCapByName(connectionWizardPopUpObject.getCapabilityNameSecondItem());
linkMenuClickOnNextButton();
linkMenuClickOnFinishButton();
}
+
+ public ImmutablePair<Integer, Integer> calcMidOfLink(ImmutablePair<Integer, Integer> location1, ImmutablePair<Integer, Integer> location2)
+ {
+ int x = (location1.getLeft()+location2.getLeft())/2;
+ int y = (location1.getRight()+location2.getRight())/2;
+
+ ImmutablePair<Integer, Integer> location = new ImmutablePair<>(x,y);
+ return location;
+ }
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
index fdd6a572a4..65fdb9dc47 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
@@ -525,9 +525,10 @@ public final class DataTestIdEnum {
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"),
+ INFO_NAME("div.sdc-tile-info-line"),
VERSION("div[class^='w-sdc-dashboard-card-info-user']"),
DASHBOARD_CARD("div[class^='w-sdc-dashboard-card ']"),
+ INFO_TITLE_XPATH("//div[contains(@class,'sdc-tile-info-line title')]"),
ASSET_TYPE_CSS("span[data-tests-id='asset-type']");
private String value;
@@ -820,7 +821,13 @@ public final class DataTestIdEnum {
INPUT_DELETE_BUTTON("delete-input-button"),
INPUT_DELETE_DIALOG_DELETE("Delete"),
INPUT_DELETE_DIALOG_CLOSE("Close"),
- FILTER_CHECKBOX_ALL("filter-checkbox-all");
+ FILTER_CHECKBOX_ALL("filter-checkbox-all"),
+ FILTER_CHECKBOX_CP("filter-checkbox-cp"),
+ FILTER_CHECKBOX_VFC("filter-checkbox-vfc"),
+ FILTER_CHECKBOX_VL("filter-checkbox-vl"),
+ FILTER_APPLY_BUTTON("filter-apply-button"),
+ FILTER_CLOSE_BUTTON("filter-close-button"),
+ PROPERTY_NAME_COLUMN("property-name");
private String value;
@@ -867,6 +874,82 @@ public final class DataTestIdEnum {
this.value = value;
}
}
-
-
+
+ public enum ComplexServiceAmdocs {
+ CREATE_BUTTON("Create"),
+ PATH_LIST_BUTTON("pathsListMenuItem"),
+ CREATE_PATH_MENU_BUTTON("createPathMenuItem"),
+ PATH_NAME("pathName"),
+ PATH_PROTOCOL("pathProtocol"),
+ PATH_PORT_NUMBER("pathPortNumbers"),
+ SAVE("Save"),
+ EXTEND_BUTTON("extendPathlnk");
+
+ private String value;
+
+ public String getValue() {
+ return value;
+ }
+
+ private ComplexServiceAmdocs(String value) {
+ this.value = value;
+ }
+ }
+
+ public enum PortMirroring {
+ COLLECTOR_NODE("collector_node"),
+ EQUIP_MODEL("equip_model"),
+ EQUIP_VENDOR("equip_vendor"),
+ PMC_NAME_IN_PALLETE("Port Mirroring Configuration"),
+ PMCP_NAME_IN_PALLETE("Port Mirroring Configuration By Policy");
+
+ private String value;
+
+ public String getValue() {
+ return value;
+ }
+
+ private PortMirroring(String value) {
+ this.value = value;
+ }
+ }
+
+ public enum CompositionRightPanel_GenerInfo {
+ TYPE("rightTab_componentType"),
+ RESOURCE_TYPE("rightTab_resourceType"),
+ SELECT_VERSION("changeVersion"),
+ CATEGORY("rightTab_category"),
+ SUB_CATEGORY("rightTab_subCategory");
+
+ private String value;
+
+ public String getValue() {
+ return value;
+ }
+
+ private CompositionRightPanel_GenerInfo(String value) {
+ this.value = value;
+ }
+ }
+
+ public enum CompositionRightPanel {
+
+ COMPONENT_TITLE("selectedCompTitle"),
+ REQS_AND_CAPS_TAB("requirements-and-capabilities"),
+ EDIT_PENCIL("editPencil"),
+ INSTANCE_NAME_TEXTBOX("instanceName"),
+ DELETE_ITEM("e-sdc-small-icon-delete"),
+ REQS_AND_CAPS_TAB_XPATH("//button[@tooltip-content='Requirements and Capabilities']");
+
+ private String value;
+
+ public String getValue() {
+ return value;
+ }
+
+ private CompositionRightPanel(String value) {
+ this.value = value;
+ }
+ }
+
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirrioringConfigurationObject.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirrioringConfigurationObject.java
new file mode 100644
index 0000000000..60804cb278
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirrioringConfigurationObject.java
@@ -0,0 +1,74 @@
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import org.openecomp.sdc.be.model.Service;
+
+public class PortMirrioringConfigurationObject {
+
+ private ServiceReqDetails serviceReqDetails;
+ private String vmmeSourceName;
+ private String vprobeSourceName;
+ private CanvasManager canvasManager;
+ private CanvasElement serviceElementVmmeSourceName;
+ private CanvasElement serviceElementVprobeCollector;
+ private CanvasElement portMirroringConfigurationElement;
+ private Service service;
+ private Service serviceContainerVmme_Source;
+ private Service serviceContainerVprobe_Collector;
+
+ public PortMirrioringConfigurationObject(ServiceReqDetails serviceReqDetails, String vmmeSourceName, String vprobeSourceName,
+ CanvasManager canvasManager, CanvasElement serviceElementVmmeSourceName,
+ CanvasElement serviceElementVprobeCollector, Service service, CanvasElement portMirroringConfigurationElement,
+ Service serviceContainerVmme_Source, Service serviceContainerVprobe_Collector )
+ {
+ this.serviceReqDetails = serviceReqDetails;
+ this.vmmeSourceName = vmmeSourceName;
+ this.vprobeSourceName = vprobeSourceName;
+ this.canvasManager = canvasManager;
+ this.serviceElementVmmeSourceName = serviceElementVmmeSourceName;
+ this.serviceElementVprobeCollector = serviceElementVprobeCollector;
+ this.service = service;
+ this.portMirroringConfigurationElement = portMirroringConfigurationElement;
+ this.serviceContainerVmme_Source = serviceContainerVmme_Source;
+ this.serviceContainerVprobe_Collector = serviceContainerVprobe_Collector;
+ }
+
+ public Service getServiceContainerVmme_Source() {
+ return serviceContainerVmme_Source;
+ }
+
+ public Service getServiceContainerVprobe_Collector() {
+ return serviceContainerVprobe_Collector;
+ }
+
+ public CanvasElement getPortMirroringConfigurationElement() {
+ return portMirroringConfigurationElement;
+ }
+
+ public ServiceReqDetails getServiceReqDetails() {
+ return serviceReqDetails;
+ }
+
+ public String getVmmeSourceName() {
+ return vmmeSourceName;
+ }
+
+ public String getVprobeSourceName() {
+ return vprobeSourceName;
+ }
+
+ public CanvasManager getCanvasManager() {
+ return canvasManager;
+ }
+
+ public CanvasElement getServiceElementVmmeSourceName() {
+ return serviceElementVmmeSourceName;
+ }
+
+ public CanvasElement getServiceElementVprobeCollector() {
+ return serviceElementVprobeCollector;
+ }
+
+ public Service getService() {
+ return service;
+ }
+}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirroringEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirroringEnum.java
new file mode 100644
index 0000000000..7cbdf6fc9c
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PortMirroringEnum.java
@@ -0,0 +1,48 @@
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public enum PortMirroringEnum {
+
+ PMC_ELEMENT_IN_PALLETE("Port Mirroring Configuration"),
+ PMCP_ELEMENT_IN_PALLETE("Port Mirroring Configuration By Policy"),
+ PM_REQ_TYPE("org.openecomp.capabilities.PortMirroring"),
+ PMC_SOURCE_CAP("Port Mirroring Configuration 0: source: [1, UNBOUNDED]"),
+ PMC1_SOURCE_CAP("Port Mirroring Configuration 1: source: [1, UNBOUNDED]"),
+ PMCP_SOURCE_CAP("Port Mirroring Configuration By Policy 0: source: [1, UNBOUNDED]"),
+ PMCP1_SOURCE_CAP("Port Mirroring Configuration By Policy 1: source: [1, UNBOUNDED]"),
+ PMC_COLLECTOR_CAP("Port Mirroring Configuration 0: collector: [1, 1]"),
+ CISCO_VENDOR_NAME("CISCO"),
+ CISCO_VENDOR_MODEL_NUMBER("4500x"),
+ APCON1_VENDOR_NAME("APCON1"),
+ APCON1_VENDOR_MODEL_NUMBER("Test_APCON1"),
+ APCON2_VENDOR_NAME("APCON2"),
+ APCON2_VENDOR_MODEL_NUMBER("Test_APCON2"),
+ VMME_ZIP("2016-227_vmme_vmme_30_1610_e2e.zip"),
+ VPROBE_ZIP("vProbe_2017-10-22_07-24.zip"),
+ SERVICE_PROXY_TYPE("Service Proxy"),
+ SERVICE_TYPE("transport"),
+ TYPE("Resource"),
+ RESOURCE_TYPE("Configuration"),
+ CATEGORY("Configuration"),
+ SUB_CATEGORY("Configuration"),
+ NETWORK_ROLE_XPATH("//input[@name='network_role']"),
+ NFC_TYPE_XPATH("//input[@name='nfc_type']"),
+ PPS_CAPACITY_XPATH("//input[@name='pps_capacity']"),
+ NF_TYPE_XPATH("//input[@name='nf_type']"),
+ NETWORK_ROLE_VALUE("NETWORK ROLE TEXT"),
+ NFC_TYPE_VALUE("NFC TYPE TEXT"),
+ PPS_CAPACITY_VALUE("PPS CAPACITY TEXT"),
+ NF_TYPE_VALUE("NF TYPE TEXT"),
+ PMCP_NEWNAME("NewPMCP_Name");
+
+
+ private String value;
+
+ public String getValue() {
+ return value;
+ }
+
+ private PortMirroringEnum(String value) {
+ this.value = value;
+ }
+
+}
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
index 799649b1b6..f51e69af01 100644
--- 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
@@ -61,6 +61,7 @@ public class UserManagementTab {
public void clickCreateButton(){
ExtentTestActions.log(Status.INFO, "Clicking on 'Create' button.");
+ GeneralUIUtils.ultimateWait();
GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.CREATE_BUTTON.getValue());
}
@@ -99,7 +100,9 @@ public class UserManagementTab {
public void deleteUser(int index){
ExtentTestActions.log(Status.INFO, "Deleting the user in row " + (index + 1));
+ GeneralUIUtils.ultimateWait();
GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.DELETE_USER.getValue() + index);
+ GeneralUIUtils.ultimateWait();
GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue());
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java
index 8b40210c0d..a6aba7f13c 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java
@@ -16,8 +16,8 @@ public class VendorSoftwareProductObject extends VendorSoftwareProductObjectReqD
this.version = version;
}
- public VendorSoftwareProductObject(String name, String description, String category, String subCategory, String vendorId, String vendorName, LicensingVersion licensingVersion, LicensingData licensingData, String onboardingMethod, String networkPackageName, String onboardingOrigin, String vspId, String componentId, String attContact, String version) {
- super(name, description, category, subCategory, vendorId, vendorName, licensingVersion, licensingData, onboardingMethod, networkPackageName, onboardingOrigin);
+ public VendorSoftwareProductObject(String name, String description, String category, String subCategory, String vendorId, String vendorName, String licensingVersion, LicensingData licensingData, String onboardingMethod, String networkPackageName, String onboardingOrigin, String icon, String vspId, String componentId, String attContact, String version) {
+ super(name, description, category, subCategory, vendorId, vendorName, licensingVersion, licensingData, onboardingMethod, networkPackageName, onboardingOrigin, icon);
this.vspId = vspId;
this.componentId = componentId;
this.attContact = attContact;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/CreatePath.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/CreatePath.java
new file mode 100644
index 0000000000..66bb693778
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/CreatePath.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.execute.AmdocsComplexService;
+
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.awt.AWTException;
+import java.io.Console;
+import java.io.File;
+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 java.util.Map;
+import java.util.stream.Collectors;
+import java.util.Random;
+import com.mongodb.util.JSON;
+import org.apache.commons.lang.RandomStringUtils;
+import org.json.JSONObject;
+import org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders;
+import org.openecomp.sdc.ci.tests.datatypes.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.CircleSize;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.execute.sanity.Service;
+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.ServiceUIUtils;
+import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebElement;
+import org.stringtemplate.v4.ST;
+import org.testng.Assert;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Optional;
+import org.testng.annotations.Parameters;
+import org.testng.annotations.Test;
+
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+
+public class CreatePath extends SetupCDTest {
+
+ protected static String filepath = FileHandling.getVnfRepositoryPath();
+ protected String makeDistributionValue;
+
+ @Parameters({"makeDistribution"})
+ @BeforeMethod
+ public void beforeTestReadParams(@Optional("true") String makeDistributionReadValue) {
+ makeDistributionValue = makeDistributionReadValue;
+ }
+
+ //------------------------------------------Tests-----------------------------------------------------
+
+
+ // Jira issue 5610
+ @Test
+ public void AssertPathButtons() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ String vnfFile = "fullComposition.zip";
+ String vspName = getToPathFlow(filepath, vnfFile);
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ openCreatePath();
+ AssertCreatePath();
+ AssertExtendPath();
+ //SetupCDTest.getExtendTest().log(Status.INFO, String.format("disables buttons are OK"));
+ }
+
+ // Jira issue 5441
+ @Test
+ public void CreatePathTestSanity() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ // List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileList();
+ //String vnfFile = fileNamesFromFolder.get(0).toString();
+ String vnfFile = "fullComposition.zip";
+ String vspName = getToPathFlow(filepath, vnfFile);
+ createPath(vspName);
+ }
+
+ // Jira issue 5611
+ @Test
+ public void CreatePathCheckIO() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ // List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileList();
+ //String vnfFile = fileNamesFromFolder.get(0).toString();
+ String vnfFile = "fullComposition.zip";
+
+ // getToPathFlow
+ String vspName = onboardAndCertify(filepath, vnfFile);
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ // create path
+ String pathName = createPath(vspName);
+
+ // @@ check in @@
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.CHECK_IN.getValue());
+ GeneralUIUtils.getWebElementByTestID("checkindialog").sendKeys("check in automated confirmation message");
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue());
+ GeneralUIUtils.ultimateWait();
+
+ // go to service composition
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(serviceMetadata.getName());
+ getDriver().findElements(By.xpath("//*[@data-tests-id='dashboard-Elements']//*[@data-tests-id='" + serviceMetadata.getName() + "']")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ AssertCreatedPathExistInCompositionPage(pathName);
+
+ // @@ check out @@
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.CHECKOUT.getValue());
+ GeneralUIUtils.ultimateWait();
+
+ AssertCreatedPathExistInCompositionPage(pathName);
+
+ }
+
+ // Jira issue 5441
+ @Test
+ public void CreateMultiplePaths() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ // List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileList();
+ //String vnfFile = fileNamesFromFolder.get(0).toString();
+ String vnfFile = "fullComposition.zip";
+ String vspName = getToPathFlow(filepath, vnfFile);
+ createPath(vspName);
+ createPath(vspName);
+ createPathNumOfRows(7);
+ createPathNumOfRows(6);
+ createPathNumOfRows(4);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("multiple paths have been created"));
+ }
+
+ // Jira issue 5506
+ @Test
+ public void CreatePathWithComplex() throws Exception, Throwable {
+ List<String> vnfFiles = new ArrayList<>();
+ vnfFiles.add("fullComposition.zip");
+ vnfFiles.add("fullCompositionNew.zip");
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ CreatePathComplexServiceFlow(filepath, vnfFiles);
+ //String vnfFile = "fullComposition.zip";
+ // String vnfFile2 = "fullCompositionNew.zip";
+ // runCreatePathComplexServiceFlow(filepath, vnfFile, vnfFile2);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("path with complex service has been created"));
+ }
+
+ // Jira issue 5506
+ @Test
+ public void RealScenarioComplex() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop\\Srini";
+ List<String> vnfFiles = new ArrayList<>();
+ vnfFiles.add("HSS.zip");
+ vnfFiles.add("VMME.zip");
+ CreatePathComplexServiceFlow(filepath, vnfFiles);
+ ExtentTestActions.addScreenshot(Status.INFO, "Complex service_" + vnfFiles.get(0) ,"Complex service created " + vnfFiles.get(1) + " is as follows : ");
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("path with complex service has been created"));
+ }
+
+ // Jira issue 5506
+ @Test
+ public void CreateExtendedPathWithComplex() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ List<String> vnfFiles = new ArrayList<>();
+ vnfFiles.add("fullComposition.zip");
+ vnfFiles.add("fullCompositionNew.zip");
+ //String vnfFile = "fullComposition.zip";
+ //String vnfFile2 = "fullCompositionNew.zip";
+ String[] services = ToComplexService(filepath, vnfFiles);
+ createComplexExtendedPath(services[0], services[1]);
+ ExtentTestActions.addScreenshot(Status.INFO, "Complex service_" + services[0] ,"Complex service created " + services[1] + " is as follows : ");
+
+ }
+
+ // Jira issue 5441
+ @Test
+ public void CreatePathExtendedTest() throws Exception, Throwable {
+ filepath = "C:\\Users\\ShiraShe\\Desktop";
+ // List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileList();
+ //String vnfFile = fileNamesFromFolder.get(0).toString();
+ String vnfFile = "fullComposition.zip";
+ runCreateExtendedPathFlow(filepath, vnfFile);
+ }
+
+ //create service
+ public ServiceReqDetails createService() throws Exception, AWTException {
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ return serviceMetadata;
+ }
+
+ // workflow leading to path
+ public String onboardAndCertify(String filepath, String vnfFile) throws Exception, IOException {
+
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
+ Pair<String, VendorSoftwareProductObject> onboardAndValidate = OnboardingUiUtils.onboardAndValidate(resourceReqDetails,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);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("relogin as TESTER"));
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ GeneralUIUtils.findComponentAndClick(vspName);
+ TesterOperationPage.certifyComponent(vspName);
+ return vspName;
+ }
+
+ public List<String> onboardAndCertifyMultipleVFs(String filepath, List<String> vnfFiles) throws Exception, IOException {
+
+ List<String> VFNames = new ArrayList<>();
+ for(int i = 0; i<vnfFiles.size(); i++)
+ {
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
+ Pair<String, VendorSoftwareProductObject> onboardAndValidate = OnboardingUiUtils.onboardAndValidate(resourceReqDetails,filepath, vnfFiles.get(i), getUser());
+ VFNames.add(i, onboardAndValidate.left);
+ DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen();
+ ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFiles.get(i) ,"The topology template for " + vnfFiles.get(i) + " is as follows : ");
+ DeploymentArtifactPage.clickSubmitForTestingButton(VFNames.get(i));
+ }
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("relogin as TESTER"));
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ for (int j = 0; j< VFNames.size(); j++)
+ {
+ GeneralUIUtils.findComponentAndClick(VFNames.get(j));
+ TesterOperationPage.certifyComponent(VFNames.get(j));
+ }
+
+ return VFNames;
+ }
+
+ // path components
+
+ public void AssertCreatePath() throws Exception, IOException {
+ String check = getDriver().findElements(By.xpath("//*[@data-tests-id='Create']")).get(0).getAttribute("disabled");
+ if (check.intern() != "true")
+ {
+ throw new Exception("Button create path should be disabled. open bug to UI team");
+ }
+ }
+
+ public void AssertCreatedPathExistInCompositionPage(String pathName) throws Exception, IOException {
+ // check path in the list filter
+ checkPathFilter(pathName, true);
+
+ openPathList();
+
+ // assert path is in the list
+ String PathListName1 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue());
+ }
+
+ public void AssertExtendPath() throws Exception, IOException {
+ String check = getDriver().findElements(By.xpath("//*[@data-tests-id='extendPathlnk']")).get(0).getAttribute("class");
+ if (check.intern() != "disabled")
+ {
+ throw new Exception("Button extend path should be disabled. open bug to UI team");
+ }
+ }
+
+ public void createPathNumOfRows(int numOfPathRows)throws Exception, AWTException{
+ openCreatePath();
+ insertValues("extended" + RandomStringUtils.randomAlphanumeric(8),"pathProtocol1", "pathPortNumbers1");
+ selectFirstLineParam();
+ extendPath(numOfPathRows);
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+ }
+
+ public void linkVFs(String vspName, int linksNum)throws Exception, AWTException {
+
+ CompositionPage.searchForElement(vspName);
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ List <CanvasElement> VFs = new ArrayList<CanvasElement>();
+
+ VFs.add(canvasManager.createElementOnCanvas(vspName));
+
+ for (int i = 1; i<linksNum; i++)
+ {
+ VFs.add(canvasManager.createElementOnCanvas(vspName));
+ GeneralUIUtils.ultimateWait();
+ canvasManager.linkElements(VFs.get(i), CircleSize.VF, VFs.get(i-1), CircleSize.VF);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("link VFs"));
+ GeneralUIUtils.ultimateWait();
+ }
+ }
+
+ public void linkServices(String Service1, String Service2, int linksNum)throws Exception, AWTException {
+
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ List <CanvasElement> VFs = new ArrayList<CanvasElement>();
+
+ // get first service
+ CompositionPage.searchForElement(Service1);
+ VFs.add(canvasManager.createElementOnCanvas(Service1));
+
+ String service = Service2;
+ for (int i = 1; i<linksNum; i++)
+ {
+ CompositionPage.searchForElement(service);
+ VFs.add(canvasManager.createElementOnCanvas(service));
+ GeneralUIUtils.ultimateWait();
+ canvasManager.linkElements(VFs.get(i), CircleSize.SERVICE, VFs.get(i-1), CircleSize.SERVICE);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("link services"));
+ GeneralUIUtils.ultimateWait();
+
+ // change service to link
+ if (service.equals(Service2)) {
+ service = Service1;
+ }
+ else {
+ service = Service2;
+ }
+ }
+ }
+
+ public void openCreatePath() throws Exception, AWTException{
+
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_PATH_MENU_BUTTON.getValue());
+ }
+
+ public void openPathList() throws Exception, AWTException {
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue());
+ }
+
+ public void sendValue(String DataTestId, String value) throws Exception, AWTException {
+
+ GeneralUIUtils.getWebElementByTestID(DataTestId).sendKeys(value);
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public void insertValues(String pathName, String pathProtocol, String pathPortNumbers) throws Exception, AWTException {
+
+ sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_NAME.getValue(),pathName);
+ sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_PROTOCOL.getValue(),pathProtocol);
+ sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_PORT_NUMBER.getValue(),pathPortNumbers);
+ }
+
+ public void selectFirstLineParam() throws Exception, AWTException{
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkSrc']//option")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkSrcCP']//option")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkTarget']//option")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkTargetCP']//option")).get(0).click();
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public void checkPathFilter(String pathName, boolean isFound) throws Exception, AWTException{
+ GeneralUIUtils.ultimateWait();
+ List<WebElement> pathFilterList = getDriver().findElements(By.xpath("//*[@data-tests-id='service-path-selector']//option"));
+ if (isFound) {
+ for (int i = 0; i < pathFilterList.size(); i++) {
+ String element_text = pathFilterList.get(i).getText();
+ if (element_text.equals(pathName))
+ {
+ break;
+ }
+ if (i == pathFilterList.size() -1 )
+ {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("path list filter check failed"));
+ throw new Exception("path filter list is missing a path");
+ }
+ }
+ }
+ else {
+ for (int i = 0; i < pathFilterList.size(); i++) {
+ String element_text = pathFilterList.get(i).getText();
+ if (element_text.equals(pathName))
+ {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("path list filter check failed"));
+ throw new Exception("path filter list is has a path that should be deleted");
+ }
+ }
+ }
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("path list filter check passed"));
+ }
+
+ public void extendPath(int numOfLines) throws Exception, AWTException {
+
+ int i;
+ for (i = 0; i < numOfLines; i++) {
+ String check;
+ String index = Integer.toString(i + 2);
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.EXTEND_BUTTON.getValue());
+ List<WebElement> linkSrcs = getDriver().findElements(By.xpath("//*[@data-tests-id='linkSrc']//select"));
+ List<WebElement> linkSrcCPs = getDriver().findElements(By.xpath("//*[@data-tests-id='linkSrcCP']//select"));
+ List<WebElement> linkTargets = getDriver().findElements(By.xpath("//*[@data-tests-id='linkTarget']//select"));
+ List<WebElement> linkTargetCPs = getDriver().findElements(By.xpath("//*[@data-tests-id='linkTargetCP']//select"));
+
+ for (int j = 0; j < i + 2; j++) {
+ check = linkSrcs.get(j).getAttribute("class");
+ if (!check.intern().contains("disabled")) {
+ throw new Exception("Source should be disabled. open bug to UI team");
+ }
+ check = linkSrcCPs.get(j).getAttribute("class");
+ if (!check.intern().contains("disabled")) {
+ throw new Exception("Source connection point of last lines should be disabled. open bug to UI team");
+ }
+ }
+ for (int j = 0; j < i + 1; j++) {
+
+ check = linkTargets.get(j).getAttribute("class");
+ if (!check.intern().contains("disabled")) {
+ throw new Exception("Target of last lines should be disabled. open bug to UI team");
+ }
+ check = linkTargetCPs.get(j).getAttribute("class");
+ if (!check.intern().contains("disabled")) {
+ throw new Exception("Target connection point of last lines should be disabled. open bug to UI team");
+ }
+ }
+
+ List <WebElement> choices = getDriver().findElements(By.xpath("//*[" + index + "]/*[@data-tests-id='linkTarget']//option"));
+ choices.get((new Random()).nextInt(choices.size())).click();
+ choices = getDriver().findElements(By.xpath("//*[" + index + "]/*[@data-tests-id='linkTargetCP']//option"));
+ choices.get((new Random()).nextInt(choices.size())).click();
+ }
+ }
+
+ public String editPath(String pathName) throws Exception, AWTException{
+ getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).get(0).click();
+ pathName = "name2";
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.PATH_NAME.getValue()).clear();
+ sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_NAME.getValue(), pathName);
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.SAVE.getValue());
+ return pathName;
+ }
+
+ public int deleteLines(int numOfLinesToDelete,int numOfLines)throws Exception, AWTException{
+
+ for (int i=0; i<numOfLinesToDelete; i++){
+ getDriver().findElements(By.xpath("//*[@data-tests-id='removeLnk']//span")).get(0).click();
+ numOfLines--;
+ }
+ if (getDriver().findElements(By.xpath("//*[@data-tests-id='linkTargetCP']//option")).size()>(numOfLines+1))
+ {
+ throw new Exception("Path element was not deleted");
+ }
+ GeneralUIUtils.ultimateWait();
+ return numOfLines;
+ }
+
+ public String getToPathFlow(String filepath, String vnfFile) throws Exception, AWTException {
+
+ String vspName = onboardAndCertify(filepath, vnfFile);
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ return vspName;
+ }
+
+ // path scenarios
+
+ public String createPath(String vspName) throws Exception, AWTException {
+
+ linkVFs(vspName, 3);
+ openCreatePath();
+ String pathName = "name1";
+ insertValues(pathName, "pathProtocol1", "pathPortNumbers1");
+ //select path elements
+ selectFirstLineParam();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("path has been created"));
+ return pathName;
+ }
+
+ // flows
+
+ public void createExtendedPath(String vspName) throws Exception, AWTException {
+ //drag and drop VFs and link them
+ linkVFs(vspName, 5);
+
+ //open create path box
+ openCreatePath();
+ String pathName = "name1";
+ insertValues(pathName, "pathProtocol1", "pathPortNumbers1");
+ selectFirstLineParam();
+ //extend path
+ int numOfLines = 3;
+ extendPath(numOfLines);
+ //delete line
+ int numOfLinesToDelete = 1;
+ numOfLines = deleteLines(numOfLinesToDelete, numOfLines);
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+ ExtentTestActions.log(Status.INFO, "path has been created");
+
+ // check that path exist in the path filter list
+ checkPathFilter(pathName, true);
+
+ // check that path exist in the path list
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue());
+ String PathListName1 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+
+ // edit path
+ pathName = editPath(pathName);
+
+ // go back to path's list
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue());
+
+ // get name
+ String PathListName2 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+
+ // assert names changed
+ if (PathListName1.equals(PathListName2))
+ {
+ throw new Exception("path name expected to change after edit but did not");
+ }
+
+ // delete path
+ int paths_before_deletion = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).size();
+ getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).get(1).click();
+ GeneralUIUtils.ultimateWait();
+ int paths_after_deletion = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).size();
+ if (paths_after_deletion == paths_before_deletion)
+ {
+ throw new Exception("path expected to be deleted but did not");
+ }
+
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue());
+ //ArtifactsCorrelationManager.addVNFtoServiceArtifactCorrelation(serviceMetadata.getName(), vspName);
+ //ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser());
+ //ExtentTestActions.addScreenshot(Status.INFO, "ServiceComposition_" + vnfFile, "The service topology is as follows: ");
+ //ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Path has been created"));
+
+ // check that path got deleted in the path filter list
+ checkPathFilter(pathName, false);
+ }
+
+ public void createComplexExtendedPath(String Service1, String Service2) throws Exception, AWTException {
+ //drag and drop Services and link them
+ linkServices(Service1, Service2, 5);
+
+ //-----------------------------------------create path-------------------------------------------------
+
+ //open create path box
+ openCreatePath();
+
+ String pathName = "name1";
+ String pathProtocol = "pathProtocol1";
+ String pathPortNumbers = "pathPortNumbers1";
+
+ insertValues(pathName, pathProtocol, pathPortNumbers);
+
+ //select path parameters
+ selectFirstLineParam();
+ //extend path
+ int numOfLines = 3;
+ extendPath(numOfLines);
+
+ //delete line
+ int numOfLinesToDelete = 1;
+ numOfLines = deleteLines(numOfLinesToDelete, numOfLines);
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+ ExtentTestActions.log(Status.INFO, "path has been created");
+
+ //---------------------------------------check path's list-----------------------------
+
+ // go to path's list
+ openPathList();
+
+ // get name
+ String PathListName1 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+
+ // edit path
+ pathName = editPath(pathName);
+
+ // go back to path's list
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue());
+
+ // get name
+ String PathListName2 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+
+ // assert names changed
+ if (PathListName1.equals(PathListName2))
+ {
+ throw new Exception("path name expected to change after edit but did not");
+ }
+
+ // delete path
+ int paths_before_deletion = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).size();
+ getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).get(1).click();
+ Thread.sleep(1000);
+ int paths_after_deletion = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).size();
+ if (paths_after_deletion == paths_before_deletion)
+ {
+ throw new Exception("path expected to be deleted but did not");
+ }
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue());
+ //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());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Path has been created"));
+ }
+
+ public String[] getToComplexService(String filepath, String vnfFile, String vnfFile2) throws Exception, AWTException{
+ // create & certify 2 VF
+ String vspName1 = onboardAndCertify(filepath, vnfFile);
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ String vspName2 = onboardAndCertify(filepath, vnfFile2);
+
+ // create service 1
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ ServiceReqDetails serviceMetadata1 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(vspName1);
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ // create service 2
+ ServiceReqDetails serviceMetadata2 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(vspName2);
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ //tester
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata2.getName());
+
+ //governor
+ reloginWithNewRole(UserRoleEnum.GOVERNOR);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata2.getName());
+
+ //create service for complex service
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ return new String[]{serviceMetadata1.getName(), serviceMetadata2.getName()};
+ }
+
+ public String[] ToComplexService(String filepath, List<String> vnfFiles) throws Exception, AWTException{
+ // create & certify 2 VF
+ List<String> VFNames = onboardAndCertifyMultipleVFs(filepath, vnfFiles);
+
+ // create service 1
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ ServiceReqDetails serviceMetadata1 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(VFNames.get(0));
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+ GeneralUIUtils.ultimateWait();;
+
+ // create service 2
+ ServiceReqDetails serviceMetadata2 = createService();
+ GeneralUIUtils.ultimateWait();;
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(VFNames.get(1));
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ //tester
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata2.getName());
+
+ //governor
+ reloginWithNewRole(UserRoleEnum.GOVERNOR);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata2.getName());
+
+ //create service for complex service
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ return new String[]{serviceMetadata1.getName(), serviceMetadata2.getName()};
+ }
+
+ public void runCreatePathComplexServiceFlow(String filepath, String vnfFile, String vnfFile2) throws Exception, AWTException {
+ // create & certify 2 VF
+ String vspName1 = onboardAndCertify(filepath, vnfFile);
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ String vspName2 = onboardAndCertify(filepath, vnfFile2);
+
+ // create service 1
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ ServiceReqDetails serviceMetadata1 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(vspName1);
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ // create service 2
+ ServiceReqDetails serviceMetadata2 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(vspName2);
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ //tester
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata2.getName());
+
+ //governor
+ reloginWithNewRole(UserRoleEnum.GOVERNOR);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata2.getName());
+
+ //create service for complex service
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // link services
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ CompositionPage.searchForElement(serviceMetadata1.getName());
+ CanvasElement service1 = canvasManager.createElementOnCanvas(serviceMetadata1.getName());
+ CompositionPage.searchForElement(serviceMetadata2.getName());
+ CanvasElement service2 = canvasManager.createElementOnCanvas(serviceMetadata2.getName());
+ canvasManager.linkElements(service1,CircleSize.SERVICE, service2, CircleSize.SERVICE);
+
+ // create path
+ openCreatePath();
+ insertValues("name1", "pathProtocol1", "pathPortNumbers1");
+ selectFirstLineParam();
+ GeneralUIUtils.getWebElementByTestID("Create").click();
+ }
+
+ public void CreatePathComplexServiceFlow(String filepath, List<String> vnfFiles) throws Exception, AWTException {
+ // create & certify 2 VF
+ List<String> vfNames = onboardAndCertifyMultipleVFs(filepath, vnfFiles);
+
+ // create service 1
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ ServiceReqDetails serviceMetadata1 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(vfNames.get(0));
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ // create service 2
+ ServiceReqDetails serviceMetadata2 = createService();
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // create path
+ createPath(vfNames.get(0));
+ getDriver().findElements(By.xpath("//*[@data-tests-id='submit_for_testing']")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='changeLifeCycleMessage']")).get(0).sendKeys("new Service to test");
+ getDriver().findElements(By.xpath("//*[@data-tests-id='OK']")).get(0).click();
+
+ //tester
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ TesterOperationPage.certifyComponent(serviceMetadata2.getName());
+
+ //governor
+ reloginWithNewRole(UserRoleEnum.GOVERNOR);
+ GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata1.getName());
+ GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName());
+ GovernorOperationPage.approveSerivce(serviceMetadata2.getName());
+
+ //create service for complex service
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+ // go to composition
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ // link services
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ CompositionPage.searchForElement(serviceMetadata1.getName());
+ CanvasElement service1 = canvasManager.createElementOnCanvas(serviceMetadata1.getName());
+ CompositionPage.searchForElement(serviceMetadata2.getName());
+ CanvasElement service2 = canvasManager.createElementOnCanvas(serviceMetadata2.getName());
+ canvasManager.linkElements(service1,CircleSize.SERVICE, service2, CircleSize.SERVICE);
+
+ // create path
+ openCreatePath();
+ insertValues("name1", "pathProtocol1", "pathPortNumbers1");
+ selectFirstLineParam();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+ }
+
+ public void runCreateExtendedPathFlow(String filepath, String vnfFile) throws Exception, AWTException {
+
+ String vspName = getToPathFlow(filepath, vnfFile);
+
+ //drag and drop VFs and link them
+ linkVFs(vspName, 5);
+
+ //-----------------------------------------create path-------------------------------------------------
+
+ //open create path box
+ openCreatePath();
+ String pathName = "name1";
+ insertValues(pathName, "pathProtocol1", "pathPortNumbers1");
+
+ //select path parameters
+ selectFirstLineParam();
+ //extend path
+ int numOfLines = 3;
+ extendPath(numOfLines);
+
+ //delete line
+ int numOfLinesToDelete = 1;
+ numOfLines = deleteLines(numOfLinesToDelete, numOfLines);
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+ ExtentTestActions.log(Status.INFO, "path has been created");
+
+ // check path is on the list
+ openPathList();
+ String PathListName1 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+
+ // edit path
+ pathName = editPath(pathName);
+
+ // go back to path's list
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue());
+
+ // get name
+ String PathListName2 = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']")).get(0).getText();
+
+ // assert names changes
+ if (PathListName1.equals(PathListName2))
+ {
+ throw new Exception("path name expected to change after edit but did not");
+ }
+
+ // delete path
+ int paths_before_deletion = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).size();
+ getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).get(1).click();
+ GeneralUIUtils.ultimateWait();
+ int paths_after_deletion = getDriver().findElements(By.xpath("//*[text()='"+pathName+"']/parent::*//span")).size();
+ if (paths_after_deletion == paths_before_deletion)
+ {
+ throw new Exception("path expected to be deleted but did not");
+ }
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue());
+ //ArtifactsCorrelationManager.addVNFtoServiceArtifactCorrelation(serviceMetadata.getName(), vspName);
+ //ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser());
+ //ExtentTestActions.addScreenshot(Status.INFO, "ServiceComposition_" + vnfFile, "The service topology is as follows: ");
+ //ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Path has been created"));
+ }
+
+ public void runCreatePathFlow(String filepath, String vnfFile) throws Exception, AWTException {
+ String vspName = onboardAndCertify(filepath, vnfFile);
+
+ reloginWithNewRole(UserRoleEnum.DESIGNER);
+ // create service
+ ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
+ ServiceUIUtils.createService(serviceMetadata, getUser());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ CompositionPage.searchForElement(vspName);
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ CanvasElement vfElement1 = canvasManager.createElementOnCanvas(vspName);
+ CanvasElement vfElement2 = canvasManager.createElementOnCanvas(vspName);
+ CanvasElement vfElement3 = canvasManager.createElementOnCanvas(vspName);
+ CanvasElement vfElement4 = canvasManager.createElementOnCanvas(vspName);
+ CanvasElement vfElement5 = canvasManager.createElementOnCanvas(vspName);
+ canvasManager.linkElements(vfElement1, CircleSize.VF, vfElement2, CircleSize.VF);
+ canvasManager.linkElements(vfElement3,CircleSize.VF, vfElement2, CircleSize.VF);
+ canvasManager.linkElements(vfElement3, CircleSize.VF, vfElement4, CircleSize.VF);
+ canvasManager.linkElements(vfElement5, CircleSize.VF, vfElement4, CircleSize.VF);
+ canvasManager.linkElements(vfElement5, CircleSize.VF, vfElement1, CircleSize.VF);
+
+ //create path
+
+ getDriver().findElements(By.xpath("//*[@data-tests-id='pathsMenuBtn']/parent::*")).get(0).click();
+// GeneralUIUtils.getWebElementByTestID("pathsMenuBtn").click();
+ GeneralUIUtils.getWebElementByTestID("createPathMenuItem").click();
+ //insert values
+ GeneralUIUtils.getWebElementByTestID("pathName").sendKeys("name");
+ GeneralUIUtils.getWebElementByTestID("pathProtocol").sendKeys("pathProtocol");
+ GeneralUIUtils.getWebElementByTestID("pathPortNumbers").sendKeys("pathPortNumbers");
+ //select path parameters
+
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkSrc']//option")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkSrcCP']//option")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkTarget']//option")).get(0).click();
+ getDriver().findElements(By.xpath("//*[@data-tests-id='linkTargetCP']//option")).get(0).click();
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue());
+
+ //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());
+ }
+
+ @Override
+ protected UserRoleEnum getRole() {
+ return UserRoleEnum.DESIGNER;
+ }
+
+} \ No newline at end of file
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/PathValidations.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/PathValidations.java
new file mode 100644
index 0000000000..42c45699f3
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/AmdocsComplexService/PathValidations.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.ci.tests.execute.AmdocsComplexService;
+
+/**
+ * validation tests for future validations
+ */
+
+import java.util.ArrayList;
+
+public class PathValidations {
+
+ String name;
+ String destinationPortNumber;
+ String protocol;
+
+ ArrayList<String> elements;
+
+ public void Ph(String parameter1 )
+ {
+ elements = new ArrayList<String>();
+ elements.add(parameter1);
+ elements.get(1);
+ }
+}
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
index e4423dd7d0..4df09a660d 100644
--- 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
@@ -48,6 +48,7 @@ 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.SkipException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -72,21 +73,23 @@ public class AdminUserManagment extends SetupCDTest {
//TC915100
@Test
- public void creatNewUserTest() throws Exception {
+ public void createNewUserTest() throws Exception {
String userId = generateValidUserId();
UserRoleEnum userRole = UserRoleEnum.DESIGNER;
AdminWorkspaceUIUtilies.createNewUser(userId, userRole);
+ GeneralUIUtils.ultimateWait();
UserManagementVerificator.validateUserCreated(userId, userRole);
}
//TC922253
@Test
- public void creatNewUser_MacIdTest() throws Exception {
+ public void createNewUser_MacIdTest() throws Exception {
String macId = generateValidMacId();
UserRoleEnum userRole = UserRoleEnum.DESIGNER;
AdminWorkspaceUIUtilies.createNewUser(macId, userRole);
+ GeneralUIUtils.ultimateWait();
UserManagementVerificator.validateUserCreated(macId, userRole);
}
@@ -106,9 +109,9 @@ public class AdminUserManagment extends SetupCDTest {
@Test
public void createInvalidMacIdTest(){
-// if(true){
-// throw new SkipException("Open bug 324032");
-// }
+ if(true){
+ throw new SkipException("Open bug 324032");
+ }
String macId = generateValidMacId();
StringBuilder invalidMacId = new StringBuilder(macId);
@@ -116,6 +119,7 @@ public class AdminUserManagment extends SetupCDTest {
UserRoleEnum userRole = UserRoleEnum.DESIGNER;
ExtentTestActions.log(Status.INFO, "Trying to create an invalid macId.");
AdminWorkspaceUIUtilies.createNewUser(invalidMacId.toString(), userRole);
+ GeneralUIUtils.ultimateWait();
ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.INVALID_USER_ID);
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java
index 5533eb38f5..cd73dfba4f 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java
@@ -20,28 +20,14 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.util.Arrays;
-import java.util.List;
-
+import com.aventstack.extentreports.Status;
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.*;
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.utilities.*;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.verificator.CatalogVerificator;
import org.openqa.selenium.WebElement;
@@ -49,7 +35,10 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.testng.AssertJUnit.assertTrue;
@Test(singleThreaded = true)
public class CatalogLeftPanelTest extends SetupCDTest{
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java
index cf510578ef..ad8347fbbe 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java
@@ -71,6 +71,7 @@ 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;
@@ -197,6 +198,11 @@ public class ImportDCAE extends SetupCDTest {
@Test
public void addPropertiesToVfcInstanceInDCAEAssetTest() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen");
+ }
+
String fileName = "importVFC_VFC15.yml";
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java
index 273a502895..9ed8ba5029 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java
@@ -57,6 +57,7 @@ import org.openecomp.sdc.ci.tests.verificator.PropertyVerificator;
import org.openecomp.sdc.ci.tests.verificator.VFCverificator;
import org.openecomp.sdc.ci.tests.verificator.VfVerificator;
import org.testng.Assert;
+import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -360,9 +361,11 @@ public class ImportVFCAsset extends SetupCDTest {
ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser());
ResourceUIUtils.fillMaxValueResourceGeneralInformationPage(atomicResourceMetaData);
- GeneralPageElements.clickUpdateButton();
- VFCverificator.verifyVFCUpdatedInUI(atomicResourceMetaData);
- GeneralPageElements.clickDeleteVersionButton();
+// GeneralPageElements.clickUpdateButton();
+// VFCverificator.verifyVFCUpdatedInUI(atomicResourceMetaData);
+// GeneralPageElements.clickDeleteVersionButton();
+ // Validate that button disabled
+ assertTrue(GeneralUIUtils.checkForDisabledAttribute(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()));
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java
index 6cea8d6c6f..bf2bda906c 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java
@@ -20,13 +20,10 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.awt.AWTException;
-import java.sql.Timestamp;
-import java.util.List;
-import java.util.Map;
-
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.LoggerContext;
+import com.clearspring.analytics.util.Pair;
+import fj.data.Either;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
@@ -40,19 +37,16 @@ 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.utils.general.AtomicOperationUtils;
-import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
+import org.openecomp.sdc.ci.tests.utils.general.*;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import com.clearspring.analytics.util.Pair;
+import java.awt.*;
+import java.sql.Timestamp;
+import java.util.List;
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.LoggerContext;
-import fj.data.Either;
+import static org.testng.AssertJUnit.assertTrue;
public class OnboardViaApis{
@@ -100,10 +94,11 @@ public class OnboardViaApis{
{
//CREATE DATA REQUIRED FOR TEST
boolean skipReport = true;
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(sdncDesignerDetails1);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, sdncDesignerDetails1, amdocsLicenseMembers);
- VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, sdncDesignerDetails1, amdocsLicenseMembers);
+// VendorSoftwareProductObject vendorSoftwareProductObject = fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+ VendorSoftwareProductObject vendorSoftwareProductObject = createVendorSoftwareProduct.right;
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
@@ -115,40 +110,17 @@ public class OnboardViaApis{
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
// TEST START
- // Update exist VLM Version (From 1.0 to 2.0)
- OnboardingUtils.updateVendorLicense(amdocsLicenseMembers, sdncDesignerDetails1, "1.0");
- // Set VLM version to 2.0 in VLM Meta data object
- amdocsLicenseMembers.setLicenseVersionId("2.0");
- amdocsLicenseMembers.setLicenseVersionLabel("2.0");
- OnboardingUtils.validateVlmExist(amdocsLicenseMembers.getVendorId(), amdocsLicenseMembers.getLicenseVersionId(), sdncDesignerDetails1);
+ VendorLicenseModelRestUtils.updateVendorLicense(amdocsLicenseMembers, sdncDesignerDetails1, false);
+ VendorLicenseModelRestUtils.validateVlmExist(amdocsLicenseMembers.getVendorId(), amdocsLicenseMembers.getVersion(), sdncDesignerDetails1);
// Update the VSP With the VLM new version and submit the VSP
- vendorSoftwareProductObject = OnboardingUtils.updateVSPWithNewVLMParameters(vendorSoftwareProductObject, amdocsLicenseMembers, sdncDesignerDetails1, "1.1", "2.0");
- OnboardingUtils.validateVspExist(vendorSoftwareProductObject.getVspId(),vendorSoftwareProductObject.getVersion(), sdncDesignerDetails1);
+ vendorSoftwareProductObject = VendorSoftwareProductRestUtils.updateVSPWithNewVLMParameters(vendorSoftwareProductObject, amdocsLicenseMembers, sdncDesignerDetails1);
+ VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1);
Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
System.out.println(distributeAndValidateService);
}
- public static VendorSoftwareProductObject fillVendorSoftwareProductObjectWithMetaData(String vnfFile, Pair<String, Map<String, String>> createVendorSoftwareProduct) {
- VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
- Map<String, String> map = createVendorSoftwareProduct.right;
- vendorSoftwareProductObject.setAttContact(map.get("attContact"));
- vendorSoftwareProductObject.setCategory(map.get("category"));
- vendorSoftwareProductObject.setComponentId(map.get("componentId"));
- vendorSoftwareProductObject.setDescription(map.get("description"));
- vendorSoftwareProductObject.setSubCategory(map.get("subCategory"));
- vendorSoftwareProductObject.setVendorName(map.get("vendorName"));
- vendorSoftwareProductObject.setVspId(map.get("vspId"));
- vendorSoftwareProductObject.setName(createVendorSoftwareProduct.left);
- String[] arrFileNameAndExtension = vnfFile.split("\\.");
- vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
- vendorSoftwareProductObject.setNetworkPackageName(arrFileNameAndExtension[0]);
- vendorSoftwareProductObject.setOnboardingOrigin(arrFileNameAndExtension[1]);
-
- return vendorSoftwareProductObject;
- }
-
public Service runOnboardViaApisOnly(ServiceReqDetails serviceReqDetails, ResourceReqDetails resourceReqDetails, String filepath, String vnfFile) throws Exception, AWTException {
Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = OnboardingUtillViaApis.createVspViaApis(resourceReqDetails, filepath, vnfFile, sdncDesignerDetails1);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlows.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java
index da43435cdf..837f834ffa 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlows.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java
@@ -1,18 +1,10 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.io.File;
-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.Resource;
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+import fj.data.Either;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.dataProviders.OnbordingDataProviders;
import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
@@ -23,21 +15,19 @@ 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.SetupCDTest;
-import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils;
-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.FileHandling;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
+import org.openecomp.sdc.ci.tests.utils.general.*;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
+import java.io.File;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
-import fj.data.Either;
+import static org.testng.AssertJUnit.assertTrue;
-public class OnboardingFlows extends SetupCDTest{
+public class OnboardingFlowsThroughAPI extends SetupCDTest{
protected boolean skipReport = false;
protected User sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
@@ -57,9 +47,9 @@ public class OnboardingFlows extends SetupCDTest{
cvfcArtifacts.put(CvfcTypeEnum.VES_EVENTS, vesArtifactFileLocation);
getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, cvfcArtifacts);
+ VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, cvfcArtifacts);
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
List<ComponentInstance> componentInstances = resource.getComponentInstances();
@@ -98,41 +88,56 @@ public class OnboardingFlows extends SetupCDTest{
String vnfFile = newRandomFileNamesFromFolder.get(0);
getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile);
// setLog(vnfFile);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
+ getExtendTest().log(Status.INFO, "Create Vendor License");
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
+ getExtendTest().log(Status.INFO, "Create Vendor Software Product: " + resourceReqDetails.getName());
+ VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
+ getExtendTest().log(Status.INFO, "Create Resource: " + resourceReqDetails.getName());
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
+ getExtendTest().log(Status.INFO, "Certify the Resource: " + resourceReqDetails.getName());
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails);
+ getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName());
org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
-
+
+ getExtendTest().log(Status.INFO, "Add VF to service");
Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
addComponentInstanceToComponentContainer.left().value();
+ getExtendTest().log(Status.INFO, "Certify the service");
service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ getExtendTest().log(Status.INFO, "Start distributing the service");
Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
+ getExtendTest().log(Status.INFO, "Service distributed");
assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService);
// update
vnfFile = newRandomFileNamesFromFolder.get(1);
- getExtendTest().log(Status.INFO, "Going to update VNF with file " + vnfFile);
- OnboardingUtils.updateVendorLicense(amdocsLicenseMembers, sdncDesignerDetails, "1.0");
- vendorSoftwareProductObject = OnboardingUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
+ getExtendTest().log(Status.INFO, "Going to update VLM with new file " + vnfFile);
+ VendorLicenseModelRestUtils.updateVendorLicense(amdocsLicenseMembers, sdncDesignerDetails, false);
+ vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
+ getExtendTest().log(Status.INFO, "Create new VSP: " + vendorSoftwareProductObject.getName());
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
+ getExtendTest().log(Status.INFO, "Create new resource: " + resourceReqDetails.getName());
resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
+ getExtendTest().log(Status.INFO, "Certify the resource");
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails);
+ getExtendTest().log(Status.INFO, "Create new service: " + serviceReqDetails.getName());
service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
-
+
+ getExtendTest().log(Status.INFO, "Add VF to service");
addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
addComponentInstanceToComponentContainer.left().value();
+ getExtendTest().log(Status.INFO, "Certify the service");
service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ getExtendTest().log(Status.INFO, "Start distributing the service");
distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
+ getExtendTest().log(Status.INFO, "Service distributed");
assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService);
-
-
}
@@ -144,9 +149,9 @@ public class OnboardingFlows extends SetupCDTest{
String filePath = FileHandling.getVnfRepositoryPath();
String vnfFile = newRandomFileNamesFromFolder.get(0);
getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
+ VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
@@ -159,11 +164,11 @@ public class OnboardingFlows extends SetupCDTest{
service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService);
-
+
// update resource to v2.0
String updateVnfFile = newRandomFileNamesFromFolder.get(1);
getExtendTest().log(Status.INFO, "Going to update VNF with file " + vnfFile);
- OnboardingUiUtils.updateVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), updateVnfFile, filePath, sdncDesignerDetails, "2.0");
+ VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails, filePath, updateVnfFile);
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
resourceReqDetails.setUniqueId(resource.getUniqueId());
resourceReqDetails.setVersion(resource.getVersion());
@@ -207,12 +212,11 @@ public class OnboardingFlows extends SetupCDTest{
String vnfFile = newRandomFileNamesFromFolder.get(0);
getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile);
User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(sdncDesignerDetails1);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
getExtendTest().log(Status.INFO, "Create Vendor License Model " + amdocsLicenseMembers.getVendorLicenseName());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
getExtendTest().log(Status.INFO, "Create Vendor Software Product " + resourceReqDetails.getName());
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+ VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
// 2. Create VF, certify - v1.0 is created
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
getExtendTest().log(Status.INFO, "Create VF " + resourceReqDetails.getName());
@@ -221,8 +225,8 @@ public class OnboardingFlows extends SetupCDTest{
resource_v1 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
// 3. Update VSP to v2.0
getExtendTest().log(Status.INFO, "Update VSP to version 2.0");
- OnboardingUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, "2.0", sdncDesignerDetails1, filePath, vnfFile);
- OnboardingUtils.validateVspExist(vendorSoftwareProductObject.getVspId(),vendorSoftwareProductObject.getVersion(),sdncDesignerDetails1);
+ VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails1, filePath, vnfFile);
+ VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1);
// 4. Update the VF with v2.0 of the VSP
getExtendTest().log(Status.INFO, "Checkout VF v1.1");
resource_v1 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
@@ -235,8 +239,8 @@ public class OnboardingFlows extends SetupCDTest{
Resource resource_v2 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
// 5. Update VSP to v3.0 wih the zip from v1.0
getExtendTest().log(Status.INFO, "Update VSP to version 3.0");
- OnboardingUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, "3.0", sdncDesignerDetails1);
- OnboardingUtils.validateVspExist(vendorSoftwareProductObject.getVspId(),vendorSoftwareProductObject.getVersion(),sdncDesignerDetails1);
+ VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails1, false);
+ VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1);
getExtendTest().log(Status.INFO, "Checkout VF v2.1");
resource_v1 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
resourceReqDetails.setUniqueId(resource_v1.getUniqueId());
@@ -262,18 +266,17 @@ public class OnboardingFlows extends SetupCDTest{
}
@Test(dataProviderClass = org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders.class, dataProvider = "updateList")
- public void distributeServiceAndUpgradeWithNewHeatFile(String vnfFile1, String vnfFile2) throws Throwable
+ public void updateVSPFlowFromOnboardToDistribution(String vnfFile1, String vnfFile2) throws Throwable
{
- setLog(String.format("Update VSP Test: Create VF from %s add it to service, distribute than upgrade the VF with file %s and update the service and distribute", vnfFile1, vnfFile2));
+ setLog(String.format("Create VSP from %s , update VSP with %s ", vnfFile1, vnfFile2));
// 1. Import VSP v1.0
String filePath = org.openecomp.sdc.ci.tests.utilities.FileHandling.getUpdateVSPVnfRepositoryPath();
User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(sdncDesignerDetails1);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName()));
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1));
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile1, createVendorSoftwareProduct);
+ VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, sdncDesignerDetails, amdocsLicenseMembers, null);
// 2. Create VF, certify - v1.0 is created
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
@@ -289,16 +292,16 @@ public class OnboardingFlows extends SetupCDTest{
getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service"));
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
getExtendTest().log(Status.INFO, String.format("Certify the Service"));
-// 5. Distribute the Service v1.0
+// 4. Distribute the Service v1.0
Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
-// 6. Update VSP to v2.0
+// 5. Update VSP to v2.0
getExtendTest().log(Status.INFO, "Upgrading the VSP with new file: " + vnfFile2);
- OnboardingUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, "2.0", sdncDesignerDetails1, filePath, vnfFile2);
+ VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails1, filePath, vnfFile2);
getExtendTest().log(Status.INFO, String.format("Validating VSP %s upgrade to version 2.0: " ,vnfFile2));
- OnboardingUtils.validateVspExist(vendorSoftwareProductObject.getVspId(),vendorSoftwareProductObject.getVersion(),sdncDesignerDetails1);
-// 7. Update the VF with v2.0 of the VSP and certify the VF
+ VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1);
+// 6. Update the VF with v2.0 of the VSP and certify the VF
getExtendTest().log(Status.INFO, String.format("Checkout the VF %s v1.1 " ,resourceReqDetails.getName()));
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
resourceReqDetails.setUniqueId(resource.getUniqueId());
@@ -308,34 +311,35 @@ public class OnboardingFlows extends SetupCDTest{
resource = AtomicOperationUtils.updateResource(resourceReqDetails, sdncDesignerDetails, true).left().value();
getExtendTest().log(Status.INFO, String.format("Certify the VF to v2.0"));
Resource resource_v2 = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-// 8. Update the Service with the VFi version 2.0
+// 7. Update the Service with the VFi version 2.0
getExtendTest().log(Status.INFO, String.format("Checkout the Service v1.1"));
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
getExtendTest().log(Status.INFO, String.format("Change the instance of the VF in the service to VFi v2.0"));
AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true);
getExtendTest().log(Status.INFO, String.format("Certify the Service to v2.0"));
service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-// 9. Distribute the service v2.0
+// 8. Distribute the service v2.0
distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
}
@Test(dataProviderClass = org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders.class, dataProvider = "VNF_List")
- public void distributeServiceFromHeatFile(String filePath, String vnfFile) throws Throwable
+ public void fromOnboardToDistribution(String filePath, String vnfFile) throws Throwable
{
// String vnfFile1 = "1-2016-20-visbc3vf-(VOIP)_v2.1.zip";
// String vnfFile2 = "2-2016-20-visbc3vf-(VOIP)_v2.0.zip";
- setLog(String.format("Distribute Service Test: Create VF from %s add it to service than distribute", vnfFile));
+ setLog(String.format("%s", vnfFile));
// 1. Import VSP v1.0
//String filePath = FileHandling.getVnfRepositoryPath();
User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(sdncDesignerDetails1);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName()));
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile));
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
+// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+ VendorSoftwareProductObject vendorSoftwareProductObject = createVendorSoftwareProduct.right;
// 2. Create VF, certify - v1.0 is created
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
@@ -351,7 +355,7 @@ public class OnboardingFlows extends SetupCDTest{
getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service"));
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
getExtendTest().log(Status.INFO, String.format("Certify the Service"));
-// 5. Distribute the Service v1.0
+// 4. Distribute the Service v1.0
Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
@@ -362,14 +366,15 @@ public class OnboardingFlows extends SetupCDTest{
{
// 1. Import VSP v1.0
String filePath = FileHandling.getVnfRepositoryPath();
- String vnfFile1 = "HeatCandidate_2017-09-20_13-37_70Name_2017-491-4vshaken-HTTP-CM-vf-v1.0-(VOIP)_10202017.zip";
+ String vnfFile1 = "1-VF-vCSCF-StateDB-new-update_v3.0.zip";
User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(sdncDesignerDetails1);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName()));
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1));
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile1, createVendorSoftwareProduct);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
+// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile1, createVendorSoftwareProduct);
+ VendorSoftwareProductObject vendorSoftwareProductObject = createVendorSoftwareProduct.right;
// 2. Create VF, certify - v1.0 is created
resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
@@ -385,7 +390,7 @@ public class OnboardingFlows extends SetupCDTest{
getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service"));
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
getExtendTest().log(Status.INFO, String.format("Certify the Service"));
-// 5. Distribute the Service v1.0
+// 4. Distribute the Service v1.0
Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
@@ -395,6 +400,5 @@ public class OnboardingFlows extends SetupCDTest{
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/OnboardingFlowsUI.java
index 7681af63c3..b2314af267 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardingFlowsUI.java
@@ -20,43 +20,24 @@
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.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
import org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders;
-import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.*;
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.pages.*;
import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils;
import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils;
+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.OnboardingUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorSoftwareProductRestUtils;
import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator;
import org.openqa.selenium.WebElement;
import org.testng.AssertJUnit;
@@ -65,10 +46,17 @@ import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
+import java.io.File;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
-public class Onboard extends SetupCDTest {
+public class OnboardingFlowsUI extends SetupCDTest {
protected static String filePath = FileHandling.getVnfRepositoryPath();
protected String makeDistributionValue;
@@ -80,18 +68,30 @@ public class Onboard extends SetupCDTest {
}
@Test
- public void onboardVNFTestSanityOneFile() throws Exception, Throwable {
-// List<String> fileNamesFromFolder = OnboardingUiUtils.getVnfNamesFileList();
-// String vnfFile = fileNamesFromFolder.get(0).toString();
- String vnfFile = "2017-302_vNSO.zip";
-// String vnfFile = "1-Fn-vprobe-be-11-2-5-1-vf-(MOBILITY)_v5.0.zip";
+ public void onboardVNFTestSanityOneFile() throws Throwable {
+ String vnfFile = "1-VF-vUSP-vCCF-DB_v11.1.zip";
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();//getServiceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
runOnboardToDistributionFlow(resourceReqDetails, serviceReqDetails, filePath, vnfFile);
}
-
+
+ @Test
+ public void performanceTest() throws Throwable {
+ System.out.println("Start test");
+ Long actualTestRunTime = Utils.getActionDuration(() -> {
+ try {
+ onboardVNFTestSanityOneFile();
+ } catch (Throwable throwable) {
+ throwable.printStackTrace();
+ }
+ });
+ Long regularTestRunTime = 400L;
+ double factor = 1.5;
+ assertTrue("Expected test run time should be less from " + regularTestRunTime*factor + ", actual time is " + actualTestRunTime , regularTestRunTime*factor>actualTestRunTime);
+ }
+
@Test
- public void onboardVNFTestSanity() throws Exception, Throwable {
+ public void onboardVNFTestSanity() throws Throwable {
List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileList();
String vnfFile = fileNamesFromFolder.get(0).toString();
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
@@ -100,7 +100,7 @@ public class Onboard extends SetupCDTest {
}
- public void runOnboardToDistributionFlow(ResourceReqDetails resourceReqDetails, ServiceReqDetails serviceMetadata, String filePath, String vnfFile) throws Exception, AWTException {
+ public void runOnboardToDistributionFlow(ResourceReqDetails resourceReqDetails, ServiceReqDetails serviceMetadata, String filePath, String vnfFile) throws Exception {
getExtendTest().log(Status.INFO, "Going to create resource with category: " + resourceReqDetails.getCategories().get(0).getName()
+ " subCategory: " + resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName()
+ " and service category: " + serviceMetadata.getCategory());
@@ -151,8 +151,8 @@ public class Onboard extends SetupCDTest {
getExtendTest().log(Status.INFO, String.format("The onboarding %s test is passed ! ", vnfFile));
}
- public String onboardAndCertify(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception, IOException {
- Pair<String,Map<String,String>> onboardAndValidate = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser());
+ public String onboardAndCertify(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception {
+ Pair<String, VendorSoftwareProductObject> onboardAndValidate = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser());
String vspName = onboardAndValidate.left;
DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen();
@@ -168,7 +168,7 @@ public class Onboard extends SetupCDTest {
@Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List")
- public void onboardVNFTest(String filePath, String vnfFile) throws Exception, Throwable {
+ public void onboardVNFTest(String filePath, String vnfFile) throws Throwable {
setLog(vnfFile);
System.out.println("printttttttttttttt - >" + makeDistributionValue);
ResourceReqDetails resourceReqDetails = ElementFactory.getRandomCategoryResource();
@@ -177,7 +177,7 @@ public class Onboard extends SetupCDTest {
}
@Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List")
- public void onboardVNFShotFlow(String filePath, String vnfFile) throws Exception, Throwable {
+ public void onboardVNFShotFlow(String filePath, String vnfFile) throws Throwable {
setLog(vnfFile);
System.out.println("printttttttttttttt - >" + makeDistributionValue);
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
@@ -185,7 +185,7 @@ public class Onboard extends SetupCDTest {
}
@Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "randomVNF_List")
- public void onboardRandomVNFsTest(String filePath, String vnfFile) throws Exception, Throwable {
+ public void onboardRandomVNFsTest(String filePath, String vnfFile) throws Throwable {
setLog(vnfFile);
System.out.println("printttttttttttttt - >" + makeDistributionValue);
System.out.println("Vnf File name is: " + vnfFile);
@@ -196,13 +196,13 @@ public class Onboard extends SetupCDTest {
@Test
- public void onboardUpdateVNFTest() throws Exception, Throwable {
+ public void onboardUpdateVNFTest() throws Throwable {
// Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filePath);
List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filePath);
// String vnfFile = fileNamesFromFolder[0].toString();
String vnfFile = fileNamesFromFolder.get(0);
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser());
String vspName = vsp.left;
ResourceGeneralPage.clickSubmitForTestingButton(vspName);
@@ -280,18 +280,17 @@ public class Onboard extends SetupCDTest {
public void threeVMMSCsInServiceTest() throws Exception{
String pathFile = FileHandling.getFilePath("VmmscArtifacts");
- List<String> vmmscList = new ArrayList<String>();
- vmmscList = Arrays.asList(new File(pathFile).list()).stream().filter(e -> e.contains("vmmsc") && e.endsWith(".zip")).collect(Collectors.toList());
+ List<String> vmmscList = Arrays.asList(new File(pathFile).list()).stream().filter(e -> e.contains("vmmsc") && e.endsWith(".zip")).collect(Collectors.toList());
assertTrue("Did not find vMMSCs", vmmscList.size() > 0);
- Map<String, String> vspNames = new HashMap<String, String>();
+ Map<String, String> 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));
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, pathFile, getUser(), amdocsLicenseMembers);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, pathFile, getUser(), amdocsLicenseMembers);
getExtendTest().log(Status.INFO, String.format("Searching for onboarded %s", vnfFile));
HomePage.showVspRepository();
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PNF.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PNF.java
index d24000806e..fa55a1e66d 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PNF.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PNF.java
@@ -1,43 +1,14 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
+import com.aventstack.extentreports.Status;
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.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.ArtifactTypeEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.CircleSize;
-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.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.*;
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.GovernorOperationPage;
-import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage;
-import org.openecomp.sdc.ci.tests.pages.OpsOperationPage;
-import org.openecomp.sdc.ci.tests.pages.PropertiesPage;
-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.pages.ToscaArtifactsPage;
-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.pages.*;
+import org.openecomp.sdc.ci.tests.utilities.*;
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;
@@ -45,11 +16,14 @@ 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 java.util.List;
+
+import static org.testng.Assert.assertTrue;
public class PNF extends SetupCDTest {
@@ -117,6 +91,10 @@ public class PNF extends SetupCDTest {
@Test
public void addPropertiesToVfcInstanceInPNFTest() throws Exception {
+ if(true){
+ throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen");
+ }
+
String fileName = "CP02.yml";
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PortMirroring.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PortMirroring.java
index b4bd55c6ca..ef957c6e32 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PortMirroring.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PortMirroring.java
@@ -1,124 +1,610 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import java.util.Map;
-
-import org.openecomp.sdc.be.model.ComponentInstance;
+import com.aventstack.extentreports.Status;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+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.datatypes.AmdocsLicenseMembers;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
-import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
-import org.openecomp.sdc.ci.tests.datatypes.ConnectionWizardPopUpObject;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceContainer;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject;
+import org.openecomp.sdc.ci.tests.datatypes.*;
import org.openecomp.sdc.ci.tests.datatypes.enums.CircleSize;
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.SetupCDTest;
import org.openecomp.sdc.ci.tests.pages.CompositionPage;
+import org.openecomp.sdc.ci.tests.pages.ResourceGeneralPage;
import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage;
-import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils;
+import org.openecomp.sdc.ci.tests.utilities.CatalogUIUtilitis;
+import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
+import org.openecomp.sdc.ci.tests.utilities.HomeUtils;
+import org.openecomp.sdc.ci.tests.utilities.PortMirroringUtils;
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.FileHandling;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
+import org.openecomp.sdc.ci.tests.verificator.PortMirroringVerificator;
import org.openecomp.sdc.ci.tests.verificator.ServiceVerificator;
+import org.testng.AssertJUnit;
+import org.testng.SkipException;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
+import java.io.File;
-import fj.data.Either;
+import static org.testng.Assert.assertTrue;
-public class PortMirroring extends SetupCDTest
-{
- @Override
- protected UserRoleEnum getRole() {
- return UserRoleEnum.DESIGNER3;
+public class PortMirroring extends SetupCDTest {
+
+ @Test
+ public void createPortMirroringConfigurationServiceProxy() throws Throwable {
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+ CanvasManager canvasManager = portMirrioringConfigurationObject.getCanvasManager();
+ CanvasElement serviceElementVmmeSourceName = portMirrioringConfigurationObject.getServiceElementVmmeSourceName();
+ String vmmeSourceName = portMirrioringConfigurationObject.getVmmeSourceName();
+ CanvasElement serviceElementVprobeCollector = portMirrioringConfigurationObject.getServiceElementVprobeCollector();
+ String vprobeSourceName = portMirrioringConfigurationObject.getVprobeSourceName();
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating links between elements were created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2);
+
+ canvasManager.clickOnCanvaElement(serviceElementVmmeSourceName);
+ PortMirroringVerificator.validatingProxyServiceNameAndType(vmmeSourceName, "0");
+
+ canvasManager.clickOnCanvaElement(serviceElementVprobeCollector);
+ PortMirroringVerificator.validatingProxyServiceNameAndType(vprobeSourceName, "0");
}
- String portMirroringElementNameInPallete = "Port Mirroring Configuration";
- String portMirroringCapReqType = "org.openecomp.capabilities.PortMirroring";
- String portMirroringSourceCapability = "Port Mirroring Configuration 0: source: [1, UNBOUNDED]";
- String portMirroringCollectorCapability = "Port Mirroring Configuration 0: collector: [1, 1]";
+ @Test
+ public void distributePortMirroringConfigurationServiceProxy() throws Throwable {
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+ Service service = portMirrioringConfigurationObject.getService();
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating links between elements were created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2);
+
+ getExtendTest().log(Status.INFO, String.format("Going to certify the Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ getExtendTest().log(Status.INFO, String.format("Service is certified"));
+ Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
+ getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
+ AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
+ }
@Test
- public void createPortMirroringServiceProxy() throws Throwable {
+ public void createPortMirroringByPolicyServiceProxy() throws Throwable {
//Using API onboard and certify 2 zip files Source: vmmme and Collector: Vprobe
String filePath = FileHandling.getPortMirroringRepositoryPath();
- ServiceContainer serviceContainerVmme_Source = createServiceFromHeatFile(filePath,"2016-227_vmme_vmme_30_1610_e2e.zip");
- ServiceContainer serviceContainerVprobe_Collector = createServiceFromHeatFile(filePath,"vProbe_2017-10-22_07-24.zip");
+ ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, "2016-227_vmme_vmme_30_1610_e2e.zip");
+
+ // create service with required pnf's and certify it
+ Resource resourceCisco = PortMirroringUtils.GeneratePNFAndUpdateInput(PortMirroringEnum.CISCO_VENDOR_NAME.getValue(), PortMirroringEnum.CISCO_VENDOR_MODEL_NUMBER.getValue(), getUser());
+ Resource resourceAPCON1 = PortMirroringUtils.GeneratePNFAndUpdateInput(PortMirroringEnum.APCON1_VENDOR_NAME.getValue(), PortMirroringEnum.APCON1_VENDOR_MODEL_NUMBER.getValue(), getUser());
+ Resource resourceAPCON2 = PortMirroringUtils.GeneratePNFAndUpdateInput(PortMirroringEnum.APCON2_VENDOR_NAME.getValue(), PortMirroringEnum.APCON2_VENDOR_MODEL_NUMBER.getValue(), getUser());
+
+ ServiceReqDetails serviceReqDetailsCollector = ElementFactory.getDefaultService();
+ serviceReqDetailsCollector.setServiceType(PortMirroringEnum.SERVICE_TYPE.getValue());
+ getExtendTest().log(Status.INFO, String.format("Creating collector service %s (PNF container)", serviceReqDetailsCollector.getName()));
+ Service serviceCollector = AtomicOperationUtils.createCustomService(serviceReqDetailsCollector, UserRoleEnum.DESIGNER, true).left().value();
+
+ getExtendTest().log(Status.INFO, String.format("Adding pnf's: %s,%s,%s to service %s", resourceCisco.getName(), resourceAPCON1.getName(), resourceAPCON2.getName(), serviceCollector.getName()));
-// String vmmeSourceName = "ciServiceb560327d162f";
-// String vprobeSourceName = "ciService3d9933d31791";
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceCisco, serviceCollector, UserRoleEnum.DESIGNER, true, "80", "80");
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceAPCON1, serviceCollector, UserRoleEnum.DESIGNER, true, "80", "200");
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceAPCON2, serviceCollector, UserRoleEnum.DESIGNER, true, "200", "200");
- // create service
- ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
- ServiceUIUtils.createService(serviceMetadata, getUser());
+ serviceCollector = (Service) AtomicOperationUtils.changeComponentState(serviceCollector, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ // create container service
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
String vmmeSourceName = serviceContainerVmme_Source.getService().getName();
- String vprobeSourceName = serviceContainerVprobe_Collector.getService().getName();
+ String collectorServiceName = serviceCollector.getName();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
CanvasManager canvasManager = CanvasManager.getCanvasManager();
CompositionPage.searchForElement(vmmeSourceName);
- CanvasElement serviceElementVmmeSourceName = canvasManager.createElementOnCanvas(vmmeSourceName);
-
- CompositionPage.searchForElement(vprobeSourceName);
- CanvasElement serviceElementVprobeCollector = canvasManager.createElementOnCanvas(vprobeSourceName);
-
- CompositionPage.searchForElement(portMirroringElementNameInPallete);
- CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(portMirroringElementNameInPallete);
-
- ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("","", portMirroringCapReqType, portMirroringSourceCapability);
- ConnectionWizardPopUpObject connectionWizardPopUpObjectVProbe = new ConnectionWizardPopUpObject("","", portMirroringCapReqType, portMirroringCollectorCapability);
-
- canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE,portMirroringConfigurationElement, CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME);
- canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVprobeCollector, CircleSize.SERVICE, portMirroringConfigurationElement, CircleSize.NORMATIVE, connectionWizardPopUpObjectVProbe);
-
- serviceMetadata.setVersion("0.1");
- ServiceVerificator.verifyLinkCreated(serviceMetadata, getUser(), 2);
-
- System.out.println("End");
- }
-
- public ServiceContainer createServiceFromHeatFile(String filePath, String vnfFile) throws Throwable
- {
- setLog(String.format("Distribute Service Test: Create VF from %s add it to service than distribute", vnfFile));
-// 1. Import VSP v1.0
- User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER3);
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(sdncDesignerDetails1);
- getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName()));
- ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
- getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile));
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
- VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
-// 2. Create VF, certify - v1.0 is created
- resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
- Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
- resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
- getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName()));
- getExtendTest().log(Status.INFO, String.format("Certify the VF"));
-// 3. Create Service add to it the certified VF and certify the Service v1.0
+ CanvasElement serviceElementVmmeSource = canvasManager.createElementOnCanvas(vmmeSourceName);
+
+ CompositionPage.searchForElement(collectorServiceName);
+ CanvasElement serviceElementCollectorService = canvasManager.createElementOnCanvas(collectorServiceName);
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("",
+ "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(),
+ PortMirroringEnum.PMCP_SOURCE_CAP.getValue());
+
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSource,
+ CircleSize.SERVICE,
+ portMirroringConfigurationByPolicyElement,
+ CircleSize.NORMATIVE,
+ connectionWizardPopUpObjectVMME);
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating link between elements was created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 1);
+
+ canvasManager.clickOnCanvaElement(serviceElementVmmeSource);
+ PortMirroringVerificator.validatingProxyServiceNameAndType(vmmeSourceName, "0");
+
+ getExtendTest().log(Status.INFO, "Adding properties to PMCP");
+
+ if(true){
+ throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen");
+ }
+
+ canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement);
+ CompositionPage.showPropertiesAndAttributesTab();
+ CompositionPage.setSingleProperty(DataTestIdEnum.PortMirroring.COLLECTOR_NODE.getValue(), PortMirroringUtils.createProxyInstanceServiceName(collectorServiceName, "1"));
+ CompositionPage.setSingleProperty(DataTestIdEnum.PortMirroring.EQUIP_MODEL.getValue(), PortMirroringEnum.CISCO_VENDOR_MODEL_NUMBER.getValue());
+ CompositionPage.setSingleProperty(DataTestIdEnum.PortMirroring.EQUIP_VENDOR.getValue(), PortMirroringEnum.CISCO_VENDOR_NAME.getValue());
+
+ // Distribute the Port Mirroning Configuration By Policy
+ getExtendTest().log(Status.INFO, String.format("Going to certify the Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ getExtendTest().log(Status.INFO, String.format("Service is certified"));
+ Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
+ getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
+ AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
+ }
+
+ @Test
+ public void deletePMCPLink() throws Throwable {
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ String filePath = FileHandling.getPortMirroringRepositoryPath();
+ ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, "2016-227_vmme_vmme_30_1610_e2e.zip");
+
+ String vmmeSourceName = serviceContainerVmme_Source.getService().getName();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CompositionPage.searchForElement(vmmeSourceName);
+ CanvasElement serviceElementVmmeSource = canvasManager.createElementOnCanvas(vmmeSourceName);
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+
+ ImmutablePair<Integer, Integer> linkLocation = canvasManager.calcMidOfLink(serviceElementVmmeSource.getLocation(), portMirroringConfigurationByPolicyElement.getLocation());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("",
+ "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(),
+ PortMirroringEnum.PMCP_SOURCE_CAP.getValue());
+
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSource,
+ CircleSize.SERVICE,
+ portMirroringConfigurationByPolicyElement,
+ CircleSize.NORMATIVE,
+ connectionWizardPopUpObjectVMME);
+
+ CanvasElement linkBetweenPMCP_VMME = new CanvasElement("Link", linkLocation);
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating link between elements was created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 1);
+
+ canvasManager.openLinkPopupReqsCapsConnection(linkBetweenPMCP_VMME);
+ canvasManager.closeLinkPopupReqsCapsConnection();
+ canvasManager.deleteLinkPopupReqsCapsConnection(linkBetweenPMCP_VMME);
+
+ getExtendTest().log(Status.INFO, "Validating link deleted");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 0);
+ }
+
+ @Test
+ public void verifyPMCNotExistInVF() throws Exception {
+ Resource resource = PortMirroringUtils.getResourceByType(ResourceTypeEnum.VF, "VF", "VendorModel");
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+
+ GeneralUIUtils.findComponentAndClick(resource.getName());
+ ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+
+ getExtendTest().log(Status.INFO, "Verify that Port Mirroring Configuration and Configuration by Policy doesn't exist for VF ");
+ boolean isPMCFound = GeneralUIUtils.isElementInvisibleByTestId(DataTestIdEnum.PortMirroring.PMC_NAME_IN_PALLETE.getValue());
+ boolean isPMCPFound = GeneralUIUtils.isElementInvisibleByTestId(DataTestIdEnum.PortMirroring.PMCP_NAME_IN_PALLETE.getValue());
+
+ assertTrue(isPMCFound);
+ assertTrue(isPMCPFound);
+ }
+
+ @Test
+ public void verifyPMCPTabs() throws Exception {
+
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement);
+
+ PortMirroringVerificator.validateGeneralInfo();
+ PortMirroringVerificator.validateReqsAndCapsTabExist();
+ }
+
+
+ @Test
+ public void editPMCPName() throws Exception {
+
ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName()));
Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
- getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName()));
- Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
- ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value();
- getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service"));
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+
+ canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement);
+
+ getExtendTest().log(Status.INFO, "Edit PMCP Name");
+ GeneralUIUtils.clickOnElementById(DataTestIdEnum.CompositionRightPanel.EDIT_PENCIL.getValue());
+ GeneralUIUtils.setTextInElementByDataTestID(DataTestIdEnum.CompositionRightPanel.INSTANCE_NAME_TEXTBOX.getValue(), PortMirroringEnum.PMCP_NEWNAME.getValue());
+ GeneralUIUtils.clickOnElementByTestId("OK");
+
+ PortMirroringVerificator.validateElementName(PortMirroringEnum.PMCP_NEWNAME.getValue());
+ }
+
+
+ @Test
+ public void deletePMCP() throws Exception {
+
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+
+ canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement);
+
+ getExtendTest().log(Status.INFO, String.format("Delete element %s", portMirroringConfigurationByPolicyElement.getElementType()));
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionRightPanel.DELETE_ITEM.getValue());
+ GeneralUIUtils.clickOnElementByTestId("OK");
+
+ PortMirroringVerificator.validateElementName(service.getName());
+ }
+
+ @Test
+ public void createPortMirroringConfigurationMulipleInstances() throws Throwable {
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+ CanvasElement serviceElementVmmeSourceName = portMirrioringConfigurationObject.getServiceElementVmmeSourceName();
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating 2 links between elements were created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2);
+
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName());
+
+ getExtendTest().log(Status.INFO, "Adding second PMC to composition");
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC1_SOURCE_CAP.getValue());
+
+ getExtendTest().log(Status.INFO, "Connect VMME to PMC again");
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE, portMirroringConfigurationElement,
+ CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME);
+
+ getExtendTest().log(Status.INFO, "Connect VMME to PMC again");
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE, portMirroringConfigurationElement,
+ CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME);
+
+ getExtendTest().log(Status.INFO, "Validating 4 links between elements exist");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 4);
+
+ getExtendTest().log(Status.INFO, "Adding second PMCP to composition");
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME_PMCP = new ConnectionWizardPopUpObject("",
+ "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(),
+ PortMirroringEnum.PMCP_SOURCE_CAP.getValue());
+
+ getExtendTest().log(Status.INFO, "Connect VMME to PMCP again");
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE, portMirroringConfigurationByPolicyElement,
+ CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME_PMCP);
+
+ getExtendTest().log(Status.INFO, "Connect VMME to PMCP again");
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE, portMirroringConfigurationByPolicyElement,
+ CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME_PMCP);
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating 6 links between elements exist");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 6);
+ }
+
+ @Test
+ public void downloadArtifactFromPMCService() throws Throwable {
+ //Scenario of bug 362271
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen();
+
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue());
+ File latestFilefromDir = org.openecomp.sdc.ci.tests.utilities.FileHandling.getLastModifiedFileNameFromDir();
+ String actualToscaModelFilename = latestFilefromDir.getName();
+
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue());
+ latestFilefromDir = org.openecomp.sdc.ci.tests.utilities.FileHandling.getLastModifiedFileNameFromDir();
+ String actualToscaTemplateFilename = latestFilefromDir.getName();
+
+ String expectedToscaModelFilename = String.format("service-%s-csar.csar", serviceReqDetails.getName());
+ String expectedToscaTemplateFilename = String.format("service-%s-template.yml", serviceReqDetails.getName());
+
+ getExtendTest().log(Status.INFO, "Validating tosca artifact downloaded successfully");
+ AssertJUnit.assertTrue(actualToscaModelFilename.equalsIgnoreCase(expectedToscaModelFilename));
+ AssertJUnit.assertTrue(actualToscaTemplateFilename.equalsIgnoreCase(expectedToscaTemplateFilename));
+ }
+
+ @Test
+ public void checkoutMirroringConfigurationServiceProxyAndDeletePMC() throws Throwable {
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+ Service service = portMirrioringConfigurationObject.getService();
+ CanvasElement portMirroringConfigurationElement = portMirrioringConfigurationObject.getPortMirroringConfigurationElement();
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating links between elements were created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2);
+
+ getExtendTest().log(Status.INFO, String.format("Going to certify the Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ getExtendTest().log(Status.INFO, String.format("Checkout Port Mirroring Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ HomeUtils.findComponentAndClickByVersion(service.getName(), "1.1");
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+ GeneralUIUtils.ultimateWait();
+ canvasManager.clickOnCanvasPosition(portMirroringConfigurationElement.getLocation().getLeft(), portMirroringConfigurationElement.getLocation().getRight());
+ getExtendTest().log(Status.INFO, String.format("Delete element %s", portMirroringConfigurationElement.getElementType()));
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionRightPanel.DELETE_ITEM.getValue());
+ GeneralUIUtils.clickOnElementByTestId("OK");
+
+ PortMirroringVerificator.validateElementName(service.getName());
+ getExtendTest().log(Status.INFO, "Validating 0 links after delete the port mirroring element");
+ serviceReqDetails.setVersion("1.1");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 0);
+
+ getExtendTest().log(Status.INFO, String.format("Going to certify the Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ getExtendTest().log(Status.INFO, String.format("Service is certified"));
+ Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
+ getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
+ AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
+ }
+
+ @Test
+ public void updatePortMirroringServiceInstance() throws Throwable {
+
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ Service service = portMirrioringConfigurationObject.getService();
+ CanvasElement vmmeCanvasElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName();
+
+ getExtendTest().log(Status.INFO, String.format("Going to certify the Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ Service serviceContainerVmme_Source = portMirrioringConfigurationObject.getServiceContainerVmme_Source();
+ getExtendTest().log(Status.INFO, String.format("Checkout the vmme Service"));
+ serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ getExtendTest().log(Status.INFO, String.format("Going to certify the vmme Service"));
+ serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ getExtendTest().log(Status.INFO, String.format("Checkout Port Mirroring Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ HomeUtils.findComponentAndClickByVersion(service.getName(), "1.1");
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ getExtendTest().log(Status.INFO, String.format("Change vmme source %s instance to version 2.0", serviceContainerVmme_Source.getName()));
+ CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "2.0",false);
+
+ getExtendTest().log(Status.INFO, String.format("Going to certify the Service"));
service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
- getExtendTest().log(Status.INFO, String.format("Certify the Service"));
- return new ServiceContainer(service,resource,vendorSoftwareProductObject,amdocsLicenseMembers);
+ getExtendTest().log(Status.INFO, String.format("Service is certified"));
+ Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service);
+ getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service"));
+ AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService);
}
+ @Test
+ public void updateLinkPropertiesPortMirroringService() throws Throwable {
+
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ String filePath = FileHandling.getPortMirroringRepositoryPath();
+ ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, "2016-227_vmme_vmme_30_1610_e2e.zip");
+
+ String vmmeSourceName = serviceContainerVmme_Source.getService().getName();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CompositionPage.searchForElement(vmmeSourceName);
+ CanvasElement serviceElementVmmeSource = canvasManager.createElementOnCanvas(vmmeSourceName);
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue());
+
+ ImmutablePair<Integer, Integer> linkLocation = canvasManager.calcMidOfLink(serviceElementVmmeSource.getLocation(), portMirroringConfigurationByPolicyElement.getLocation());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("",
+ "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(),
+ PortMirroringEnum.PMCP_SOURCE_CAP.getValue());
+
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSource,
+ CircleSize.SERVICE,
+ portMirroringConfigurationByPolicyElement,
+ CircleSize.NORMATIVE,
+ connectionWizardPopUpObjectVMME);
+
+ CanvasElement linkBetweenPMCP_VMME = new CanvasElement("Link", linkLocation);
+
+ serviceReqDetails.setVersion("0.1");
+ getExtendTest().log(Status.INFO, "Validating link between elements was created");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 1);
+
+ canvasManager.openLinkPopupReqsCapsConnection(linkBetweenPMCP_VMME);
+
+ getExtendTest().log(Status.INFO, "Fill link properties with data");
+ GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.NETWORK_ROLE_XPATH.getValue(),PortMirroringEnum.NETWORK_ROLE_VALUE.getValue());
+ GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.NFC_TYPE_XPATH.getValue(),PortMirroringEnum.NFC_TYPE_VALUE.getValue());
+ GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.PPS_CAPACITY_XPATH.getValue(),PortMirroringEnum.PPS_CAPACITY_VALUE.getValue());
+ GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.NF_TYPE_XPATH.getValue(),PortMirroringEnum.NF_TYPE_VALUE.getValue());
+ GeneralUIUtils.ultimateWait();
+
+ if(true){
+ throw new SkipException("Open bug 373765, Can't update link property on Port Mirroring connection");
+ }
+
+ canvasManager.clickSaveOnLinkPopup();
+ Thread.sleep(3000); //Temp solution. Don't remove.
+ canvasManager.openLinkPopupReqsCapsConnection(linkBetweenPMCP_VMME);
+
+ PortMirroringVerificator.validateLinkProperties();
+ }
+
+ @Test
+ public void restorePortMirroringServiceLink() throws Throwable {
+ //Scenario is taken from bug 361475 - Second Scenario
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+ Service service = portMirrioringConfigurationObject.getService();
+ CanvasElement vmmeCanvasElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName();
+ Service serviceContainerVmme_Source = portMirrioringConfigurationObject.getServiceContainerVmme_Source();
+
+ getExtendTest().log(Status.INFO, String.format("Checkout the vmme Service"));
+ serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ getExtendTest().log(Status.INFO, String.format("Going to certify the vmme Service"));
+ serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ HomeUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 2.0", serviceContainerVmme_Source.getName()));
+ CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "2.0",false);
+
+ getExtendTest().log(Status.INFO, "Validating 1 link exist after change version to the vmme service (Newer version)");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2);
+
+ getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 1.0", serviceContainerVmme_Source.getName()));
+ CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "1.0",false);
+
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2);
+ }
+
+ @Test
+ public void restoreServiceVersionOnContainerService() throws Throwable {
+ //Scenario is taken from bug 361475 - First Scenario
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure();
+ ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails();
+ Service service = portMirrioringConfigurationObject.getService();
+ CanvasElement vmmeCanvasElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName();
+ Service serviceContainerVmme_Source = portMirrioringConfigurationObject.getServiceContainerVmme_Source();
+ Service serviceContainerVprobe_Vprobe_Collector = portMirrioringConfigurationObject.getServiceContainerVprobe_Collector();
+ CanvasElement vprobeCanvasElement = portMirrioringConfigurationObject.getServiceElementVprobeCollector();
+
+
+ getExtendTest().log(Status.INFO, String.format("Checkout the vmme Service"));
+ serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ getExtendTest().log(Status.INFO, String.format("Going to certify the vmme Service"));
+ serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ HomeUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ canvasManager.linkElements(vmmeCanvasElement, CircleSize.SERVICE, vprobeCanvasElement, CircleSize.SERVICE);
+
+ getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 2.0", serviceContainerVmme_Source.getName()));
+ CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "2.0",false);
+
+ getExtendTest().log(Status.INFO, "Validating 1 link exist after change version to the vmme service (Newer version)");
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 3);
+
+ getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 1.0", serviceContainerVmme_Source.getName()));
+ CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "1.0",false);
+
+ ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 3);
+ }
+
+ @Override
+ protected UserRoleEnum getRole() {
+ return UserRoleEnum.DESIGNER;
+ }
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignment.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignment.java
index 4ccc7b024b..ae7d4770ba 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignment.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/PropertiesAssignment.java
@@ -20,7 +20,10 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
+import static org.testng.Assert.assertTrue;
+
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;
@@ -29,8 +32,10 @@ import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
import org.openecomp.sdc.ci.tests.pages.PropertiesAssignmentPage;
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.PropertiesAssignmentVerificator;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
@@ -41,7 +46,9 @@ import com.aventstack.extentreports.Status;
public class PropertiesAssignment extends SetupCDTest {
- private String filePath;
+ private static String filePath;
+ private static String csarFile = "PCRF_OS_FIXED.csar";
+
@BeforeClass
public void beforeClass(){
filePath = FileHandling.getFilePath("");
@@ -60,13 +67,13 @@ public class PropertiesAssignment extends SetupCDTest {
// ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
// ResourceUIUtils.createResource(vfMetaData, getUser());
- String csarFile = "PCRF_OS_FIXED.csar";
+ String csarTestFile = csarFile;
String componentName = "abstract_pcm";
String propertyName = "min_instances";
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());
+ ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser());
ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen();
@@ -85,6 +92,36 @@ public class PropertiesAssignment extends SetupCDTest {
}
+
+
+ @Test
+ public void filterAllVfTest() throws Exception {
+// ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+// ResourceUIUtils.createResource(vfMetaData, getUser());
+
+ String csarTestFile = csarFile;
+ String propertyName = "name";
+ String propertyLocation = DataTestIdEnum.PropertiesAssignmentScreen.PROPERTY_NAME_COLUMN.getValue();
+ int propertiesCountFilter = 22;
+ int propertiesCountWithoutFilter = 0;
+
+ ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString());
+ resourceMetaData.setVersion("0.1");
+ ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser());
+
+
+ ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen();
+ //Count current properties number before filter is applied
+ propertiesCountWithoutFilter = GeneralUIUtils.getWebElementsListByContainsClassName(propertyLocation).size();
+ PropertiesAssignmentPage.clickOnFilterButton();
+ PropertiesAssignmentPage.clickOnFilterAllCheckbox();
+ PropertiesAssignmentPage.findFilterBoxAndClick(propertyName);
+ PropertiesAssignmentPage.clickOnFilterApplyButton();
+ PropertiesAssignmentVerificator.validateFilteredPropertiesCount(propertiesCountFilter, propertyLocation);
+
+ PropertiesAssignmentPage.clickOnFilterClearAllButton();
+ PropertiesAssignmentVerificator.validateFilteredPropertiesCount(propertiesCountWithoutFilter, propertyLocation);
+ }
@Override
protected UserRoleEnum getRole() {
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java
index d6370c10dc..71466f3211 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java
@@ -20,45 +20,22 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.AssertJUnit.assertTrue;
-
-import java.awt.AWTException;
-import java.util.Arrays;
-import java.util.List;
-
+import com.aventstack.extentreports.Status;
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.GroupDefinition;
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.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.*;
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.TopMenuButtonsEnum;
-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.datatypes.enums.*;
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.pages.*;
+import org.openecomp.sdc.ci.tests.utilities.*;
+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.validation.ErrorValidationUtils;
@@ -68,11 +45,17 @@ 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;
+import java.awt.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.testng.AssertJUnit.assertTrue;
public class Service extends SetupCDTest {
@@ -579,21 +562,35 @@ public class Service extends SetupCDTest {
}
@Test
- public void deploymentViewServiceTest() throws Exception{
- String fileName2 = "vSeGWNew.csar";
+ public void deploymentViewServiceTest() throws Exception{
+ User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String fileName2 = "vSeGWNew.csar";
+
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString());
ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser());
+ Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1");
+ List<GroupDefinition> groups = resource.getGroups();
+ for (GroupDefinition group : groups) {
+ if(group.getType().equals("org.openecomp.groups.VfModule")) {
+ for(PropertyDataDefinition property : group.getProperties()){
+ if(property.getName().equals("max_vf_module_instances")) {
+ property.setValue("100");
+ List<PropertyDataDefinition> propertyList = new ArrayList<>();
+ propertyList.add(property);
+ AtomicOperationUtils.updateGroupPropertyOnResource(propertyList, resource, group.getUniqueId(), user, true);
+ break;
+ }
+ }
+ }
+ }
+
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<WebElement> instanceRowsFromTable = GeneralUIUtils.getElementsByCSS("div[data-tests-id^='hierarchy-instance'] span[class^='expand-collapse-title-text']");
for(WebElement instanceRow: instanceRowsFromTable){
@@ -602,14 +599,14 @@ public class Service extends SetupCDTest {
for (WebElement instanceModule: instanceModulesList){
String instanceModuleText = instanceModule.getText();
ResourceUIUtils.clickOnElementByText(instanceModuleText, "instance");
-
ServiceVerificator.verifyDeploymentPageSubElements(instanceModuleText.split("\\.\\.")[2], new DeploymentViewVerificator(filePath + fileName2));
-
ServiceVerificator.verifyDisabledServiceProperties();
- String isBaseValue = ServiceVerificator.getVFModulePropertieValue(serviceMetadata, "isBase", instanceModuleText);
+ if(true){
+ throw new SkipException("Sent email to Edith Ronen, waiting for answer");
+ }
+ String isBaseValue = ServiceVerificator.getVFModulePropertyValue(serviceMetadata, "isBase", instanceModuleText);
if (isBaseValue.equals("false"))
ServiceVerificator.verifyEnabledServiceProperties();
-
ResourceUIUtils.clickOnElementByText(instanceModuleText, "instance");
}
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ToscaValidationTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ToscaValidationTest.java
index d42df64a5a..14583607c7 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ToscaValidationTest.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ToscaValidationTest.java
@@ -1,34 +1,24 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+import fj.data.Either;
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.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.*;
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.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject;
+import org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders;
+import org.openecomp.sdc.ci.tests.datatypes.*;
+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.setup.SetupCDTest;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaInputsTopologyTemplateDefinition;
-import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.*;
import org.openecomp.sdc.ci.tests.tosca.model.ToscaMetadataFieldsPresentationEnum;
import org.openecomp.sdc.ci.tests.utilities.DownloadManager;
import org.openecomp.sdc.ci.tests.utilities.FileHandling;
+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;
@@ -37,15 +27,14 @@ import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
import org.openecomp.sdc.ci.tests.verificator.ToscaValidation;
import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;
import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory;
+import org.openecomp.sdc.toscaparser.api.Group;
import org.openecomp.sdc.toscaparser.api.NodeTemplate;
import org.openecomp.sdc.toscaparser.api.elements.Metadata;
import org.testng.Assert;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
-
-import fj.data.Either;
+import java.io.File;
+import java.util.*;
public class ToscaValidationTest extends SetupCDTest{
@@ -53,50 +42,11 @@ public class ToscaValidationTest extends SetupCDTest{
private static final String GENERIC_VF = "Generic_VF";
private static final String GENERIC_PNF = "Generic_PNF";
-// private ToscaDefinition toscaMainAmdocsDefinition, toscaMainVfDefinition, toscaMainServiceDefinition, toscaExpectedMainServiceDefinition;
- protected String vnfFile;
- protected String filepath;
-// protected File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
protected SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
-// protected ISdcCsarHelper fdntCsarHelper;
-// protected ResourceReqDetails resourceReqDetails;
-// protected Resource resource;
-// protected ServiceReqDetails serviceReqDetails;
-// protected Service service;
-// protected ComponentInstance componentInstanceDefinition;
User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
-// File importToscaFilesFolder = new File("C:/Git_work/sdc/catalog-be/src/main/resources/import/tosca/");
-
-// File dataTypesLocation = new File(importToscaFilesFolder.getPath() + "/data-types/dataTypes.yml");
-// List<Boolean> status = new ArrayList<>();
-
-// File genericVfFileLocation = new File(importToscaFilesFolder.getPath() + "/heat-types/Generic_VF/Generic_VF.yml");
-// File genericVfcFileLocation = new File (importToscaFilesFolder.getPath() + "/heat-types/Generic_VFC/Generic_VFC.yml");
-// File genericPnfFileLocation = new File (importToscaFilesFolder.getPath() + "/heat-types/Generic_PNF/Generic_PNF.yml");
-// File genericServiceFileLocation = new File (importToscaFilesFolder.getPath() + "/heat-types/Generic_Service/Generic_Service.yml");
-
-// Map<String, DataTypeDefinition> parseDataTypesYaml = FileHandling.parseDataTypesYaml(dataTypesLocation.getAbsoluteFile().toString());
-
-// toscaMainAmdocsDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + amdocsCsarFileName));
-// toscaMainVfDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + VfCsarFileName));
-// toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + serviceCsarFileName));
-// ToscaTopologyTemplateDefinition topologyTemplate = toscaMainAmdocsDefinition.getTopology_template();
-// ToscaDefinition objectHelper = ToscaParserUtils.parseToscaYamlToJavaObject(genericVfFileLocation);
-
- public ToscaValidationTest(String filepath, String vnfFile) {
- this.filepath = filepath;
- this.vnfFile = vnfFile;
- }
-
- public ToscaValidationTest() {
- }
-
-
-
-// @BeforeClass
- @Test()
- public void toscaFileValidator() throws Exception{
+ @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List")
+ public void toscaFileValidator(String filePath, String vnfFile) throws Exception, Throwable{
//--------------------------GENERAL--------------------------------
/*// for debugging only
setLog("Test");
@@ -104,40 +54,35 @@ public class ToscaValidationTest extends SetupCDTest{
toscaMainAmdocsDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(amdocsCsarFileName);
toscaMainVfDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File("C:\\Users\\al714h\\Downloads\\resource-Civfonboarded2016073VmxBv301072E2eE60f5c15-csar.csar"));
*/
+// vnfFile = "BE-HEAT.zip";
setLog(vnfFile);
List<Boolean> status = new ArrayList<>();
ISdcCsarHelper fdntCsarHelper;
File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
-// filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
-//--------------------------AMDOCS--------------------------------
-// vnfFile = "HeatCandidate_2017-09-22_01-32_60Name_Vdbe-vsp-15.1x49-d50.3-v1.0-(VOIP).zip";
+//--------------------------AMDOCS--------------------------------
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, user);//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- resourceReqDetails = createCustomizedVsp(resourceReqDetails, filepath, vnfFile);
-
+ resourceReqDetails = createCustomizedVsp(resourceReqDetails, filePath, vnfFile);
ToscaDefinition toscaMainAmdocsDefinition = downloadAndGetToscaMainYamlObjectUI(resourceReqDetails, filesFolder);
//------adding generic inputs to expected object
toscaMainAmdocsDefinition = addGenericPropertiesToToscaDefinitionObject(toscaMainAmdocsDefinition, GENERIC_VF);
// copy object
ToscaDefinition toscaExpectedMainServiceDefinition = new ToscaDefinition(toscaMainAmdocsDefinition);
+// create list of modules from HEAT.meta file
+ File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
+ List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(latestFilefromDir);
+//TODO VfModuleVerificator.verifyGroupMetadata();
//TODO--------------------------AMDOCS DOWNLOAD VIA APIS--------------------------------
-
//--------------------------VF--------------------------------
// create VF base on VNF imported from previous step - have, resourceReqDetails object include part of resource metadata
Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
ToscaDefinition toscaMainVfDefinition = downloadAndGetToscaMainYamlObjectApi(resource, filesFolder);
-
-//--------------------------SERVICE--------------------------------
+//--------------------------SERVICE--------------------------------
ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();//getServiceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
-// serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(serviceReqDetails, user);
Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
-
Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value();
-
//--------------------------getProperties set values and declare--------------------
-
Component componentObject = AtomicOperationUtils.getComponentObject(service, UserRoleEnum.DESIGNER);
Map<String, List<ComponentInstanceInput>> componentInstancesInputs = componentObject.getComponentInstancesInputs();
setValuesToPropertiesList(componentInstancesInputs, toscaExpectedMainServiceDefinition);
@@ -147,11 +92,70 @@ public class ToscaValidationTest extends SetupCDTest{
File ServiceCsarFileName = new File(File.separator + "ServiceCsar_" + ElementFactory.generateUUIDforSufix() + ".csar");
OnboardingUtillViaApis.downloadToscaCsarToDirectory(service, new File(filesFolder.getPath() + ServiceCsarFileName));
ToscaDefinition toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + ServiceCsarFileName));
+//--------------------------initialization of Tosca Parser--------------------------------
+ fdntCsarHelper = initSdcCsarHelper(ServiceCsarFileName, filesFolder);
+////---------------------------TESTS--------------------------------------------------
+ status = validateVfMetadata(toscaMainAmdocsDefinition, toscaMainVfDefinition, resourceReqDetails, resource, vnfFile, status);
+ status = validateResourceNodeTemplateMetadata(toscaMainVfDefinition, resource, vnfFile, status);
+ status = validateServiceMetadata(toscaMainServiceDefinition, serviceReqDetails, service, vnfFile, status);
+ status = validateServiceNodeTemplateMetadata(toscaMainServiceDefinition, componentInstanceDefinition, resourceReqDetails, resource, vnfFile, status);
+ status = validateServiceMetadataUsingParser(fdntCsarHelper, serviceReqDetails, service, vnfFile, status);
+ status = validateServiceNodeTemplateMetadataUsingParser(fdntCsarHelper, resourceReqDetails, resource, componentInstanceDefinition, vnfFile, status);
+ status = validateResourceInputs(toscaMainAmdocsDefinition, toscaMainVfDefinition, vnfFile, status);
+ status = validateServiceInputs(toscaExpectedMainServiceDefinition, toscaMainServiceDefinition, vnfFile, status);
+ status = validateServiceInputsUsingParser(fdntCsarHelper, toscaExpectedMainServiceDefinition, vnfFile, status);
+ Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject = createExpectedToscaServiceGroupsDefinitionObject(resource, service, listTypeHeatMetaDefinition);
+ status = validateServiceModuleMetadata(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition, vnfFile, status);
+ status = validateServiceModuleProperty(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition, vnfFile, status);
+ status = validateServiceModuleMetadataUsingParser(fdntCsarHelper, expectedToscaServiceGroupsDefinitionObject, vnfFile, status);
+ status = validateServiceModulePropertyUsingParser(fdntCsarHelper, expectedToscaServiceGroupsDefinitionObject, vnfFile, status);
+ if(status.contains(false)){
+ SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: tosca validation test failed with zip file " + vnfFile);
+ Assert.assertFalse(true);
+ }
+ }
+ @Test()
+ public void NetworkModel() throws Exception{
+//--------------------------GENERAL--------------------------------
+ String vnfFile = "networkModel";
+ setLog(vnfFile);
+ List<Boolean> status = new ArrayList<>();
+ ISdcCsarHelper fdntCsarHelper;
+ ToscaDefinition toscaMainAmdocsDefinition = new ToscaDefinition();
+ File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
+// filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
+
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.PNF, user);
+ toscaMainAmdocsDefinition = addGenericPropertiesToToscaDefinitionObject(toscaMainAmdocsDefinition, GENERIC_PNF);
+ ToscaDefinition toscaExpectedMainServiceDefinition = new ToscaDefinition(toscaMainAmdocsDefinition);
+//--------------------------VF--------------------------------
+ Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails,UserRoleEnum.DESIGNER,true).left().value();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ ToscaDefinition toscaMainVfDefinition = downloadAndGetToscaMainYamlObjectApi(resource, filesFolder);
+
+//--------------------------SERVICE--------------------------------
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
+ ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value();
+
+//--------------------------getProperties set values and declare--------------------
+
+ Component componentObject = AtomicOperationUtils.getComponentObject(service, UserRoleEnum.DESIGNER);
+ Map<String, List<ComponentInstanceInput>> componentInstancesInputs = componentObject.getComponentInstancesInputs();
+ setValuesToPropertiesList(componentInstancesInputs, toscaExpectedMainServiceDefinition);
+ PropertyRestUtils.declareProporties(componentObject, componentInstancesInputs, user);
+
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ File ServiceCsarFileName = new File(File.separator + "ServiceCsar_" + ElementFactory.generateUUIDforSufix() + ".csar");
+ OnboardingUtillViaApis.downloadToscaCsarToDirectory(service, new File(filesFolder.getPath() + ServiceCsarFileName));
+ ToscaDefinition toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + ServiceCsarFileName));
-
//--------------------------initialization of Tosca Parser--------------------------------
fdntCsarHelper = initSdcCsarHelper(ServiceCsarFileName, filesFolder);
@@ -167,20 +171,14 @@ public class ToscaValidationTest extends SetupCDTest{
status = validateResourceInputs(toscaMainAmdocsDefinition, toscaMainVfDefinition, vnfFile, status);
status = validateServiceInputs(toscaExpectedMainServiceDefinition, toscaMainServiceDefinition, vnfFile, status);
status = validateServiceInputsUsingParser(fdntCsarHelper, toscaExpectedMainServiceDefinition, vnfFile, status);
-
+
if(status.contains(false)){
SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: tosca validation test failed with zip file " + vnfFile);
Assert.assertFalse(true);
}
}
-
-
-
-
-
-
- /**The method set values to toscaDefinition object service level only, to resource level should put instead of setDefault --> setValue
+ /**The method set values to toscaDefinition object service level only, to resource level should put instead of setDefault --> setValue
* inputs.get(componentInstanceInput.getName()).setValue(randomString);
* @param componentInstancesInputs
* @param toscaDefinition
@@ -225,7 +223,17 @@ public class ToscaValidationTest extends SetupCDTest{
componentInstanceInput.setValue(myListofStrings);
inputs.get(componentInstanceInput.getName()).setDefault(myListofStrings);
}
-
+ else if (type.equals("json") ){
+ String myJson = "{\"firstParam\":\"my First Param Value\",\"secondParam\":\"my Second Param Value\",\"numberParam\":666}";
+ componentInstanceInput.setValue(myJson);
+ inputs.get(componentInstanceInput.getName()).setDefault(myJson);
+ }
+ else if (type.equals("comma_delimited_list") ){
+ String commaDelimitedList = "[\"one\", \"two\"]";
+ componentInstanceInput.setValue(commaDelimitedList);
+ inputs.get(componentInstanceInput.getName()).setDefault(commaDelimitedList);
+ }
+
String expectedServiceInputName = expectedServiceInputPrefix + componentInstanceInput.getName();
ToscaInputsTopologyTemplateDefinition oldInput = inputs.get(componentInstanceInput.getName());
inputs.put(expectedServiceInputName, oldInput);
@@ -258,7 +266,6 @@ public class ToscaValidationTest extends SetupCDTest{
}
-
//--------------------------Metadata verification--------------------------------
//--------------------------Resource--------------------------------
@@ -331,8 +338,6 @@ public class ToscaValidationTest extends SetupCDTest{
return status;
}
-
-
//--------------------------Input verification--------------------------------
//--------------------------Resource--------------------------------
@@ -357,11 +362,29 @@ public class ToscaValidationTest extends SetupCDTest{
status.add(false);
return status;
}
-
+
+ public List<Boolean> validateServiceModuleMetadata(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, ToscaDefinition toscaMainServiceDefinition, String vnfFile, List<Boolean> status) {
+ reportStartTestPrint("validateServiceModuleMetadata", vnfFile);
+
+ Either<Boolean,Map<String, Object>> toscaServiceModuleMetadataValidator = ToscaValidation.serviceToscaGroupMetadataValidator(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition);
+ if(toscaServiceModuleMetadataValidator.isRight())
+ status.add(false);
+ return status;
+ }
+
+ public List<Boolean> validateServiceModuleProperty(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, ToscaDefinition toscaMainServiceDefinition, String vnfFile, List<Boolean> status) {
+ reportStartTestPrint("validateServiceModuleProperty", vnfFile);
+
+ Either<Boolean,Map<String, Object>> toscaServiceModulePropertyValidator = ToscaValidation.serviceToscaGroupPropertyValidator(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition);
+ if(toscaServiceModulePropertyValidator.isRight())
+ status.add(false);
+ return status;
+ }
+
//--------------------------Service verification against Pavel Parser--------------------------------
public List<Boolean> validateServiceInputsUsingParser(ISdcCsarHelper fdntCsarHelper, ToscaDefinition toscaExpectedMainServiceDefinition, String vnfFile, List<Boolean> status) throws Exception{
if(fdntCsarHelper == null){
- reportSkipTestPrint("validateServiceInputsUsingParser", status);
+ reportSkipTestPrint("validateServiceInputsUsingParser", status);
}else{
reportStartTestPrint("validateServiceInputsUsingParser", vnfFile);
Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputsMap = toscaExpectedMainServiceDefinition.getTopology_template().getInputs();
@@ -371,24 +394,143 @@ public class ToscaValidationTest extends SetupCDTest{
}
return status;
}
-
- //--------------------------XXX verification--------------------------------
-
- //--------------------------Resource--------------------------------
-
-
- //--------------------------Service--------------------------------
-
-
- //--------------------------Service verification against Pavel Parser--------------------------------
-
-
-
-
-
-
-
-
+
+ public List<Boolean> validateServiceModuleMetadataUsingParser(ISdcCsarHelper fdntCsarHelper, Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, String vnfFile, List<Boolean> status) {
+ reportStartTestPrint("validateServiceModuleMetadataUsingParser", vnfFile);
+ String customizationUUID = fdntCsarHelper.getServiceNodeTemplates().get(0).getMetaData().getValue("customizationUUID");
+ List<Group> actualGroups = fdntCsarHelper.getVfModulesByVf(customizationUUID);
+ Either<Boolean,Map<String, Object>> toscaServiceModuleMetadataValidator = ToscaValidation.serviceToscaGroupMetadataValidatorUsingParser(expectedToscaServiceGroupsDefinitionObject, actualGroups);
+ if(toscaServiceModuleMetadataValidator.isRight())
+ status.add(false);
+ return status;
+ }
+
+ public List<Boolean> validateServiceModulePropertyUsingParser(ISdcCsarHelper fdntCsarHelper, Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, String vnfFile, List<Boolean> status) {
+ reportStartTestPrint("validateServiceModuleMetadataUsingParser", vnfFile);
+ String customizationUUID = fdntCsarHelper.getServiceNodeTemplates().get(0).getMetaData().getValue("customizationUUID");
+ List<Group> actualGroups = fdntCsarHelper.getVfModulesByVf(customizationUUID);
+ Either<Boolean,Map<String, Object>> toscaServiceModuleMetadataValidator = ToscaValidation.serviceToscaGroupPropertyValidatorUsingParser(expectedToscaServiceGroupsDefinitionObject, actualGroups);
+ if(toscaServiceModuleMetadataValidator.isRight())
+ status.add(false);
+ return status;
+ }
+
+ private Map<String, ToscaGroupsTopologyTemplateDefinition> createExpectedToscaServiceGroupsDefinitionObject(Resource resource, Service service, List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition) {
+ Map<String, ToscaGroupsTopologyTemplateDefinition> toscaGroupsTopologyTemplateDefinitionMap = new HashMap<>();
+
+ for (TypeHeatMetaDefinition moduleType : listTypeHeatMetaDefinition) {
+ if (!moduleType.getTypeName().equals("artifacts")) {
+ for(GroupHeatMetaDefinition module : moduleType.getGroupHeatMetaDefinition()){
+ ToscaGroupsTopologyTemplateDefinition toscaGroupsTopologyTemplateDefinition = new ToscaGroupsTopologyTemplateDefinition();
+ String resourceModuleName = buildResourceModuleName(resource, module.getGroupName());
+ ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = setGroupMetadataFromResourceObject(resourceModuleName, resource);
+ if(!toscaServiceGroupsMetadataDefinition.equals("")){
+ String serviceModuleName = buildServiceModuleName(service.getComponentInstances().get(0).getNormalizedName(), toscaServiceGroupsMetadataDefinition.getVfModuleModelName());
+ toscaServiceGroupsMetadataDefinition = setGroupMetadataFromServiceObject(toscaServiceGroupsMetadataDefinition, serviceModuleName, service);
+ toscaGroupsTopologyTemplateDefinition.setMetadata(toscaServiceGroupsMetadataDefinition);
+ ToscaGroupPropertyDefinition toscaGroupPropertyDefinition = setGroupProperty(module);
+ toscaGroupsTopologyTemplateDefinition.setProperties(toscaGroupPropertyDefinition);
+ toscaGroupsTopologyTemplateDefinitionMap.put(serviceModuleName,toscaGroupsTopologyTemplateDefinition);
+
+ }else{
+ getExtendTest().log(Status.FAIL, "module name [" + module.getGroupName() + "] didn't represent in resource");
+ }
+ }
+ }
+ }
+ return toscaGroupsTopologyTemplateDefinitionMap;
+
+ }
+
+ private ToscaGroupPropertyDefinition setGroupProperty(GroupHeatMetaDefinition module) {
+ ToscaGroupPropertyDefinition toscaGroupPropertyDefinition = new ToscaGroupPropertyDefinition();
+ toscaGroupPropertyDefinition.setVf_module_label(module.getGroupName());
+ Boolean isBase = module.getPropertyHeatMetaDefinition().getValue();
+ if(isBase){
+ toscaGroupPropertyDefinition.setInitial_count("1");
+ toscaGroupPropertyDefinition.setMin_vf_module_instances("1");
+ toscaGroupPropertyDefinition.setMax_vf_module_instances("1");
+ toscaGroupPropertyDefinition.setVf_module_type("Base");
+ }else{
+ toscaGroupPropertyDefinition.setInitial_count("0");
+ toscaGroupPropertyDefinition.setMin_vf_module_instances("0");
+ toscaGroupPropertyDefinition.setMax_vf_module_instances(null);
+ toscaGroupPropertyDefinition.setVf_module_type("Expansion");
+ }
+ toscaGroupPropertyDefinition.setAvailability_zone_count(null);
+ toscaGroupPropertyDefinition.setVfc_list(null);
+ toscaGroupPropertyDefinition.setVf_module_description(null);
+ toscaGroupPropertyDefinition.setVolume_group(isVolumeGroup(module));
+
+ return toscaGroupPropertyDefinition;
+ }
+
+ private String isVolumeGroup(GroupHeatMetaDefinition module) {
+ String isVolumeGroup = "false";
+ for( HeatMetaFirstLevelDefinition artifactList : module.getArtifactList()){
+ if(artifactList.getType().equals(ArtifactTypeEnum.HEAT_VOL.getType())){
+ isVolumeGroup = "true";
+ return isVolumeGroup;
+ }
+ }
+ return isVolumeGroup;
+ }
+
+ private Map<String,ToscaServiceGroupsMetadataDefinition> createExpectedToscaServiceGroupsPropertyDefinitionObject(Resource resource, Service service, List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition) {
+
+ Map<String,ToscaServiceGroupsMetadataDefinition> toscaServiceGroupsMetadataDefinitionMap = new HashMap<>();
+ for (TypeHeatMetaDefinition moduleType : listTypeHeatMetaDefinition) {
+ Map<String, String> groupProperty = new HashMap<>();
+
+ ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = new ToscaServiceGroupsMetadataDefinition();
+ for(GroupHeatMetaDefinition module : moduleType.getGroupHeatMetaDefinition()){
+ String resourceModuleName = buildResourceModuleName(resource, module.getGroupName());
+ toscaServiceGroupsMetadataDefinition = setGroupMetadataFromResourceObject(resourceModuleName, resource);
+ if(!toscaServiceGroupsMetadataDefinition.equals("")){
+ String serviceModuleName = buildServiceModuleName(service.getComponentInstances().get(0).getNormalizedName(), toscaServiceGroupsMetadataDefinition.getVfModuleModelName());
+ toscaServiceGroupsMetadataDefinition = setGroupMetadataFromServiceObject(toscaServiceGroupsMetadataDefinition, serviceModuleName, service);
+ toscaServiceGroupsMetadataDefinitionMap.put(serviceModuleName, toscaServiceGroupsMetadataDefinition);
+ }else{
+ getExtendTest().log(Status.FAIL, "module name [" + module.getGroupName() + "] didn't represent in resource");
+ }
+ }
+ }
+ return toscaServiceGroupsMetadataDefinitionMap;
+
+ }
+
+ private ToscaServiceGroupsMetadataDefinition setGroupMetadataFromServiceObject(ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition, String serviceModuleName, Service service) {
+ for (GroupInstance groupInstance : service.getComponentInstances().get(0).getGroupInstances()) {
+ if (groupInstance.getName().equals(serviceModuleName)) {
+ toscaServiceGroupsMetadataDefinition.setVfModuleModelCustomizationUUID(groupInstance.getCustomizationUUID());
+ return toscaServiceGroupsMetadataDefinition;
+ }
+ }
+ return toscaServiceGroupsMetadataDefinition;
+ }
+
+ private ToscaServiceGroupsMetadataDefinition setGroupMetadataFromResourceObject(String resourceModuleName, Resource resource) {
+ ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = new ToscaServiceGroupsMetadataDefinition();
+ for (GroupDefinition group : resource.getGroups()) {
+ if (group.getName().contains(resourceModuleName)) {
+ toscaServiceGroupsMetadataDefinition.setVfModuleModelName(group.getName());
+ toscaServiceGroupsMetadataDefinition.setVfModuleModelInvariantUUID(group.getInvariantUUID());
+ toscaServiceGroupsMetadataDefinition.setVfModuleModelUUID(group.getGroupUUID());
+ toscaServiceGroupsMetadataDefinition.setVfModuleModelVersion(group.getVersion());
+ return toscaServiceGroupsMetadataDefinition;
+ }
+ }
+ return toscaServiceGroupsMetadataDefinition;
+ }
+
+ public static String buildResourceModuleName(Resource resource, String groupName ){
+ return resource.getSystemName()+".."+groupName+".."+"module-";
+ }
+ public static String buildServiceModuleName(String resourceInstanceNormalizedName, String resourceGroupName ){
+ return resourceInstanceNormalizedName+".."+resourceGroupName;
+ }
+
+
@Override
protected UserRoleEnum getRole() {
return UserRoleEnum.DESIGNER;
@@ -427,8 +569,6 @@ public class ToscaValidationTest extends SetupCDTest{
return toscaDefinition;
}
-
-
public static ToscaDefinition addAndGenerateResourceMetadataToExpectedObject(ToscaDefinition toscaDefinition, ResourceReqDetails resourceReqDetails, Component component) {
Map<String, String> metadata = convertResourceMetadataToMap(resourceReqDetails, component);
@@ -436,7 +576,6 @@ public class ToscaValidationTest extends SetupCDTest{
return toscaDefinition;
}
-
public static Map<String, String> convertResourceMetadataToMap(ResourceReqDetails resourceReqDetails, Component component) {
Map<String, String> metadata = new HashMap<>();
@@ -474,8 +613,8 @@ public class ToscaValidationTest extends SetupCDTest{
metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.VERSION.value, componentInstance.getComponentVersion());
return metadata;
-
}
+
public static Map<String, String> generateServiceNodeTemplateMetadataToExpectedObject(ResourceReqDetails resourceReqDetails, Component component, ComponentInstance componentInstanceDefinition) {
Map<String, String> metadata = convertResourceMetadataToMap(resourceReqDetails, component);
@@ -580,71 +719,11 @@ public class ToscaValidationTest extends SetupCDTest{
SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: allottedResourceModelTest tosca validation test failed with zip file " + vnfFile);
Assert.assertFalse(true);
}
- }
-
-
-
- @Test()
- public void NetworkModel() throws Exception{
-//--------------------------GENERAL--------------------------------
- String vnfFile = "networkModel";
- setLog(vnfFile);
- List<Boolean> status = new ArrayList<>();
- ISdcCsarHelper fdntCsarHelper;
- ToscaDefinition toscaMainAmdocsDefinition = new ToscaDefinition();
- File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
-// filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory());
-
- ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.PNF, user);
- toscaMainAmdocsDefinition = addGenericPropertiesToToscaDefinitionObject(toscaMainAmdocsDefinition, GENERIC_PNF);
- ToscaDefinition toscaExpectedMainServiceDefinition = new ToscaDefinition(toscaMainAmdocsDefinition);
-//--------------------------VF--------------------------------
- Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails,UserRoleEnum.DESIGNER,true).left().value();
- resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
-
- ToscaDefinition toscaMainVfDefinition = downloadAndGetToscaMainYamlObjectApi(resource, filesFolder);
-
-//--------------------------SERVICE--------------------------------
- ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
- Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
-
- Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
- ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value();
-
-//--------------------------getProperties set values and declare--------------------
-
- Component componentObject = AtomicOperationUtils.getComponentObject(service, UserRoleEnum.DESIGNER);
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = componentObject.getComponentInstancesInputs();
- setValuesToPropertiesList(componentInstancesInputs, toscaExpectedMainServiceDefinition);
- PropertyRestUtils.declareProporties(componentObject, componentInstancesInputs, user);
-
- service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
- File ServiceCsarFileName = new File(File.separator + "ServiceCsar_" + ElementFactory.generateUUIDforSufix() + ".csar");
- OnboardingUtillViaApis.downloadToscaCsarToDirectory(service, new File(filesFolder.getPath() + ServiceCsarFileName));
- ToscaDefinition toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + ServiceCsarFileName));
+ }*/
-//--------------------------initialization of Tosca Parser--------------------------------
- fdntCsarHelper = initSdcCsarHelper(ServiceCsarFileName, filesFolder);
-//---------------------------TESTS--------------------------------------------------
- status = validateVfMetadata(toscaMainAmdocsDefinition, toscaMainVfDefinition, resourceReqDetails, resource, vnfFile, status);
- status = validateResourceNodeTemplateMetadata(toscaMainVfDefinition, resource, vnfFile, status);
- status = validateServiceMetadata(toscaMainServiceDefinition, serviceReqDetails, service, vnfFile, status);
- status = validateServiceNodeTemplateMetadata(toscaMainServiceDefinition, componentInstanceDefinition, resourceReqDetails, resource, vnfFile, status);
- status = validateServiceMetadataUsingParser(fdntCsarHelper, serviceReqDetails, service, vnfFile, status);
- status = validateServiceNodeTemplateMetadataUsingParser(fdntCsarHelper, resourceReqDetails, resource, componentInstanceDefinition, vnfFile, status);
- status = validateResourceInputs(toscaMainAmdocsDefinition, toscaMainVfDefinition, vnfFile, status);
- status = validateServiceInputs(toscaExpectedMainServiceDefinition, toscaMainServiceDefinition, vnfFile, status);
- status = validateServiceInputsUsingParser(fdntCsarHelper, toscaExpectedMainServiceDefinition, vnfFile, status);
-
- if(status.contains(false)){
- SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: tosca validation test failed with zip file " + vnfFile);
- Assert.assertFalse(true);
- }
- }*/
-
// help method to toscaValidation tests
private ISdcCsarHelper initSdcCsarHelper(File serviceCsarFileName, File filesFolder) {
@@ -704,11 +783,6 @@ public class ToscaValidationTest extends SetupCDTest{
return ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + VfCsarFileName));
}
- /*public static void main(String[] args) {
- ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
- List<CategoryDefinition> categories = resourceReqDetails.getCategories();
- System.out.println(categories);
- }*/
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java
index b79393a0c9..20cd8886fd 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java
@@ -20,18 +20,13 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.Assert.assertTrue;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject;
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;
@@ -43,20 +38,21 @@ 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.OnboardingUiUtils;
-import org.openecomp.sdc.ci.tests.utilities.ResourceUIUtils;
-import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
+import org.openecomp.sdc.ci.tests.utilities.*;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
import org.openecomp.sdc.ci.tests.verificator.VFCArtifactVerificator;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.testng.Assert.assertTrue;
+import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorSoftwareProductRestUtils;
public class VFCArtifacts extends SetupCDTest {
@@ -215,17 +211,17 @@ public class VFCArtifacts extends SetupCDTest {
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- String vnfFile = "vProbes_FE.zip";
+ String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip";
String snmpFile = "Fault-alarms-ASDC-vprobes-vLB.zip";
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
- Pair<String, Map<String, String>> createVSP = OnboardingUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), amdocsLicenseMembers);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
+ Pair<String, VendorSoftwareProductObject> createVSP = VendorSoftwareProductRestUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), amdocsLicenseMembers);
String vspName = createVSP.left;
resourceMetaData.setName(vspName);
- Map<String, String> resourceMeta = createVSP.right;
- String vspid = resourceMeta.get("vspId");
- OnboardingUtils.addVFCArtifacts(filePath, snmpFile, null, vspid, getUser());
- OnboardingUtils.prepareVspForUse(getUser(), vspid, "0.1");
+ VendorSoftwareProductObject resourceMeta = createVSP.right;
+ String vspid = resourceMeta.getVspId();
+ VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpFile, null, resourceMeta, getUser());
+ VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), resourceMeta, true);
String downloadDirectory = getWindowTest().getDownloadDirectory();
String csarFile = vspid + ".csar";
@@ -248,18 +244,18 @@ public class VFCArtifacts extends SetupCDTest {
//check of version is 1
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- String vnfFile = "vProbes_FE.zip";
+ String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip";
String snmpPollFile = "vprobes-vLB.zip";
String updatedSnmpPollFile = "vprobes-vLBAgent.zip";
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
- Pair<String, Map<String, String>> createVSP = OnboardingUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), amdocsLicenseMembers);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
+ Pair<String, VendorSoftwareProductObject> createVSP = VendorSoftwareProductRestUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), amdocsLicenseMembers);
String vspName = createVSP.left;
resourceMetaData.setName(vspName);
- Map<String, String> resourceMeta = createVSP.right;
- String vspid = resourceMeta.get("vspId");
- String montoringComponentId = OnboardingUtils.addVFCArtifacts(filePath, snmpPollFile, null, vspid, getUser());
- OnboardingUiUtils.prepareVspForUse(getUser(), vspid, "0.1");
+ VendorSoftwareProductObject resourceMeta = createVSP.right;
+ String vspid = resourceMeta.getVspId();
+ String montoringComponentId = VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpPollFile, null, resourceMeta, getUser());
+ VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), resourceMeta, true);
String downloadDirectory = getWindowTest().getDownloadDirectory();
String csarFile = vspid + ".csar";
@@ -275,7 +271,7 @@ public class VFCArtifacts extends SetupCDTest {
TesterOperationPage.certifyComponent(vspName);
reloginWithNewRole(UserRoleEnum.DESIGNER);
- OnboardingUtils.updateVspWithVfcArtifacts(filePath, vspid, updatedSnmpPollFile, null, montoringComponentId, getUser(), "0.1");
+ VendorSoftwareProductRestUtils.updateVspWithVfcArtifacts(filePath, updatedSnmpPollFile, null, montoringComponentId, getUser(), resourceMeta);
DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid);
HomePage.showVspRepository();
OnboardingUiUtils.updateVSP(createVSP);
@@ -294,18 +290,18 @@ public class VFCArtifacts extends SetupCDTest {
//check of version is 2
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
- String vnfFile = "vProbes_FE.zip";
+ String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip";
String snmpFile = "vprobes-vLB.zip";
String updatedSnmpFile = "vprobes-vLB-Modified.zip";
- AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUiUtils.createVendorLicense(getUser());
- Pair<String, Map<String, String>> createVSP = OnboardingUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), amdocsLicenseMembers);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(getUser());
+ Pair<String, VendorSoftwareProductObject> createVSP = VendorSoftwareProductRestUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), amdocsLicenseMembers);
String vspName = createVSP.left;
resourceMetaData.setName(vspName);
- Map<String, String> resourceMeta = createVSP.right;
- String vspid = resourceMeta.get("vspId");
- String monitoringId = OnboardingUtils.addVFCArtifacts(filePath, snmpFile, null, vspid, getUser());
- OnboardingUiUtils.prepareVspForUse(getUser(), vspid, "0.1");
+ VendorSoftwareProductObject resourceMeta = createVSP.right;
+ String vspid = resourceMeta.getVspId();
+ String monitoringId = VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpFile, null, resourceMeta, getUser());
+ VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), resourceMeta, true);
String downloadDirectory = getWindowTest().getDownloadDirectory();
String csarFile = vspid + ".csar";
@@ -328,7 +324,7 @@ public class VFCArtifacts extends SetupCDTest {
TesterOperationPage.certifyComponent(vspName);
reloginWithNewRole(UserRoleEnum.DESIGNER);
- OnboardingUtils.updateVspWithVfcArtifacts(filePath, vspid, updatedSnmpFile, null, monitoringId, getUser(), "0.1");
+ VendorSoftwareProductRestUtils.updateVspWithVfcArtifacts(filePath, updatedSnmpFile, null, monitoringId, getUser(), resourceMeta);
DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid);
HomePage.showVspRepository();
OnboardingUiUtils.updateVSP(createVSP);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
index fe2187f338..dbe0a971c6 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
@@ -32,16 +32,11 @@ 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.*;
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;
@@ -60,13 +55,8 @@ 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.*;
import org.openecomp.sdc.ci.tests.utilities.OnboardingUiUtils;
-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.ToscaParserUtils;
import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
@@ -79,6 +69,7 @@ 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;
@@ -225,6 +216,10 @@ public class Vf extends SetupCDTest {
@Test
public void addPropertiesToVfcInstanceInVfTest() throws Exception {
+ if(true){
+ throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen");
+ }
+
String fileName = "vFW_VFC.yml";
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
@@ -648,7 +643,7 @@ public class Vf extends SetupCDTest {
public void exportToscaWithModulePropertiesVFTest() throws AWTException, Exception {
String vnfFile = "1-Vf-zrdm5bpxmc02-092017-(MOBILITY)_v2.0.zip";
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
String vspName = vsp.left;
ResourceGeneralPage.clickSubmitForTestingButton(vsp.left);
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1");
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfAPI.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfAPI.java
new file mode 100644
index 0000000000..e0eaf74de6
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfAPI.java
@@ -0,0 +1,738 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 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.*;
+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.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.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.*;
+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.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.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 VfAPI extends SetupCDTest {
+
+ private String filePath;
+ @BeforeClass
+ public void beforeClass(){
+ filePath = FileHandling.getFilePath("");
+ }
+
+ @BeforeMethod
+ public void beforeTest(){
+ System.out.println("File repository is : " + filePath);
+ getExtendTest().log(Status.INFO, "File repository is : " + filePath);
+ }
+
+ private ResourceReqDetails createVFviaAPI() {
+ ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating VF %s", vfMetaData.getName()));
+ AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value();
+ return vfMetaData;
+ }
+
+
+ @Test
+ public void updateVF() throws Exception {
+
+ // create Resource
+ ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+ ResourceUIUtils.createVF(resourceMetaData, getUser());
+
+ // update Resource
+ ResourceReqDetails updatedResource = new ResourceReqDetails();
+ updatedResource.setName(ElementFactory.getResourcePrefix() + "UpdatedName" + resourceMetaData.getName());
+ 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<String> 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 vfcLinkedToComputeInVfFlowApi() throws Exception {
+ String fileName = "vFW_VFC2.yml";
+ ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
+
+ try{
+ //Create VFC via API
+ Resource vfc = AtomicOperationUtils.importResource(filePath, fileName).left().value();
+ atomicResourceMetaData.setName(vfc.getName());
+
+ //Certify VFC via API
+ vfc = (Resource) AtomicOperationUtils.changeComponentState(vfc, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ //Create VF via API
+ ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+ AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ //Composition - drag the created VFC and another element, link between them
+ 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 addUpdateDeleteDeploymentArtifactToVfTestApi() throws Exception {
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
+
+ List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>();
+ deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"));
+ deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML"));
+ 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 addUpdateDeleteInformationalArtifactApi() throws Exception {
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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 addPropertiesToVfcInstanceInVfTestApi() throws Exception {
+
+ String fileName = "vFW_VFC.yml";
+ ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
+
+ try{
+ //Create VFC via API
+ Resource vfc = AtomicOperationUtils.importResource(filePath, fileName).left().value();
+ atomicResourceMetaData.setName(vfc.getName());
+
+ //Certify VFC via API
+ vfc = (Resource) AtomicOperationUtils.changeComponentState(vfc, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager vfCanvasManager = CanvasManager.getCanvasManager();
+ CompositionPage.searchForElement(atomicResourceMetaData.getName());
+ CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName());
+
+ vfCanvasManager.clickOnCanvaElement(vfcElement);
+ CompositionPage.showPropertiesAndAttributesTab();
+ List<WebElement> 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{
+
+ 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.createVF(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");
+
+ //verification
+ 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.createVF(vfMetaData, getUser());
+
+ ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen();
+ List<PropertyTypeEnum> 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.createVF(vfMetaData, getUser());
+
+ ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager vfCanvasManager = CanvasManager.getCanvasManager();
+
+ Map<String, String> elementsIntancesMap = new HashMap<String, String>();
+ 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<String, String> propertiesNameTypeJson = ResponseParser.getPropertiesNameType(restResponse);
+
+ List<WebElement> 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 addAllInformationalArtifactPlaceholdersInVfTestApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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 verifyToscaArtifactsExistApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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 vfCertificationTestApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+ Resource vf = AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value();
+
+ //Certify VF via API
+ vf = (Resource) AtomicOperationUtils.changeComponentState(vf, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED);
+ }
+
+ @Test
+ public void deleteVfCheckedoutTestApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ GeneralPageElements.clickTrashButtonAndConfirm();
+
+ vfMetaData.setVersion("0.1");
+ VfVerificator.verifyVfDeleted(vfMetaData, getUser());
+ }
+
+ @Test
+ public void revertVfMetadataTestApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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 addDeploymentArtifactInCompositionScreenTestApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3","OTHER");
+ CompositionPage.showDeploymentArtifactTab();
+ CompositionPage.clickAddArtifactButton();
+ ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup());
+
+ List<WebElement> 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.createVF(vfMetaData, getUser());
+
+ ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
+
+ CompositionPage.showPropertiesAndAttributesTab();
+ List<PropertyTypeEnum> 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 addDeploymentArtifactAndVerifyInCompositionScreenApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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<WebElement> 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.createVF(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 deleteInstanceFromVfCanvasApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager vfCanvasManager = CanvasManager.getCanvasManager();
+ CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.COMPUTE);
+ vfCanvasManager.createElementOnCanvas(LeftPanelCanvasItems.PORT);
+
+ vfCanvasManager.clickOnCanvaElement(computeElement);
+ vfCanvasManager.deleteElementFromCanvas(computeElement);
+
+ VfVerificator.verifyNumOfComponentInstances(vfMetaData, 1, getUser());
+ }
+
+ @Test
+ public void changeInstanceNameInVfTestApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = createVFviaAPI();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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 submitVfForTestingWithNonCertifiedAssetApi() throws Exception{
+ String fileName = "vFW_VFC4.yml";
+ ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
+
+ //Create VFC via API
+ Resource vfc = AtomicOperationUtils.importResource(filePath, fileName).left().value();
+ atomicResourceMetaData.setName(vfc.getName());
+
+ //Submit VFC for testing via API
+ vfc = (Resource) AtomicOperationUtils.changeComponentState(vfc, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft();
+
+ //Create VF via API
+ ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+ AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(vfMetaData.getName());
+
+ 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 isDisabledAndReadOnlyInCheckinApi() throws Exception{
+ //Create VF via API
+ ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
+ Resource vf = AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value();
+
+ //Check in VF via API
+ vf = (Resource) AtomicOperationUtils.changeComponentState(vf, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ //Go to Catalog and find the created VF
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ 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 = "1-Vf-zrdm5bpxmc02-092017-(MOBILITY)_v2.0.zip";
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
+ Pair<String, VendorSoftwareProductObject> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), 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 = "1-Vf-zrdm5bpxmc02-092017-(MOBILITY)_v2.0.zip";
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
+ OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
+ ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen();
+ GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue());
+ File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
+ ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(latestFilefromDir);
+ 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
index 8055a86d58..9847d341c0 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java
@@ -20,16 +20,8 @@
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 com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Resource;
@@ -40,6 +32,7 @@ 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.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject;
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;
@@ -47,11 +40,7 @@ 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.OnboardingUiUtils;
+import org.openecomp.sdc.ci.tests.utilities.*;
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;
@@ -61,8 +50,15 @@ 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;
+import java.awt.*;
+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 static org.testng.AssertJUnit.assertTrue;
public class VfArtifacts extends SetupCDTest{
@@ -115,10 +111,10 @@ public class VfArtifacts extends SetupCDTest{
@Test
public void uploadUpdatedHeatEnv() throws Exception{
- String vnfFile = VMSP_PXMC_30_1607_E2E_ZIP;
+ String vnfFile = VFW_FNAT_30_1607_E2E_ZIP;
File updateEnvFile = null;
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = vsp.left;
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1");
Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
@@ -143,7 +139,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = VFW_FNAT_30_1607_E2E_ZIP;
File updateEnvFile = null;
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = vsp.left;
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1");
Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
@@ -167,7 +163,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = VLANDSLIDE_LDST_30_1607_E2E_ZIP;
File updateEnvFile = null;
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = vsp.left;
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1");
Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
@@ -196,7 +192,7 @@ public class VfArtifacts extends SetupCDTest{
String updatedVnfFile= VLANDSLIDE_LDSA_30_1607_E2E_ZIP;
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> CreatedVsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> CreatedVsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = CreatedVsp.left;
GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
OnboardingUiUtils.updateVnfAndValidate(vnfsRepositoryPath, CreatedVsp, updatedVnfFile, getUser());
@@ -222,7 +218,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = VSAEGW_FDNT_30_1607_E2E_ZIP;
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String,VendorSoftwareProductObject> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
Map<String, File> currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.left,downloadDirPath);
GeneralUIUtils.findComponentAndClick(vsp.left);
ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
@@ -246,7 +242,7 @@ public class VfArtifacts extends SetupCDTest{
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
String vnfFile = VSAEGW_FDNT_30_1607_E2E_ZIP;
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
Map<String, File> currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.left,downloadDirPath);
GeneralUIUtils.findComponentAndClick(vsp.left);
ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
@@ -271,7 +267,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = VFW_FCGI_30_1607_E2E_ZIP;
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String, Map<String, String>> CreatedVsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> CreatedVsp= OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, CreatedVsp.left, "0.1");
Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
List<HeatWithParametersDefinition> envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts);
@@ -315,7 +311,7 @@ public class VfArtifacts extends SetupCDTest{
public void checkDefaultCreatedEnvArtifacts() throws Exception{
String vnfFile = VIXIA_IXLA_30_1607_E2E_ZIP;
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = vsp.left;
Map<String, File> generatedEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath);
HomeUtils.findComponentAndClick(vspName);
@@ -337,7 +333,7 @@ public class VfArtifacts extends SetupCDTest{
String stringForLog = String.format("%s:%s:%s:%s", vnfFile, updatedVnfFile, expectedHeatVersion, expectedHeatEnvVersion);
setLog(stringForLog);
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = vsp.left;
GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
OnboardingUiUtils.updateVnfAndValidate(vnfsRepositoryPath, vsp, updatedVnfFile, getUser());
@@ -362,7 +358,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = VFW_FCGI_30_1607_E2E_ZIP;
String updatedVnfFile = VFW_FCGI_30_1607_E2E_ZIP;
ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT);
- Pair<String,Map<String,String>> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
+ Pair<String, VendorSoftwareProductObject> vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser());
String vspName = vsp.left;
GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click();
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java
index ef8a337394..bb4d754bbf 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java
@@ -43,6 +43,7 @@ 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;
@@ -234,6 +235,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1443736 - Update With One New Deployment Artifact
@Test
public void updateWithOneNewDeploymentArtifact() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String fileName = "ImportTC1443736.csar";
String folder ="US825779";
@@ -257,6 +263,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1443737 - Update With One Removed Deployment Artifact
@Test
public void updateWithOneRemovedDeploymentArtifact() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String fileName = "ImportTC1443737.csar";
String folder ="US825779";
@@ -284,6 +295,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1443738 - Update With One New Version Deployment Artifact
@Test
public void updateWithOneNewVersionDeploymentArtifact() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String fileName = "ImportTC1443738.csar";
String folder ="US825779";
@@ -309,6 +325,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1443887 - Update With One New Informational Artifact
@Test
public void updateWithOneNewInformationalArtifact() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String fileName = "ImportTC1443887.csar";
String folder ="US825779";
@@ -332,6 +353,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1443888 - Update With One Removed Informational Artifact
@Test
public void updateWithOneRemovedInformationalArtifact() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String folder ="US825779";
String fileName = "ImportTC1443888.csar";
@@ -361,6 +387,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1443890 - Update With One New Artifact Version Informational Artifact
@Test
public void updateWithOneNewArtifactVersionInformationalArtifact() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String folder ="US825779";
String fileName = "ImportTC1443890.csar";
@@ -385,7 +416,12 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// US825779 - Story: [BE] Import VSP - VF informational artifacts - Update
// TC1443893 - Update CSAR With Same Artifacts As Imported
@Test
- public void updateCSARWithSameArtifactsAsImported() throws Exception {
+ public void updateCSARWithSameArtifactsAsImported() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
+
String folder ="US825779";
String fileName = "ImportUpdateTC1443893.csar";
@@ -611,6 +647,10 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// TC1444530 - Update Deployment Artifact With Invalid Type
@Test
public void updateDeploymentArtifactWithInvalidType() throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 310971 and 369139");
+ }
String folder ="US825779";
String fileName = "ImportTC1444530.csar";
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java
index 6c76e327f0..0ba51de87a 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java
@@ -21,16 +21,6 @@
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;
@@ -40,6 +30,12 @@ import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.*;
+
public class DriverFactory {
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
index 09dcad7c36..0a66f5f610 100644
--- 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
@@ -20,8 +20,11 @@
package org.openecomp.sdc.ci.tests.execute.setup;
-import java.io.File;
-
+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;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
@@ -29,11 +32,12 @@ 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;
+import java.io.File;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
public class ExtentManager {
@@ -70,9 +74,8 @@ public class ExtentManager {
if (extent == null) {
extentxReporter = new ExtentXReporter(dbIp, dbPort);
- extent = new ExtentReports();
- initAndSetExtentHtmlReporter(filePath, htmlFile, isAppend);
-
+ extent = new ExtentReports();
+ initAndSetExtentHtmlReporter(filePath, htmlFile, isAppend);
if(extentxReporter.config().getReportObjectId() != null){
setExtentXReporter(isAppend);
}else{
@@ -88,7 +91,7 @@ public class ExtentManager {
}
public synchronized static void initAndSetExtentHtmlReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception{
- htmlReporter = new ExtentHtmlReporter(filePath + htmlFile);
+ htmlReporter = new ExtentHtmlReporter(filePath + htmlFile);
setConfiguration(htmlReporter);
htmlReporter.setAppendExisting(isAppend);
extent.attachReporter(htmlReporter);
@@ -105,11 +108,11 @@ public class ExtentManager {
Config config = Utils.getConfig();
String envData = config.getUrl();
String suiteName = getSuiteName(context);
-
+ String reportStartDate = null;
if(suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())){
- if (config.getUseBrowserMobProxy())
- setTrafficCaptue(config);
-
+ if (config.getUseBrowserMobProxy()) {
+ setTrafficCaptue(config);
+ }
setReporter(filepath, htmlFile, true);
String suiteNameFromVersionInfoFile = FileHandling.getKeyByValueFromPropertyFormatFile(filepath + VERSIONS_INFO_FILE_NAME, "suiteName");
reporterDataDefinition(onboardVersion, osVersion, envData, suiteNameFromVersionInfoFile);
@@ -117,8 +120,11 @@ public class ExtentManager {
FileHandling.deleteDirectory(SetupCDTest.getReportFolder());
FileHandling.createDirectory(filepath);
setReporter(filepath, htmlFile, false);
+ Calendar calendar = new GregorianCalendar();
+ SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
+ reportStartDate = formatter.format(calendar.getTime());
reporterDataDefinition(onboardVersion, osVersion, envData, suiteName);
- AutomationUtils.createVersionsInfoFile(filepath + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData, suiteName);
+ AutomationUtils.createVersionsInfoFile(filepath + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData, suiteName, reportStartDate);
}
}
@@ -152,6 +158,7 @@ public class ExtentManager {
htmlReporter.config().setReportName("SDC Automation Report");
htmlReporter.config().setChartVisibilityOnOpen(false);
htmlReporter.config().setJS(icon);
+ htmlReporter.setStartTime(null);
return htmlReporter;
}
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
index 6d9b367460..4d28e9a8b4 100644
--- 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
@@ -20,12 +20,11 @@
package org.openecomp.sdc.ci.tests.execute.setup;
-import java.util.HashMap;
-
-import org.openecomp.sdc.ci.tests.api.SomeInterface;
-
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
+import org.openecomp.sdc.ci.tests.api.SomeInterface;
+
+import java.util.HashMap;
public class ExtentTestManager implements SomeInterface{
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
index 3bb4c7598c..2e05c2c059 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
@@ -26,14 +26,21 @@ 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.json.simple.JSONObject;
+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.execute.setup.ExtentTestManager;
import org.openecomp.sdc.ci.tests.api.SomeInterface;
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.sanity.OnboardingFlowsUI;
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;
@@ -59,11 +66,14 @@ import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
+import com.aventstack.extentreports.ExtentReports;
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 {
@@ -195,9 +205,9 @@ public abstract class SetupCDTest extends DriverFactory {
addTrafficFileToReport(result);
}
- if (result.getInstanceName().equals(Onboard.class.getName()) && result.getStatus() == ITestResult.FAILURE){
+ if (result.getInstanceName().equals(OnboardingFlowsUI.class.getName()) && result.getStatus() == ITestResult.FAILURE){
System.out.println("Onboarding test failed, closign browser....");
- getExtendTest().log(Status.INFO, "Onboarding test failed, closign browser....");
+ getExtendTest().log(Status.INFO, "Onboarding test failed, closing browser....");
quitDriver();
}
else if (!getUser().getRole().toLowerCase().equals(UserRoleEnum.ADMIN.name().toLowerCase())){
@@ -217,21 +227,28 @@ public abstract class SetupCDTest extends DriverFactory {
ExtentTestManager.endTest();
- addResultToCSV(result, context);
+ String suiteName = ExtentManager.getSuiteName(context);
+// write result to csv file
+ if((!suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) && (result.getStatus() == ITestResult.SKIP)) {
+ addResultToCSV(result, context);
+ }
+ if(suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue()) && !(result.getStatus() == ITestResult.SUCCESS)) {
+ addResultToCSV(result, context);
+ }
// ExtentManager.closeReporter();
FileHandling.cleanCurrentDownloadDir();
}
}
public void addResultToCSV(ITestResult result, ITestContext context) {
- String suiteName = ExtentManager.getSuiteName(context);
+// String suiteName = ExtentManager.getSuiteName(context);
ExtentTest test = getExtendTest();
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)) {
+// if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue()) && !(result.getStatus() == ITestResult.SUCCESS)) {
getCsvReport().writeRow(result.getInstanceName(), name.replace(RE_RUN,""), status);
- }
+// }
}
public void generateReport4Jenkins(ITestContext context) {
@@ -288,7 +305,7 @@ public abstract class SetupCDTest extends DriverFactory {
String message = "no URL found";
System.out.println(message);
Assert.fail(message);
- } else if (!url.contains("localhost") && !url.contains("127.0.0.1")) {
+ } else if (!url.contains("localhost") && !url.contains("192.168.33.10") && !url.contains("127.0.0.1")) {
localEnv = false;
}
return url;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
index 264971e2d9..e9789ca850 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
@@ -20,8 +20,7 @@
package org.openecomp.sdc.ci.tests.pages;
-import java.util.List;
-
+import com.aventstack.extentreports.Status;
import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
@@ -32,8 +31,9 @@ import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
+import org.testng.AssertJUnit;
-import com.aventstack.extentreports.Status;
+import java.util.List;
public class CompositionPage extends GeneralPageElements {
@@ -92,6 +92,10 @@ public class CompositionPage extends GeneralPageElements {
}
public static void changeComponentVersion(CanvasManager canvasManager, CanvasElement element, String version) {
+ changeComponentVersion(canvasManager,element,version,false);
+ }
+
+ public static void changeComponentVersion(CanvasManager canvasManager, CanvasElement element, String version, boolean isValidate) {
try{
SetupCDTest.getExtendTest().log(Status.INFO, String.format("Changing component version to %s", version));
canvasManager.clickOnCanvaElement(element);
@@ -105,6 +109,16 @@ public class CompositionPage extends GeneralPageElements {
selectlist.selectByValue(version);
GeneralUIUtils.ultimateWait();
GeneralUIUtils.clickSomewhereOnPage();
+
+ // Validate Selection
+ if(isValidate)
+ {
+ GeneralUIUtils.ultimateWait();
+ canvasManager.clickOnCanvaElement(element);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating component version changed to %s", version));
+ String actualSelectedValue = GeneralUIUtils.getWebElementBy(By.xpath(String.format("//select[@data-tests-id='%s']//option[@selected='selected']",DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue()))).getText();
+ AssertJUnit.assertTrue(actualSelectedValue.equals(version));
+ }
}
catch(Exception e){
throw e;
@@ -117,7 +131,7 @@ public class CompositionPage extends GeneralPageElements {
}
public static String getSelectedInstanceName(){
- return GeneralUIUtils.getWebElementByTestID("selectedCompTitle").getText();
+ return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText();
}
public static void showInformationArtifactTab() throws Exception {
@@ -188,6 +202,21 @@ public class CompositionPage extends GeneralPageElements {
return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() +fileName);
}
+ public static void setSingleProperty(String propertyDataTestID, String propertyValue)
+ {
+ WebElement findElement = GeneralUIUtils.getWebElementByTestID(propertyDataTestID);
+ findElement.click();
+ PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue);
+ PropertiesPage.getPropertyPopup().clickSave();
+ GeneralUIUtils.ultimateWait();
+ findElement = GeneralUIUtils.getWebElementByTestID("value_" + propertyDataTestID);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating property %s is set", propertyValue));
+ AssertJUnit.assertTrue(findElement.getText().equals(propertyValue));
+ GeneralUIUtils.ultimateWait();
+ }
+
+
+
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
index cc6f9b7c89..4230769692 100644
--- 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
@@ -20,10 +20,7 @@
package org.openecomp.sdc.ci.tests.pages;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
+import com.aventstack.extentreports.Status;
import org.apache.commons.lang.WordUtils;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
@@ -37,7 +34,9 @@ import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.collections.Lists;
-import com.aventstack.extentreports.Status;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
public class DeploymentArtifactPage extends GeneralPageElements {
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java
index cdf68da0dd..1dd67b1036 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/PropertiesAssignmentPage.java
@@ -1,6 +1,8 @@
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.PropertiesAssignmentScreen;
import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
@@ -41,7 +43,7 @@ public class PropertiesAssignmentPage {
}
public static void findSearchBoxAndClick(String resourceName) throws Exception {
- SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in homepage");
+ SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in Properties");
WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.SEARCH_BOX.getValue());
try{
searchTextbox.clear();
@@ -55,7 +57,7 @@ public class PropertiesAssignmentPage {
try{
- SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component from home screen", resourceName));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component in Properties", resourceName));
GeneralUIUtils.clickOnElementByTestId(resourceName);
GeneralUIUtils.ultimateWait();
GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue());
@@ -84,15 +86,11 @@ public class PropertiesAssignmentPage {
GeneralUIUtils.ultimateWait();
}
- public static void clickOnFilterAll() {
- SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on property %s "));
- GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_ALL.getValue());
- GeneralUIUtils.ultimateWait();
- }
+
public static void clickOnComponentInComposition(String resourceName) throws Exception{
try{
- SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component from properties composition", resourceName));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component on Properties screen", resourceName));
GeneralUIUtils.clickOnElementByTestId(resourceName);
GeneralUIUtils.ultimateWait();
GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue());
@@ -104,7 +102,7 @@ public class PropertiesAssignmentPage {
}
public static void findInput(String componentName, String resourceName) throws Exception {
- SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + componentName + "_" + resourceName + " in homepage");
+ SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + componentName + "_" + resourceName + " on Inputs screen");
WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.SEARCH_BOX.getValue());
String searchPattern = componentName + "_" + resourceName;
try{
@@ -120,7 +118,7 @@ public class PropertiesAssignmentPage {
}
public static void findProperty(String resourceName) throws Exception {
- SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in homepage");
+ SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " property on Properties screen");
WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.SEARCH_BOX.getValue());
try{
@@ -146,4 +144,69 @@ public class PropertiesAssignmentPage {
}
+ //Filter Actions
+ public static void clickOnFilterButton() {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter button "));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_BUTTON.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterAllCheckbox() {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter All Checkbox "));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_ALL.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterCPCheckbox() {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter CP Checkbox "));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_CP.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterVfcCheckbox() {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter VFC Checkbox "));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_VFC.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterVlCheckbox() {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter VL Checkbox "));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_VL.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterApplyButton(){
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter Apply Button"));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_APPLY_BUTTON.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterCloseButton(){
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter Close Button"));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CLOSE_BUTTON.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickOnFilterClearAllButton(){
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Filter Clear All Button"));
+ GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.CLEAR_FILTER_BUTTON.getValue());
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void findFilterBoxAndClick(String resourceName) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " property in Properties table");
+ WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.FILTER_BOX.getValue());
+ try{
+ searchTextbox.clear();
+ searchTextbox.sendKeys(resourceName);
+ GeneralUIUtils.ultimateWait();
+ }
+ catch(Exception e){
+ SetupCDTest.getExtendTest().log(Status.INFO, "Can't interact with search bar");
+ e.printStackTrace();
+ }
+
+ }
+
+
}
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
index 2f581cc009..501a7471a5 100644
--- 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
@@ -38,6 +38,7 @@ 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.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
@@ -502,7 +503,7 @@ public final class ArtifactUIUtils {
Map<String, Object> mapExpectedFile = FileHandling.parseYamlFileToMapByPattern(expectedFile, pattern);
Map<String, Object> mapActualFile = FileHandling.parseYamlFileToMapByPattern(actualFile, pattern);
SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare file " + expectedFile.getName());
- assertTrue("File" + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size());
+ assertTrue("File " + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size());
assertTrue("File " + actualFile.getName() + " does not contains all expected parameters", mapActualFile.entrySet().containsAll(mapExpectedFile.entrySet()));
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java
index cbe3283a66..d455243227 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java
@@ -48,6 +48,7 @@ import org.openecomp.sdc.be.model.DataTypeDefinition;
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.ci.tests.utils.general.OnboardingUtils;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.yaml.snakeyaml.Yaml;
@@ -209,6 +210,9 @@ public class FileHandling {
for (File file : dir.listFiles(extensionFilter)) {
filenames.add(file.getName());
}
+
+ filenames.removeAll(OnboardingUtils.exludeVnfList);
+
return filenames;
}
@@ -222,21 +226,21 @@ public class FileHandling {
try{
ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
-
- String[] artifactNames = new String[zipFile.size() - 1];
- int i = 0;
+ List<String> artifactNames = new ArrayList<String>();
+
while(entries.hasMoreElements()){
ZipEntry nextElement = entries.nextElement();
if (!nextElement.isDirectory()){
if (!nextElement.getName().equals("MANIFEST.json")){
String name = nextElement.getName();
- artifactNames[i++] = name;
+ artifactNames.add(name);
}
}
}
zipFile.close();
- return artifactNames;
+ // convert list to array
+ return artifactNames.toArray(new String[0]);
}
catch(ZipException zipEx){
System.err.println("Error in zip file named : " + zipFilename);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
index 526ed7a8f4..f198ed98a1 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
@@ -20,8 +20,19 @@
package org.openecomp.sdc.ci.tests.utilities;
-import java.awt.Robot;
-import java.awt.Toolkit;
+import com.aventstack.extentreports.Status;
+import org.apache.commons.io.FileUtils;
+import org.openecomp.sdc.ci.tests.datatypes.CatalogFilterTitlesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
+import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.DashboardCardEnum;
+import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory;
+import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
+import org.openqa.selenium.*;
+import org.openqa.selenium.firefox.FirefoxDriver;
+import org.openqa.selenium.interactions.Actions;
+import org.openqa.selenium.support.ui.*;
+
+import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
@@ -34,30 +45,6 @@ import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
-import org.apache.commons.io.FileUtils;
-import org.openecomp.sdc.ci.tests.datatypes.CatalogFilterTitlesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.DashboardCardEnum;
-import org.openecomp.sdc.ci.tests.execute.setup.DriverFactory;
-import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
-import org.openqa.selenium.By;
-import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.Keys;
-import org.openqa.selenium.NoSuchElementException;
-import org.openqa.selenium.OutputType;
-import org.openqa.selenium.TakesScreenshot;
-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.support.ui.ExpectedCondition;
-import org.openqa.selenium.support.ui.ExpectedConditions;
-import org.openqa.selenium.support.ui.FluentWait;
-import org.openqa.selenium.support.ui.Select;
-import org.openqa.selenium.support.ui.WebDriverWait;
-
-import com.aventstack.extentreports.Status;
-
public final class GeneralUIUtils {
@@ -164,6 +151,13 @@ public final class GeneralUIUtils {
return true;
}
+ public static boolean isWebElementExistByClass(String className) {
+ if(getDriver().findElements(By.className(className)).size() == 0) {
+ return false;
+ }
+ return true;
+ }
+
public static WebElement getInputElement(String dataTestId) {
try{
ultimateWait();
@@ -180,6 +174,7 @@ public final class GeneralUIUtils {
}
+
public static WebElement getWebElementBy(By by) {
return getWebElementBy(by, timeOut);
}
@@ -274,6 +269,18 @@ public final class GeneralUIUtils {
clickOnElementByTestIdWithoutWait(dataTestId);
ultimateWait();
}
+
+ public static void clickOnElementByClassName(String className) {
+ WebDriverWait wait = new WebDriverWait(getDriver(), timeOut);
+ wait.until(ExpectedConditions.elementToBeClickable(By.className(className))).click();
+ ultimateWait();
+ }
+
+ public static void clickOnElementById(String id) {
+ WebDriverWait wait = new WebDriverWait(getDriver(), timeOut);
+ wait.until(ExpectedConditions.elementToBeClickable(By.id(id))).click();
+ ultimateWait();
+ }
public static void clickOnElementByTestIdWithoutWait(String dataTestId) {
WebDriverWait wait = new WebDriverWait(getDriver(), timeOut);
@@ -790,5 +797,59 @@ public final class GeneralUIUtils {
Object elementAttributes = getAllElementAttributes(getDriver().findElement(By.cssSelector(cssString)));
return elementAttributes.toString().contains("disabled");
}
+
+ public static void setTextInElementByDataTestID(String dataTestsID, String text)
+ {
+ WebElement webElement = GeneralUIUtils.getWebElementByTestID(dataTestsID);
+ webElement.clear();
+ webElement.sendKeys(text);
+ ultimateWait();
+ }
+
+ public static void selectByValueTextContained(String dataTestsId, String value) {
+
+ List<WebElement> options = GeneralUIUtils.getWebElementsListBy(By.xpath(String.format("//select[@data-tests-id='%s']//option[contains(@value,'%s')]",dataTestsId,value)));
+
+ boolean matched = false;
+ for (WebElement option : options) {
+ option.click();
+ matched = true;
+ }
+
+ if (!matched) {
+ throw new NoSuchElementException("Cannot locate option with value: " + value);
+ }
+
+ ultimateWait();
+ }
+
+ public static void setTextInElementByXpath(String xPath, String text)
+ {
+ WebElement webElement = GeneralUIUtils.getWebElementBy(By.xpath(xPath));
+ webElement.clear();
+ webElement.click();
+ webElement.sendKeys(text);
+ ultimateWait();
+ }
+
+ public static String getTextValueFromInput(WebElement webElement)
+ {
+ return webElement.getAttribute("value");
+ }
+
+ public static String getTextValueFromWebElementByXpath(String Xpath)
+ {
+ WebElement webElement = getWebElementBy(By.xpath(Xpath));
+ return webElement.getAttribute("value");
+ }
+
+ public static void refreshPage(){
+ Actions actions = new Actions(getDriver());
+ actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
+ }
+
+
+
+
}
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
index ca4dd567d6..b40ebf86fc 100644
--- 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
@@ -20,6 +20,7 @@
package org.openecomp.sdc.ci.tests.utilities;
+import com.aventstack.extentreports.Status;
import org.openecomp.sdc.ci.tests.datatypes.CheckBoxStatusEnum;
import org.openecomp.sdc.ci.tests.datatypes.CreateAndImportButtonsEnum;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
@@ -29,7 +30,7 @@ import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
-import com.aventstack.extentreports.Status;
+import java.util.List;
public final class HomeUtils {
@@ -110,7 +111,28 @@ public final class HomeUtils {
Assert.fail(msg);
}
}
-
-
+ public static void findComponentAndClickByVersion(String componentName, String version) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("finding component %s v%s", componentName, version));
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName);
+ List<WebElement> foundComp = null;
+ try {
+ foundComp = GeneralUIUtils.getWebElementsListByTestID(componentName + "Version");
+
+ for (WebElement webElement : foundComp)
+ {
+ if(webElement.getText().contains(version))
+ {
+ webElement.click();
+ GeneralUIUtils.ultimateWait();
+ break;
+ }
+ }
+ } 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/OnboardingUiUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java
index b610cf1c54..e2956774bf 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUiUtils.java
@@ -20,746 +20,34 @@
package org.openecomp.sdc.ci.tests.utilities;
-import static org.testng.AssertJUnit.assertEquals;
-
-import java.io.File;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers;
-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.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.datatypes.*;
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.general.OnboardingUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.general.VendorLicenseModelRestUtils;
+import org.openecomp.sdc.ci.tests.utils.general.VendorSoftwareProductRestUtils;
import org.openecomp.sdc.ci.tests.verificator.VfVerificator;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
-import com.aventstack.extentreports.Status;
-import com.clearspring.analytics.util.Pair;
-
-
-
-
-
-
-
+import java.io.File;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
public class OnboardingUiUtils {
-// /**
-// * excluded VNF file list
-// */
-// protected static List<String> exludeVnfList =
-//// new ArrayList<String>();
-//
-// Arrays.asList(
-//
-//// new VNFs
-// "Vhss-epc-rdm3-lab-vf-0921-v2.0-MOBILITY-10-20.zip", "Apndns-1710-vf-v3.0-10-20.zip",
-// "HeatCandidate_2017-09-22_01-48_55Name_2016-182-asbg-nsbg-tsbg-v1.0-(VOIP).zip", "HeatCandidate_2017-09-22_01-47_55Name_2016-182-asbg-nsbg-tsbg-v7.0-(VOIP).zip",
-// "Efmc-dbe-nin-v24.0-VOIP-10-20.zip", "VF_LMSP_v5-062317-V3.0-(Mobility).zip", "base_bwks_nfm_volume-236262502.zip",
-//
-//// newest failed VNFs
-// "HeatCandidate_2017-09-20_15-07_66Name_2016-20-visbc1vf-v4.0-(VOIP).zip",
-// "HeatCandidate_2017-09-20_15-06_66Name_2016-20-visbc1vf-v6.0-(VOIP).zip", "1-Vf-zrdm5bpxtc02-092017-(MOBILITY)_v3.0.zip",
-// "2-Vf-zrdm5bpxtc02-092017-(MOBILITY)_v2.0.zip", "1-2017-491-4vshaken-HTTP-CM-vf-(VOIP)_v2.0.zip"
-//
-// );
-//
-// /**
-// * additional files to exludeVnfList files for tosca parser tests
-// */
-// protected static List<String> exludeVnfListForToscaParser = new ArrayList<String>();
-// //Arrays.asList("2016-043_vsaegw_fdnt_30_1607_e2e.zip", "vIRC_CC.zip",
-//// "2016-045_vlb_lmsp_30_1607_e2e.zip", "2016-050_vdns_vmdns_30_1607_e2e.zip",
-//// "2016-247_mns_mns_30_1610_e2e.zip", "2016-044_vfw_fcgi_30_1607_e2e.zip");
-
- public OnboardingUiUtils() {
- }
-
-// public static Pair<String, Map<String, String>> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts)
-// throws Exception {
-//
-// Pair<String, Map<String, String>> pair = createVSP(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers);
-// String vspid = pair.right.get("vspId");
-// if(cvfcArtifacts != null && ! cvfcArtifacts.isEmpty()){
-// OnboardingUiUtils.addCvfcArtifacts(cvfcArtifacts, vspid, user, null);
-//
-// }
-// prepareVspForUse(user, vspid, "0.1");
-// return pair;
-// }
-
- public static void prepareVspForUse(User user, String vspid, String vspVersion) throws Exception {
-
- RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspid, user, vspVersion);
- assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspid, user, vspVersion);
- assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue());
-
- RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspid, user, vspVersion);
- assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue());
- if(SetupCDTest.getExtendTest() != null){
- SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product");
- }
- }
-
-
-// public static VendorSoftwareProductObject createAndFillVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filePath, User user, AmdocsLicenseMembers amdocsLicenseMembers, Map<CvfcTypeEnum, String> cvfcArtifacts)
-// throws Exception {
-//
-// Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUiUtils.createVendorSoftwareProduct(resourceReqDetails, heatFileName, filePath, user, amdocsLicenseMembers, cvfcArtifacts);
-// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(heatFileName, createVendorSoftwareProduct);
-// return vendorSoftwareProductObject;
-//
-// }
-
-// public static Pair<String, Map<String, String>> createVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers)
-// throws Exception {
-//
-// Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>();
-// return createVendorSoftwareProduct(resourceReqDetails, heatFileName, filepath, user, amdocsLicenseMembers, cvfcArtifacts);
-// }
-
-// public static Pair<String, Map<String, String>> createVSP(ResourceReqDetails resourceReqDetails, String heatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception {
-// String vspName = handleFilename(heatFileName);
-//
-// if(SetupCDTest.getExtendTest() != null){
-// SetupCDTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product");
-// }
-//
-// Pair<RestResponse, Map<String, String>> createNewVspPair = createNewVendorSoftwareProduct(resourceReqDetails, vspName, amdocsLicenseMembers, 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<String, String> vspMeta = createNewVspPair.right;
-// Map<String, String> vspObject = new HashMap<String, String>();
-// Iterator<String> 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", amdocsLicenseMembers.getVendorLicenseName());
-// vspObject.put("attContact", user.getUserId());
-//
-// RestResponse uploadHeatPackage = uploadHeatPackage(filepath, heatFileName, vspid, user, "0.1");
-// assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
-//
-// RestResponse validateUpload = validateUpload(vspid, user, "0.1");
-// assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), 200, validateUpload.getErrorCode().intValue());
-//
-// Pair<String, Map<String, String>> pair = new Pair<String, Map<String, String>>(vspName, vspObject);
-//
-// return pair;
-// }
-
-// public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user, String vspVersion) throws Exception{
-// RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user, vspVersion);
-// assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-// ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL");
-// deleteArtifactByType(componentId, vspId, user, CvfcTypeEnum.SNMP_POLL);
-// ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP");
-// deleteArtifactByType(componentId, vspId, user, CvfcTypeEnum.SNMP_TRAP);
-// addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId);
-// prepareVspForUse(user, vspId, vspVersion);
-// }
-
- public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user, String vspVersion)
- throws Exception, Throwable {
- String vspName = OnboardingUtils.handleFilename(HeatFileName);
- SetupCDTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product");
-
- RestResponse checkout = OnboardingUtils.checkoutVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-
- RestResponse uploadHeatPackage = OnboardingUtils.uploadHeatPackage(filepath, HeatFileName, vspId, user, vspVersion);
- assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue());
-
- RestResponse validateUpload = OnboardingUtils.validateUpload(vspId, user, vspVersion);
- assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue());
-
- RestResponse checkin = OnboardingUtils.checkinVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
-
- RestResponse submit = OnboardingUtils.submitVendorSoftwareProduct(vspId, user, vspVersion);
- assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
-
- RestResponse createPackage = OnboardingUtils.createPackageOfVendorSoftwareProduct(vspId, user, vspVersion);
- 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 void updateVendorSoftwareProductToNextVersion(VendorSoftwareProductObject vendorSoftwareProductObject, String toVspVersion, User user)
-// throws Exception, Throwable {
-//
-// RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
-// assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-//
-// RestResponse checkin = checkinVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
-// assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
-//
-// RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vendorSoftwareProductObject.getVersion());
-// assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
-//
-// vendorSoftwareProductObject.setVersion(toVspVersion);
-// }
-
-// public static String handleFilename(String heatFileName) {
-// final String namePrefix = String.format("%sVFOnboarded-", ElementFactory.getResourcePrefix());
-// 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 addCvfcArtifacts(Map<CvfcTypeEnum, String> componentVfcArtifacts, String vspid, User user, String vspComponentId) throws Exception{
-// vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId;
-// if (vspComponentId != null){
-// for(Entry<CvfcTypeEnum, String> entry : componentVfcArtifacts.entrySet()){
-// ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type " + entry.getKey().getValue() + " with the file " + entry.getValue());
-// RestResponse uploadSnmpPollArtifact = uploadCvfcArtifact(entry.getValue(), entry.getKey().getValue(), vspid, user, vspComponentId);
-// assertEquals("Did not succeed to add " + entry.getKey().getValue(), BaseRestUtils.STATUS_CODE_SUCCESS, uploadSnmpPollArtifact.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);
-// }
-
-// public static RestResponse uploadCvfcArtifact(String filepath, String cvfcType, String vspid, User user, String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException {
-// Config config = Utils.getConfig();
-// String snmpPollUrl = String.format(Urls.UPLOAD_AMDOCS_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId, cvfcType);
-// return uploadFile(filepath, null, snmpPollUrl, user);
-// }
-
-// 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(Urls.UPLOAD_SNMP_POLL_ARTIFACT, 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(Urls.UPLOAD_SNMP_POLL_ARTIFACT, config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId);
-// return uploadFile(filepath, zipArtifact, snmpTrapUrl, user);
-// }
-
-// private static RestResponse deleteArtifactByType(String componentId, String vspId, User user, CvfcTypeEnum snmpType) throws Exception
-// {
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.DELETE_AMDOCS_ARTIFACT_BY_TYPE, config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue());
-// String userId = user.getUserId();
-// Map<String, String> 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<String, Object> responseMap = (Map<String, Object>) JSONValue.parse(response);
-// JSONArray results = (JSONArray)responseMap.get("results");
-// for (Object res : results){
-// Map<String, Object> compMap= (Map<String, Object>) 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(Urls.GET_VSP_COMPONENTS, config.getCatalogBeHost(),config.getCatalogBePort(), vspid);
-// String userId = user.getUserId();
-//
-// Map<String, String> headersMap = prepareHeadersMap(userId);
-//
-// HttpRequest http = new HttpRequest();
-// RestResponse response = http.httpSendGet(url, headersMap);
-// return response;
-// }
-
-// private static RestResponse getVSPComponentByVersion(String vspId, String vspVersion, User user) throws Exception{
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.GET_VSP_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vspId,vspVersion);
-// String userId = user.getUserId();
-//
-// Map<String, String> headersMap = prepareHeadersMap(userId);
-//
-// HttpRequest http = new HttpRequest();
-// RestResponse response = http.httpSendGet(url, headersMap);
-// return response;
-// }
-
-// private static RestResponse getVLMComponentByVersion(String vlmId, String vlmVersion, User user) throws Exception{
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.GET_VLM_COMPONENT_BY_VERSION, config.getCatalogBeHost(),config.getCatalogBePort(), vlmId,vlmVersion);
-// String userId = user.getUserId();
-//
-// Map<String, String> headersMap = prepareHeadersMap(userId);
-//
-// HttpRequest http = new HttpRequest();
-// RestResponse response = http.httpSendGet(url, headersMap);
-// return response;
-// }
-
-// public static boolean validateVspExist(String vspId, String vspVersion, User user) throws Exception {
-// RestResponse restResponse = getVSPComponentByVersion(vspId, vspVersion, user);
-// assertEquals(String.format("Vsp version not updated, reponse message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
-// return (restResponse.getErrorCode()==200);
-// }
-//
-// public static boolean validateVlmExist(String vlmId, String vlmVersion, User user) throws Exception {
-// RestResponse restResponse = getVLMComponentByVersion(vlmId, vlmVersion, user);
-// assertEquals(String.format("VLM version not updated, reponse code message: %s", restResponse.getResponse()),restResponse.getErrorCode().intValue(),200);
-// return (restResponse.getErrorCode()==200);
-// }
-
- public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception {
-
- AmdocsLicenseMembers amdocsLicenseMembers;
- if(SetupCDTest.getExtendTest() != null){
- SetupCDTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license");
- }
- String vendorLicenseName = "ciLicense" + OnboardingUtils.getShortUUID();
- RestResponse vendorLicenseResponse = OnboardingUtils.createVendorLicenseModels_1(vendorLicenseName, user);
- assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue());
- String 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());
- String 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());
- String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value");
-
- RestResponse checkinVendorLicense = OnboardingUtils.checkinVendorLicense(vendorId, user, "0.1");
- assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
-
- RestResponse submitVendorLicense = OnboardingUtils.submitVendorLicense(vendorId, user, "0.1");
- assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
-
- if(SetupCDTest.getExtendTest() != null){
- SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license");
- }
-
- amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId);
- amdocsLicenseMembers.setVersion("1.0"); // Once object created and submitted, his initial version is 1.0
-
- return amdocsLicenseMembers;
- }
-
-// public static void updateVendorLicense(AmdocsLicenseMembers amdocsLicenseMembers, User user, String vlmVersion) throws Exception {
-//
-// RestResponse checkoutVendorLicense = checkoutVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion);
-// assertEquals("did not succeed to checkout vendor license", 200, checkoutVendorLicense.getErrorCode().intValue());
-//
-// RestResponse checkinVendorLicense = checkinVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion);
-// assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue());
-//
-// RestResponse submitVendorLicense = submitVendorLicense(amdocsLicenseMembers.getVendorId(), user, vlmVersion);
-// assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue());
-//
-// if(SetupCDTest.getExtendTest() != null){
-// SetupCDTest.getExtendTest().log(Status.INFO, "Succeeded in updating 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, String componentVersion)
-// throws Exception {
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.ACTION_ON_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), onboardComponent, vspid, componentVersion);
-// String userId = user.getUserId();
-//
-// JSONObject jObject = new JSONObject();
-// jObject.put("action", action);
-//
-// Map<String, String> 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, String vlmVersion) throws Exception {
-// return actionOnComponent(vspid, "Checkin", "vendor-license-models", user, vlmVersion);
-// }
-//
-// public static RestResponse checkoutVendorLicense(String vspid, User user, String vlmVersion) throws Exception {
-// return actionOnComponent(vspid, "Checkout", "vendor-license-models", user, vlmVersion);
-// }
-//
-// public static RestResponse submitVendorLicense(String vspid, User user, String vlmVersion) throws Exception {
-// return actionOnComponent(vspid, "Submit", "vendor-license-models", user, vlmVersion);
-// }
-
-// public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception {
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.CREATE_VENDOR_LISENCE_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<String, String> 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(Urls.CREATE_VENDOR_LISENCE_AGREEMENT, 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<String, String> 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(Urls.CREATE_VENDOR_LISENCE_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("manufacturerReferenceNumber", "5");
-// jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
-// jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
-//
-// Map<String, String> 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(Urls.CREATE_VENDOR_LISENCE_ENTITLEMENT_POOL, 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"+ getShortUUID());
-// 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<String, String> 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(Urls.CREATE_VENDOR_LISENCE_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" + getShortUUID());
-// jObjectBody.put("description", "new vendor license key group");
-// jObjectBody.put("operationalScope", jOperationalScope);
-// jObjectBody.put("type", "Universal");
-//
-// Map<String, String> headersMap = prepareHeadersMap(userId);
-//
-// HttpRequest http = new HttpRequest();
-// RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap);
-// return response;
-// }
-
-// public static Pair<RestResponse, Map<String, String>> createNewVendorSoftwareProduct(ResourceReqDetails resourceReqDetails, String vspName, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception {
-// Map<String, String> vspMetadta = new HashMap<String, String>();
-//
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.CREATE_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
-// String userId = user.getUserId();
-// VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject();
-// LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()));
-// LicensingVersion licensingVersion = new LicensingVersion("1.0", "1.0");
-// ResourceCategoryEnum resourceCategoryEnum = ResourceCategoryEnum.findEnumNameByValues(resourceReqDetails.getCategories().get(0).getName(), resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName());
-//
-// vendorSoftwareProductObject.setLicensingVersion(licensingVersion);
-//
-// vendorSoftwareProductObject.setName(vspName);
-// vendorSoftwareProductObject.setDescription(resourceReqDetails.getDescription());
-// vendorSoftwareProductObject.setCategory(resourceCategoryEnum.getCategoryUniqeId());
-// vendorSoftwareProductObject.setSubCategory(resourceCategoryEnum.getSubCategoryUniqeId());
-// vendorSoftwareProductObject.setOnboardingMethod("NetworkPackage");
-// vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName());
-// vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId());
-// vendorSoftwareProductObject.setIcon("icon");
-// vendorSoftwareProductObject.setLicensingData(licensingData);
-//
-// vspMetadta.put("description", resourceReqDetails.getDescription());
-// vspMetadta.put("category", resourceCategoryEnum.getCategory());
-// vspMetadta.put("subCategory", resourceCategoryEnum.getSubCategory());
-//
-// Map<String, String> headersMap = prepareHeadersMap(userId);
-// HttpRequest http = new HttpRequest();
-// Gson gson = new Gson();
-// String body = gson.toJson(vendorSoftwareProductObject);
-//
-// RestResponse response = http.httpSendPost(url, body, headersMap);
-// return new Pair<RestResponse, Map<String, String>>(response, vspMetadta);
-// }
-
-
-// public static RestResponse validateUpload(String vspid, User user, String vspVersion) throws Exception {
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.VALIDATE_UPLOAD, config.getCatalogBeHost(), config.getCatalogBePort(), vspid,vspVersion);
-//
-// String userId = user.getUserId();
-//
-// Map<String, String> 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, String vspVersion) throws Exception {
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.UPLOAD_HEAT_PACKAGE, config.getCatalogBeHost(), config.getCatalogBePort(), vspid, vspVersion);
-// 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<String, String> 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<String> 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();
-// try {
-// StringWriter writer = new StringWriter();
-// IOUtils.copy(instream, writer);
-// responseBody = writer.toString();
-// } 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;
-// if(filename == null){
-// filePath = FileSystems.getDefault().getPath(filepath);
-// }else{
-// filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename);
-// }
-// return filePath.toFile();
-// }
-
-// public static RestResponse checkinVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
-// return actionOnComponent(vspid, "Checkin", "vendor-software-products", user, vspVersion);
-// }
-//
-// private static RestResponse checkoutVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
-// return actionOnComponent(vspid, "Checkout", "vendor-software-products", user, vspVersion);
-// }
-//
-// public static RestResponse submitVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
-// return actionOnComponent(vspid, "Submit", "vendor-software-products", user, vspVersion);
-// }
-//
-// public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user, String vspVersion) throws Exception {
-// return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user, vspVersion);
-// }
-
-// protected static Map<String, String> prepareHeadersMap(String userId) {
-// Map<String, String> headersMap = new HashMap<String, String>();
-// 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<String, Map<String, String>> vsp, boolean isUpdate) throws Exception{
+ private static void importUpdateVSP(Pair<String, VendorSoftwareProductObject> vsp, boolean isUpdate) throws Exception{
String vspName = vsp.left;
- Map<String, String> vspMetadata = vsp.right;
+ VendorSoftwareProductObject vspMetadata = vsp.right;
boolean vspFound = HomePage.searchForVSP(vspName);
if (vspFound){
@@ -773,7 +61,6 @@ public class OnboardingUiUtils {
if (isUpdate){
GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue());
-
}
else{
GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue());
@@ -786,7 +73,6 @@ public class OnboardingUiUtils {
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();
@@ -813,39 +99,36 @@ public class OnboardingUiUtils {
GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue());
}
- public static void updateVSP(Pair<String, Map<String, String>> vsp) throws Exception{
+ public static void updateVSP(Pair<String, VendorSoftwareProductObject> vsp) throws Exception{
ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left);
importUpdateVSP(vsp, true);
}
- public static void importVSP(Pair<String, Map<String, String>> vsp) throws Exception{
+ public static void importVSP(Pair<String, VendorSoftwareProductObject> vsp) throws Exception{
ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left);
importUpdateVSP(vsp, false);
}
- public static void updateVnfAndValidate(String filepath, Pair<String, Map<String, String>> vsp, String updatedVnfFile, User user) throws Exception, Throwable {
+ public static void updateVnfAndValidate(String filePath, Pair<String, VendorSoftwareProductObject> 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<String, String> vspMap = vsp.right;
- String vspId = vspMap.get("vspId");
-
- updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user, "0.1");
+
+ VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vsp.right, user, filePath, updatedVnfFile);
HomePage.showVspRepository();
updateVSP(vsp);
ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
- DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile);
+ DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, updatedVnfFile);
}
- public static Pair<String, Map<String, String>> onboardAndValidate(ResourceReqDetails resourceReqDetails, String filepath, String vnfFile, User user) throws Exception {
+ public static Pair<String, VendorSoftwareProductObject> onboardAndValidate(ResourceReqDetails resourceReqDetails, 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));
- AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user);
- Pair<String, Map<String, String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(user);
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, amdocsLicenseMembers);
String vspName = createVendorSoftwareProduct.left;
- DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId"));
+ DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.getVspId());
File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir();
ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile));
@@ -894,76 +177,4 @@ public class OnboardingUiUtils {
}
}
-// public static VendorSoftwareProductObject updateVSPWithNewVLMParameters(VendorSoftwareProductObject vendorSoftwareProductObject,
-// AmdocsLicenseMembers amdocsLicenseMembers, User user, String vspCurrentVersion, String vspNextVersion) throws Exception {
-//
-// LicensingVersion licensingVersion = new LicensingVersion(amdocsLicenseMembers.getLicenseVersionId(),amdocsLicenseMembers.getLicenseVersionId());
-// LicensingData licensingData = new LicensingData(amdocsLicenseMembers.getVendorLicenseAgreementId(), Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()));
-// vendorSoftwareProductObject.setVendorId(amdocsLicenseMembers.getVendorId());
-// vendorSoftwareProductObject.setVendorName(amdocsLicenseMembers.getVendorLicenseName());
-// vendorSoftwareProductObject.setLicensingVersion(licensingVersion);
-// vendorSoftwareProductObject.setLicensingData(licensingData);
-//
-// VendorSoftwareProductObjectReqDetails vendorSoftwareProductObjectReqDetails = new VendorSoftwareProductObjectReqDetails(
-// vendorSoftwareProductObject.getName(),
-// vendorSoftwareProductObject.getDescription(),
-// vendorSoftwareProductObject.getCategory(),
-// vendorSoftwareProductObject.getSubCategory(),
-// vendorSoftwareProductObject.getVendorId(),
-// vendorSoftwareProductObject.getVendorName(),
-// licensingVersion,
-// licensingData,
-// vendorSoftwareProductObject.getOnboardingMethod(),
-// vendorSoftwareProductObject.getNetworkPackageName(),
-// vendorSoftwareProductObject.getOnboardingOrigin());
-//
-// Gson gson = new Gson();
-// String json = gson.toJson(vendorSoftwareProductObjectReqDetails);
-//
-// RestResponse checkout = checkoutVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, "1.0");
-// assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue());
-//
-// Config config = Utils.getConfig();
-// String url = String.format(Urls.UPDATE_VSP, config.getCatalogBeHost(), config.getCatalogBePort(), vendorSoftwareProductObject.getVspId(), vspCurrentVersion);
-// String userId = user.getUserId();
-//
-// Map<String, String> headersMap = prepareHeadersMap(userId);
-// HttpRequest http = new HttpRequest();
-//
-// RestResponse response = http.httpSendPut(url, json, headersMap);
-//
-// RestResponse checkin = checkinVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vspCurrentVersion);
-// assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue());
-//
-// RestResponse submit = submitVendorSoftwareProduct(vendorSoftwareProductObject.getVspId(), user, vspCurrentVersion);
-// assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue());
-//
-// vendorSoftwareProductObject.setVersion(vspNextVersion);
-//
-// return vendorSoftwareProductObject;
-// }
-
-// /**
-// * @return
-// * The method returns VNF names list from Files directory under sdc-vnfs repository
-// */
-// public static List<String> getVnfNamesFileList() {
-// String filepath = FileHandling.getVnfRepositoryPath();
-// List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
-// fileNamesFromFolder.removeAll(exludeVnfList);
-// return fileNamesFromFolder;
-// }
-//
-// /**
-// * @return
-// * The method returns VNF names list from Files directory under sdc-vnfs repository excluding zip files that known as failed in tosca parser
-// */
-// public static List<String> getVnfNamesFileListExcludeToscaParserFailure() {
-// List<String> fileNamesFromFolder = getVnfNamesFileList();
-// fileNamesFromFolder.removeAll(exludeVnfListForToscaParser);
-// return fileNamesFromFolder;
-// }
-
}
-
-
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java
new file mode 100644
index 0000000000..404325190e
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/PortMirroringUtils.java
@@ -0,0 +1,132 @@
+package org.openecomp.sdc.ci.tests.utilities;
+
+import com.aventstack.extentreports.Status;
+import com.clearspring.analytics.util.Pair;
+import fj.data.Either;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.ci.tests.datatypes.*;
+import org.openecomp.sdc.ci.tests.datatypes.enums.CircleSize;
+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.execute.setup.SetupCDTest;
+import org.openecomp.sdc.ci.tests.pages.CompositionPage;
+import org.openecomp.sdc.ci.tests.pages.ServiceGeneralPage;
+import org.openecomp.sdc.ci.tests.utils.general.*;
+import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
+import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis;
+import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
+
+import java.util.List;
+
+public class PortMirroringUtils {
+
+
+ public static ServiceContainer createServiceFromHeatFile(String filePath, String vnfFile) throws Throwable {
+// 1. Import VSP v1.0
+ User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ AmdocsLicenseMembers amdocsLicenseMembers = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", amdocsLicenseMembers.getVendorLicenseName()));
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile));
+ Pair<String, VendorSoftwareProductObject> createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, amdocsLicenseMembers);
+// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct);
+ VendorSoftwareProductObject vendorSoftwareProductObject = createVendorSoftwareProduct.right;
+// 2. Create VF, certify - v1.0 is created
+ resourceReqDetails = org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject);
+ Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName()));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the VF"));
+// 3. Create Service add to it the certified VF and certify the Service v1.0
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName()));
+ Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
+ ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service"));
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the Service"));
+
+ return new ServiceContainer(service, resource, vendorSoftwareProductObject, amdocsLicenseMembers);
+ }
+
+ public static Resource GeneratePNFAndUpdateInput(String resourceName, String vendorModelNumber, User user) throws Exception {
+ Resource resource = getResourceByType(ResourceTypeEnum.PNF, resourceName, vendorModelNumber);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating pnf %s and certify it", resource.getName()));
+ Component componentObject = AtomicOperationUtils.getComponentObject(resource, UserRoleEnum.DESIGNER);
+ UpdateResourceInputViaAPI(user, componentObject, "physicalProbe", "nf_role");
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ return resource;
+ }
+
+ private static void UpdateResourceInputViaAPI(User user, Component componentObject, String defaultValue, String inputName) throws Exception {
+ List<InputDefinition> componentInputs = componentObject.getInputs();
+ PropertyObject propertyObject = new PropertyObject(defaultValue, inputName, componentInputs.get(1).getParentUniqueId(), componentInputs.get(1).getUniqueId());
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Update input %s to %s", "nf_role", "physicalProbe"));
+ PropertyRestUtils.updateInput(componentObject, propertyObject, user);
+ }
+
+ public static Resource getResourceByType(ResourceTypeEnum resourceTypeEnum, String resourceName, String vendorModelNumber) {
+ ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(resourceTypeEnum, resourceName, ResourceCategoryEnum.NETWORK_L2_3_INFRASTRUCTURE, resourceName, vendorModelNumber);
+ return AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+ }
+
+ public static String createProxyInstanceServiceName(String serviceName, String instanceId) {
+ String serviceProxyInstanceName = String.format("%s_proxy %s", serviceName, instanceId);
+ return serviceProxyInstanceName;
+ }
+
+ public static PortMirrioringConfigurationObject createPortMirriongConfigurationStructure() throws Throwable {
+
+ //Using API onboard and certify 2 zip files Source: vmmme and Collector: Vprobe
+ String filePath = FileHandling.getPortMirroringRepositoryPath();
+ ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VMME_ZIP.getValue());
+ ServiceContainer serviceContainerVprobe_Collector = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VPROBE_ZIP.getValue());
+
+// String vmmeSourceName = "ciServiceb560327d162f";
+// String vprobeSourceName = "ciService3d9933d31791";
+
+ // create service
+ ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();
+ //ServiceUIUtils.createService(serviceMetadata, getUser());
+
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating container %s: ", serviceReqDetails.getName()));
+ Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value();
+
+ String vmmeSourceName = serviceContainerVmme_Source.getService().getName();
+ String vprobeSourceName = serviceContainerVprobe_Collector.getService().getName();
+
+ CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG);
+ GeneralUIUtils.findComponentAndClick(service.getName());
+
+ ServiceGeneralPage.getLeftMenu().moveToCompositionScreen();
+ CanvasManager canvasManager = CanvasManager.getCanvasManager();
+
+ CompositionPage.searchForElement(vmmeSourceName);
+ CanvasElement serviceElementVmmeSourceName = canvasManager.createElementOnCanvas(vmmeSourceName);
+
+ CompositionPage.searchForElement(vprobeSourceName);
+ CanvasElement serviceElementVprobeCollector = canvasManager.createElementOnCanvas(vprobeSourceName);
+
+ CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+ CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue());
+
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_SOURCE_CAP.getValue());
+ ConnectionWizardPopUpObject connectionWizardPopUpObjectVProbe = new ConnectionWizardPopUpObject("", "",
+ PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_COLLECTOR_CAP.getValue());
+
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, CircleSize.SERVICE, portMirroringConfigurationElement, CircleSize.NORMATIVE, connectionWizardPopUpObjectVMME);
+ canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVprobeCollector, CircleSize.SERVICE, portMirroringConfigurationElement, CircleSize.NORMATIVE, connectionWizardPopUpObjectVProbe);
+
+ PortMirrioringConfigurationObject portMirrioringConfigurationObject = new PortMirrioringConfigurationObject(serviceReqDetails, vmmeSourceName,
+ vprobeSourceName, canvasManager, serviceElementVmmeSourceName, serviceElementVprobeCollector, service,
+ portMirroringConfigurationElement, serviceContainerVmme_Source.getService(), serviceContainerVprobe_Collector.getService());
+
+ return portMirrioringConfigurationObject;
+ }
+
+}
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
index aa219d0d12..0f6999c28f 100644
--- 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
@@ -20,18 +20,8 @@
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 com.aventstack.extentreports.Status;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.codehaus.jettison.json.JSONObject;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.model.Component;
@@ -56,7 +46,16 @@ 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;
+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 static org.testng.AssertJUnit.assertTrue;
public class RestCDUtils {
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
index 8eb2122b3d..4dcd26c3a1 100644
--- 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
@@ -38,6 +38,7 @@ import java.util.stream.Stream;
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.datatypes.enums.GroupPropertyEnum;
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;
@@ -51,24 +52,26 @@ import org.openqa.selenium.WebElement;
import com.aventstack.extentreports.Status;
public class DeploymentViewVerificator {
-
- private static List<String> currentPropertiesForUI = Arrays.asList("isBase",
+
+ //GroupPropertyEnum.getGroupPropertyNames();
+ private static List<String> currentPropertiesForUI = Arrays.asList("isBase",
"vf_module_label",
"vf_module_description",
"min_vf_module_instances",
"max_vf_module_instances",
"initial_count",
- "vf_module_type",
+ "vf_module_type", //works as isBase property, value can be Base/Expantion
"volume_group",
"vfc_list",
"availability_zone_count");
- private static List<String> currentPropertiesWithoutIsBaseForFile = Arrays.asList("vf_module_label",
- "vf_module_description",
- "min_vf_module_instances",
- "max_vf_module_instances",
- "initial_count",
- "vf_module_type",
+ //GroupPropertyEnum.getGroupPropertyNamesWithoutIsbase();
+ private static List<String> currentPropertiesWithoutIsBaseForFile = Arrays.asList("vf_module_label",
+ "vf_module_description",
+ "min_vf_module_instances",
+ "max_vf_module_instances",
+ "initial_count",
+ "vf_module_type", //works as isBase property, value can be Base/Expantion
"volume_group",
"vfc_list",
"availability_zone_count");
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PortMirroringVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PortMirroringVerificator.java
new file mode 100644
index 0000000000..2c8e8c486a
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PortMirroringVerificator.java
@@ -0,0 +1,85 @@
+package org.openecomp.sdc.ci.tests.verificator;
+
+import com.aventstack.extentreports.Status;
+import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
+import org.openecomp.sdc.ci.tests.datatypes.PortMirroringEnum;
+import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
+import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
+import org.openecomp.sdc.ci.tests.utilities.PortMirroringUtils;
+import org.openqa.selenium.By;
+
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.IOException;
+
+import static org.testng.Assert.assertTrue;
+
+public class PortMirroringVerificator {
+
+ public static void checkProxyServiceName(String serviceName, String instanceId)
+ {
+ String serviceActualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText();
+ String serviceExpectedName = PortMirroringUtils.createProxyInstanceServiceName(serviceName,instanceId);
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the instance name is %s", serviceExpectedName));
+ assertTrue(serviceActualName.equalsIgnoreCase(serviceExpectedName));
+ }
+
+ public static void checkProxyServiceType()
+ {
+ String serviceActualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel_GenerInfo.TYPE.getValue()).getText();
+ SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the instance type is Service Proxy");
+ assertTrue(serviceActualName.equalsIgnoreCase(PortMirroringEnum.SERVICE_PROXY_TYPE.getValue()));
+ }
+
+ public static void validatingProxyServiceNameAndType(String serviceName, String instanceId)
+ {
+ checkProxyServiceName(serviceName, instanceId);
+ checkProxyServiceType();
+ }
+
+ public static void validateGeneralInfo()
+ {
+ String type = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel_GenerInfo.TYPE.getValue()).getText();
+ String resourceType = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel_GenerInfo.RESOURCE_TYPE.getValue()).getText();
+ String category = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel_GenerInfo.CATEGORY.getValue()).getText();
+ String subCategory = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel_GenerInfo.SUB_CATEGORY.getValue()).getText();
+
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the type equals %s", PortMirroringEnum.TYPE.getValue()));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the resource type equals %s", PortMirroringEnum.RESOURCE_TYPE.getValue()));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the category equals %s", PortMirroringEnum.CATEGORY.getValue()));
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the sub category equals %s", PortMirroringEnum.SUB_CATEGORY.getValue()));
+
+ assertTrue(type.equalsIgnoreCase(PortMirroringEnum.TYPE.getValue()));
+ assertTrue(resourceType.equalsIgnoreCase(PortMirroringEnum.RESOURCE_TYPE.getValue()));
+ assertTrue(category.equalsIgnoreCase(PortMirroringEnum.CATEGORY.getValue()));
+ assertTrue(subCategory.equalsIgnoreCase(PortMirroringEnum.SUB_CATEGORY.getValue()));
+ }
+
+ public static void validateReqsAndCapsTabExist()
+ {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Verifying tab reqs and caps exist for PMC element");
+ GeneralUIUtils.getWebElementBy(By.xpath(DataTestIdEnum.CompositionRightPanel.REQS_AND_CAPS_TAB_XPATH.getValue())).click();
+ }
+
+ public static void validateElementName(String expectedName)
+ {
+ String serviceActualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the instance name is %s", expectedName));
+ assertTrue(serviceActualName.equalsIgnoreCase(expectedName));
+ }
+
+ public static void validateLinkProperties() throws IOException, UnsupportedFlavorException {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Validate Link properties values");
+ String actualNetworkRole = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.NETWORK_ROLE_XPATH.getValue());
+ String actualNfcType = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.NFC_TYPE_XPATH.getValue());
+ String actualPpsCapacity = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.PPS_CAPACITY_XPATH.getValue());
+ String actualNfType = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.NF_TYPE_XPATH.getValue());
+
+ assertTrue(actualNetworkRole.equalsIgnoreCase(PortMirroringEnum.NETWORK_ROLE_VALUE.getValue()));
+ assertTrue(actualNfcType.equalsIgnoreCase(PortMirroringEnum.NFC_TYPE_VALUE.getValue()));
+ assertTrue(actualPpsCapacity.equalsIgnoreCase(PortMirroringEnum.PPS_CAPACITY_VALUE.getValue()));
+ assertTrue(actualNfType.equalsIgnoreCase(PortMirroringEnum.NF_TYPE_VALUE.getValue()));
+ }
+
+
+
+}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PropertiesAssignmentVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PropertiesAssignmentVerificator.java
new file mode 100644
index 0000000000..fa68f4123d
--- /dev/null
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/PropertiesAssignmentVerificator.java
@@ -0,0 +1,18 @@
+package org.openecomp.sdc.ci.tests.verificator;
+
+import static org.testng.Assert.assertTrue;
+
+import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
+import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
+
+import com.aventstack.extentreports.Status;
+
+public class PropertiesAssignmentVerificator {
+
+ public static void validateFilteredPropertiesCount(int propertiesCount, String propertyLocation){
+ int actualPropertiesCount = GeneralUIUtils.getWebElementsListByContainsClassName(propertyLocation).size();
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating. Expected properties count: %s , Actual: %s", propertiesCount, actualPropertiesCount));
+ String errMsg = String.format("Properties amount not as expected, expected: %s ,Actual: %s", propertiesCount, actualPropertiesCount);
+ assertTrue(actualPropertiesCount == propertiesCount, errMsg);
+ }
+}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java
index 90861cacd5..407ce13328 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java
@@ -75,10 +75,15 @@ public class ServiceVerificator {
} else if (component instanceof ResourceReqDetails) {
responseAfterDrag = RestCDUtils.getResource((ResourceReqDetails) component, user).getResponse();
}
+ int size = 0;
JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
- int size = ((JSONArray) jsonResource.get("componentInstances")).size();
- assertTrue(size == numOfVFC, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size);
- ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified.");
+ if(jsonResource.get("componentInstances")!= null){
+ size = ((JSONArray) jsonResource.get("componentInstances")).size();
+ assertTrue(size == numOfVFC, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size);
+ ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified.");
+ }else{
+ assertTrue(false, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size);
+ }
}
public static void verifyServiceUpdatedInUI(ServiceReqDetails service) {
@@ -190,7 +195,7 @@ public class ServiceVerificator {
return customizationUUIDList;
}
- public static String getVFModulePropertieValue(ServiceReqDetails service, String propertyName, String moduleName) throws Exception {
+ public static String getVFModulePropertyValue(ServiceReqDetails service, String propertyName, String moduleName) throws Exception {
Service serviceObj = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service.getName(), service.getVersion());
List<GroupInstance> groupInstances = serviceObj.getComponentInstances().get(0).getGroupInstances();
List<GroupInstanceProperty> groupInstancesProperties = groupInstances.stream().
@@ -198,12 +203,12 @@ public class ServiceVerificator {
findFirst().
get().
convertToGroupInstancesProperties();
- String propertieValue = groupInstancesProperties.stream().
+ String propertyValue = groupInstancesProperties.stream().
filter(e -> e.getName().equals(propertyName)).
findFirst().
get().
getValue();
- return propertieValue;
+ return propertyValue;
}
public static boolean isEqualCustomizationUUIDsAfterChanges(List<String> listBefore, List<String> listAfter){
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ToscaValidation.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ToscaValidation.java
index 922c6e4a03..203368d361 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ToscaValidation.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ToscaValidation.java
@@ -1,21 +1,21 @@
package org.openecomp.sdc.ci.tests.verificator;
-import java.lang.reflect.Field;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import com.aventstack.extentreports.Status;
+import fj.data.Either;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
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.ToscaInputsTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.*;
import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;
+import org.openecomp.sdc.toscaparser.api.Group;
+import org.openecomp.sdc.toscaparser.api.Property;
import org.openecomp.sdc.toscaparser.api.elements.Metadata;
import org.openecomp.sdc.toscaparser.api.parameters.Input;
-import com.aventstack.extentreports.Status;
-
-import fj.data.Either;
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
public class ToscaValidation {
@@ -63,6 +63,278 @@ public class ToscaValidation {
return serviceToscaMetadataValidator;
}
+ public static Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidator(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, ToscaDefinition actualToscaDefinition){
+
+ SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group metadata...");
+ Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups = actualToscaDefinition.getTopology_template().getGroups();
+ Either<Boolean,Map<String,Object>> serviceToscaGroupMetadataValidator = compareServiceGroupMetadata(expectedServiceGroup, actualServiceGroups);
+ if(serviceToscaGroupMetadataValidator.isLeft()){
+ SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group metadata verification success");
+ }else{
+ SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group metadata verification failed" + serviceToscaGroupMetadataValidator.right().value().toString());
+ }
+ return serviceToscaGroupMetadataValidator;
+ }
+
+ public static Either<Boolean,Map<String,Object>> compareServiceGroupMetadata(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups) {
+
+ Map<String, Object> errorMap = new HashMap<>();
+ for (String groupName : expectedServiceGroup.keySet()){
+ if (actualServiceGroups.get(groupName) == null ){
+ errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml");
+ }else{
+ compareServiceGroupData(expectedServiceGroup.get(groupName).getMetadata(), actualServiceGroups.get(groupName).getMetadata(), groupName, errorMap);
+ }
+ }
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+ public static Either<Boolean, Map<String, Object>> compareServiceGroupData(ToscaServiceGroupsMetadataDefinition expectedServiceGroupMetadata, ToscaServiceGroupsMetadataDefinition actualServiceGroupMetadata, String groupName, Map<String, Object> errorMap) {
+
+ Field[] declaredFields = expectedServiceGroupMetadata.getClass().getDeclaredFields();
+ for (Field field : declaredFields){
+ try {
+ String expectedValue = field.get(expectedServiceGroupMetadata).toString();
+ String actualValue = field.get(actualServiceGroupMetadata).toString();
+ if(expectedValue != null && !expectedValue.toString().trim().equals("")) {
+ if (actualValue != null) {
+ Boolean result = compareValue(expectedValue, actualValue);
+ if(! result ){
+ errorMap.put("Data field [" + field.getName()+"] in group service metadata [" + groupName + "]", "expected: " + expectedValue + ", actual: " + actualValue);
+ }
+ } else {
+ errorMap.put("Data field [" + field.getName() + "] in group service metadata [" + groupName + "]", " does not exist in actual object");
+ System.out.println("Data field [" + field.getName() + "] in group service metadata [" + groupName + "] does not exist in actual object");
+ }
+ }
+ }catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+
+// ###########################UsingParser############################
+public static Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidatorUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups){
+
+ SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group metadata...");
+ Either<Boolean,Map<String,Object>> serviceToscaGroupMetadataValidator = compareServiceGroupMetadataUsingParser(expectedServiceGroup, actualServiceGroups);
+ if(serviceToscaGroupMetadataValidator.isLeft()){
+ SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group metadata verification vs. tosca parser success");
+ }else{
+ SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group metadata verification vs. tosca parser failed" + serviceToscaGroupMetadataValidator.right().value().toString());
+ }
+ return serviceToscaGroupMetadataValidator;
+}
+
+ public static Either<Boolean,Map<String,Object>> compareServiceGroupMetadataUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups) {
+
+ Map<String, Object> errorMap = new HashMap<>();
+ for (String groupName : expectedServiceGroup.keySet()){
+ Group actualGroup = getServiceToscaParserGroupFromObject(groupName, actualServiceGroups);
+ if (actualGroup == null ){
+ errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml");
+ }else{
+ compareServiceGroupDataUsingParser(expectedServiceGroup.get(groupName).getMetadata(), actualGroup.getMetadata(), groupName, errorMap);
+ }
+ }
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+ private static Group getServiceToscaParserGroupFromObject(String groupName, List<Group> actualServiceGroups) {
+ for(Group group : actualServiceGroups){
+ if(group.getName().equals(groupName)){
+ return group;
+ }
+ }
+ return null;
+ }
+
+ public static Either<Boolean, Map<String, Object>> compareServiceGroupDataUsingParser(ToscaServiceGroupsMetadataDefinition expectedServiceGroupMetadata, Metadata actualServiceGroupMetadata, String groupName, Map<String, Object> errorMap) {
+
+ Field[] declaredFields = expectedServiceGroupMetadata.getClass().getDeclaredFields();
+ for (Field field : declaredFields){
+ try {
+ String expectedValue = field.get(expectedServiceGroupMetadata).toString();
+ String actualValue = actualServiceGroupMetadata.getValue(field.getName());
+ if(expectedValue != null && !expectedValue.toString().trim().equals("")) {
+ if (actualValue != null) {
+ Boolean result = compareValue(expectedValue, actualValue);
+ if(! result ){
+ errorMap.put("Data field [" + field.getName()+"] in group service metadata [" + groupName + "]", "expected: " + expectedValue + ", actual: " + actualValue);
+ }
+ } else {
+ errorMap.put("Data field [" + field.getName() + "] in group service metadata [" + groupName + "]", " does not exist in actual object");
+ System.out.println("Data field [" + field.getName() + "] in group service metadata [" + groupName + "] does not exist in actual object");
+ }
+ }
+ }catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+// ############################################################################################
+
+
+
+ // ###########################Property UsingParser############################
+ public static Either<Boolean, Map<String, Object>> serviceToscaGroupPropertyValidatorUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups){
+
+ SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group property...");
+ Either<Boolean,Map<String,Object>> serviceToscaGroupMetadataValidator = compareServiceGroupPropertyUsingParser(expectedServiceGroup, actualServiceGroups);
+ if(serviceToscaGroupMetadataValidator.isLeft()){
+ SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group property verification vs. tosca parser success");
+ }else{
+ SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group property verification vs. tosca parser failed" + serviceToscaGroupMetadataValidator.right().value().toString());
+ }
+ return serviceToscaGroupMetadataValidator;
+ }
+
+ public static Either<Boolean,Map<String,Object>> compareServiceGroupPropertyUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups) {
+
+ Map<String, Object> errorMap = new HashMap<>();
+ for (String groupName : expectedServiceGroup.keySet()){
+ Group actualGroup = getServiceToscaParserGroupFromObject(groupName, actualServiceGroups);
+ if (actualGroup == null ){
+ errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml");
+ }else{
+ compareServiceGroupPropertyUsingParser(expectedServiceGroup.get(groupName).getProperties(), actualGroup.getProperties(), groupName, errorMap);
+ }
+ }
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+ public static Either<Boolean, Map<String, Object>> compareServiceGroupPropertyUsingParser(ToscaGroupPropertyDefinition expectedServiceGroupProperty, LinkedHashMap<String, Property> actualServiceGroupProperty, String groupName, Map<String, Object> errorMap) {
+
+ Field[] declaredFields = expectedServiceGroupProperty.getClass().getDeclaredFields();
+ for (Field field : declaredFields){
+ try {
+ String expectedValue = (String) field.get(expectedServiceGroupProperty);
+ String actualValue = null;
+ if(actualServiceGroupProperty.get(field.getName()).getValue()!= null) {
+ actualValue = actualServiceGroupProperty.get(field.getName()).getValue().toString();
+ }
+ if(expectedValue != null && !expectedValue.toString().trim().equals("")) {
+ if (actualValue != null) {
+ Boolean result = compareValue(expectedValue, actualValue);
+ if(! result ){
+ errorMap.put("Data field [" + field.getName()+"] in group service property [" + groupName + "]", "expected: " + expectedValue + ", actual: " + actualValue);
+ }
+ } else {
+ errorMap.put("Data field [" + field.getName() + "] in group service property [" + groupName + "]", " does not exist in actual object");
+ System.out.println("Data field [" + field.getName() + "] in group service property [" + groupName + "] does not exist in actual object");
+ }
+ }
+ }catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+// ############################################################################################
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+//?-------
+ public static Either<Boolean, Map<String, Object>> serviceToscaGroupPropertyValidator(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, ToscaDefinition actualToscaDefinition){
+
+ SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group property...");
+ Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups = actualToscaDefinition.getTopology_template().getGroups();
+ Either<Boolean,Map<String,Object>> serviceToscaGroupPropertyValidator = compareServiceGroupProperty(expectedServiceGroup, actualServiceGroups);
+ if(serviceToscaGroupPropertyValidator.isLeft()){
+ SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group property verification success");
+ }else{
+ SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group property verification failed" + serviceToscaGroupPropertyValidator.right().value().toString());
+ }
+ return serviceToscaGroupPropertyValidator;
+ }
+
+ public static Either<Boolean,Map<String,Object>> compareServiceGroupProperty(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups) {
+
+ Map<String, Object> errorMap = new HashMap<>();
+ for (String groupName : expectedServiceGroup.keySet()){
+ if (actualServiceGroups.get(groupName) == null ){
+ errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml");
+ }else{
+ compareServiceGroupProperty(expectedServiceGroup.get(groupName).getProperties(), actualServiceGroups.get(groupName).getProperties(), groupName, errorMap);
+ }
+ }
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+ public static Either<Boolean, Map<String, Object>> compareServiceGroupProperty(ToscaGroupPropertyDefinition expectedServiceGroupProperty, ToscaGroupPropertyDefinition actualServiceGroupProperty, String groupName, Map<String, Object> errorMap) {
+
+ Field[] declaredFields = expectedServiceGroupProperty.getClass().getDeclaredFields();
+ for (Field field : declaredFields){
+ try {
+ String expectedValue = (String) field.get(expectedServiceGroupProperty);
+ String actualValue = (String) field.get(actualServiceGroupProperty);
+ if(expectedValue != null && !expectedValue.toString().trim().equals("")) {
+ if (actualValue != null) {
+ Boolean result = compareValue(expectedValue, actualValue);
+ if(! result ){
+ errorMap.put("Data field [" + field.getName()+"] in group service property [" + groupName + "]", "expected: " + expectedValue + ", actual: " + actualValue);
+ }
+ } else {
+ errorMap.put("Data field [" + field.getName() + "] in group service property [" + groupName + "]", " does not exist in actual object");
+ System.out.println("Data field [" + field.getName() + "] in group service property [" + groupName + "] does not exist in actual object");
+ }
+ }
+ }catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ }
+
+ if(errorMap != null && !errorMap.isEmpty()){
+ return Either.right(errorMap);
+ }
+ return Either.left(true);
+ }
+
+
+// ----------------------------------
public static Either<Boolean, Map<String, Object>> componentToscaNodeTemplateMetadataValidator(Map<String, String> expectedMetadata, ToscaDefinition actualToscaDefinition, String nodeTemplateName, ComponentTypeEnum componentType, String componentName){
SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate "+ componentName + " " + componentType.getValue() + " node template TOSCA metadata...");
@@ -166,7 +438,7 @@ public class ToscaValidation {
Object expectedValue = field.get(expectedInputDefinition);
Object actualValue = field.get(actualInputDefinition);
// verification exclude fields as (immutable, hidden, constraints, entry_schema) according Renana
- if(expectedValue != null && expectedValue.toString().trim()!= "" && field.getName() != "name" && field.getName() != "immutable" && field.getName() != "hidden" && field.getName() != "constraints" && field.getName() != "entry_schema" && field.getName() != "required") {
+ if(expectedValue != null && !expectedValue.toString().trim().equals("") && field.getName() != "name" && field.getName() != "immutable" && field.getName() != "hidden" && field.getName() != "constraints" && field.getName() != "entry_schema" && field.getName() != "required") {
if (actualValue != null) {
compareInputValue(expectedInputDefinition, errorMap, field, expectedValue, actualValue);
} else {
@@ -285,5 +557,4 @@ public class ToscaValidation {
return actualInputsMap;
}
-
}
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
index 588e984106..02e92f8943 100644
--- 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
@@ -25,6 +25,8 @@ import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
+import java.lang.reflect.Field;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@@ -58,7 +60,9 @@ public class VfModuleVerificator {
int heatMetaGroupCount = 0;
int toscaDefinitionGroupCount = 0;
for (TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition) {
- heatMetaGroupCount = typeHeatMetaDefinition.getGroupHeatMetaDefinition().size();
+ if(!typeHeatMetaDefinition.getTypeName().equals("artifacts")) {
+ 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);
@@ -127,8 +131,14 @@ public class VfModuleVerificator {
for(String propertyType : PROPERTY_TYPES){
int numberOfTypes = (int) vfModules.stream().
- filter(e -> e.getProperties().containsKey(propertyType)).
- count();
+ // Get all declared fields from class ToscaGroupPropertyDefinition, collect them to List and check that current property exist and declared class
+ filter(e -> Arrays.asList(e.getProperties().getClass().getDeclaredFields()).stream().
+ map(p -> p.getName()).
+ collect(Collectors.toList()).
+ contains(propertyType)
+ ).
+ collect(Collectors.toList()).
+ size();
SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF property %s exist, Expected: %s, Actual: %s ", propertyType, vfModules.size(), numberOfTypes));
assertTrue(numberOfTypes == vfModules.size());
}
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
index 38fb351179..b2397cb23f 100644
--- 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
@@ -20,15 +20,7 @@
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 com.aventstack.extentreports.Status;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@@ -40,6 +32,7 @@ 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.VendorSoftwareProductObject;
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;
@@ -54,7 +47,12 @@ import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
-import com.aventstack.extentreports.Status;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import static org.testng.Assert.*;
public final class VfVerificator {
@@ -77,7 +75,8 @@ public final class VfVerificator {
ExtentTestActions.log(Status.INFO, "The link was verified.");
}
-
+
+// @Step(description="Verifying fields on General screen through UI ...")
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()));
@@ -94,6 +93,7 @@ public final class VfVerificator {
assertTrue(vf.getContactId().equals(ResourceGeneralPage.getContactIdText()));
}
+// @Step(description="Verifying fields on General screen through Backend ...")
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();
@@ -217,17 +217,22 @@ public final class VfVerificator {
}
}
- public static void verifyOnboardedVnfMetadata(String vspName, Map<String, String> vspMetadata) {
+ public static void verifyOnboardedVnfMetadata(String vspName, VendorSoftwareProductObject 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().trim()), "VSP category is not valid.");
- assertTrue(vspMetadata.get("vendorName").equals(ResourceGeneralPage.getVendorNameText()), "VSP vendor name is not valid.");
+ assertTrue(vspMetadata.getDescription().equals(ResourceGeneralPage.getDescriptionText()), "VSP description is not valid.");
+
+ String [] splitedSubCategorey = vspMetadata.getSubCategory().split("\\.");
+ String expectedSubCategory = splitedSubCategorey[splitedSubCategorey.length-1];
+ String actualSubCategory = GeneralUIUtils.getSelectedElementFromDropDown(ResourceGeneralPage.getCategoryDataTestsIdAttribute()).getText().trim().toLowerCase();
+
+ assertTrue(expectedSubCategory.equals(actualSubCategory), "VSP category is not valid.");
+ assertTrue(vspMetadata.getVendorName().equals(ResourceGeneralPage.getVendorNameText()), "VSP vendor name is not valid.");
assertTrue("1.0".equals(ResourceGeneralPage.getVendorReleaseText()), "VSP version is not valid.");
List<WebElement> 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.");
+ assertTrue(vspMetadata.getAttContact().equals(ResourceGeneralPage.getContactIdText()), "VSP attContact is not valid.");
}
public static void verifyIsElementDisabled(String elementLocator, String elementName){
diff --git a/ui-ci/src/main/resources/META-INF/aop-ajc.xml b/ui-ci/src/main/resources/META-INF/aop-ajc.xml
new file mode 100644
index 0000000000..8587abb2e1
--- /dev/null
+++ b/ui-ci/src/main/resources/META-INF/aop-ajc.xml
@@ -0,0 +1,15 @@
+<aspectj>
+
+<aspects>
+<aspect name="com.att.automation.common.report_portal_integration.aspects.StepAspects"/>
+<aspect name="com.att.automation.common.report_portal_integration.aspects.WebDriverAspects"/>
+<aspect name="com.att.automation.common.report_portal_integration.aspects.AssertAspects"/>
+<aspect name="com.att.automation.common.report_portal_integration.aspects.ReportPortalAspects"/>
+</aspects>
+<weaver options="-Xset:weaveJavaxPackages=true -warn:none -Xlint:ignore">
+<include within="org.openecomp.sdc.ci.tests..*"/>
+<include within="com.att.automation..*"/>
+<include within="com.epam..*"/>
+<include within="org.testng.TestNG"/>
+</weaver>
+</aspectj> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/ci/conf/attsdc.yaml b/ui-ci/src/main/resources/ci/conf/attsdc.yaml
index 9537cf5360..403d915aef 100644
--- a/ui-ci/src/main/resources/ci/conf/attsdc.yaml
+++ b/ui-ci/src/main/resources/ci/conf/attsdc.yaml
@@ -39,6 +39,8 @@ windowsDownloadDirectory: "c:\\apache-ftpserver-1.1.0\\res\\home\\"
systemUnderDebug: false
reportDBhost: dbhost
reportDBport: 27017
+sdcHttpMethod: https
+localDataCenter: DC-Automate01
useBrowserMobProxy: false
captureTraffic: false
diff --git a/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh b/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh
index 1b6f0258d6..e695db26b2 100644
--- a/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh
+++ b/ui-ci/src/main/resources/ci/scripts/addUsersFromList_new.sh
@@ -46,12 +46,12 @@ function addUser ()
firstName=`echo $user|awk '{print $3}'`
lastName=`echo $user|awk '{print $4}'`
email=`echo $user|awk '{print $5}'`
- curl --noproxy '*' -i -X post -d '{ "userId" : "'${userId}'", "role" : "'${role}'", "firstName" : "'${firstName}'", "lastName" : "'${lastName}'", "email" : "'${email}'" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" http://${IP}:8080/sdc2/rest/v1/user
+ curl --noproxy '*' -i -X post -d '{ "userId" : "'${userId}'", "role" : "'${role}'", "firstName" : "'${firstName}'", "lastName" : "'${lastName}'", "email" : "'${email}'" }' -H "Content-Type: application/json" -H "USER_ID: jh0003" https://${IP}:8443/sdc2/rest/v1/user
else
echo "Host" $IP "Is Unreachable"
fi
done
-curl --noproxy '*' -i -X post -d '{"consumerName": "ci","consumerSalt": "2a1f887d607d4515d4066fe0f5452a50","consumerPassword": "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"}' -H "Content-Type: application/json" -H "USER_ID: jh0003" -H "Authorization:Basic Y2k6MTIzNDU2" http://${IP}:8080/sdc2/rest/v1/consumers
+curl --noproxy '*' -i -X post -d '{"consumerName": "ci","consumerSalt": "2a1f887d607d4515d4066fe0f5452a50","consumerPassword": "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b"}' -H "Content-Type: application/json" -H "USER_ID: jh0003" -H "Authorization:Basic Y2k6MTIzNDU2" https://${IP}:8443/sdc2/rest/v1/consumers
}
diff --git a/ui-ci/src/main/resources/ci/scripts/sendMail.sh b/ui-ci/src/main/resources/ci/scripts/sendMail.sh
index 794534fc8a..ead4e343d6 100644
--- a/ui-ci/src/main/resources/ci/scripts/sendMail.sh
+++ b/ui-ci/src/main/resources/ci/scripts/sendMail.sh
@@ -6,8 +6,9 @@ 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"
+RECIPIENTS1="dl-sdcqa@att.com,ml636r@att.com,bl5783@att.com,ak314p@att.com,el489u@att.com,hk096q@att.com,bs5719@att.com"
+#RECIPIENTS2="dl-asdcqa@att.com"
+RECIPIENTS2="md9897@att.com,ms656r@att.com,al714h@att.com,ak991p@att.com,ya107f@att.com,bv095y@att.com,st198j@att.com,th0695@att.com,vk195d@att.com,gg980r@att.com,il0695@att.com,el489u@att.com"
source ExtentReport/versions.info
if [ -z "$REPORT_NAME" ]
diff --git a/ui-ci/src/main/resources/ci/scripts/startTest.sh b/ui-ci/src/main/resources/ci/scripts/startTest.sh
index 8bf35a5d88..e1065583aa 100644
--- a/ui-ci/src/main/resources/ci/scripts/startTest.sh
+++ b/ui-ci/src/main/resources/ci/scripts/startTest.sh
@@ -22,7 +22,7 @@ function isBoolean ()
VALUE=$2
if [[ ${VALUE} != "true" ]] && [[ ${VALUE} != "false" ]]; then
echo "Valid parameter" ${PARAM_NAME} "values are: true/false"
- help_usage
+ help_usage
fi
}
@@ -32,6 +32,27 @@ function prepareFailedXmlFile ()
PATTERN=`grep -w "test name=" ${FULL_PATH}/${TEST_SUITES}/$2 | awk -F'"' '{print $2}'`
sed '/<test name="'${PATTERN}'"/,/<!-- '${PATTERN}' --/d' $1 > ${FULL_PATH}/${TEST_SUITES}/${fileName}
sed -i 's/thread-count="[0-9]\+"/thread-count="1"/g' ${FULL_PATH}/${TEST_SUITES}/${fileName}
+ if [ -s "ExtentReport/ShortReport.csv" ]
+ then
+ SKIP_TESTS_LIST=$(cat ExtentReport/ShortReport.csv |awk -F, '{print $2}' | sed 's/&.*//g' | uniq)
+ for SKIP_TEST in ${SKIP_TESTS_LIST}; do
+ sed -i "s/.*\"${SKIP_TEST}\".*//g" ${FULL_PATH}/${TEST_SUITES}/${fileName};
+ done;
+ fi
+}
+
+function setUpdatedTimeToReport ()
+{
+ LINE_NUMBER_OF_START_REPORT_DATE=`grep -A1 -nw "Start" ExtentReport/SDC_UI_Extent_Report.html | tail -1 | awk '{print $1}' | tr -d -`
+ END_REPORT_DATE=`grep -A1 -nw "End" ExtentReport/SDC_UI_Extent_Report.html | tail -1 | awk -F'[>|<]' '{print $3}'`
+ EPOCH_START_REPORT_DATE=`date --date="${1}" +%s`
+ EPOCH_END_REPORT_DATE=`date --date="${END_REPORT_DATE}" +%s`
+ let DIFF_EPOCH_TIME=${EPOCH_END_REPORT_DATE}-${EPOCH_START_REPORT_DATE}
+ TAKEN_TIME_IN_MINUTES=`echo $((${DIFF_EPOCH_TIME}/60))`
+ LINE_NUMBER_OF_TAKEN_REPORT_TIME=`grep -A1 -nw "Time Taken" ExtentReport/SDC_UI_Extent_Report.html | tail -1 | awk '{print $1}' | tr -d -`
+ PATTERN="div class='panel-lead'>";
+ sed -i "${LINE_NUMBER_OF_START_REPORT_DATE}s/${PATTERN}.*\</${PATTERN}$1\<\//1" ExtentReport/SDC_UI_Extent_Report.html
+ sed -i "${LINE_NUMBER_OF_TAKEN_REPORT_TIME}s/${PATTERN}.*\</${PATTERN}${TAKEN_TIME_IN_MINUTES} min\<\//1" ExtentReport/SDC_UI_Extent_Report.html
}
#main
@@ -92,7 +113,7 @@ ADD_USERS_SCRIPT="addUsersFromList_new.sh"
USER_LIST="conf/userList.txt"
chmod +x ${ADD_USERS_SCRIPT}
echo "add users..."
-`./${ADD_USERS_SCRIPT} -ip ${BE_IP} -f ${USER_LIST}`
+./${ADD_USERS_SCRIPT} -ip ${BE_IP} -f ${USER_LIST}
@@ -117,7 +138,7 @@ if [ ${RERUN} == "true" ]; 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="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
@@ -128,6 +149,11 @@ source ExtentReport/versions.info
now=$(date +'%Y-%m-%d_%H_%M')
REPORT_NAME=${now}
VERSION=${osVersion}
+REPORT_START_DATE=${reportStartTime}
+
+if [ ${RERUN} == "true" ]; then
+ setUpdatedTimeToReport "${REPORT_START_DATE}";
+fi
if [[ $env == *"DEV20"* ]]
then
@@ -139,7 +165,7 @@ fi
COPY_REPORT_SCRIPT="copyToStorage.sh"
chmod +x ${COPY_REPORT_SCRIPT}
echo "copy report to storage..."
-sh ./${COPY_REPORT_SCRIPT} ${REPORT_NAME} ${VERSION} ${MYENV}
+( ./${COPY_REPORT_SCRIPT} ${REPORT_NAME} ${VERSION} ${MYENV} )
MAILING_SCRIPT_NAME="sendMail.sh"
diff --git a/ui-ci/src/main/resources/ci/testSuites/PortMirroring.xml b/ui-ci/src/main/resources/ci/testSuites/PortMirroring.xml
new file mode 100644
index 0000000000..da03e8285e
--- /dev/null
+++ b/ui-ci/src/main/resources/ci/testSuites/PortMirroring.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
+<suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="2">
+ <test name="PortMirroringTests">
+ <classes>
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.PortMirroring"/>
+ </classes>
+ </test>
+</suite> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml b/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml
index f4f99db3a1..3e3efdd9cd 100644
--- a/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml
+++ b/ui-ci/src/main/resources/ci/testSuites/andreyPara.xml
@@ -1,10 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="2" data-provider-thread-count="2">
- <test name="uiSanity">
+ <suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="2" data-provider-thread-count="2">
+
+<listeners>
+ <listener class-name="com.att.automation.common.report_portal_integration.listeners.ReportPortalListener"/>
+</listeners>
+
+ <test name="VF1">
<classes>
- <class name="org.openecomp.sdc.ci.tests.execute.sanity.VfArtifacts"/>
- <!-- <class name="org.openecomp.sdc.ci.tests.execute.sanity.Vf"/> -->
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.Vf">
+ <methods>
+ <include name="updateVF"/>
+ </methods>
+ </class>
+
+ </classes>
+ </test> <!-- uitests -->
+
+ <test name="VF2">
+ <classes>
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.Vf">
+ <methods>
+ <include name="addUpdateDeleteDeploymentArtifactToVfTest"/>
+ <include name="addPropertiesToVfcInstanceInVfTest"/>
+ </methods>
+ </class>
+
</classes>
</test> <!-- uitests -->
</suite> <!-- uisuite --> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/ci/testSuites/devOnboardE2EOneFileSanity.xml b/ui-ci/src/main/resources/ci/testSuites/devOnboardE2EOneFileSanity.xml
index 73ddc90cf3..8802e9f8ef 100644
--- a/ui-ci/src/main/resources/ci/testSuites/devOnboardE2EOneFileSanity.xml
+++ b/ui-ci/src/main/resources/ci/testSuites/devOnboardE2EOneFileSanity.xml
@@ -4,7 +4,7 @@
<test name="uitests">
<classes>
<!--onboard-->
- <class name="org.openecomp.sdc.ci.tests.execute.sanity.Onboard">
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.OnboardingFlowsUI">
<methods>
<include name="onboardVNFTestSanityOneFile"/>
</methods>
diff --git a/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml b/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml
index 87a52bde7a..b0bcc333a5 100644
--- a/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml
+++ b/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml
@@ -1,17 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="2" data-provider-thread-count="2">
+<suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="4" data-provider-thread-count="2">
<parameter name="makeDistribution" value="true"/>
<test name="uiSanity">
<classes>
- <class name="org.openecomp.sdc.ci.tests.dataProvider.OnbordingDataProviders">
- <methods>
- <include name="OnbordingDataProviders"/>
- </methods>
- </class>
- <class name="org.openecomp.sdc.ci.tests.execute.sanity.Onboard">
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.ToscaValidationTest"/>
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.OnboardingFlowsUI">
<methods>
<exclude name="onboardVNFTestSanity"/>
<exclude name="onboardVNFShotFlow"/>
@@ -21,6 +17,7 @@
</class>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.CatalogLeftPanelTest"/>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.Vf"/>
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.VfAPI"/>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.Service"/>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.ImportVFCAsset"/>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.ImportDCAE"/>
@@ -37,7 +34,7 @@
<class name="org.openecomp.sdc.ci.tests.US.MIBsArtifactsOnResourceInstance"/>
<class name="org.openecomp.sdc.ci.tests.US.NewArtifactTypeGuide"/>
<class name="org.openecomp.sdc.ci.tests.US.RemoveRestrictionOfDeploymentArtifacts"/>
- <class name="org.openecomp.sdc.ci.tests.execute.sanity.OnboardingFlows"/>
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.OnboardingFlowsThroughAPI"/>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.PortMirroring"/>
<!-- <class name="org.openecomp.sdc.ci.tests.US.AddComponentInstancesArtifactsInCsar"/> -->
diff --git a/ui-ci/src/main/resources/log4j2.xml b/ui-ci/src/main/resources/log4j2.xml
new file mode 100644
index 0000000000..5a92e611b0
--- /dev/null
+++ b/ui-ci/src/main/resources/log4j2.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Configuration status="ERROR" packages="com.epam.ta.reportportal.log4j.appender">
+ <properties>
+ <property name="pattern">[%d{HH:mm:ss,SSS}] %-5p (%F:%L) - %m%n</property>
+ <property name="report.pattern">%m%n</property>
+ </properties>
+ <Appenders>
+ <Console name="Console" target="SYSTEM_OUT">
+ <PatternLayout pattern="${pattern}"/>
+ </Console>
+ <ReportPortalLog4j2Appender name="ReportPortalAppender">
+ <PatternLayout pattern="${pattern}"/>
+ </ReportPortalLog4j2Appender>
+ <Console name="ConsoleReport" target="SYSTEM_OUT">
+ <PatternLayout pattern="${report.pattern}"/>
+ </Console>
+ <ReportPortalLog4j2Appender name="ReportPortalLogReport">
+ <PatternLayout pattern="${report.pattern}"/>
+ </ReportPortalLog4j2Appender>
+ </Appenders>
+ <Loggers>
+ <Root level="all">
+ <AppenderRef ref="Console"/>
+ <AppenderRef ref="ReportPortalAppender"/>
+ </Root>
+ <logger name="upload.file.to.reportportal" level="all" additivity="false">
+ <AppenderRef ref="ReportPortalAppender"/>
+ </logger>
+ <logger name="logger.report" level="all" additivity="false">
+<!-- <AppenderRef ref="ConsoleReport"/> -->
+ <AppenderRef ref="ReportPortalLogReport"/>
+ </logger>
+ <logger name="rp.org.apache.http" level="WARN"/>
+ <logger name="org.apache.http" level="WARN"/>
+ <logger name="com.epam.reportportal" level="WARN"/>
+ <logger name="CouchDbDataAdapter" level="WARN"/>
+ </Loggers>
+</Configuration> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/reportportal.properties b/ui-ci/src/main/resources/reportportal.properties
new file mode 100644
index 0000000000..373610ef62
--- /dev/null
+++ b/ui-ci/src/main/resources/reportportal.properties
@@ -0,0 +1,5 @@
+rp.endpoint = http://reportportal.intl.att.com:8080
+rp.uuid = 4be0a132-e2ea-4a8c-a0d4-54367259d8d2
+rp.project= ASDC
+rp.mode = DEBUG
+rp.enable = true \ No newline at end of file
diff --git a/utils/DmaapPublisher/pom.xml b/utils/DmaapPublisher/pom.xml
new file mode 100644
index 0000000000..6152fdff83
--- /dev/null
+++ b/utils/DmaapPublisher/pom.xml
@@ -0,0 +1,131 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.openecomp.sdc</groupId>
+ <artifactId>dmaap-publisher</artifactId>
+ <version>1.0.0</version>
+
+
+ <properties>
+ <fasterxml.jackson.version>2.8.6</fasterxml.jackson.version>
+ </properties>
+
+ <dependencies>
+ <!--spock testing-->
+ <dependency>
+ <groupId>org.spockframework</groupId>
+ <artifactId>spock-core</artifactId>
+ <version>1.1-groovy-2.4</version>
+ <scope>test</scope>
+ </dependency>
+ <!--groovy-->
+ <dependency>
+ <groupId>org.codehaus.groovy</groupId>
+ <artifactId>groovy</artifactId>
+ <version>2.4.11</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.7</version>
+ </dependency>
+ <dependency>
+ <groupId>com.att.nsa</groupId>
+ <artifactId>dmaapClient</artifactId>
+ <version>0.2.16</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.7.25</version>
+ </dependency>
+ <dependency>
+ <groupId>args4j</groupId>
+ <artifactId>args4j</artifactId>
+ <version>2.33</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>22.0</version>
+ </dependency>
+ <!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ <version>1.18</version>
+ </dependency>
+
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>2.8.47</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <version>3.8.0</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.6.1</version>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.0.0</version>
+ <configuration>
+ <createDependencyReducedPom>true</createDependencyReducedPom>
+ <filters>
+ <filter>
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <transformers>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass>org.openecomp.sdc.dmaap.DmaapPublisher</mainClass>
+ </transformer>
+ </transformers>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+</project> \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/CliArgs.java b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/CliArgs.java
new file mode 100644
index 0000000000..38e53c824f
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/CliArgs.java
@@ -0,0 +1,59 @@
+package org.openecomp.sdc.dmaap;
+
+import org.kohsuke.args4j.Option;
+import com.google.common.base.MoreObjects;
+
+public class CliArgs {
+
+ @Option(name="yml",aliases = {"-YML","YML","-yml","-YAML","YAML","-yaml"}, usage="mandatory arg. YAML filename", required=true)
+ private String yamlFilename;
+
+ @Option(name="path",aliases = {"-path","PATH","-PATH"}, usage="mandatory arg. path to the yaml file which contains topic config (publisher data + messages)", required=true)
+ private String yamlPath;
+
+ @Option(name="cr",aliases = {"CR","-cr","-CR"}, usage="optional arg. concurrent requests", required=false)
+ private String concurrentRequests;
+
+ @Option(name="notification",aliases = {"NOTIFICATION","-NOTIFICATION","-notification"}, usage="optional load dynamic messages", required=false)
+ private String notificationData;
+
+ public String getYamlPath() {
+ return yamlPath;
+ }
+
+ public String getYamlFilename() {
+ return yamlFilename;
+ }
+
+ public void setYamlPath(String yamlPath) {
+ this.yamlPath = yamlPath;
+ }
+
+
+ public String getConcurrentRequests() {
+ return concurrentRequests;
+ }
+
+ public void setConcurrentRequests(String concurrentRequests) {
+ this.concurrentRequests = concurrentRequests;
+ }
+
+ public String getNotificationData() {
+ return notificationData;
+ }
+
+
+ public void setYamlFilename(String yamlFilename) {
+ this.yamlFilename = yamlFilename;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("yamlPath", yamlPath)
+ .add("concurrentRequests", concurrentRequests)
+ .toString();
+ }
+
+
+}
diff --git a/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublishTool.java b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublishTool.java
new file mode 100644
index 0000000000..61e48fa50e
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublishTool.java
@@ -0,0 +1,97 @@
+package org.openecomp.sdc.dmaap;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.Yaml;
+
+import com.att.nsa.mr.client.MRBatchingPublisher;
+import com.att.nsa.mr.client.MRClientFactory;
+import com.att.nsa.mr.client.MRPublisher.message;
+
+public class DmaapPublishTool {
+
+ private static final Logger logger = LoggerFactory.getLogger(DmaapPublishTool.class);
+ final private TopicConfig topicConfig;
+
+ public DmaapPublishTool(String yamlPath) throws FileNotFoundException {
+ topicConfig = loadTopicConfig(yamlPath);
+ System.out.println("yaml file loaded.");
+ }
+ public DmaapPublishTool(String yamlPath , String notifications) throws FileNotFoundException {
+ topicConfig = loadTopicConfig(yamlPath);
+ if (StringUtils.isNotBlank(notifications) )
+ topicConfig.add( notifications );
+ System.out.println("yaml file loaded.");
+ }
+
+ public void addNotifications(Collection<String> notification){
+ topicConfig.addAll( notification );
+ }
+
+ //safe stream doesn't throw null pointer exception
+ public <T> Collection<T> safe(Collection<T> obj){
+ return Optional.ofNullable(obj).orElse(Collections.emptySet());
+ }
+ public <T> List<T> safe(List<T> obj){
+ return Optional.ofNullable(obj).orElse(Collections.emptyList());
+ }
+
+ public void publish(String path) throws IOException, InterruptedException {
+ MRBatchingPublisher pub = createPublisher( topicConfig, path );
+ System.out.println( "pending message count -> "+pub.getPendingMessageCount() );
+ List<String> list = this.topicConfig.getIncomingTopicMessages();
+ for(String msg : safe(list) ){
+ publishOne( pub , msg );
+ }
+ closePublisher(pub);
+ }
+
+ private MRBatchingPublisher createPublisher(TopicConfig topicConfig,String path) throws IOException {
+ MRBatchingPublisher publisher = MRClientFactory.createBatchingPublisher(Objects.requireNonNull(Util.toPath(path,topicConfig.getPublisherPropertiesFilePath())));
+ System.out.println("publisher created.");
+ return publisher;
+ }
+
+ private TopicConfig loadTopicConfig(String yamlPath) throws FileNotFoundException {
+ File yamlFile = new File(Objects.requireNonNull(yamlPath));
+ InputStream input = new FileInputStream(yamlFile);
+ Yaml yamlHelper = new Yaml();
+ return yamlHelper.loadAs(input, TopicConfig.class);
+ }
+
+ private void publishOne(MRBatchingPublisher pub, String msg) throws IOException, InterruptedException {
+ System.out.println("sending: " + msg);
+ pub.send(msg);
+ System.out.println("message sent.");
+ }
+
+ private void closePublisher(MRBatchingPublisher pub) throws IOException, InterruptedException {
+ System.out.println("closing publisher...");
+ // close the publisher to make sure everything's sent before exiting. The batching
+ // publisher interface allows the app to get the set of unsent messages. It could
+ // write them to disk, for example, to try to send them later.
+ final List<message> stuck = pub.close(20, TimeUnit.SECONDS);
+ if(!stuck.isEmpty())
+ {
+ final String errMsg = stuck.size() + " messages unsent";
+ logger.error(errMsg);
+ System.err.println(errMsg);
+ }
+ else
+ {
+ final String successMsg = "Clean exit; all messages sent.";
+ logger.info(successMsg);
+ System.out.println(successMsg);
+ }
+ }
+}
diff --git a/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublisher.java b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublisher.java
new file mode 100644
index 0000000000..fd558356ed
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/DmaapPublisher.java
@@ -0,0 +1,149 @@
+package org.openecomp.sdc.dmaap;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.OptionHandlerFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.function.Consumer;
+import java.util.stream.IntStream;
+
+
+import static org.openecomp.sdc.dmaap.Util.*;
+
+public class DmaapPublisher {
+ private static final Logger logger = LoggerFactory.getLogger(DmaapPublisher.class);
+ private static RequestManager requestManager ;
+ private static final ConcurrentLinkedDeque notificationBuffer = new ConcurrentLinkedDeque();
+
+
+ private static final List<Long> registeredTasks = new CopyOnWriteArrayList<>();
+ private DmaapPublisher() {}
+
+ public static void add(String notification){
+ notificationBuffer.add( notification );
+ }
+ public static void addAll(List<String> notifications){
+ notificationBuffer.addAll( notifications );
+ }
+ public static void main(String[] args) {
+ doPublish(args);
+ }
+
+ private static void doPublish( String[] args ) {
+ CliArgs cliArgs = new CliArgs();
+ CmdLineParser parser = new CmdLineParser(cliArgs);
+
+ try {
+ // parse the arguments.
+ parser.parseArgument( args );
+ doPublish( cliArgs );
+ }
+ catch(CmdLineException e) {
+ logger.error("#doPublish - failed to parse arguments.", e);
+ printUsage(parser, e);
+ return;
+ }
+ }
+
+ public static void doPublish( CliArgs cliArgs ){
+ try {
+ // parse the arguments.
+ DmaapPublishTool tool = new DmaapPublishTool( toPath(cliArgs.getYamlPath() , cliArgs.getYamlFilename()) , cliArgs.getNotificationData() );
+ Collection<String> notifications = new ArrayList<String>( notificationBuffer );
+ tool.addNotifications( notifications );
+ notificationBuffer.removeAll(notifications);
+ Integer concurrentRequestCount = 1;
+ if ( StringUtils.isNotBlank( cliArgs.getConcurrentRequests() ) )
+ concurrentRequestCount = Integer.parseInt( cliArgs.getConcurrentRequests() );
+ requestManager = new RequestManager( concurrentRequestCount );
+
+ IntStream.range(0,concurrentRequestCount).forEach( it -> {
+ //region - report upon finish mechanishem
+ long ticket = System.nanoTime();
+ registeredTasks.add( ticket );
+ Consumer callback = ( uniqueTicket ) -> {
+ synchronized ( registeredTasks ){
+ registeredTasks.remove( (long)uniqueTicket );
+ registeredTasks.notifyAll();
+ }};
+
+ RunnableReporter task = new RunnableReporter( ticket , tool , cliArgs , callback );
+ requestManager.getExecutor().execute( task ) ;
+ });
+ }
+ catch(NumberFormatException e) {
+ logger.error("#doPublish - failed to parse argument CR.", e);
+ return;
+ }
+ catch(Exception e) {
+ logger.error("#doPublish - failed to publish.", e);
+ }
+ }
+
+ public static class RunnableReporter implements Runnable{
+
+ final private long ticket ;
+ final private DmaapPublishTool tool;
+ final private CliArgs cliArgs;
+ final Consumer reporter;
+
+ public RunnableReporter(final long ticket , final DmaapPublishTool tool , final CliArgs args , Consumer reporter){
+ this.ticket = ticket ;
+ this.tool = tool ;
+ this.cliArgs = args ;
+ this.reporter = reporter;
+ }
+ @Override
+ public void run() {
+ try {
+ tool.publish( cliArgs.getYamlPath() );
+ reporter.accept(ticket);
+ }catch(IOException e){
+ logger.error("#doPublish - failed to publish.", e);
+ }catch(InterruptedException e){
+ logger.error("#doPublish - cannot complete publish, thread interuppted.", e);
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+
+ public static List<Long> getRegisteredTasks() {
+ return registeredTasks;
+ }
+
+ public static void preparePublish( String path, String filename , String concurrentRequests ){
+
+ CliArgs cliArgs = new CliArgs();
+ if ( StringUtils.isNotBlank( filename ) )
+ cliArgs.setYamlFilename( filename );
+ if ( StringUtils.isNotBlank( path ) )
+ cliArgs.setYamlPath( path );
+ if ( NumberUtils.isCreatable( concurrentRequests ) )
+ cliArgs.setConcurrentRequests( concurrentRequests );
+
+ doPublish( cliArgs );
+
+ }
+
+
+ private static void printUsage(CmdLineParser parser, CmdLineException e) {
+ System.err.println( e.getMessage() );
+ System.err.println("java DmaapPublisher [options...] arguments...");
+ // print the list of available options
+ parser.printUsage(System.err);
+ System.err.println();
+ // print option sample. This is useful some time
+ System.err.println(" Example: java DmaapPublisher " + parser.printExample(OptionHandlerFilter.ALL));
+
+ }
+}
diff --git a/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/RequestManager.java b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/RequestManager.java
new file mode 100644
index 0000000000..597baac2bd
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/RequestManager.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.dmaap;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+public class RequestManager {
+
+ private Executor executor;
+
+ public RequestManager(int poolSize ){
+ int sz = Math.max( poolSize , 1);
+ int recommendedMaxSz = Runtime.getRuntime().availableProcessors() * 2;
+ executor = Executors.newFixedThreadPool( Math.min( sz , recommendedMaxSz ) );
+ }
+
+ public Executor getExecutor() {
+ return executor;
+ }
+}
diff --git a/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/TopicConfig.java b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/TopicConfig.java
new file mode 100644
index 0000000000..a5b43ad0d5
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/TopicConfig.java
@@ -0,0 +1,52 @@
+package org.openecomp.sdc.dmaap;
+
+import com.google.common.base.MoreObjects;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+public class TopicConfig {
+
+ private String publisherPropertiesFilePath;
+ private String[] topicMessages; //messages from file
+ private final List<String> incomingTopicMessages = Collections.synchronizedList( new ArrayList<String>() ); //incoming messages from network stream|Main
+
+ public String getPublisherPropertiesFilePath() {
+ return publisherPropertiesFilePath;
+ }
+ public void setPublisherPropertiesFilePath(String publisherPropertiesFilePath) {
+ this.publisherPropertiesFilePath = publisherPropertiesFilePath;
+ }
+
+ public List<String> getIncomingTopicMessages() {
+ return incomingTopicMessages;
+ }
+ public String[] getTopicMessages() {
+ return topicMessages;
+ }
+ //add incoming message
+ public TopicConfig add( String notifications ){
+ incomingTopicMessages.add( notifications);
+ return this;
+ }
+
+ public TopicConfig addAll( Collection<String> notifications ){
+ incomingTopicMessages.addAll( notifications );
+ return this;
+ }
+
+ public void setTopicMessages(String[] topicMessages) {
+ this.topicMessages = topicMessages;
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("publisherPropertiesFilePath", publisherPropertiesFilePath)
+ .add("topicMessages", topicMessages)
+ .toString();
+ }
+
+}
diff --git a/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/Util.java b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/Util.java
new file mode 100644
index 0000000000..491b07abdd
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/java/org/openecomp/sdc/dmaap/Util.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.dmaap;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.nio.file.InvalidPathException;
+
+public class Util {
+
+ public static String toPath(String path , String filename) throws InvalidPathException{
+ if (StringUtils.isNotBlank(path) ){
+ if (path.trim().endsWith("/") || path.trim().endsWith("/")){
+ return path+(filename!=null ? filename : "");
+ }
+ return path+"/"+(filename!=null ? filename : "");
+
+ }
+ throw new InvalidPathException("wrong path configuration cannot find path -> ",path);
+ }
+}
diff --git a/utils/DmaapPublisher/src/main/resources/catalogMgmt.properties b/utils/DmaapPublisher/src/main/resources/catalogMgmt.properties
new file mode 100644
index 0000000000..ff739f1e3f
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/resources/catalogMgmt.properties
@@ -0,0 +1,35 @@
+TransportType=DME2
+Latitude =32.109333
+Longitude =34.855499
+Version =1.0
+ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+Environment =TEST
+Partner=BOT_R
+routeOffer=MR1
+SubContextPath =/
+Protocol =https
+MethodType =POST
+username = m09875@sdc.att.com
+password =Aa123456
+contenttype = application/json
+Authorization = Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2
+authKey=
+authDate=
+#Dmaap Server Url port 3904-HTTP 3905-https
+host=olsd004.wnsnet.attws.com:3905
+###topic=com.att.ccd.CCD-CatalogManagement-go539p or com.att.sdc.SDCforTestDev | com.att.sdc.23911-SDCforTestDev-v001
+#com.att.sdc.23911-scdc001dev001test-v1
+topic=com.att.sdc.23911-SDCforTestDev-v001
+partition=1
+maxBatchSize=100
+maxAgeMs=250
+AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler
+AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler
+AFT_DME2_REQ_TRACE_ON=true
+AFT_ENVIRONMENT=AFTUAT
+AFT_DME2_EP_CONN_TIMEOUT=15000
+AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000
+AFT_DME2_EP_READ_TIMEOUT_MS=50000
+sessionstickinessrequired=NO
+DME2preferredRouterFilePath=src/main/resources/preferredRouter.txt
+MessageSentThreadOccurance=50 \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/main/resources/catalogMgmt.yaml b/utils/DmaapPublisher/src/main/resources/catalogMgmt.yaml
new file mode 100644
index 0000000000..04ac9fb992
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/resources/catalogMgmt.yaml
@@ -0,0 +1,7 @@
+publisherPropertiesFilePath: "catalogMgmt.properties"
+topicMessages:
+ - "{\"operationalEnvironmentId\": \"1234\",\"operationalEnvironmentName\":\"Op Env Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"Test\",\"workloadContext\":\"VNF_E2E-IST\",\"action\":\"CREATE\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"product\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"logo\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"availabilitymatrix\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"product\",\"availabilitymatrix\"],\"republish\":\"No\"}" \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/main/resources/catalogWfMgmt.properties b/utils/DmaapPublisher/src/main/resources/catalogWfMgmt.properties
new file mode 100644
index 0000000000..119c94ef3b
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/resources/catalogWfMgmt.properties
@@ -0,0 +1,32 @@
+TransportType=DME2
+Latitude =32.109333
+Longitude =34.855499
+Version =1.0
+ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+Environment =TEST
+Partner=BOT_R
+routeOffer=MR1
+SubContextPath =/
+Protocol =https
+MethodType =POST
+username =m13331@ccd.att.com
+password =Aa123456
+contenttype = application/json
+authKey=
+authDate=
+host=olsd004.wnsnet.attws.com:3904
+###topic=com.att.ccd.CCD-CatalogWorkflowManagement-go539p-v1
+topic=com.att.ccd.CCD-CatalogWorkflowManagement-v1
+partition=1
+maxBatchSize=100
+maxAgeMs=250
+AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler
+AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler
+AFT_DME2_REQ_TRACE_ON=true
+AFT_ENVIRONMENT=AFTUAT
+AFT_DME2_EP_CONN_TIMEOUT=15000
+AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000
+AFT_DME2_EP_READ_TIMEOUT_MS=50000
+sessionstickinessrequired=NO
+DME2preferredRouterFilePath=resources/preferredRouter.txt
+MessageSentThreadOccurance=50 \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/main/resources/catalogWfMgmt.yaml b/utils/DmaapPublisher/src/main/resources/catalogWfMgmt.yaml
new file mode 100644
index 0000000000..da2ebd635a
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/resources/catalogWfMgmt.yaml
@@ -0,0 +1,6 @@
+publisherPropertiesFilePath: "resources/catalogWfMgmt.properties"
+topicMessages:
+ - "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"action\":\"Activate\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"action\":\"Rollback\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"action\":\"Activate\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"action\":\"Activate\"}" \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/main/resources/preferredRouter.txt b/utils/DmaapPublisher/src/main/resources/preferredRouter.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/utils/DmaapPublisher/src/main/resources/preferredRouter.txt
diff --git a/utils/DmaapPublisher/src/test/java/org/openecomp/sdc/dmaap/DmaapPublisherTest.java b/utils/DmaapPublisher/src/test/java/org/openecomp/sdc/dmaap/DmaapPublisherTest.java
new file mode 100644
index 0000000000..19dbdeaed4
--- /dev/null
+++ b/utils/DmaapPublisher/src/test/java/org/openecomp/sdc/dmaap/DmaapPublisherTest.java
@@ -0,0 +1,22 @@
+package org.openecomp.sdc.dmaap;
+
+import org.junit.Test;
+
+import java.io.File;
+import java.net.URL;
+import java.nio.file.Paths;
+
+import static org.junit.Assert.*;
+
+public class DmaapPublisherTest {
+ @Test
+ public void main() throws Exception {
+ File resource = new File("src/test/resources");
+ String absPath = resource.getAbsolutePath();
+
+ String msg = "{\"operationalEnvironmentId\":\"12345\",\"operationalEnvironmentName\":\"Op_Env_Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"Test\",\"workloadContext\":\"VNF_E2E-IST\",\"action\":\"CREATE\"}";
+ String cmd = "-cr 5 "+ "-notification=" + msg+ " -path "+absPath+" -yaml catalogMgmtTest.yaml" ;
+ DmaapPublisher.main( cmd.split(" ") );
+ Thread.sleep(10000);
+ }
+} \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/test/resources/catalogMgmtTest.properties b/utils/DmaapPublisher/src/test/resources/catalogMgmtTest.properties
new file mode 100644
index 0000000000..7f922214a9
--- /dev/null
+++ b/utils/DmaapPublisher/src/test/resources/catalogMgmtTest.properties
@@ -0,0 +1,34 @@
+TransportType=DME2
+Latitude =32.109333
+Longitude =34.855499
+Version =1.0
+ServiceName =dmaap-v1.dev.dmaap.dt.saat.acsi.att.com/events
+Environment =TEST
+Partner=BOT_R
+routeOffer=MR1
+SubContextPath =/
+Protocol =https
+MethodType =POST
+username = m09875@sdc.att.com
+password =Aa123456
+contenttype = application/json
+Authorization = Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2
+authKey=
+authDate=
+#Dmaap Server Url port 3904-HTTP 3905-https
+host=olsd004.wnsnet.attws.com:3905
+###topic=com.att.ccd.CCD-CatalogManagement-go539p or com.att.sdc.SDCforTestDev | com.att.sdc.23911-SDCforTestDev-v001
+topic=com.att.sdc.23911-SDCforTestDev-v001
+partition=1
+maxBatchSize=100
+maxAgeMs=250
+AFT_DME2_EXCHANGE_REQUEST_HANDLERS=com.att.nsa.test.PreferredRouteRequestHandler
+AFT_DME2_EXCHANGE_REPLY_HANDLERS=com.att.nsa.test.PreferredRouteReplyHandler
+AFT_DME2_REQ_TRACE_ON=true
+AFT_ENVIRONMENT=AFTUAT
+AFT_DME2_EP_CONN_TIMEOUT=15000
+AFT_DME2_ROUNDTRIP_TIMEOUT_MS=240000
+AFT_DME2_EP_READ_TIMEOUT_MS=50000
+sessionstickinessrequired=NO
+DME2preferredRouterFilePath=src/test/resources/preferredRouter.txt
+MessageSentThreadOccurance=50 \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/test/resources/catalogMgmtTest.yaml b/utils/DmaapPublisher/src/test/resources/catalogMgmtTest.yaml
new file mode 100644
index 0000000000..f55641d859
--- /dev/null
+++ b/utils/DmaapPublisher/src/test/resources/catalogMgmtTest.yaml
@@ -0,0 +1,7 @@
+publisherPropertiesFilePath: "catalogMgmtTest.properties"
+topicMessages:
+
+ - "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"product\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"logo\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"availabilitymatrix\"],\"republish\":\"No\"}"
+ #- "{\"transactionId\": \"221e8cbe-493d-4848-b46c-a552b8928075\",\"notificationReason\":[\"product\",\"availabilitymatrix\"],\"republish\":\"No\"}" \ No newline at end of file
diff --git a/utils/DmaapPublisher/src/test/resources/preferredRouter.txt b/utils/DmaapPublisher/src/test/resources/preferredRouter.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/utils/DmaapPublisher/src/test/resources/preferredRouter.txt
diff --git a/utils/webseal-simulator/pom.xml b/utils/webseal-simulator/pom.xml
index c0e9fe6327..fb1246d3f2 100644
--- a/utils/webseal-simulator/pom.xml
+++ b/utils/webseal-simulator/pom.xml
@@ -212,17 +212,16 @@
<verbose>true</verbose>
<apiVersion>1.23</apiVersion>
<registry>nexus3.onap.org:10001</registry>
- <authConfig>
- <pull>
- <username>docker</username>
- <password>docker</password>
- </pull>
- </authConfig>
+ <authConfig>
+ <pull>
+ <username>docker</username>
+ <password>docker</password>
+ </pull>
+ </authConfig>
<images>
-
<!-- Build simulator image -->
<image>
- <name>openecomp/sdc-simulator</name>
+ <name>onap/sdc-simulator</name>
<alias>sdc-simulator</alias>
<build>
<cleanup>try</cleanup>
@@ -251,11 +250,11 @@
</goals>
</execution>
<execution>
- <id>push-images</id>
- <phase>deploy</phase>
- <goals>
+ <id>push-images</id>
+ <phase>deploy</phase>
+ <goals>
<goal>push</goal>
- </goals>
+ </goals>
</execution>
</executions>
</plugin>
diff --git a/utils/webseal-simulator/scripts/simulator_docker_run.sh b/utils/webseal-simulator/scripts/simulator_docker_run.sh
index 079dc1e578..0bcd30bb3d 100644
--- a/utils/webseal-simulator/scripts/simulator_docker_run.sh
+++ b/utils/webseal-simulator/scripts/simulator_docker_run.sh
@@ -8,7 +8,7 @@ function usage {
function cleanup {
echo "performing old dockers cleanup"
- docker_ids=`docker ps -a | egrep "openecomp/sdc-simulator|Exit" | awk '{print $1}'`
+ docker_ids=`docker ps -a | egrep "onap/sdc-simulator|Exit" | awk '{print $1}'`
for X in ${docker_ids}
do
docker rm -f ${X}
@@ -61,9 +61,9 @@ cleanup
export IP=`ifconfig eth0 | awk -F: '/inet addr/ {gsub(/ .*/,"",$2); print $2}'`
-export PREFIX=${NEXUS_DOCKER_REPO}'/openecomp'
+export PREFIX=${NEXUS_DOCKER_REPO}'/onap'
-PREFIX='openecomp'
+PREFIX='onap'
echo ""
echo "${PREFIX}"
diff --git a/utils/webseal-simulator/sdc-simulator/startup.sh b/utils/webseal-simulator/sdc-simulator/startup.sh
index 029126d183..89582082eb 100644
--- a/utils/webseal-simulator/sdc-simulator/startup.sh
+++ b/utils/webseal-simulator/sdc-simulator/startup.sh
@@ -17,11 +17,6 @@ JAVA_OPTIONS=" ${JAVA_OPTIONS} \
-Dlogback.configurationFile=${JETTY_BASE}/config/sdc-simulator/logback.xml \
-Djetty.logging.dir=${JETTY_BASE}/logs"
-echo "---------------------------------------------"
-echo $TMPDIR
-echo $JAVA_OPTIONS
-echo $JETTY_BASE
-echo "---------------------------------------------"
cd /var/lib/jetty
/docker-entrypoint.sh
diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java
index 30d98146c2..a11dec43b9 100644
--- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java
@@ -1,18 +1,19 @@
package org.openecomp.sdc.webseal.simulator.SSL;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactory {
diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java
index df7a1d2b65..dcfef828e0 100644
--- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java
@@ -1,14 +1,15 @@
package org.openecomp.sdc.webseal.simulator.SSL;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509TrustManager;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
+
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
public class DummyX509TrustManager implements X509TrustManager
{
diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java
index 74d93a97df..724bf9ebc6 100644
--- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java
+++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java
@@ -1,30 +1,14 @@
package org.openecomp.sdc.webseal.simulator;
-import org.apache.commons.httpclient.Header;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.methods.*;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.openecomp.sdc.webseal.simulator.SSL.DummySSLProtocolSocketFactory;
-import org.openecomp.sdc.webseal.simulator.conf.Conf;
-
-
-import javax.net.ssl.*;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.*;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
@@ -33,6 +17,28 @@ import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
+import javax.net.ssl.X509TrustManager;
+import javax.servlet.RequestDispatcher;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.HttpMethodBase;
+import org.apache.commons.httpclient.methods.DeleteMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.protocol.Protocol;
+import org.openecomp.sdc.webseal.simulator.SSL.DummySSLProtocolSocketFactory;
+import org.openecomp.sdc.webseal.simulator.conf.Conf;
+
public class SdcProxy extends HttpServlet {
private static final long serialVersionUID = 1L;
diff --git a/utils/webseal-simulator/src/main/resources/webseal.conf b/utils/webseal-simulator/src/main/resources/webseal.conf
index a7026e39fa..7065725ab1 100644
--- a/utils/webseal-simulator/src/main/resources/webseal.conf
+++ b/utils/webseal-simulator/src/main/resources/webseal.conf
@@ -1,22 +1,22 @@
{
webseal {
- fe="http://localhost:8181"
+ fe="http://10.0.2.15:8181"
users = [
{
- userId="cs0008"
+ userId="m08740"
password="123123a"
firstName="Carlos"
lastName="Santana"
role="Designer"
- email="csantana@sdc.com"
- },
+ email="csantana@sdc.com"
+ },
{
userId="op0001"
password="123123a"
firstName="Aretha"
lastName="Franklin"
role="Ops"
- email="afranklin@sdc.com"
+ email="afranklin@sdc.com"
},
{
userId="jh0003"
@@ -41,9 +41,24 @@
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"
}
]
}
-
-}
+}